onScrollUpdate method

void onScrollUpdate({
  1. required List<String> urls,
  2. required int currentIndex,
  3. int? prefetchCount,
  4. int? prefetchBehind,
  5. int? keepRange,
  6. Map<String, String>? headers,
})

Update prefetch based on current scroll position. Cancels downloads far from current, starts prefetch for next/previous videos. Uses network-adaptive configuration for prefetch counts.

Implementation

void onScrollUpdate({
  required List<String> urls,
  required int currentIndex,
  int? prefetchCount, // Optional override, uses config.prefetchAhead if null
  int?
      prefetchBehind, // Optional override, uses config.prefetchBehind if null
  int? keepRange, // Optional override, uses config.keepRange if null
  Map<String, String>? headers,
}) {
  final effectiveConfig = config;
  final effectivePrefetchAhead =
      prefetchCount ?? effectiveConfig.prefetchAhead;
  final effectivePrefetchBehind =
      prefetchBehind ?? effectiveConfig.prefetchBehind;
  final effectiveKeepRange = keepRange ?? effectiveConfig.keepRange;

  // Cancel downloads outside keep range
  final urlsToCancel = <String>[];
  for (final url in _activeDownloads.keys) {
    final idx = urls.indexOf(url);
    if (idx < 0 || (idx - currentIndex).abs() > effectiveKeepRange) {
      urlsToCancel.add(url);
    }
  }
  for (final url in urlsToCancel) {
    cancelDownload(url);
  }

  // Cancel HLS downloads outside keep range
  final keepUrls = <String>{};
  for (int i = currentIndex - effectiveKeepRange;
      i <= currentIndex + effectiveKeepRange;
      i++) {
    if (i >= 0 && i < urls.length) {
      keepUrls.add(urls[i]);
    }
  }
  for (final url in _activeHls.toList()) {
    if (!keepUrls.contains(url)) {
      cancelDownload(url);
    }
  }

  // Priority-based prefetch: next video first, then previous, then further ahead
  final prefetchQueue = <int>[];

  // Add next videos (highest priority)
  for (int i = 1; i <= effectivePrefetchAhead; i++) {
    final idx = currentIndex + i;
    if (idx >= 0 && idx < urls.length) {
      prefetchQueue.add(idx);
    }
  }

  // Add previous videos (for smooth swipe-up)
  for (int i = 1; i <= effectivePrefetchBehind; i++) {
    final idx = currentIndex - i;
    if (idx >= 0 && idx < urls.length) {
      prefetchQueue.add(idx);
    }
  }

  // Start prefetch for queued videos
  for (final idx in prefetchQueue) {
    getPlayablePath(urls[idx], headers: headers);
  }
}