BlueGit

timfa filemanager

Warm first-minute image subtitles on load

Image subtitle warmup now starts immediately when a subtitle track is selected, prefetching an initial timeline window before playback advances. This reduces missing caption frames at the beginning of playback for longer videos and avoids needing to pause or rewind to catch early lines.\n\nThe app and share player both use a 60-second startup warmup while keeping cache-only foreground subtitle rendering and background walker ownership of subtitle network requests.

timfa Tim Falken · pushed by timfa

Authored 2026-05-27 · 5 months ago

Hash
c88ad7de12b5fb2f4b3f57ad171dc70207e637d8
Parent
e29c4a14
5 files changed +79 −5
.github/technical-reference.md +1 −1
@@ -185,7 +185,7 @@
185 185 ## public/shared-video-player.js
186 186 - 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.
187 187 - 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.
188 - 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), supports cache-only foreground playback with `currentFetchEnabled: false` (foreground uses cached frames while walker owns server fetches), 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.
188 - 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), supports cache-only foreground playback with `currentFetchEnabled: false` (foreground uses cached frames while walker owns server fetches), supports startup warmup with `initialPrefetchSeconds` (default 60s) so early timeline subtitle frames are requested immediately on player load before playback advances, 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.
189 189 - 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 (primary from playlist segment durations, with filename-based segment-index fallback for `.ts/.m4s` naming and a section-ratio fallback from fetched segments/total discovered segments when absolute timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
190 190 - 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, updates tooltip text with formatted cached-through time, and removes itself on detach.
191 191 - 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.
@@ -185,7 +185,7 @@
185## public/shared-video-player.js
185## public/shared-video-player.js
186- 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.
186- 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.
187- 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.
187- 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.
188- 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), supports cache-only foreground playback with `currentFetchEnabled: false` (foreground uses cached frames while walker owns server fetches), 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.
188- 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), supports cache-only foreground playback with `currentFetchEnabled: false` (foreground uses cached frames while walker owns server fetches), supports startup warmup with `initialPrefetchSeconds` (default 60s) so early timeline subtitle frames are requested immediately on player load before playback advances, 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.
189- 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 (primary from playlist segment durations, with filename-based segment-index fallback for `.ts/.m4s` naming and a section-ratio fallback from fetched segments/total discovered segments when absolute timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
189- 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 (primary from playlist segment durations, with filename-based segment-index fallback for `.ts/.m4s` naming and a section-ratio fallback from fetched segments/total discovered segments when absolute timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
190- 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, updates tooltip text with formatted cached-through time, and removes itself on detach.
190- 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, updates tooltip text with formatted cached-through time, and removes itself on detach.
191- 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.
191- 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.
public/app.js +2 −0
@@ -113,6 +113,7 @@ const FOLDER_GROUP_OPTIONS = [
113 113 const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
114 114 const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
115 115 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
116 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS = 60;
116 117 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
117 118 let videoJsLoaderPromise = null;
118 119 let threePreviewModulesPromise = null;
@@ -431,6 +432,7 @@ function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
431 432 savePrefs: saveUserVideoPrefs,
432 433 currentFetchEnabled: false,
433 434 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
435 initialPrefetchSeconds: IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS,
434 436 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
435 437 sendSubtitleLogBatch,
436 438 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
@@ -113,6 +113,7 @@ const FOLDER_GROUP_OPTIONS = [
113const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
113const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
114const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
114const VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED = false;
115const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
115const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
116const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS = 60;
116const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
117const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
117let videoJsLoaderPromise = null;
118let videoJsLoaderPromise = null;
118let threePreviewModulesPromise = null;
119let threePreviewModulesPromise = null;
@@ -431,6 +432,7 @@ function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
431 savePrefs: saveUserVideoPrefs,
432 savePrefs: saveUserVideoPrefs,
432 currentFetchEnabled: false,
433 currentFetchEnabled: false,
433 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
434 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
435 initialPrefetchSeconds: IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS,
434 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
436 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
435 sendSubtitleLogBatch,
437 sendSubtitleLogBatch,
436 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
438 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
public/share.html +2 −0
@@ -250,6 +250,7 @@
250 250 const token = location.pathname.split('/').pop();
251 251 const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
252 252 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
253 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS = 60;
253 254 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
254 255 const SHARE_VIDEO_PREFS_KEY = 'filemanager.share-video-prefs.v1';
255 256 let expiresAt = null;
@@ -508,6 +509,7 @@
508 509 savePrefs: saveShareVideoPrefs,
509 510 currentFetchEnabled: false,
510 511 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
512 initialPrefetchSeconds: IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS,
511 513 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
512 514 sendSubtitleLogBatch: (entries) =>
513 515 {
@@ -250,6 +250,7 @@
250 const token = location.pathname.split('/').pop();
250 const token = location.pathname.split('/').pop();
251 const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
251 const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
252 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
252 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
253 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS = 60;
253 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
254 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
254 const SHARE_VIDEO_PREFS_KEY = 'filemanager.share-video-prefs.v1';
255 const SHARE_VIDEO_PREFS_KEY = 'filemanager.share-video-prefs.v1';
255 let expiresAt = null;
256 let expiresAt = null;
@@ -508,6 +509,7 @@
508 savePrefs: saveShareVideoPrefs,
509 savePrefs: saveShareVideoPrefs,
509 currentFetchEnabled: false,
510 currentFetchEnabled: false,
510 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
511 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
512 initialPrefetchSeconds: IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS,
511 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
513 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
512 sendSubtitleLogBatch: (entries) =>
514 sendSubtitleLogBatch: (entries) =>
513 {
515 {
public/shared-video-player.js +30 −4
@@ -11,6 +11,8 @@
11 11 const SUBTITLE_LOG_FLUSH_DELAY_MS = 500;
12 12 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15;
13 13 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30;
14 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_DEFAULT = 60;
15 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_MAX = 120;
14 16 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS = 0.5;
15 17 const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
16 18 const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
@@ -289,6 +291,10 @@
289 291 const currentRequestTimeoutMs = Number.isFinite(requestedCurrentRequestTimeoutMs)
290 292 ? Math.max(250, requestedCurrentRequestTimeoutMs)
291 293 : IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT;
294 const requestedInitialPrefetchSeconds = Number(opts.initialPrefetchSeconds);
295 const initialPrefetchSeconds = Number.isFinite(requestedInitialPrefetchSeconds)
296 ? Math.max(0, Math.min(IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_MAX, requestedInitialPrefetchSeconds))
297 : IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_DEFAULT;
292 298 const requestedPrefetchRequestTimeoutMs = Number(opts.prefetchRequestTimeoutMs);
293 299 const prefetchRequestTimeoutMs = Number.isFinite(requestedPrefetchRequestTimeoutMs)
294 300 ? Math.max(250, requestedPrefetchRequestTimeoutMs)
@@ -829,11 +835,23 @@
829 835
830 836 if (selectedStreamIndex !== null)
831 837 {
832 void refreshFrame(true);
838 if (initialPrefetchSeconds > 0)
839 {
840 queueLookaheadPrefetch(0, {
841 reset: true,
842 includeCurrentTime: true,
843 maxTargetTimeSeconds: initialPrefetchSeconds,
844 });
845 }
846 void refreshFrame();
833 847 }
834 848 };
835 849
836 const queueLookaheadPrefetch = (currentTime, { reset = false, includeCurrentTime = false } = {}) =>
850 const queueLookaheadPrefetch = (currentTime, {
851 reset = false,
852 includeCurrentTime = false,
853 maxTargetTimeSeconds = null,
854 } = {}) =>
837 855 {
838 856 if (selectedStreamIndex === null) return;
839 857 if (trackDisabled) return;
@@ -875,17 +893,25 @@
875 893 const startTime = includeCurrentTime
876 894 ? currentTime
877 895 : currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS;
878 const endTime = Math.max(
896 const uncappedEndTime = Math.max(
879 897 currentTime + lookaheadSeconds,
880 898 Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1,
881 899 Number.isFinite(knownVideoEndSeconds) ? knownVideoEndSeconds : -1,
882 900 );
901 const capEndTime = Number.isFinite(maxTargetTimeSeconds) && maxTargetTimeSeconds >= 0
902 ? maxTargetTimeSeconds
903 : null;
904 const endTime = Number.isFinite(capEndTime)
905 ? Math.min(uncappedEndTime, capEndTime)
906 : uncappedEndTime;
883 907 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
884 908
885 909 if (reset || prefetchedThroughTimeSeconds < 0)
886 910 {
887 911 cancelPrefetchRequests({ resetProgress: true });
888 prefetchedThroughTimeSeconds = currentTime;
912 prefetchedThroughTimeSeconds = includeCurrentTime
913 ? currentTime - IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS
914 : currentTime;
889 915 } else if (prefetchedThroughTimeSeconds < currentTime)
890 916 {
891 917 // Keep the prefetch frontier at or ahead of current playback so
@@ -11,6 +11,8 @@
11 const SUBTITLE_LOG_FLUSH_DELAY_MS = 500;
11 const SUBTITLE_LOG_FLUSH_DELAY_MS = 500;
12 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15;
12 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15;
13 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30;
13 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30;
14 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_DEFAULT = 60;
15 const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_MAX = 120;
14 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS = 0.5;
16 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS = 0.5;
15 const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
17 const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
16 const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
18 const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
@@ -289,6 +291,10 @@
289 const currentRequestTimeoutMs = Number.isFinite(requestedCurrentRequestTimeoutMs)
291 const currentRequestTimeoutMs = Number.isFinite(requestedCurrentRequestTimeoutMs)
290 ? Math.max(250, requestedCurrentRequestTimeoutMs)
292 ? Math.max(250, requestedCurrentRequestTimeoutMs)
291 : IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT;
293 : IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT;
294 const requestedInitialPrefetchSeconds = Number(opts.initialPrefetchSeconds);
295 const initialPrefetchSeconds = Number.isFinite(requestedInitialPrefetchSeconds)
296 ? Math.max(0, Math.min(IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_MAX, requestedInitialPrefetchSeconds))
297 : IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_DEFAULT;
292 const requestedPrefetchRequestTimeoutMs = Number(opts.prefetchRequestTimeoutMs);
298 const requestedPrefetchRequestTimeoutMs = Number(opts.prefetchRequestTimeoutMs);
293 const prefetchRequestTimeoutMs = Number.isFinite(requestedPrefetchRequestTimeoutMs)
299 const prefetchRequestTimeoutMs = Number.isFinite(requestedPrefetchRequestTimeoutMs)
294 ? Math.max(250, requestedPrefetchRequestTimeoutMs)
300 ? Math.max(250, requestedPrefetchRequestTimeoutMs)
@@ -829,11 +835,23 @@
829
835
830 if (selectedStreamIndex !== null)
836 if (selectedStreamIndex !== null)
831 {
837 {
832 void refreshFrame(true);
838 if (initialPrefetchSeconds > 0)
839 {
840 queueLookaheadPrefetch(0, {
841 reset: true,
842 includeCurrentTime: true,
843 maxTargetTimeSeconds: initialPrefetchSeconds,
844 });
845 }
846 void refreshFrame();
833 }
847 }
834 };
848 };
835
849
836 const queueLookaheadPrefetch = (currentTime, { reset = false, includeCurrentTime = false } = {}) =>
850 const queueLookaheadPrefetch = (currentTime, {
851 reset = false,
852 includeCurrentTime = false,
853 maxTargetTimeSeconds = null,
854 } = {}) =>
837 {
855 {
838 if (selectedStreamIndex === null) return;
856 if (selectedStreamIndex === null) return;
839 if (trackDisabled) return;
857 if (trackDisabled) return;
@@ -875,17 +893,25 @@
875 const startTime = includeCurrentTime
893 const startTime = includeCurrentTime
876 ? currentTime
894 ? currentTime
877 : currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS;
895 : currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS;
878 const endTime = Math.max(
896 const uncappedEndTime = Math.max(
879 currentTime + lookaheadSeconds,
897 currentTime + lookaheadSeconds,
880 Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1,
898 Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1,
881 Number.isFinite(knownVideoEndSeconds) ? knownVideoEndSeconds : -1,
899 Number.isFinite(knownVideoEndSeconds) ? knownVideoEndSeconds : -1,
882 );
900 );
901 const capEndTime = Number.isFinite(maxTargetTimeSeconds) && maxTargetTimeSeconds >= 0
902 ? maxTargetTimeSeconds
903 : null;
904 const endTime = Number.isFinite(capEndTime)
905 ? Math.min(uncappedEndTime, capEndTime)
906 : uncappedEndTime;
883 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
907 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
884
908
885 if (reset || prefetchedThroughTimeSeconds < 0)
909 if (reset || prefetchedThroughTimeSeconds < 0)
886 {
910 {
887 cancelPrefetchRequests({ resetProgress: true });
911 cancelPrefetchRequests({ resetProgress: true });
888 prefetchedThroughTimeSeconds = currentTime;
912 prefetchedThroughTimeSeconds = includeCurrentTime
913 ? currentTime - IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS
914 : currentTime;
889 } else if (prefetchedThroughTimeSeconds < currentTime)
915 } else if (prefetchedThroughTimeSeconds < currentTime)
890 {
916 {
891 // Keep the prefetch frontier at or ahead of current playback so
917 // Keep the prefetch frontier at or ahead of current playback so
tests/shared-video-player.test.js +44 −0
@@ -293,6 +293,7 @@ describe('shared image subtitle prefetching', () =>
293 293 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
294 294 }, {
295 295 lookaheadSeconds: 0,
296 initialPrefetchSeconds: 0,
296 297 buildFrameRequest: ({ currentTime, streamIndex }) => ({
297 298 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
298 299 }),
@@ -329,6 +330,7 @@ describe('shared image subtitle prefetching', () =>
329 330 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
330 331 }, {
331 332 lookaheadSeconds: 0,
333 initialPrefetchSeconds: 0,
332 334 buildFrameRequest: ({ currentTime, streamIndex }) => ({
333 335 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
334 336 }),
@@ -386,6 +388,7 @@ describe('shared image subtitle prefetching', () =>
386 388 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
387 389 }, {
388 390 lookaheadSeconds: 0,
391 initialPrefetchSeconds: 0,
389 392 buildFrameRequest: ({ currentTime, streamIndex }) => ({
390 393 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
391 394 }),
@@ -620,6 +623,47 @@ describe('shared image subtitle prefetching', () =>
620 623 window.close();
621 624 });
622 625
626 test('cache-only mode performs initial warmup prefetch window on load', async () =>
627 {
628 const window = createWindow();
629 const helper = loadSharedVideoPlayer(window);
630 const { player, videojs } = buildPlayerHarness(window);
631 const requestedTimes = [];
632
633 window.fetch = jest.fn(async (url) =>
634 {
635 const parsed = new URL(url, 'http://localhost/');
636 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
637 return new Response(null, {
638 status: 204,
639 headers: {
640 'X-Subtitle-Frame-Status': 'none',
641 'X-Subtitle-Request-Received-At-Ms': '1000',
642 'X-Subtitle-Response-Sent-At-Ms': '1010',
643 },
644 });
645 });
646
647 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
648 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
649 }, {
650 currentFetchEnabled: false,
651 lookaheadSeconds: 0,
652 initialPrefetchSeconds: 2,
653 buildFrameRequest: ({ currentTime, streamIndex }) => ({
654 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
655 }),
656 });
657
658 await flushAsyncWork(window, 12);
659
660 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2]));
661
662 controller.detach();
663 await flushAsyncWork(window, 2);
664 window.close();
665 });
666
623 667 test('renders requested and received subtitle markers on the seek bar', async () =>
624 668 {
625 669 const window = createWindow();
@@ -293,6 +293,7 @@ describe('shared image subtitle prefetching', () =>
293 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
293 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
294 }, {
294 }, {
295 lookaheadSeconds: 0,
295 lookaheadSeconds: 0,
296 initialPrefetchSeconds: 0,
296 buildFrameRequest: ({ currentTime, streamIndex }) => ({
297 buildFrameRequest: ({ currentTime, streamIndex }) => ({
297 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
298 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
298 }),
299 }),
@@ -329,6 +330,7 @@ describe('shared image subtitle prefetching', () =>
329 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
330 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
330 }, {
331 }, {
331 lookaheadSeconds: 0,
332 lookaheadSeconds: 0,
333 initialPrefetchSeconds: 0,
332 buildFrameRequest: ({ currentTime, streamIndex }) => ({
334 buildFrameRequest: ({ currentTime, streamIndex }) => ({
333 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
335 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
334 }),
336 }),
@@ -386,6 +388,7 @@ describe('shared image subtitle prefetching', () =>
386 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
388 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
387 }, {
389 }, {
388 lookaheadSeconds: 0,
390 lookaheadSeconds: 0,
391 initialPrefetchSeconds: 0,
389 buildFrameRequest: ({ currentTime, streamIndex }) => ({
392 buildFrameRequest: ({ currentTime, streamIndex }) => ({
390 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
393 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
391 }),
394 }),
@@ -620,6 +623,47 @@ describe('shared image subtitle prefetching', () =>
620 window.close();
623 window.close();
621 });
624 });
622
625
626 test('cache-only mode performs initial warmup prefetch window on load', async () =>
627 {
628 const window = createWindow();
629 const helper = loadSharedVideoPlayer(window);
630 const { player, videojs } = buildPlayerHarness(window);
631 const requestedTimes = [];
632
633 window.fetch = jest.fn(async (url) =>
634 {
635 const parsed = new URL(url, 'http://localhost/');
636 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
637 return new Response(null, {
638 status: 204,
639 headers: {
640 'X-Subtitle-Frame-Status': 'none',
641 'X-Subtitle-Request-Received-At-Ms': '1000',
642 'X-Subtitle-Response-Sent-At-Ms': '1010',
643 },
644 });
645 });
646
647 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
648 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
649 }, {
650 currentFetchEnabled: false,
651 lookaheadSeconds: 0,
652 initialPrefetchSeconds: 2,
653 buildFrameRequest: ({ currentTime, streamIndex }) => ({
654 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
655 }),
656 });
657
658 await flushAsyncWork(window, 12);
659
660 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2]));
661
662 controller.detach();
663 await flushAsyncWork(window, 2);
664 window.close();
665 });
666
623 test('renders requested and received subtitle markers on the seek bar', async () =>
667 test('renders requested and received subtitle markers on the seek bar', async () =>
624 {
668 {
625 const window = createWindow();
669 const window = createWindow();