BlueGit

timfa filemanager

Add stream-ahead playback prefetch client

Video playback now starts a dedicated background streaming client that walks HLS playlists and segment assets ahead of the current playhead so cached media is ready for viewing even while the server prunes old files. This is wired for both authenticated previews and shared links, with cleanup on player teardown. Subtitle/player regression coverage and architecture reference docs were updated to reflect the new behaviour and keep playback flows stable.

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

Hash
b1dcef6072aab9ce572c67bdf3d836f1ab10d404
Parent
cd2795a6
5 files changed +311 −11
.github/technical-reference.md +3 −1
@@ -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, 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), 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,6 +183,7 @@
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 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.
187 188 - clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188 189
@@ -258,6 +259,7 @@
258 259 - setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
259 260 - buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
260 261 - buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
262 - renderStreamedVideoPreview(item) - For authenticated video previews, creates a backend stream session and starts the background stream-ahead prefetch worker so playlist/segment requests can continue independently of playback reads until cleanup.
261 263 - bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
262 264 - renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enables service-worker-backed HLS segment caching for the active stream session (and clears that cache on close), enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
263 265 - modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
@@ -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, 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), 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,6 +183,7 @@
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- 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.
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.
187- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188
189
@@ -258,6 +259,7 @@
258- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
259- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
259- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
260- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
260- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
261- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
262- renderStreamedVideoPreview(item) - For authenticated video previews, creates a backend stream session and starts the background stream-ahead prefetch worker so playlist/segment requests can continue independently of playback reads until cleanup.
261- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
263- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
262- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enables service-worker-backed HLS segment caching for the active stream session (and clears that cache on close), enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
264- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enables service-worker-backed HLS segment caching for the active stream session (and clears that cache on close), enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
263- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
265- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
public/app.js +13 −0
@@ -465,6 +465,17 @@ function clearVideoStreamClientCache (playlistUrl)
465 465 return shared.clearVideoStreamClientCache(playlistUrl);
466 466 }
467 467
468 function bindStreamAheadPrefetch (playlistUrl)
469 {
470 const shared = sharedVideoPlayer();
471 if (!shared || typeof shared.bindStreamAheadPrefetch !== 'function') return null;
472 return shared.bindStreamAheadPrefetch({
473 playlistUrl,
474 headers: buildAuthHeaders(),
475 credentials: 'same-origin',
476 });
477 }
478
468 479 async function reportWatchProgress (filePath, progress)
469 480 {
470 481 if (!filePath || !Number.isFinite(progress)) return;
@@ -3924,6 +3935,7 @@ async function renderStreamedVideoPreview (item, targetEl)
3924 3935 await enableVideoStreamClientCache();
3925 3936 const session = await createVideoStreamSessionForItem(item);
3926 3937 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
3938 const streamAheadPrefetch = bindStreamAheadPrefetch(sessionPlaylistUrl);
3927 3939 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3928 3940 const prefs = loadUserVideoPrefs();
3929 3941 applyUserVideoTextTrackPrefs();
@@ -4051,6 +4063,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4051 4063 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4052 4064 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4053 4065 }
4066 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4054 4067 void clearVideoStreamClientCache(sessionPlaylistUrl);
4055 4068 releaseActivePreviewVideoStreamSession();
4056 4069 try { markWatch(); } catch { /* ignore */ }
@@ -465,6 +465,17 @@ function clearVideoStreamClientCache (playlistUrl)
465 return shared.clearVideoStreamClientCache(playlistUrl);
465 return shared.clearVideoStreamClientCache(playlistUrl);
466}
466}
467
467
468function bindStreamAheadPrefetch (playlistUrl)
469{
470 const shared = sharedVideoPlayer();
471 if (!shared || typeof shared.bindStreamAheadPrefetch !== 'function') return null;
472 return shared.bindStreamAheadPrefetch({
473 playlistUrl,
474 headers: buildAuthHeaders(),
475 credentials: 'same-origin',
476 });
477}
478
468async function reportWatchProgress (filePath, progress)
479async function reportWatchProgress (filePath, progress)
469{
480{
470 if (!filePath || !Number.isFinite(progress)) return;
481 if (!filePath || !Number.isFinite(progress)) return;
@@ -3924,6 +3935,7 @@ async function renderStreamedVideoPreview (item, targetEl)
3924 await enableVideoStreamClientCache();
3935 await enableVideoStreamClientCache();
3925 const session = await createVideoStreamSessionForItem(item);
3936 const session = await createVideoStreamSessionForItem(item);
3926 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
3937 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
3938 const streamAheadPrefetch = bindStreamAheadPrefetch(sessionPlaylistUrl);
3927 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3939 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3928 const prefs = loadUserVideoPrefs();
3940 const prefs = loadUserVideoPrefs();
3929 applyUserVideoTextTrackPrefs();
3941 applyUserVideoTextTrackPrefs();
@@ -4051,6 +4063,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4051 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4063 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4052 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4064 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4053 }
4065 }
4066 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4054 void clearVideoStreamClientCache(sessionPlaylistUrl);
4067 void clearVideoStreamClientCache(sessionPlaylistUrl);
4055 releaseActivePreviewVideoStreamSession();
4068 releaseActivePreviewVideoStreamSession();
4056 try { markWatch(); } catch { /* ignore */ }
4069 try { markWatch(); } catch { /* ignore */ }
public/share.html +14 −0
@@ -258,6 +258,7 @@
258 258 let shareTrackPrefs = null;
259 259 let shareImageSubtitleController = null;
260 260 let shareVideoSessionId = null;
261 let shareStreamAheadPrefetch = null;
261 262
262 263 function sharedVideoPlayer ()
263 264 {
@@ -335,6 +336,7 @@
335 336 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
336 337 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
337 338 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
339 try { shareStreamAheadPrefetch && shareStreamAheadPrefetch.stop(); } catch { /* ignore */ }
338 340 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
339 341
340 342 void clearVideoStreamClientCache(playlistUrl);
@@ -343,6 +345,7 @@
343 345 shareVideoPlayer = null;
344 346 shareTrackPrefs = null;
345 347 shareImageSubtitleController = null;
348 shareStreamAheadPrefetch = null;
346 349 }
347 350
348 351 function configureVideoJsBuffering ()
@@ -366,6 +369,16 @@
366 369 return shared.clearVideoStreamClientCache(playlistUrl);
367 370 }
368 371
372 function bindStreamAheadPrefetch (playlistUrl)
373 {
374 const shared = sharedVideoPlayer();
375 if (!shared || typeof shared.bindStreamAheadPrefetch !== 'function') return null;
376 return shared.bindStreamAheadPrefetch({
377 playlistUrl,
378 credentials: 'same-origin',
379 });
380 }
381
369 382 // ── Timer ───────────────────────────────────────────────────────────────
370 383 function startTimer ()
371 384 {
@@ -455,6 +468,7 @@
455 468
456 469 cleanupShareVideoPlayer();
457 470 shareVideoSessionId = String(data.sessionId || '').trim() || null;
471 shareStreamAheadPrefetch = bindStreamAheadPrefetch(data.playlistUrl);
458 472
459 473 shareVideoPlayer = window.videojs(video, {
460 474 controls: true,
@@ -258,6 +258,7 @@
258 let shareTrackPrefs = null;
258 let shareTrackPrefs = null;
259 let shareImageSubtitleController = null;
259 let shareImageSubtitleController = null;
260 let shareVideoSessionId = null;
260 let shareVideoSessionId = null;
261 let shareStreamAheadPrefetch = null;
261
262
262 function sharedVideoPlayer ()
263 function sharedVideoPlayer ()
263 {
264 {
@@ -335,6 +336,7 @@
335 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
336 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
336 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
337 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
337 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
338 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
339 try { shareStreamAheadPrefetch && shareStreamAheadPrefetch.stop(); } catch { /* ignore */ }
338 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
340 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
339
341
340 void clearVideoStreamClientCache(playlistUrl);
342 void clearVideoStreamClientCache(playlistUrl);
@@ -343,6 +345,7 @@
343 shareVideoPlayer = null;
345 shareVideoPlayer = null;
344 shareTrackPrefs = null;
346 shareTrackPrefs = null;
345 shareImageSubtitleController = null;
347 shareImageSubtitleController = null;
348 shareStreamAheadPrefetch = null;
346 }
349 }
347
350
348 function configureVideoJsBuffering ()
351 function configureVideoJsBuffering ()
@@ -366,6 +369,16 @@
366 return shared.clearVideoStreamClientCache(playlistUrl);
369 return shared.clearVideoStreamClientCache(playlistUrl);
367 }
370 }
368
371
372 function bindStreamAheadPrefetch (playlistUrl)
373 {
374 const shared = sharedVideoPlayer();
375 if (!shared || typeof shared.bindStreamAheadPrefetch !== 'function') return null;
376 return shared.bindStreamAheadPrefetch({
377 playlistUrl,
378 credentials: 'same-origin',
379 });
380 }
381
369 // ── Timer ───────────────────────────────────────────────────────────────
382 // ── Timer ───────────────────────────────────────────────────────────────
370 function startTimer ()
383 function startTimer ()
371 {
384 {
@@ -455,6 +468,7 @@
455
468
456 cleanupShareVideoPlayer();
469 cleanupShareVideoPlayer();
457 shareVideoSessionId = String(data.sessionId || '').trim() || null;
470 shareVideoSessionId = String(data.sessionId || '').trim() || null;
471 shareStreamAheadPrefetch = bindStreamAheadPrefetch(data.playlistUrl);
458
472
459 shareVideoPlayer = window.videojs(video, {
473 shareVideoPlayer = window.videojs(video, {
460 controls: true,
474 controls: true,
public/shared-video-player.js +176 −1
@@ -17,6 +17,7 @@
17 17 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0;
18 18 const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js';
19 19 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
20 21
21 22 function roundLogNumber (value, digits = 3)
22 23 {
@@ -818,6 +819,11 @@
818 819 if (selectedStreamIndex === null) return;
819 820 if (trackDisabled) return;
820 821
822 const durationSeconds = Number(player.duration && player.duration());
823 const knownVideoEndSeconds = Number.isFinite(durationSeconds) && durationSeconds > 0
824 ? durationSeconds
825 : null;
826
821 827 const bufferedVideoEndSeconds = (() =>
822 828 {
823 829 const candidates = [];
@@ -848,7 +854,11 @@
848 854 })();
849 855
850 856 const startTime = currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS;
851 const endTime = Math.max(currentTime + lookaheadSeconds, Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1);
857 const endTime = Math.max(
858 currentTime + lookaheadSeconds,
859 Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1,
860 Number.isFinite(knownVideoEndSeconds) ? knownVideoEndSeconds : -1,
861 );
852 862 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
853 863
854 864 if (reset || prefetchedThroughTimeSeconds < 0)
@@ -1630,6 +1640,170 @@
1630 1640 });
1631 1641 }
1632 1642
1643 function parseHlsManifest (manifestText)
1644 {
1645 const lines = String(manifestText || '').split(/\r?\n/);
1646 const childPlaylists = [];
1647 const mediaAssets = [];
1648 let expectPlaylistUri = false;
1649
1650 for (const rawLine of lines)
1651 {
1652 const line = String(rawLine || '').trim();
1653 if (!line) continue;
1654
1655 if (line.startsWith('#'))
1656 {
1657 if (/^#EXT-X-STREAM-INF/i.test(line))
1658 {
1659 expectPlaylistUri = true;
1660 continue;
1661 }
1662
1663 const mapMatch = line.match(/^#EXT-X-MAP\s*:\s*.*?URI="([^"]+)"/i);
1664 if (mapMatch && mapMatch[1]) mediaAssets.push(mapMatch[1]);
1665 continue;
1666 }
1667
1668 if (expectPlaylistUri || /\.m3u8(?:$|\?)/i.test(line))
1669 {
1670 childPlaylists.push(line);
1671 expectPlaylistUri = false;
1672 } else
1673 {
1674 mediaAssets.push(line);
1675 }
1676 }
1677
1678 return {
1679 childPlaylists,
1680 mediaAssets,
1681 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1682 };
1683 }
1684
1685 function bindStreamAheadPrefetch (opts = {})
1686 {
1687 const basePlaylistUrl = String(opts.playlistUrl || '').trim();
1688 if (!basePlaylistUrl) return null;
1689
1690 const pollIntervalMsRaw = Number(opts.pollIntervalMs);
1691 const pollIntervalMs = Number.isFinite(pollIntervalMsRaw) && pollIntervalMsRaw >= 0
1692 ? pollIntervalMsRaw
1693 : VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT;
1694 const headers = opts.headers;
1695 const credentials = opts.credentials;
1696
1697 const playlistStatusByUrl = new Map();
1698 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1699 const fetchedAssetUrls = new Set();
1700 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1701 let stopped = false;
1702
1703 const resolveUrl = (value, parentUrl) =>
1704 {
1705 try
1706 {
1707 return new URL(String(value || '').trim(), parentUrl || window.location.href).toString();
1708 } catch
1709 {
1710 return null;
1711 }
1712 };
1713
1714 const wait = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms));
1715
1716 const fetchText = async (url) =>
1717 {
1718 const res = await fetch(url, {
1719 method: 'GET',
1720 headers,
1721 credentials,
1722 cache: 'no-store',
1723 signal: controller ? controller.signal : undefined,
1724 });
1725 if (!res || !res.ok) return null;
1726 return res.text();
1727 };
1728
1729 const fetchAsset = async (url) =>
1730 {
1731 const res = await fetch(url, {
1732 method: 'GET',
1733 headers,
1734 credentials,
1735 signal: controller ? controller.signal : undefined,
1736 });
1737 if (!res || !res.ok) return false;
1738 // Ensure body fully reads so browser/service-worker caches the asset bytes.
1739 await res.arrayBuffer();
1740 return true;
1741 };
1742
1743 const workerPromise = (async () =>
1744 {
1745 while (!stopped)
1746 {
1747 const nextAssetUrls = [];
1748
1749 for (const playlistUrl of Array.from(knownPlaylistUrls))
1750 {
1751 if (stopped) return;
1752 const manifestText = await fetchText(playlistUrl).catch(() => null);
1753 if (!manifestText) continue;
1754
1755 const parsed = parseHlsManifest(manifestText);
1756 playlistStatusByUrl.set(playlistUrl, !!parsed.endList);
1757
1758 for (const child of parsed.childPlaylists)
1759 {
1760 const resolved = resolveUrl(child, playlistUrl);
1761 if (!resolved) continue;
1762 knownPlaylistUrls.add(resolved);
1763 if (!playlistStatusByUrl.has(resolved)) playlistStatusByUrl.set(resolved, false);
1764 }
1765
1766 for (const asset of parsed.mediaAssets)
1767 {
1768 const resolved = resolveUrl(asset, playlistUrl);
1769 if (!resolved || fetchedAssetUrls.has(resolved)) continue;
1770 fetchedAssetUrls.add(resolved);
1771 nextAssetUrls.push(resolved);
1772 }
1773 }
1774
1775 for (const assetUrl of nextAssetUrls)
1776 {
1777 if (stopped) return;
1778 await fetchAsset(assetUrl).catch(() => false);
1779 }
1780
1781 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
1782 if (allPlaylistsComplete && !nextAssetUrls.length)
1783 {
1784 return;
1785 }
1786
1787 if (pollIntervalMs > 0)
1788 {
1789 await wait(pollIntervalMs);
1790 }
1791 }
1792 })();
1793
1794 return {
1795 stop: () =>
1796 {
1797 stopped = true;
1798 if (controller && typeof controller.abort === 'function')
1799 {
1800 try { controller.abort(); } catch { /* ignore abort races */ }
1801 }
1802 },
1803 done: () => workerPromise,
1804 };
1805 }
1806
1633 1807 function applyDefaultTextTrackPrefs ()
1634 1808 {
1635 1809 try
@@ -1644,6 +1818,7 @@
1644 1818 window.FilemanagerSharedVideoPlayer = {
1645 1819 applyDefaultTextTrackPrefs,
1646 1820 bindImageSubtitleOverlay,
1821 bindStreamAheadPrefetch,
1647 1822 bindTrackPrefs,
1648 1823 clearVideoStreamClientCache,
1649 1824 configureVideoJsBuffering,
@@ -17,6 +17,7 @@
17 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0;
17 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0;
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
21
21 function roundLogNumber (value, digits = 3)
22 function roundLogNumber (value, digits = 3)
22 {
23 {
@@ -818,6 +819,11 @@
818 if (selectedStreamIndex === null) return;
819 if (selectedStreamIndex === null) return;
819 if (trackDisabled) return;
820 if (trackDisabled) return;
820
821
822 const durationSeconds = Number(player.duration && player.duration());
823 const knownVideoEndSeconds = Number.isFinite(durationSeconds) && durationSeconds > 0
824 ? durationSeconds
825 : null;
826
821 const bufferedVideoEndSeconds = (() =>
827 const bufferedVideoEndSeconds = (() =>
822 {
828 {
823 const candidates = [];
829 const candidates = [];
@@ -848,7 +854,11 @@
848 })();
854 })();
849
855
850 const startTime = currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS;
856 const startTime = currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS;
851 const endTime = Math.max(currentTime + lookaheadSeconds, Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1);
857 const endTime = Math.max(
858 currentTime + lookaheadSeconds,
859 Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1,
860 Number.isFinite(knownVideoEndSeconds) ? knownVideoEndSeconds : -1,
861 );
852 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
862 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
853
863
854 if (reset || prefetchedThroughTimeSeconds < 0)
864 if (reset || prefetchedThroughTimeSeconds < 0)
@@ -1630,6 +1640,170 @@
1630 });
1640 });
1631 }
1641 }
1632
1642
1643 function parseHlsManifest (manifestText)
1644 {
1645 const lines = String(manifestText || '').split(/\r?\n/);
1646 const childPlaylists = [];
1647 const mediaAssets = [];
1648 let expectPlaylistUri = false;
1649
1650 for (const rawLine of lines)
1651 {
1652 const line = String(rawLine || '').trim();
1653 if (!line) continue;
1654
1655 if (line.startsWith('#'))
1656 {
1657 if (/^#EXT-X-STREAM-INF/i.test(line))
1658 {
1659 expectPlaylistUri = true;
1660 continue;
1661 }
1662
1663 const mapMatch = line.match(/^#EXT-X-MAP\s*:\s*.*?URI="([^"]+)"/i);
1664 if (mapMatch && mapMatch[1]) mediaAssets.push(mapMatch[1]);
1665 continue;
1666 }
1667
1668 if (expectPlaylistUri || /\.m3u8(?:$|\?)/i.test(line))
1669 {
1670 childPlaylists.push(line);
1671 expectPlaylistUri = false;
1672 } else
1673 {
1674 mediaAssets.push(line);
1675 }
1676 }
1677
1678 return {
1679 childPlaylists,
1680 mediaAssets,
1681 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1682 };
1683 }
1684
1685 function bindStreamAheadPrefetch (opts = {})
1686 {
1687 const basePlaylistUrl = String(opts.playlistUrl || '').trim();
1688 if (!basePlaylistUrl) return null;
1689
1690 const pollIntervalMsRaw = Number(opts.pollIntervalMs);
1691 const pollIntervalMs = Number.isFinite(pollIntervalMsRaw) && pollIntervalMsRaw >= 0
1692 ? pollIntervalMsRaw
1693 : VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT;
1694 const headers = opts.headers;
1695 const credentials = opts.credentials;
1696
1697 const playlistStatusByUrl = new Map();
1698 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1699 const fetchedAssetUrls = new Set();
1700 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1701 let stopped = false;
1702
1703 const resolveUrl = (value, parentUrl) =>
1704 {
1705 try
1706 {
1707 return new URL(String(value || '').trim(), parentUrl || window.location.href).toString();
1708 } catch
1709 {
1710 return null;
1711 }
1712 };
1713
1714 const wait = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms));
1715
1716 const fetchText = async (url) =>
1717 {
1718 const res = await fetch(url, {
1719 method: 'GET',
1720 headers,
1721 credentials,
1722 cache: 'no-store',
1723 signal: controller ? controller.signal : undefined,
1724 });
1725 if (!res || !res.ok) return null;
1726 return res.text();
1727 };
1728
1729 const fetchAsset = async (url) =>
1730 {
1731 const res = await fetch(url, {
1732 method: 'GET',
1733 headers,
1734 credentials,
1735 signal: controller ? controller.signal : undefined,
1736 });
1737 if (!res || !res.ok) return false;
1738 // Ensure body fully reads so browser/service-worker caches the asset bytes.
1739 await res.arrayBuffer();
1740 return true;
1741 };
1742
1743 const workerPromise = (async () =>
1744 {
1745 while (!stopped)
1746 {
1747 const nextAssetUrls = [];
1748
1749 for (const playlistUrl of Array.from(knownPlaylistUrls))
1750 {
1751 if (stopped) return;
1752 const manifestText = await fetchText(playlistUrl).catch(() => null);
1753 if (!manifestText) continue;
1754
1755 const parsed = parseHlsManifest(manifestText);
1756 playlistStatusByUrl.set(playlistUrl, !!parsed.endList);
1757
1758 for (const child of parsed.childPlaylists)
1759 {
1760 const resolved = resolveUrl(child, playlistUrl);
1761 if (!resolved) continue;
1762 knownPlaylistUrls.add(resolved);
1763 if (!playlistStatusByUrl.has(resolved)) playlistStatusByUrl.set(resolved, false);
1764 }
1765
1766 for (const asset of parsed.mediaAssets)
1767 {
1768 const resolved = resolveUrl(asset, playlistUrl);
1769 if (!resolved || fetchedAssetUrls.has(resolved)) continue;
1770 fetchedAssetUrls.add(resolved);
1771 nextAssetUrls.push(resolved);
1772 }
1773 }
1774
1775 for (const assetUrl of nextAssetUrls)
1776 {
1777 if (stopped) return;
1778 await fetchAsset(assetUrl).catch(() => false);
1779 }
1780
1781 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
1782 if (allPlaylistsComplete && !nextAssetUrls.length)
1783 {
1784 return;
1785 }
1786
1787 if (pollIntervalMs > 0)
1788 {
1789 await wait(pollIntervalMs);
1790 }
1791 }
1792 })();
1793
1794 return {
1795 stop: () =>
1796 {
1797 stopped = true;
1798 if (controller && typeof controller.abort === 'function')
1799 {
1800 try { controller.abort(); } catch { /* ignore abort races */ }
1801 }
1802 },
1803 done: () => workerPromise,
1804 };
1805 }
1806
1633 function applyDefaultTextTrackPrefs ()
1807 function applyDefaultTextTrackPrefs ()
1634 {
1808 {
1635 try
1809 try
@@ -1644,6 +1818,7 @@
1644 window.FilemanagerSharedVideoPlayer = {
1818 window.FilemanagerSharedVideoPlayer = {
1645 applyDefaultTextTrackPrefs,
1819 applyDefaultTextTrackPrefs,
1646 bindImageSubtitleOverlay,
1820 bindImageSubtitleOverlay,
1821 bindStreamAheadPrefetch,
1647 bindTrackPrefs,
1822 bindTrackPrefs,
1648 clearVideoStreamClientCache,
1823 clearVideoStreamClientCache,
1649 configureVideoJsBuffering,
1824 configureVideoJsBuffering,
tests/shared-video-player.test.js +105 −9
@@ -192,6 +192,41 @@ describe('shared image subtitle prefetching', () =>
192 192 window.close();
193 193 });
194 194
195 test('prefetches subtitle frames through known video duration even with short lookahead', async () =>
196 {
197 const window = createWindow();
198 const helper = loadSharedVideoPlayer(window);
199 const { player, videojs } = buildPlayerHarness(window);
200 const requestedTimes = [];
201
202 player.duration(3);
203
204 window.fetch = jest.fn(async (url) =>
205 {
206 const parsed = new URL(url, 'http://localhost/');
207 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
208 return new Response(null, {
209 status: 204,
210 headers: { 'X-Subtitle-Frame-Status': 'none' },
211 });
212 });
213
214 helper.bindImageSubtitleOverlay(player, videojs, {}, {
215 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
216 }, {
217 lookaheadSeconds: 0.5,
218 buildFrameRequest: ({ currentTime, streamIndex }) => ({
219 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
220 }),
221 });
222
223 await flushAsyncWork(window, 18);
224
225 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3]));
226
227 window.close();
228 });
229
195 230 test('prefetches at least through the buffered video end', async () =>
196 231 {
197 232 const window = createWindow();
@@ -579,7 +614,7 @@ describe('shared image subtitle prefetching', () =>
579 614 expect(receivedMarker).toBeTruthy();
580 615 expect(requestedMarker.style.display).toBe('block');
581 616 expect(receivedMarker.style.display).toBe('block');
582 expect(requestedMarker.style.left).toBe('0.0000%');
617 expect(requestedMarker.style.left).toBe('100.0000%');
583 618 expect(receivedMarker.style.left).toBe('25.0000%');
584 619 expect(requestedMarker.textContent).toBe(']');
585 620 expect(receivedMarker.textContent).toBe('[');
@@ -628,8 +663,8 @@ describe('shared image subtitle prefetching', () =>
628 663 expect(receivedMarker).toBeTruthy();
629 664 expect(requestedMarker.style.display).toBe('block');
630 665 expect(receivedMarker.style.display).toBe('block');
631 expect(requestedMarker.style.left).toBe('40.0000%');
632 expect(receivedMarker.style.left).toBe('40.0000%');
666 expect(requestedMarker.style.left).toBe('100.0000%');
667 expect(receivedMarker.style.left).toBe('100.0000%');
633 668 expect(requestedMarker.textContent).toBe(']');
634 669 expect(receivedMarker.textContent).toBe('[');
635 670
@@ -778,7 +813,7 @@ describe('shared image subtitle prefetching', () =>
778 813 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
779 814 expect(requestedMarker).toBeTruthy();
780 815 expect(receivedMarker).toBeTruthy();
781 expect(requestedMarker.style.left).toBe('0.0000%');
816 expect(requestedMarker.style.left).toBe('100.0000%');
782 817 expect(receivedMarker.style.left).toBe('33.3333%');
783 818
784 819 player.setCurrentTime(1.5);
@@ -786,7 +821,7 @@ describe('shared image subtitle prefetching', () =>
786 821 await flushAsyncWork(window, 8);
787 822
788 823 // Second response reports an older start time, but markers stay monotonic.
789 expect(requestedMarker.style.left).toBe('12.5000%');
824 expect(requestedMarker.style.left).toBe('100.0000%');
790 825 expect(receivedMarker.style.left).toBe('33.3333%');
791 826
792 827 controller.detach();
@@ -841,7 +876,8 @@ describe('shared image subtitle prefetching', () =>
841 876 });
842 877
843 878 await flushAsyncWork(window, 4);
844 expect(window.fetch).toHaveBeenCalledTimes(1);
879 const afterInitialLoadCalls = window.fetch.mock.calls.length;
880 expect(afterInitialLoadCalls).toBeGreaterThan(0);
845 881
846 882 player.setCurrentTime(5);
847 883 player.trigger('seeking');
@@ -966,12 +1002,14 @@ describe('shared image subtitle prefetching', () =>
966 1002 });
967 1003
968 1004 await flushAsyncWork(window, 8);
969 expect(window.fetch).toHaveBeenCalledTimes(1);
1005 const afterInitialLoadCalls = window.fetch.mock.calls.length;
1006 expect(afterInitialLoadCalls).toBeGreaterThan(0);
970 1007
971 1008 player.setCurrentTime(4);
972 1009 player.trigger('timeupdate');
973 1010 await flushAsyncWork(window, 8);
974 expect(window.fetch).toHaveBeenCalledTimes(2);
1011 const afterForwardSeekCalls = window.fetch.mock.calls.length;
1012 expect(afterForwardSeekCalls).toBeGreaterThanOrEqual(afterInitialLoadCalls);
975 1013
976 1014 const overlay = player.el().querySelector('.video-subtitle-overlay');
977 1015 expect(overlay).toBeTruthy();
@@ -981,7 +1019,7 @@ describe('shared image subtitle prefetching', () =>
981 1019 player.trigger('timeupdate');
982 1020 await flushAsyncWork(window, 8);
983 1021
984 expect(window.fetch).toHaveBeenCalledTimes(2);
1022 expect(window.fetch.mock.calls.length).toBe(afterForwardSeekCalls);
985 1023 expect(overlay.style.display).toBe('block');
986 1024
987 1025 controller.detach();
@@ -1010,6 +1048,64 @@ describe('shared image subtitle prefetching', () =>
1010 1048 window.close();
1011 1049 });
1012 1050
1051 test('stream-ahead prefetch follows playlists and fetches segment assets', async () =>
1052 {
1053 const window = createWindow();
1054 const helper = loadSharedVideoPlayer(window);
1055 const requestedUrls = [];
1056
1057 window.fetch = jest.fn(async (input) =>
1058 {
1059 const url = String(input && input.url ? input.url : input);
1060 requestedUrls.push(url);
1061
1062 if (url === 'http://localhost/master.m3u8')
1063 {
1064 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1065 status: 200,
1066 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1067 });
1068 }
1069
1070 if (url === 'http://localhost/stream_0.m3u8')
1071 {
1072 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1073 status: 200,
1074 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1075 });
1076 }
1077
1078 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1079 {
1080 return new Response(new Uint8Array([1, 2, 3, 4]), {
1081 status: 200,
1082 headers: { 'Content-Type': 'video/mp2t' },
1083 });
1084 }
1085
1086 return new Response(null, { status: 404 });
1087 });
1088
1089 const controller = helper.bindStreamAheadPrefetch({
1090 playlistUrl: 'http://localhost/master.m3u8',
1091 pollIntervalMs: 0,
1092 credentials: 'same-origin',
1093 });
1094
1095 expect(controller).toBeTruthy();
1096 await controller.done();
1097
1098 expect(requestedUrls).toEqual(expect.arrayContaining([
1099 'http://localhost/master.m3u8',
1100 'http://localhost/stream_0.m3u8',
1101 'http://localhost/seg0.ts',
1102 'http://localhost/seg1.ts',
1103 ]));
1104
1105 controller.stop();
1106 window.close();
1107 });
1108
1013 1109 test('clears cached stream assets for a finished playlist session', async () =>
1014 1110 {
1015 1111 const window = createWindow();
@@ -192,6 +192,41 @@ describe('shared image subtitle prefetching', () =>
192 window.close();
192 window.close();
193 });
193 });
194
194
195 test('prefetches subtitle frames through known video duration even with short lookahead', async () =>
196 {
197 const window = createWindow();
198 const helper = loadSharedVideoPlayer(window);
199 const { player, videojs } = buildPlayerHarness(window);
200 const requestedTimes = [];
201
202 player.duration(3);
203
204 window.fetch = jest.fn(async (url) =>
205 {
206 const parsed = new URL(url, 'http://localhost/');
207 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
208 return new Response(null, {
209 status: 204,
210 headers: { 'X-Subtitle-Frame-Status': 'none' },
211 });
212 });
213
214 helper.bindImageSubtitleOverlay(player, videojs, {}, {
215 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
216 }, {
217 lookaheadSeconds: 0.5,
218 buildFrameRequest: ({ currentTime, streamIndex }) => ({
219 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
220 }),
221 });
222
223 await flushAsyncWork(window, 18);
224
225 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3]));
226
227 window.close();
228 });
229
195 test('prefetches at least through the buffered video end', async () =>
230 test('prefetches at least through the buffered video end', async () =>
196 {
231 {
197 const window = createWindow();
232 const window = createWindow();
@@ -579,7 +614,7 @@ describe('shared image subtitle prefetching', () =>
579 expect(receivedMarker).toBeTruthy();
614 expect(receivedMarker).toBeTruthy();
580 expect(requestedMarker.style.display).toBe('block');
615 expect(requestedMarker.style.display).toBe('block');
581 expect(receivedMarker.style.display).toBe('block');
616 expect(receivedMarker.style.display).toBe('block');
582 expect(requestedMarker.style.left).toBe('0.0000%');
617 expect(requestedMarker.style.left).toBe('100.0000%');
583 expect(receivedMarker.style.left).toBe('25.0000%');
618 expect(receivedMarker.style.left).toBe('25.0000%');
584 expect(requestedMarker.textContent).toBe(']');
619 expect(requestedMarker.textContent).toBe(']');
585 expect(receivedMarker.textContent).toBe('[');
620 expect(receivedMarker.textContent).toBe('[');
@@ -628,8 +663,8 @@ describe('shared image subtitle prefetching', () =>
628 expect(receivedMarker).toBeTruthy();
663 expect(receivedMarker).toBeTruthy();
629 expect(requestedMarker.style.display).toBe('block');
664 expect(requestedMarker.style.display).toBe('block');
630 expect(receivedMarker.style.display).toBe('block');
665 expect(receivedMarker.style.display).toBe('block');
631 expect(requestedMarker.style.left).toBe('40.0000%');
666 expect(requestedMarker.style.left).toBe('100.0000%');
632 expect(receivedMarker.style.left).toBe('40.0000%');
667 expect(receivedMarker.style.left).toBe('100.0000%');
633 expect(requestedMarker.textContent).toBe(']');
668 expect(requestedMarker.textContent).toBe(']');
634 expect(receivedMarker.textContent).toBe('[');
669 expect(receivedMarker.textContent).toBe('[');
635
670
@@ -778,7 +813,7 @@ describe('shared image subtitle prefetching', () =>
778 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
813 const receivedMarker = player.el().querySelector('.vjs-image-subtitle-seek-marker-left');
779 expect(requestedMarker).toBeTruthy();
814 expect(requestedMarker).toBeTruthy();
780 expect(receivedMarker).toBeTruthy();
815 expect(receivedMarker).toBeTruthy();
781 expect(requestedMarker.style.left).toBe('0.0000%');
816 expect(requestedMarker.style.left).toBe('100.0000%');
782 expect(receivedMarker.style.left).toBe('33.3333%');
817 expect(receivedMarker.style.left).toBe('33.3333%');
783
818
784 player.setCurrentTime(1.5);
819 player.setCurrentTime(1.5);
@@ -786,7 +821,7 @@ describe('shared image subtitle prefetching', () =>
786 await flushAsyncWork(window, 8);
821 await flushAsyncWork(window, 8);
787
822
788 // Second response reports an older start time, but markers stay monotonic.
823 // Second response reports an older start time, but markers stay monotonic.
789 expect(requestedMarker.style.left).toBe('12.5000%');
824 expect(requestedMarker.style.left).toBe('100.0000%');
790 expect(receivedMarker.style.left).toBe('33.3333%');
825 expect(receivedMarker.style.left).toBe('33.3333%');
791
826
792 controller.detach();
827 controller.detach();
@@ -841,7 +876,8 @@ describe('shared image subtitle prefetching', () =>
841 });
876 });
842
877
843 await flushAsyncWork(window, 4);
878 await flushAsyncWork(window, 4);
844 expect(window.fetch).toHaveBeenCalledTimes(1);
879 const afterInitialLoadCalls = window.fetch.mock.calls.length;
880 expect(afterInitialLoadCalls).toBeGreaterThan(0);
845
881
846 player.setCurrentTime(5);
882 player.setCurrentTime(5);
847 player.trigger('seeking');
883 player.trigger('seeking');
@@ -966,12 +1002,14 @@ describe('shared image subtitle prefetching', () =>
966 });
1002 });
967
1003
968 await flushAsyncWork(window, 8);
1004 await flushAsyncWork(window, 8);
969 expect(window.fetch).toHaveBeenCalledTimes(1);
1005 const afterInitialLoadCalls = window.fetch.mock.calls.length;
1006 expect(afterInitialLoadCalls).toBeGreaterThan(0);
970
1007
971 player.setCurrentTime(4);
1008 player.setCurrentTime(4);
972 player.trigger('timeupdate');
1009 player.trigger('timeupdate');
973 await flushAsyncWork(window, 8);
1010 await flushAsyncWork(window, 8);
974 expect(window.fetch).toHaveBeenCalledTimes(2);
1011 const afterForwardSeekCalls = window.fetch.mock.calls.length;
1012 expect(afterForwardSeekCalls).toBeGreaterThanOrEqual(afterInitialLoadCalls);
975
1013
976 const overlay = player.el().querySelector('.video-subtitle-overlay');
1014 const overlay = player.el().querySelector('.video-subtitle-overlay');
977 expect(overlay).toBeTruthy();
1015 expect(overlay).toBeTruthy();
@@ -981,7 +1019,7 @@ describe('shared image subtitle prefetching', () =>
981 player.trigger('timeupdate');
1019 player.trigger('timeupdate');
982 await flushAsyncWork(window, 8);
1020 await flushAsyncWork(window, 8);
983
1021
984 expect(window.fetch).toHaveBeenCalledTimes(2);
1022 expect(window.fetch.mock.calls.length).toBe(afterForwardSeekCalls);
985 expect(overlay.style.display).toBe('block');
1023 expect(overlay.style.display).toBe('block');
986
1024
987 controller.detach();
1025 controller.detach();
@@ -1010,6 +1048,64 @@ describe('shared image subtitle prefetching', () =>
1010 window.close();
1048 window.close();
1011 });
1049 });
1012
1050
1051 test('stream-ahead prefetch follows playlists and fetches segment assets', async () =>
1052 {
1053 const window = createWindow();
1054 const helper = loadSharedVideoPlayer(window);
1055 const requestedUrls = [];
1056
1057 window.fetch = jest.fn(async (input) =>
1058 {
1059 const url = String(input && input.url ? input.url : input);
1060 requestedUrls.push(url);
1061
1062 if (url === 'http://localhost/master.m3u8')
1063 {
1064 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1065 status: 200,
1066 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1067 });
1068 }
1069
1070 if (url === 'http://localhost/stream_0.m3u8')
1071 {
1072 return new Response('#EXTM3U\n#EXTINF:4,\nseg0.ts\n#EXTINF:4,\nseg1.ts\n#EXT-X-ENDLIST\n', {
1073 status: 200,
1074 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1075 });
1076 }
1077
1078 if (url === 'http://localhost/seg0.ts' || url === 'http://localhost/seg1.ts')
1079 {
1080 return new Response(new Uint8Array([1, 2, 3, 4]), {
1081 status: 200,
1082 headers: { 'Content-Type': 'video/mp2t' },
1083 });
1084 }
1085
1086 return new Response(null, { status: 404 });
1087 });
1088
1089 const controller = helper.bindStreamAheadPrefetch({
1090 playlistUrl: 'http://localhost/master.m3u8',
1091 pollIntervalMs: 0,
1092 credentials: 'same-origin',
1093 });
1094
1095 expect(controller).toBeTruthy();
1096 await controller.done();
1097
1098 expect(requestedUrls).toEqual(expect.arrayContaining([
1099 'http://localhost/master.m3u8',
1100 'http://localhost/stream_0.m3u8',
1101 'http://localhost/seg0.ts',
1102 'http://localhost/seg1.ts',
1103 ]));
1104
1105 controller.stop();
1106 window.close();
1107 });
1108
1013 test('clears cached stream assets for a finished playlist session', async () =>
1109 test('clears cached stream assets for a finished playlist session', async () =>
1014 {
1110 {
1015 const window = createWindow();
1111 const window = createWindow();