BlueGit

timfa filemanager

Add walker cache marker on seek bar

Video playback now shows a seek-bar ':' marker indicating how far the background HLS walker has cached ahead. The walker reports cached-through progress to subscribers, and both authenticated and share players bind and clean up that marker with stream lifecycle events. VHS buffering thresholds were also expanded so players hold larger forward buffers while continuing to read segment bytes from service-worker cache on seeks and rewinds.

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

Hash
2abeb94a8f15422a8bb6341bd1c74636c2d5598f
Parent
feb493fc
5 files changed +313 −7
.github/technical-reference.md +4 −3
@@ -175,7 +175,7 @@
175 175 - Standalone public share page served at /share/:token; no auth required.
176 176 - Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
177 177 - tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
178 - Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, background stream-ahead prefetch (session playlist/variant/segment fetches continue towards video end while playback reads cache), service-worker-backed HLS segment cache enablement during playback (with per-session cache cleanup on close), and explicit backend session release on unload.
178 - Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, background stream-ahead prefetch (session playlist/variant/segment fetches continue towards video end while playback reads cache), seek-bar cache frontier marker (`:`) for walker progress, service-worker-backed HLS segment cache enablement during playback (with per-session cache cleanup on close), and explicit backend session release on unload.
179 179 - Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
180 180 - Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
181 181
@@ -183,13 +183,14 @@
183 183 - applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
184 184 - bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
185 185 - bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), merges buffered-end signals from both Video.js/player APIs and underlying media buffered ranges so under-reported player values do not cap subtitle prefetch early, keeps the prefetch frontier pinned to at least current playback time so it chases buffered-ahead range instead of replaying stale lag after video/session changes, coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, ensures force-seek aborts still clear in-flight current-request state so subtitle refreshes continue instead of deadlocking, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
186 - bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; returns a controller with stop()/done().
186 - bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; tracks cached-through timeline progress and returns a controller with stop()/done()/getStatus()/subscribe().
187 - bindStreamAheadSeekMarker(player, streamAheadPrefetch, opts) - Renders a non-interactive `:` marker on the playback seek bar showing how far the stream-ahead walker has cached through the timeline; subscribes to walker progress updates and removes itself on detach.
187 188 - enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
188 189 - clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
189 190
190 191 ## public/stream-cache-sw.js
191 192 - fetch handler - Caches successful segment/init GET responses for `/api/files/video-stream/*` and `/api/share/video-stream/*` (`.ts/.m4s/.mp4/.aac/.vtt`), intentionally skips `.m3u8` manifests to avoid stale-playlist seek regressions, warms full-body cache entries when playback uses byte-range requests, and can synthesize 206 partial responses from cached full segments so backward seeks keep working after server-side prune.
192 - configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
193 - configureVideoJsBuffering(videojs, opts) - Applies long forward-buffer settings used for file playback when VHS exposes those knobs (goal/max goal plus low-water-line thresholds) so clients keep larger forward buffers before needing network fetches.
193 194 - ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
194 195
195 196 ## public/index.html
@@ -175,7 +175,7 @@
175- Standalone public share page served at /share/:token; no auth required.
175- Standalone public share page served at /share/:token; no auth required.
176- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
176- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
177- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
177- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
178- Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, background stream-ahead prefetch (session playlist/variant/segment fetches continue towards video end while playback reads cache), service-worker-backed HLS segment cache enablement during playback (with per-session cache cleanup on close), and explicit backend session release on unload.
178- Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, background stream-ahead prefetch (session playlist/variant/segment fetches continue towards video end while playback reads cache), seek-bar cache frontier marker (`:`) for walker progress, service-worker-backed HLS segment cache enablement during playback (with per-session cache cleanup on close), and explicit backend session release on unload.
179- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
179- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
180- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
180- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
181
181
@@ -183,13 +183,14 @@
183- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
183- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
184- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
184- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
185- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), merges buffered-end signals from both Video.js/player APIs and underlying media buffered ranges so under-reported player values do not cap subtitle prefetch early, keeps the prefetch frontier pinned to at least current playback time so it chases buffered-ahead range instead of replaying stale lag after video/session changes, coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, ensures force-seek aborts still clear in-flight current-request state so subtitle refreshes continue instead of deadlocking, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
185- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), merges buffered-end signals from both Video.js/player APIs and underlying media buffered ranges so under-reported player values do not cap subtitle prefetch early, keeps the prefetch frontier pinned to at least current playback time so it chases buffered-ahead range instead of replaying stale lag after video/session changes, coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, ensures force-seek aborts still clear in-flight current-request state so subtitle refreshes continue instead of deadlocking, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
186- bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; returns a controller with stop()/done().
186- bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; tracks cached-through timeline progress and returns a controller with stop()/done()/getStatus()/subscribe().
187- bindStreamAheadSeekMarker(player, streamAheadPrefetch, opts) - Renders a non-interactive `:` marker on the playback seek bar showing how far the stream-ahead walker has cached through the timeline; subscribes to walker progress updates and removes itself on detach.
187- enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
188- enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
188- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
189- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
189
190
190## public/stream-cache-sw.js
191## public/stream-cache-sw.js
191- fetch handler - Caches successful segment/init GET responses for `/api/files/video-stream/*` and `/api/share/video-stream/*` (`.ts/.m4s/.mp4/.aac/.vtt`), intentionally skips `.m3u8` manifests to avoid stale-playlist seek regressions, warms full-body cache entries when playback uses byte-range requests, and can synthesize 206 partial responses from cached full segments so backward seeks keep working after server-side prune.
192- fetch handler - Caches successful segment/init GET responses for `/api/files/video-stream/*` and `/api/share/video-stream/*` (`.ts/.m4s/.mp4/.aac/.vtt`), intentionally skips `.m3u8` manifests to avoid stale-playlist seek regressions, warms full-body cache entries when playback uses byte-range requests, and can synthesize 206 partial responses from cached full segments so backward seeks keep working after server-side prune.
192- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
193- configureVideoJsBuffering(videojs, opts) - Applies long forward-buffer settings used for file playback when VHS exposes those knobs (goal/max goal plus low-water-line thresholds) so clients keep larger forward buffers before needing network fetches.
193- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
194- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
194
195
195## public/index.html
196## public/index.html
public/app.js +9 −0
@@ -476,6 +476,13 @@ function bindStreamAheadPrefetch (playlistUrl)
476 476 });
477 477 }
478 478
479 function bindStreamAheadSeekMarker (player, streamAheadPrefetch)
480 {
481 const shared = sharedVideoPlayer();
482 if (!shared || typeof shared.bindStreamAheadSeekMarker !== 'function') return null;
483 return shared.bindStreamAheadSeekMarker(player, streamAheadPrefetch);
484 }
485
479 486 async function reportWatchProgress (filePath, progress)
480 487 {
481 488 if (!filePath || !Number.isFinite(progress)) return;
@@ -3978,6 +3985,7 @@ async function renderStreamedVideoPreview (item, targetEl)
3978 3985 });
3979 3986
3980 3987 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
3988 const streamAheadSeekMarker = bindStreamAheadSeekMarker(player, streamAheadPrefetch);
3981 3989
3982 3990 ensureVideoPlaybackUi(player, session.durationSeconds);
3983 3991 const imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item);
@@ -4063,6 +4071,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4063 4071 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4064 4072 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4065 4073 }
4074 try { streamAheadSeekMarker && streamAheadSeekMarker.detach(); } catch { /* ignore */ }
4066 4075 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4067 4076 void clearVideoStreamClientCache(sessionPlaylistUrl);
4068 4077 releaseActivePreviewVideoStreamSession();
@@ -476,6 +476,13 @@ function bindStreamAheadPrefetch (playlistUrl)
476 });
476 });
477}
477}
478
478
479function bindStreamAheadSeekMarker (player, streamAheadPrefetch)
480{
481 const shared = sharedVideoPlayer();
482 if (!shared || typeof shared.bindStreamAheadSeekMarker !== 'function') return null;
483 return shared.bindStreamAheadSeekMarker(player, streamAheadPrefetch);
484}
485
479async function reportWatchProgress (filePath, progress)
486async function reportWatchProgress (filePath, progress)
480{
487{
481 if (!filePath || !Number.isFinite(progress)) return;
488 if (!filePath || !Number.isFinite(progress)) return;
@@ -3978,6 +3985,7 @@ async function renderStreamedVideoPreview (item, targetEl)
3978 });
3985 });
3979
3986
3980 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
3987 const trackPrefs = bindUserVideoTrackPrefs(player, prefs);
3988 const streamAheadSeekMarker = bindStreamAheadSeekMarker(player, streamAheadPrefetch);
3981
3989
3982 ensureVideoPlaybackUi(player, session.durationSeconds);
3990 ensureVideoPlaybackUi(player, session.durationSeconds);
3983 const imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item);
3991 const imageSubtitleController = bindImageSubtitleOverlay(player, videojs, prefs, session, item);
@@ -4063,6 +4071,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4063 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4071 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4064 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4072 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4065 }
4073 }
4074 try { streamAheadSeekMarker && streamAheadSeekMarker.detach(); } catch { /* ignore */ }
4066 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4075 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4067 void clearVideoStreamClientCache(sessionPlaylistUrl);
4076 void clearVideoStreamClientCache(sessionPlaylistUrl);
4068 releaseActivePreviewVideoStreamSession();
4077 releaseActivePreviewVideoStreamSession();
public/share.html +11 −0
@@ -259,6 +259,7 @@
259 259 let shareImageSubtitleController = null;
260 260 let shareVideoSessionId = null;
261 261 let shareStreamAheadPrefetch = null;
262 let shareStreamAheadSeekMarker = null;
262 263
263 264 function sharedVideoPlayer ()
264 265 {
@@ -336,6 +337,7 @@
336 337 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
337 338 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
338 339 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
340 try { shareStreamAheadSeekMarker && shareStreamAheadSeekMarker.detach(); } catch { /* ignore */ }
339 341 try { shareStreamAheadPrefetch && shareStreamAheadPrefetch.stop(); } catch { /* ignore */ }
340 342 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
341 343
@@ -345,6 +347,7 @@
345 347 shareVideoPlayer = null;
346 348 shareTrackPrefs = null;
347 349 shareImageSubtitleController = null;
350 shareStreamAheadSeekMarker = null;
348 351 shareStreamAheadPrefetch = null;
349 352 }
350 353
@@ -379,6 +382,13 @@
379 382 });
380 383 }
381 384
385 function bindStreamAheadSeekMarker (player, streamAheadPrefetch)
386 {
387 const shared = sharedVideoPlayer();
388 if (!shared || typeof shared.bindStreamAheadSeekMarker !== 'function') return null;
389 return shared.bindStreamAheadSeekMarker(player, streamAheadPrefetch);
390 }
391
382 392 // ── Timer ───────────────────────────────────────────────────────────────
383 393 function startTimer ()
384 394 {
@@ -520,6 +530,7 @@
520 530 }),
521 531 })
522 532 : null;
533 shareStreamAheadSeekMarker = bindStreamAheadSeekMarker(shareVideoPlayer, shareStreamAheadPrefetch);
523 534 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
524 535
525 536 shareVideoPlayer.ready(() =>
@@ -259,6 +259,7 @@
259 let shareImageSubtitleController = null;
259 let shareImageSubtitleController = null;
260 let shareVideoSessionId = null;
260 let shareVideoSessionId = null;
261 let shareStreamAheadPrefetch = null;
261 let shareStreamAheadPrefetch = null;
262 let shareStreamAheadSeekMarker = null;
262
263
263 function sharedVideoPlayer ()
264 function sharedVideoPlayer ()
264 {
265 {
@@ -336,6 +337,7 @@
336 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
337 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
337 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
338 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
338 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
339 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
340 try { shareStreamAheadSeekMarker && shareStreamAheadSeekMarker.detach(); } catch { /* ignore */ }
339 try { shareStreamAheadPrefetch && shareStreamAheadPrefetch.stop(); } catch { /* ignore */ }
341 try { shareStreamAheadPrefetch && shareStreamAheadPrefetch.stop(); } catch { /* ignore */ }
340 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
342 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
341
343
@@ -345,6 +347,7 @@
345 shareVideoPlayer = null;
347 shareVideoPlayer = null;
346 shareTrackPrefs = null;
348 shareTrackPrefs = null;
347 shareImageSubtitleController = null;
349 shareImageSubtitleController = null;
350 shareStreamAheadSeekMarker = null;
348 shareStreamAheadPrefetch = null;
351 shareStreamAheadPrefetch = null;
349 }
352 }
350
353
@@ -379,6 +382,13 @@
379 });
382 });
380 }
383 }
381
384
385 function bindStreamAheadSeekMarker (player, streamAheadPrefetch)
386 {
387 const shared = sharedVideoPlayer();
388 if (!shared || typeof shared.bindStreamAheadSeekMarker !== 'function') return null;
389 return shared.bindStreamAheadSeekMarker(player, streamAheadPrefetch);
390 }
391
382 // ── Timer ───────────────────────────────────────────────────────────────
392 // ── Timer ───────────────────────────────────────────────────────────────
383 function startTimer ()
393 function startTimer ()
384 {
394 {
@@ -520,6 +530,7 @@
520 }),
530 }),
521 })
531 })
522 : null;
532 : null;
533 shareStreamAheadSeekMarker = bindStreamAheadSeekMarker(shareVideoPlayer, shareStreamAheadPrefetch);
523 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
534 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
524
535
525 shareVideoPlayer.ready(() =>
536 shareVideoPlayer.ready(() =>
public/shared-video-player.js +231 −4
@@ -18,6 +18,7 @@
18 18 const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js';
19 19 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
20 20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
21 const VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS = 4;
21 22
22 23 function roundLogNumber (value, digits = 3)
23 24 {
@@ -1568,6 +1569,8 @@
1568 1569 {
1569 1570 videojs.Vhs.GOAL_BUFFER_LENGTH = bufferSeconds;
1570 1571 videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = bufferSeconds;
1572 videojs.Vhs.BUFFER_LOW_WATER_LINE = Math.max(30, Math.floor(bufferSeconds / 2));
1573 videojs.Vhs.MAX_BUFFER_LOW_WATER_LINE = bufferSeconds;
1571 1574 } catch
1572 1575 {
1573 1576 // Ignore builds that do not expose VHS buffer configuration.
@@ -1645,7 +1648,10 @@
1645 1648 const lines = String(manifestText || '').split(/\r?\n/);
1646 1649 const childPlaylists = [];
1647 1650 const mediaAssets = [];
1651 const mediaSegments = [];
1648 1652 let expectPlaylistUri = false;
1653 let segmentCursorSeconds = 0;
1654 let pendingSegmentDurationSeconds = null;
1649 1655
1650 1656 for (const rawLine of lines)
1651 1657 {
@@ -1660,6 +1666,16 @@
1660 1666 continue;
1661 1667 }
1662 1668
1669 const segmentDurationMatch = line.match(/^#EXTINF\s*:\s*([0-9]+(?:\.[0-9]+)?)/i);
1670 if (segmentDurationMatch)
1671 {
1672 const parsed = Number.parseFloat(segmentDurationMatch[1]);
1673 pendingSegmentDurationSeconds = Number.isFinite(parsed) && parsed > 0
1674 ? parsed
1675 : VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS;
1676 continue;
1677 }
1678
1663 1679 const mapMatch = line.match(/^#EXT-X-MAP\s*:\s*.*?URI="([^"]+)"/i);
1664 1680 if (mapMatch && mapMatch[1]) mediaAssets.push(mapMatch[1]);
1665 1681 continue;
@@ -1672,16 +1688,166 @@
1672 1688 } else
1673 1689 {
1674 1690 mediaAssets.push(line);
1691 if (Number.isFinite(pendingSegmentDurationSeconds) && pendingSegmentDurationSeconds > 0)
1692 {
1693 const startTimeSeconds = segmentCursorSeconds;
1694 segmentCursorSeconds += pendingSegmentDurationSeconds;
1695 mediaSegments.push({
1696 uri: line,
1697 startTimeSeconds,
1698 endTimeSeconds: segmentCursorSeconds,
1699 });
1700 }
1701 pendingSegmentDurationSeconds = null;
1675 1702 }
1676 1703 }
1677 1704
1678 1705 return {
1679 1706 childPlaylists,
1680 1707 mediaAssets,
1708 mediaSegments,
1681 1709 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1682 1710 };
1683 1711 }
1684 1712
1713 function bindStreamAheadSeekMarker (player, streamAheadPrefetch, opts = {})
1714 {
1715 if (!player || typeof player.on !== 'function' || !streamAheadPrefetch) return null;
1716
1717 const markerChar = String(opts.markerChar || ':').slice(0, 1) || ':';
1718 const markerColor = String(opts.markerColor || '#d6d6d6');
1719 let markerEl = null;
1720 let markerContainerEl = null;
1721 let cachedThroughSeconds = null;
1722 let detachProgressListener = null;
1723
1724 const currentDuration = () =>
1725 {
1726 const duration = Number(player.duration && player.duration());
1727 return Number.isFinite(duration) && duration > 0 ? duration : null;
1728 };
1729
1730 const updateMarker = () =>
1731 {
1732 if (!markerEl) return;
1733
1734 const duration = currentDuration();
1735 if (!duration || !Number.isFinite(cachedThroughSeconds) || cachedThroughSeconds < 0)
1736 {
1737 markerEl.style.display = 'none';
1738 return;
1739 }
1740
1741 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1742 markerEl.style.display = 'block';
1743 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1744 };
1745
1746 const ensureMarker = () =>
1747 {
1748 if (markerContainerEl && markerContainerEl.isConnected)
1749 {
1750 updateMarker();
1751 return;
1752 }
1753
1754 const playerEl = player.el && player.el();
1755 if (!playerEl) return;
1756
1757 const seekBarEl = playerEl.querySelector('.vjs-seek-bar')
1758 || playerEl.querySelector('.vjs-progress-holder')
1759 || playerEl.querySelector('.vjs-progress-control');
1760 if (!seekBarEl) return;
1761
1762 const computedPosition = window.getComputedStyle(seekBarEl).position;
1763 if (computedPosition === 'static') seekBarEl.style.position = 'relative';
1764
1765 markerContainerEl = document.createElement('div');
1766 markerContainerEl.className = 'vjs-stream-ahead-cache-marker-container';
1767 markerContainerEl.style.position = 'absolute';
1768 markerContainerEl.style.left = '0';
1769 markerContainerEl.style.right = '0';
1770 markerContainerEl.style.top = '50%';
1771 markerContainerEl.style.height = '10px';
1772 markerContainerEl.style.transform = 'translateY(-50%)';
1773 markerContainerEl.style.pointerEvents = 'none';
1774 markerContainerEl.style.zIndex = '4';
1775
1776 markerEl = document.createElement('span');
1777 markerEl.className = 'vjs-stream-ahead-cache-marker';
1778 markerEl.style.position = 'absolute';
1779 markerEl.style.top = '50%';
1780 markerEl.style.width = '10px';
1781 markerEl.style.height = '10px';
1782 markerEl.style.transform = 'translate(-50%, -50%)';
1783 markerEl.style.color = markerColor;
1784 markerEl.style.fontFamily = 'monospace';
1785 markerEl.style.fontSize = '12px';
1786 markerEl.style.fontWeight = '700';
1787 markerEl.style.lineHeight = '10px';
1788 markerEl.style.textAlign = 'center';
1789 markerEl.style.display = 'none';
1790 markerEl.style.textShadow = '0 0 2px rgba(0, 0, 0, 0.65)';
1791 markerEl.textContent = markerChar;
1792 markerEl.setAttribute('aria-hidden', 'true');
1793 markerEl.title = 'Walker cached through';
1794
1795 markerContainerEl.appendChild(markerEl);
1796 seekBarEl.appendChild(markerContainerEl);
1797 updateMarker();
1798 };
1799
1800 const onDurationHint = () =>
1801 {
1802 ensureMarker();
1803 updateMarker();
1804 };
1805
1806 player.on('loadedmetadata', onDurationHint);
1807 player.on('durationchange', onDurationHint);
1808 player.on('loadedplaylist', onDurationHint);
1809 player.ready(onDurationHint);
1810
1811 if (typeof streamAheadPrefetch.subscribe === 'function')
1812 {
1813 detachProgressListener = streamAheadPrefetch.subscribe((status) =>
1814 {
1815 const nextCachedThrough = status && Number.isFinite(Number(status.cachedThroughSeconds))
1816 ? Number(status.cachedThroughSeconds)
1817 : null;
1818 cachedThroughSeconds = nextCachedThrough;
1819 ensureMarker();
1820 updateMarker();
1821 });
1822 } else if (typeof streamAheadPrefetch.getStatus === 'function')
1823 {
1824 const status = streamAheadPrefetch.getStatus();
1825 cachedThroughSeconds = status && Number.isFinite(Number(status.cachedThroughSeconds))
1826 ? Number(status.cachedThroughSeconds)
1827 : null;
1828 ensureMarker();
1829 updateMarker();
1830 }
1831
1832 return {
1833 detach: () =>
1834 {
1835 if (typeof detachProgressListener === 'function')
1836 {
1837 try { detachProgressListener(); } catch { /* ignore detach races */ }
1838 detachProgressListener = null;
1839 }
1840
1841 if (markerContainerEl && markerContainerEl.parentNode)
1842 {
1843 markerContainerEl.parentNode.removeChild(markerContainerEl);
1844 }
1845 markerContainerEl = null;
1846 markerEl = null;
1847 },
1848 };
1849 }
1850
1685 1851 function bindStreamAheadPrefetch (opts = {})
1686 1852 {
1687 1853 const basePlaylistUrl = String(opts.playlistUrl || '').trim();
@@ -1697,8 +1863,11 @@
1697 1863 const playlistStatusByUrl = new Map();
1698 1864 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1699 1865 const fetchedAssetUrls = new Set();
1866 const segmentEndSecondsByAssetUrl = new Map();
1867 const progressListeners = new Set();
1700 1868 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1701 1869 let stopped = false;
1870 let cachedThroughSeconds = null;
1702 1871
1703 1872 const resolveUrl = (value, parentUrl) =>
1704 1873 {
@@ -1740,11 +1909,34 @@
1740 1909 return true;
1741 1910 };
1742 1911
1912 const getStatus = () => ({
1913 cachedThroughSeconds,
1914 knownPlaylistCount: knownPlaylistUrls.size,
1915 fetchedAssetCount: fetchedAssetUrls.size,
1916 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1917 stopped,
1918 });
1919
1920 const emitProgress = () =>
1921 {
1922 const status = getStatus();
1923 for (const listener of Array.from(progressListeners))
1924 {
1925 try
1926 {
1927 listener(status);
1928 } catch
1929 {
1930 // Keep progress listeners best-effort only.
1931 }
1932 }
1933 };
1934
1743 1935 const workerPromise = (async () =>
1744 1936 {
1745 1937 while (!stopped)
1746 1938 {
1747 const nextAssetUrls = [];
1939 const nextAssetUrlSet = new Set();
1748 1940
1749 1941 for (const playlistUrl of Array.from(knownPlaylistUrls))
1750 1942 {
@@ -1767,20 +1959,42 @@
1767 1959 {
1768 1960 const resolved = resolveUrl(asset, playlistUrl);
1769 1961 if (!resolved || fetchedAssetUrls.has(resolved)) continue;
1770 fetchedAssetUrls.add(resolved);
1771 nextAssetUrls.push(resolved);
1962 nextAssetUrlSet.add(resolved);
1963 }
1964
1965 for (const segment of parsed.mediaSegments)
1966 {
1967 if (!segment || !segment.uri) continue;
1968 const resolved = resolveUrl(segment.uri, playlistUrl);
1969 if (!resolved) continue;
1970 if (!Number.isFinite(segment.endTimeSeconds) || segment.endTimeSeconds < 0) continue;
1971 segmentEndSecondsByAssetUrl.set(resolved, Number(segment.endTimeSeconds));
1772 1972 }
1773 1973 }
1774 1974
1975 const nextAssetUrls = Array.from(nextAssetUrlSet);
1775 1976 for (const assetUrl of nextAssetUrls)
1776 1977 {
1777 1978 if (stopped) return;
1778 await fetchAsset(assetUrl).catch(() => false);
1979 const fetched = await fetchAsset(assetUrl).catch(() => false);
1980 if (!fetched) continue;
1981
1982 fetchedAssetUrls.add(assetUrl);
1983 const segmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
1984 if (Number.isFinite(segmentEndSeconds))
1985 {
1986 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
1987 {
1988 cachedThroughSeconds = segmentEndSeconds;
1989 emitProgress();
1990 }
1991 }
1779 1992 }
1780 1993
1781 1994 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
1782 1995 if (allPlaylistsComplete && !nextAssetUrls.length)
1783 1996 {
1997 emitProgress();
1784 1998 return;
1785 1999 }
1786 2000
@@ -1799,8 +2013,20 @@
1799 2013 {
1800 2014 try { controller.abort(); } catch { /* ignore abort races */ }
1801 2015 }
2016 emitProgress();
1802 2017 },
1803 2018 done: () => workerPromise,
2019 getStatus,
2020 subscribe: (listener) =>
2021 {
2022 if (typeof listener !== 'function') return () => { };
2023 progressListeners.add(listener);
2024 try { listener(getStatus()); } catch { /* ignore listener failures */ }
2025 return () =>
2026 {
2027 progressListeners.delete(listener);
2028 };
2029 },
1804 2030 };
1805 2031 }
1806 2032
@@ -1819,6 +2045,7 @@
1819 2045 applyDefaultTextTrackPrefs,
1820 2046 bindImageSubtitleOverlay,
1821 2047 bindStreamAheadPrefetch,
2048 bindStreamAheadSeekMarker,
1822 2049 bindTrackPrefs,
1823 2050 clearVideoStreamClientCache,
1824 2051 configureVideoJsBuffering,
@@ -18,6 +18,7 @@
18 const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js';
18 const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js';
19 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
19 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
21 const VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS = 4;
21
22
22 function roundLogNumber (value, digits = 3)
23 function roundLogNumber (value, digits = 3)
23 {
24 {
@@ -1568,6 +1569,8 @@
1568 {
1569 {
1569 videojs.Vhs.GOAL_BUFFER_LENGTH = bufferSeconds;
1570 videojs.Vhs.GOAL_BUFFER_LENGTH = bufferSeconds;
1570 videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = bufferSeconds;
1571 videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = bufferSeconds;
1572 videojs.Vhs.BUFFER_LOW_WATER_LINE = Math.max(30, Math.floor(bufferSeconds / 2));
1573 videojs.Vhs.MAX_BUFFER_LOW_WATER_LINE = bufferSeconds;
1571 } catch
1574 } catch
1572 {
1575 {
1573 // Ignore builds that do not expose VHS buffer configuration.
1576 // Ignore builds that do not expose VHS buffer configuration.
@@ -1645,7 +1648,10 @@
1645 const lines = String(manifestText || '').split(/\r?\n/);
1648 const lines = String(manifestText || '').split(/\r?\n/);
1646 const childPlaylists = [];
1649 const childPlaylists = [];
1647 const mediaAssets = [];
1650 const mediaAssets = [];
1651 const mediaSegments = [];
1648 let expectPlaylistUri = false;
1652 let expectPlaylistUri = false;
1653 let segmentCursorSeconds = 0;
1654 let pendingSegmentDurationSeconds = null;
1649
1655
1650 for (const rawLine of lines)
1656 for (const rawLine of lines)
1651 {
1657 {
@@ -1660,6 +1666,16 @@
1660 continue;
1666 continue;
1661 }
1667 }
1662
1668
1669 const segmentDurationMatch = line.match(/^#EXTINF\s*:\s*([0-9]+(?:\.[0-9]+)?)/i);
1670 if (segmentDurationMatch)
1671 {
1672 const parsed = Number.parseFloat(segmentDurationMatch[1]);
1673 pendingSegmentDurationSeconds = Number.isFinite(parsed) && parsed > 0
1674 ? parsed
1675 : VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS;
1676 continue;
1677 }
1678
1663 const mapMatch = line.match(/^#EXT-X-MAP\s*:\s*.*?URI="([^"]+)"/i);
1679 const mapMatch = line.match(/^#EXT-X-MAP\s*:\s*.*?URI="([^"]+)"/i);
1664 if (mapMatch && mapMatch[1]) mediaAssets.push(mapMatch[1]);
1680 if (mapMatch && mapMatch[1]) mediaAssets.push(mapMatch[1]);
1665 continue;
1681 continue;
@@ -1672,16 +1688,166 @@
1672 } else
1688 } else
1673 {
1689 {
1674 mediaAssets.push(line);
1690 mediaAssets.push(line);
1691 if (Number.isFinite(pendingSegmentDurationSeconds) && pendingSegmentDurationSeconds > 0)
1692 {
1693 const startTimeSeconds = segmentCursorSeconds;
1694 segmentCursorSeconds += pendingSegmentDurationSeconds;
1695 mediaSegments.push({
1696 uri: line,
1697 startTimeSeconds,
1698 endTimeSeconds: segmentCursorSeconds,
1699 });
1700 }
1701 pendingSegmentDurationSeconds = null;
1675 }
1702 }
1676 }
1703 }
1677
1704
1678 return {
1705 return {
1679 childPlaylists,
1706 childPlaylists,
1680 mediaAssets,
1707 mediaAssets,
1708 mediaSegments,
1681 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1709 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1682 };
1710 };
1683 }
1711 }
1684
1712
1713 function bindStreamAheadSeekMarker (player, streamAheadPrefetch, opts = {})
1714 {
1715 if (!player || typeof player.on !== 'function' || !streamAheadPrefetch) return null;
1716
1717 const markerChar = String(opts.markerChar || ':').slice(0, 1) || ':';
1718 const markerColor = String(opts.markerColor || '#d6d6d6');
1719 let markerEl = null;
1720 let markerContainerEl = null;
1721 let cachedThroughSeconds = null;
1722 let detachProgressListener = null;
1723
1724 const currentDuration = () =>
1725 {
1726 const duration = Number(player.duration && player.duration());
1727 return Number.isFinite(duration) && duration > 0 ? duration : null;
1728 };
1729
1730 const updateMarker = () =>
1731 {
1732 if (!markerEl) return;
1733
1734 const duration = currentDuration();
1735 if (!duration || !Number.isFinite(cachedThroughSeconds) || cachedThroughSeconds < 0)
1736 {
1737 markerEl.style.display = 'none';
1738 return;
1739 }
1740
1741 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1742 markerEl.style.display = 'block';
1743 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1744 };
1745
1746 const ensureMarker = () =>
1747 {
1748 if (markerContainerEl && markerContainerEl.isConnected)
1749 {
1750 updateMarker();
1751 return;
1752 }
1753
1754 const playerEl = player.el && player.el();
1755 if (!playerEl) return;
1756
1757 const seekBarEl = playerEl.querySelector('.vjs-seek-bar')
1758 || playerEl.querySelector('.vjs-progress-holder')
1759 || playerEl.querySelector('.vjs-progress-control');
1760 if (!seekBarEl) return;
1761
1762 const computedPosition = window.getComputedStyle(seekBarEl).position;
1763 if (computedPosition === 'static') seekBarEl.style.position = 'relative';
1764
1765 markerContainerEl = document.createElement('div');
1766 markerContainerEl.className = 'vjs-stream-ahead-cache-marker-container';
1767 markerContainerEl.style.position = 'absolute';
1768 markerContainerEl.style.left = '0';
1769 markerContainerEl.style.right = '0';
1770 markerContainerEl.style.top = '50%';
1771 markerContainerEl.style.height = '10px';
1772 markerContainerEl.style.transform = 'translateY(-50%)';
1773 markerContainerEl.style.pointerEvents = 'none';
1774 markerContainerEl.style.zIndex = '4';
1775
1776 markerEl = document.createElement('span');
1777 markerEl.className = 'vjs-stream-ahead-cache-marker';
1778 markerEl.style.position = 'absolute';
1779 markerEl.style.top = '50%';
1780 markerEl.style.width = '10px';
1781 markerEl.style.height = '10px';
1782 markerEl.style.transform = 'translate(-50%, -50%)';
1783 markerEl.style.color = markerColor;
1784 markerEl.style.fontFamily = 'monospace';
1785 markerEl.style.fontSize = '12px';
1786 markerEl.style.fontWeight = '700';
1787 markerEl.style.lineHeight = '10px';
1788 markerEl.style.textAlign = 'center';
1789 markerEl.style.display = 'none';
1790 markerEl.style.textShadow = '0 0 2px rgba(0, 0, 0, 0.65)';
1791 markerEl.textContent = markerChar;
1792 markerEl.setAttribute('aria-hidden', 'true');
1793 markerEl.title = 'Walker cached through';
1794
1795 markerContainerEl.appendChild(markerEl);
1796 seekBarEl.appendChild(markerContainerEl);
1797 updateMarker();
1798 };
1799
1800 const onDurationHint = () =>
1801 {
1802 ensureMarker();
1803 updateMarker();
1804 };
1805
1806 player.on('loadedmetadata', onDurationHint);
1807 player.on('durationchange', onDurationHint);
1808 player.on('loadedplaylist', onDurationHint);
1809 player.ready(onDurationHint);
1810
1811 if (typeof streamAheadPrefetch.subscribe === 'function')
1812 {
1813 detachProgressListener = streamAheadPrefetch.subscribe((status) =>
1814 {
1815 const nextCachedThrough = status && Number.isFinite(Number(status.cachedThroughSeconds))
1816 ? Number(status.cachedThroughSeconds)
1817 : null;
1818 cachedThroughSeconds = nextCachedThrough;
1819 ensureMarker();
1820 updateMarker();
1821 });
1822 } else if (typeof streamAheadPrefetch.getStatus === 'function')
1823 {
1824 const status = streamAheadPrefetch.getStatus();
1825 cachedThroughSeconds = status && Number.isFinite(Number(status.cachedThroughSeconds))
1826 ? Number(status.cachedThroughSeconds)
1827 : null;
1828 ensureMarker();
1829 updateMarker();
1830 }
1831
1832 return {
1833 detach: () =>
1834 {
1835 if (typeof detachProgressListener === 'function')
1836 {
1837 try { detachProgressListener(); } catch { /* ignore detach races */ }
1838 detachProgressListener = null;
1839 }
1840
1841 if (markerContainerEl && markerContainerEl.parentNode)
1842 {
1843 markerContainerEl.parentNode.removeChild(markerContainerEl);
1844 }
1845 markerContainerEl = null;
1846 markerEl = null;
1847 },
1848 };
1849 }
1850
1685 function bindStreamAheadPrefetch (opts = {})
1851 function bindStreamAheadPrefetch (opts = {})
1686 {
1852 {
1687 const basePlaylistUrl = String(opts.playlistUrl || '').trim();
1853 const basePlaylistUrl = String(opts.playlistUrl || '').trim();
@@ -1697,8 +1863,11 @@
1697 const playlistStatusByUrl = new Map();
1863 const playlistStatusByUrl = new Map();
1698 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1864 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1699 const fetchedAssetUrls = new Set();
1865 const fetchedAssetUrls = new Set();
1866 const segmentEndSecondsByAssetUrl = new Map();
1867 const progressListeners = new Set();
1700 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1868 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1701 let stopped = false;
1869 let stopped = false;
1870 let cachedThroughSeconds = null;
1702
1871
1703 const resolveUrl = (value, parentUrl) =>
1872 const resolveUrl = (value, parentUrl) =>
1704 {
1873 {
@@ -1740,11 +1909,34 @@
1740 return true;
1909 return true;
1741 };
1910 };
1742
1911
1912 const getStatus = () => ({
1913 cachedThroughSeconds,
1914 knownPlaylistCount: knownPlaylistUrls.size,
1915 fetchedAssetCount: fetchedAssetUrls.size,
1916 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1917 stopped,
1918 });
1919
1920 const emitProgress = () =>
1921 {
1922 const status = getStatus();
1923 for (const listener of Array.from(progressListeners))
1924 {
1925 try
1926 {
1927 listener(status);
1928 } catch
1929 {
1930 // Keep progress listeners best-effort only.
1931 }
1932 }
1933 };
1934
1743 const workerPromise = (async () =>
1935 const workerPromise = (async () =>
1744 {
1936 {
1745 while (!stopped)
1937 while (!stopped)
1746 {
1938 {
1747 const nextAssetUrls = [];
1939 const nextAssetUrlSet = new Set();
1748
1940
1749 for (const playlistUrl of Array.from(knownPlaylistUrls))
1941 for (const playlistUrl of Array.from(knownPlaylistUrls))
1750 {
1942 {
@@ -1767,20 +1959,42 @@
1767 {
1959 {
1768 const resolved = resolveUrl(asset, playlistUrl);
1960 const resolved = resolveUrl(asset, playlistUrl);
1769 if (!resolved || fetchedAssetUrls.has(resolved)) continue;
1961 if (!resolved || fetchedAssetUrls.has(resolved)) continue;
1770 fetchedAssetUrls.add(resolved);
1962 nextAssetUrlSet.add(resolved);
1771 nextAssetUrls.push(resolved);
1963 }
1964
1965 for (const segment of parsed.mediaSegments)
1966 {
1967 if (!segment || !segment.uri) continue;
1968 const resolved = resolveUrl(segment.uri, playlistUrl);
1969 if (!resolved) continue;
1970 if (!Number.isFinite(segment.endTimeSeconds) || segment.endTimeSeconds < 0) continue;
1971 segmentEndSecondsByAssetUrl.set(resolved, Number(segment.endTimeSeconds));
1772 }
1972 }
1773 }
1973 }
1774
1974
1975 const nextAssetUrls = Array.from(nextAssetUrlSet);
1775 for (const assetUrl of nextAssetUrls)
1976 for (const assetUrl of nextAssetUrls)
1776 {
1977 {
1777 if (stopped) return;
1978 if (stopped) return;
1778 await fetchAsset(assetUrl).catch(() => false);
1979 const fetched = await fetchAsset(assetUrl).catch(() => false);
1980 if (!fetched) continue;
1981
1982 fetchedAssetUrls.add(assetUrl);
1983 const segmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
1984 if (Number.isFinite(segmentEndSeconds))
1985 {
1986 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
1987 {
1988 cachedThroughSeconds = segmentEndSeconds;
1989 emitProgress();
1990 }
1991 }
1779 }
1992 }
1780
1993
1781 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
1994 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
1782 if (allPlaylistsComplete && !nextAssetUrls.length)
1995 if (allPlaylistsComplete && !nextAssetUrls.length)
1783 {
1996 {
1997 emitProgress();
1784 return;
1998 return;
1785 }
1999 }
1786
2000
@@ -1799,8 +2013,20 @@
1799 {
2013 {
1800 try { controller.abort(); } catch { /* ignore abort races */ }
2014 try { controller.abort(); } catch { /* ignore abort races */ }
1801 }
2015 }
2016 emitProgress();
1802 },
2017 },
1803 done: () => workerPromise,
2018 done: () => workerPromise,
2019 getStatus,
2020 subscribe: (listener) =>
2021 {
2022 if (typeof listener !== 'function') return () => { };
2023 progressListeners.add(listener);
2024 try { listener(getStatus()); } catch { /* ignore listener failures */ }
2025 return () =>
2026 {
2027 progressListeners.delete(listener);
2028 };
2029 },
1804 };
2030 };
1805 }
2031 }
1806
2032
@@ -1819,6 +2045,7 @@
1819 applyDefaultTextTrackPrefs,
2045 applyDefaultTextTrackPrefs,
1820 bindImageSubtitleOverlay,
2046 bindImageSubtitleOverlay,
1821 bindStreamAheadPrefetch,
2047 bindStreamAheadPrefetch,
2048 bindStreamAheadSeekMarker,
1822 bindTrackPrefs,
2049 bindTrackPrefs,
1823 clearVideoStreamClientCache,
2050 clearVideoStreamClientCache,
1824 configureVideoJsBuffering,
2051 configureVideoJsBuffering,
tests/shared-video-player.test.js +58 −0
@@ -1106,6 +1106,64 @@ describe('shared image subtitle prefetching', () =>
1106 1106 window.close();
1107 1107 });
1108 1108
1109 test('stream-ahead prefetch reports cached-through progress for fetched segments', async () =>
1110 {
1111 const window = createWindow();
1112 const helper = loadSharedVideoPlayer(window);
1113 const progressSamples = [];
1114
1115 window.fetch = jest.fn(async (input) =>
1116 {
1117 const url = String(input && input.url ? input.url : input);
1118
1119 if (url === 'http://localhost/master.m3u8')
1120 {
1121 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1122 status: 200,
1123 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1124 });
1125 }
1126
1127 if (url === 'http://localhost/stream_0.m3u8')
1128 {
1129 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1130 status: 200,
1131 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1132 });
1133 }
1134
1135 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1136 {
1137 return new Response(new Uint8Array([1, 2, 3, 4]), {
1138 status: 200,
1139 headers: { 'Content-Type': 'video/mp2t' },
1140 });
1141 }
1142
1143 return new Response(null, { status: 404 });
1144 });
1145
1146 const controller = helper.bindStreamAheadPrefetch({
1147 playlistUrl: 'http://localhost/master.m3u8',
1148 pollIntervalMs: 0,
1149 credentials: 'same-origin',
1150 });
1151
1152 expect(controller).toBeTruthy();
1153 const unsubscribe = controller.subscribe((status) =>
1154 {
1155 progressSamples.push(status && status.cachedThroughSeconds);
1156 });
1157
1158 await controller.done();
1159 unsubscribe();
1160
1161 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1162
1163 controller.stop();
1164 window.close();
1165 });
1166
1109 1167 test('clears cached stream assets for a finished playlist session', async () =>
1110 1168 {
1111 1169 const window = createWindow();
@@ -1106,6 +1106,64 @@ describe('shared image subtitle prefetching', () =>
1106 window.close();
1106 window.close();
1107 });
1107 });
1108
1108
1109 test('stream-ahead prefetch reports cached-through progress for fetched segments', async () =>
1110 {
1111 const window = createWindow();
1112 const helper = loadSharedVideoPlayer(window);
1113 const progressSamples = [];
1114
1115 window.fetch = jest.fn(async (input) =>
1116 {
1117 const url = String(input && input.url ? input.url : input);
1118
1119 if (url === 'http://localhost/master.m3u8')
1120 {
1121 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1122 status: 200,
1123 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1124 });
1125 }
1126
1127 if (url === 'http://localhost/stream_0.m3u8')
1128 {
1129 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1130 status: 200,
1131 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1132 });
1133 }
1134
1135 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1136 {
1137 return new Response(new Uint8Array([1, 2, 3, 4]), {
1138 status: 200,
1139 headers: { 'Content-Type': 'video/mp2t' },
1140 });
1141 }
1142
1143 return new Response(null, { status: 404 });
1144 });
1145
1146 const controller = helper.bindStreamAheadPrefetch({
1147 playlistUrl: 'http://localhost/master.m3u8',
1148 pollIntervalMs: 0,
1149 credentials: 'same-origin',
1150 });
1151
1152 expect(controller).toBeTruthy();
1153 const unsubscribe = controller.subscribe((status) =>
1154 {
1155 progressSamples.push(status && status.cachedThroughSeconds);
1156 });
1157
1158 await controller.done();
1159 unsubscribe();
1160
1161 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1162
1163 controller.stop();
1164 window.close();
1165 });
1166
1109 test('clears cached stream assets for a finished playlist session', async () =>
1167 test('clears cached stream assets for a finished playlist session', async () =>
1110 {
1168 {
1111 const window = createWindow();
1169 const window = createWindow();