BlueGit

timfa filemanager

Improve subtitle display timing

Subtitle display now runs a playback-clock cache sync while playing, so captions can start and stop at their cached timing boundaries even between sparse timeupdate events.\n\nThis reduces perceived late starts and early cut-offs when subtitle frames are already prefetched, and adds regression coverage for cache-driven visibility updates between timeupdate ticks.

timfa Tim Falken · pushed by timfa

Authored 2026-05-28 · 5 months ago

Hash
34ec2083b5d688340897af748a5814c1a06f4757
Parent
9fdb6124
3 files changed +129 −2
.github/technical-reference.md +1 −0
@@ -211,6 +211,7 @@
211 211 - 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.
212 212 - 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.
213 213 - 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, can optionally use a separate range-prefetch request builder (`buildPrefetchRequest`) so the walker caches multiple subtitle images from one window request, 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, supports fixed prefetch stride (`prefetchStepSeconds`) and adaptive stride mode (`prefetchAdaptiveStepEnabled` with `prefetchStepSecondsMin`/`prefetchStepSecondsMax`) plus optional adaptive pacing (`prefetchAdaptivePacingEnabled`) to balance cache fill speed against backend request pressure, extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), clamps tail requests to the known video duration when that boundary is available, drives range-prefetch seek markers from the covered-through window end instead of the window start so empty tail windows still reach the video end, 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.
214 - bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Playback display timing now includes a high-frequency cache-sync loop while playing, so captions can start/end at frame-window boundaries even between sparse `timeupdate` events, reducing late starts and early cut-offs when data is already prefetched.
214 215 - bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Cache-frame time matching now uses a small epsilon window around start/end timestamps to avoid boundary misses; cache-only mode can also perform a throttled direct current-frame fallback fetch on cache miss (`cacheMissFallbackEnabled`, `cacheMissFallbackIntervalMs`) so subtitles recover without waiting for another seek/timeupdate cycle, fallback fetches preserve prefetch progress so repeated cache misses do not keep resetting subtitle lookahead, and duration metadata hints now extend lookahead prefetch to the known video end even before playback advances.
215 216 - 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().
216 217 - 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.
@@ -211,6 +211,7 @@
211- 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.
211- 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.
212- 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.
212- 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.
213- 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, can optionally use a separate range-prefetch request builder (`buildPrefetchRequest`) so the walker caches multiple subtitle images from one window request, 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, supports fixed prefetch stride (`prefetchStepSeconds`) and adaptive stride mode (`prefetchAdaptiveStepEnabled` with `prefetchStepSecondsMin`/`prefetchStepSecondsMax`) plus optional adaptive pacing (`prefetchAdaptivePacingEnabled`) to balance cache fill speed against backend request pressure, extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), clamps tail requests to the known video duration when that boundary is available, drives range-prefetch seek markers from the covered-through window end instead of the window start so empty tail windows still reach the video end, 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.
213- 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, can optionally use a separate range-prefetch request builder (`buildPrefetchRequest`) so the walker caches multiple subtitle images from one window request, 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, supports fixed prefetch stride (`prefetchStepSeconds`) and adaptive stride mode (`prefetchAdaptiveStepEnabled` with `prefetchStepSecondsMin`/`prefetchStepSecondsMax`) plus optional adaptive pacing (`prefetchAdaptivePacingEnabled`) to balance cache fill speed against backend request pressure, extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), clamps tail requests to the known video duration when that boundary is available, drives range-prefetch seek markers from the covered-through window end instead of the window start so empty tail windows still reach the video end, 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.
214- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Playback display timing now includes a high-frequency cache-sync loop while playing, so captions can start/end at frame-window boundaries even between sparse `timeupdate` events, reducing late starts and early cut-offs when data is already prefetched.
214- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Cache-frame time matching now uses a small epsilon window around start/end timestamps to avoid boundary misses; cache-only mode can also perform a throttled direct current-frame fallback fetch on cache miss (`cacheMissFallbackEnabled`, `cacheMissFallbackIntervalMs`) so subtitles recover without waiting for another seek/timeupdate cycle, fallback fetches preserve prefetch progress so repeated cache misses do not keep resetting subtitle lookahead, and duration metadata hints now extend lookahead prefetch to the known video end even before playback advances.
215- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Cache-frame time matching now uses a small epsilon window around start/end timestamps to avoid boundary misses; cache-only mode can also perform a throttled direct current-frame fallback fetch on cache miss (`cacheMissFallbackEnabled`, `cacheMissFallbackIntervalMs`) so subtitles recover without waiting for another seek/timeupdate cycle, fallback fetches preserve prefetch progress so repeated cache misses do not keep resetting subtitle lookahead, and duration metadata hints now extend lookahead prefetch to the known video end even before playback advances.
215- 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().
216- 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().
216- 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.
217- 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.
public/shared-video-player.js +69 −2
@@ -384,8 +384,29 @@
384 384 let subtitleLogQueue = [];
385 385 let subtitleLogFlushTimer = null;
386 386 let lastCacheMissFallbackAtMs = 0;
387 let playbackClockSyncHandle = null;
387 388 const cachedSubtitleFrames = new Map();
388 389
390 const requestFrame = (fn) =>
391 {
392 if (typeof window.requestAnimationFrame === 'function')
393 {
394 return { kind: 'raf', id: window.requestAnimationFrame(fn) };
395 }
396 return { kind: 'timeout', id: window.setTimeout(fn, 16) };
397 };
398
399 const cancelFrameRequest = (handle) =>
400 {
401 if (!handle || !Number.isFinite(Number(handle.id))) return;
402 if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function')
403 {
404 window.cancelAnimationFrame(handle.id);
405 return;
406 }
407 window.clearTimeout(handle.id);
408 };
409
389 410 const flushSubtitleLogs = () =>
390 411 {
391 412 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
@@ -512,6 +533,13 @@
512 533 cancelPrefetchRequests({ resetProgress: true });
513 534 };
514 535
536 const stopPlaybackClockSync = () =>
537 {
538 if (!playbackClockSyncHandle) return;
539 cancelFrameRequest(playbackClockSyncHandle);
540 playbackClockSyncHandle = null;
541 };
542
515 543 const closeObjectUrl = () =>
516 544 {
517 545 activeObjectUrl = null;
@@ -679,8 +707,11 @@
679 707 {
680 708 if (!overlayEl || !overlayImgEl || !frame || !frame.objectUrl) return;
681 709
682 activeObjectUrl = frame.objectUrl;
683 overlayImgEl.src = frame.objectUrl;
710 if (activeObjectUrl !== frame.objectUrl)
711 {
712 activeObjectUrl = frame.objectUrl;
713 overlayImgEl.src = frame.objectUrl;
714 }
684 715
685 716 if (frame.frameWidth > 0 && frame.frameHeight > 0 && frame.canvasWidth > 0 && frame.canvasHeight > 0)
686 717 {
@@ -702,6 +733,32 @@
702 733 overlayImgEl.style.display = 'block';
703 734 };
704 735
736 const syncOverlayToPlaybackClock = () =>
737 {
738 if (selectedStreamIndex === null || trackDisabled)
739 {
740 stopPlaybackClockSync();
741 return;
742 }
743
744 const currentTime = Number(player.currentTime());
745 if (Number.isFinite(currentTime) && currentTime >= 0)
746 {
747 const cachedFrame = findCachedFrameForTime(selectedStreamIndex, currentTime);
748 if (cachedFrame) renderSubtitleFrame(cachedFrame);
749 else hideOverlay();
750 }
751
752 playbackClockSyncHandle = requestFrame(syncOverlayToPlaybackClock);
753 };
754
755 const ensurePlaybackClockSync = () =>
756 {
757 if (selectedStreamIndex === null || trackDisabled) return;
758 if (playbackClockSyncHandle) return;
759 playbackClockSyncHandle = requestFrame(syncOverlayToPlaybackClock);
760 };
761
705 762 const setSeekMarkerTime = (kind, timeSeconds) =>
706 763 {
707 764 const numericTime = Number(timeSeconds);
@@ -888,6 +945,7 @@
888 945 trackDisabled = true;
889 946 selectedStreamIndex = null;
890 947 activeBucket = -1;
948 stopPlaybackClockSync();
891 949 setSeekMarkerTime('requested', null);
892 950 setSeekMarkerTime('received', null);
893 951 updateSeekBarMarkers();
@@ -924,6 +982,7 @@
924 982
925 983 if (selectedStreamIndex !== null)
926 984 {
985 ensurePlaybackClockSync();
927 986 if (initialPrefetchSeconds > 0)
928 987 {
929 988 queueLookaheadPrefetch(0, {
@@ -934,6 +993,10 @@
934 993 }
935 994 void refreshFrame();
936 995 }
996 else
997 {
998 stopPlaybackClockSync();
999 }
937 1000 };
938 1001
939 1002 const queueLookaheadPrefetch = (currentTime, {
@@ -1484,6 +1547,7 @@
1484 1547
1485 1548 const dispose = () =>
1486 1549 {
1550 stopPlaybackClockSync();
1487 1551 resetRequestState();
1488 1552 flushSubtitleLogs();
1489 1553 closeMenu();
@@ -1659,6 +1723,9 @@
1659 1723 player.on('timeupdate', () => { void refreshFrame(); });
1660 1724 player.on('seeking', () => { void refreshFrame(true); });
1661 1725 player.on('play', () => { void refreshFrame(true); });
1726 player.on('play', ensurePlaybackClockSync);
1727 player.on('pause', stopPlaybackClockSync);
1728 player.on('ended', stopPlaybackClockSync);
1662 1729 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
1663 1730 player.on('dispose', dispose);
1664 1731 player.ready(() =>
@@ -384,8 +384,29 @@
384 let subtitleLogQueue = [];
384 let subtitleLogQueue = [];
385 let subtitleLogFlushTimer = null;
385 let subtitleLogFlushTimer = null;
386 let lastCacheMissFallbackAtMs = 0;
386 let lastCacheMissFallbackAtMs = 0;
387 let playbackClockSyncHandle = null;
387 const cachedSubtitleFrames = new Map();
388 const cachedSubtitleFrames = new Map();
388
389
390 const requestFrame = (fn) =>
391 {
392 if (typeof window.requestAnimationFrame === 'function')
393 {
394 return { kind: 'raf', id: window.requestAnimationFrame(fn) };
395 }
396 return { kind: 'timeout', id: window.setTimeout(fn, 16) };
397 };
398
399 const cancelFrameRequest = (handle) =>
400 {
401 if (!handle || !Number.isFinite(Number(handle.id))) return;
402 if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function')
403 {
404 window.cancelAnimationFrame(handle.id);
405 return;
406 }
407 window.clearTimeout(handle.id);
408 };
409
389 const flushSubtitleLogs = () =>
410 const flushSubtitleLogs = () =>
390 {
411 {
391 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
412 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
@@ -512,6 +533,13 @@
512 cancelPrefetchRequests({ resetProgress: true });
533 cancelPrefetchRequests({ resetProgress: true });
513 };
534 };
514
535
536 const stopPlaybackClockSync = () =>
537 {
538 if (!playbackClockSyncHandle) return;
539 cancelFrameRequest(playbackClockSyncHandle);
540 playbackClockSyncHandle = null;
541 };
542
515 const closeObjectUrl = () =>
543 const closeObjectUrl = () =>
516 {
544 {
517 activeObjectUrl = null;
545 activeObjectUrl = null;
@@ -679,8 +707,11 @@
679 {
707 {
680 if (!overlayEl || !overlayImgEl || !frame || !frame.objectUrl) return;
708 if (!overlayEl || !overlayImgEl || !frame || !frame.objectUrl) return;
681
709
682 activeObjectUrl = frame.objectUrl;
710 if (activeObjectUrl !== frame.objectUrl)
683 overlayImgEl.src = frame.objectUrl;
711 {
712 activeObjectUrl = frame.objectUrl;
713 overlayImgEl.src = frame.objectUrl;
714 }
684
715
685 if (frame.frameWidth > 0 && frame.frameHeight > 0 && frame.canvasWidth > 0 && frame.canvasHeight > 0)
716 if (frame.frameWidth > 0 && frame.frameHeight > 0 && frame.canvasWidth > 0 && frame.canvasHeight > 0)
686 {
717 {
@@ -702,6 +733,32 @@
702 overlayImgEl.style.display = 'block';
733 overlayImgEl.style.display = 'block';
703 };
734 };
704
735
736 const syncOverlayToPlaybackClock = () =>
737 {
738 if (selectedStreamIndex === null || trackDisabled)
739 {
740 stopPlaybackClockSync();
741 return;
742 }
743
744 const currentTime = Number(player.currentTime());
745 if (Number.isFinite(currentTime) && currentTime >= 0)
746 {
747 const cachedFrame = findCachedFrameForTime(selectedStreamIndex, currentTime);
748 if (cachedFrame) renderSubtitleFrame(cachedFrame);
749 else hideOverlay();
750 }
751
752 playbackClockSyncHandle = requestFrame(syncOverlayToPlaybackClock);
753 };
754
755 const ensurePlaybackClockSync = () =>
756 {
757 if (selectedStreamIndex === null || trackDisabled) return;
758 if (playbackClockSyncHandle) return;
759 playbackClockSyncHandle = requestFrame(syncOverlayToPlaybackClock);
760 };
761
705 const setSeekMarkerTime = (kind, timeSeconds) =>
762 const setSeekMarkerTime = (kind, timeSeconds) =>
706 {
763 {
707 const numericTime = Number(timeSeconds);
764 const numericTime = Number(timeSeconds);
@@ -888,6 +945,7 @@
888 trackDisabled = true;
945 trackDisabled = true;
889 selectedStreamIndex = null;
946 selectedStreamIndex = null;
890 activeBucket = -1;
947 activeBucket = -1;
948 stopPlaybackClockSync();
891 setSeekMarkerTime('requested', null);
949 setSeekMarkerTime('requested', null);
892 setSeekMarkerTime('received', null);
950 setSeekMarkerTime('received', null);
893 updateSeekBarMarkers();
951 updateSeekBarMarkers();
@@ -924,6 +982,7 @@
924
982
925 if (selectedStreamIndex !== null)
983 if (selectedStreamIndex !== null)
926 {
984 {
985 ensurePlaybackClockSync();
927 if (initialPrefetchSeconds > 0)
986 if (initialPrefetchSeconds > 0)
928 {
987 {
929 queueLookaheadPrefetch(0, {
988 queueLookaheadPrefetch(0, {
@@ -934,6 +993,10 @@
934 }
993 }
935 void refreshFrame();
994 void refreshFrame();
936 }
995 }
996 else
997 {
998 stopPlaybackClockSync();
999 }
937 };
1000 };
938
1001
939 const queueLookaheadPrefetch = (currentTime, {
1002 const queueLookaheadPrefetch = (currentTime, {
@@ -1484,6 +1547,7 @@
1484
1547
1485 const dispose = () =>
1548 const dispose = () =>
1486 {
1549 {
1550 stopPlaybackClockSync();
1487 resetRequestState();
1551 resetRequestState();
1488 flushSubtitleLogs();
1552 flushSubtitleLogs();
1489 closeMenu();
1553 closeMenu();
@@ -1659,6 +1723,9 @@
1659 player.on('timeupdate', () => { void refreshFrame(); });
1723 player.on('timeupdate', () => { void refreshFrame(); });
1660 player.on('seeking', () => { void refreshFrame(true); });
1724 player.on('seeking', () => { void refreshFrame(true); });
1661 player.on('play', () => { void refreshFrame(true); });
1725 player.on('play', () => { void refreshFrame(true); });
1726 player.on('play', ensurePlaybackClockSync);
1727 player.on('pause', stopPlaybackClockSync);
1728 player.on('ended', stopPlaybackClockSync);
1662 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
1729 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
1663 player.on('dispose', dispose);
1730 player.on('dispose', dispose);
1664 player.ready(() =>
1731 player.ready(() =>
tests/shared-video-player.test.js +59 −0
@@ -726,6 +726,65 @@ describe('shared image subtitle prefetching', () =>
726 726 window.close();
727 727 });
728 728
729 test('syncs caption visibility from cache between sparse timeupdate events', async () =>
730 {
731 const window = createWindow();
732 const helper = loadSharedVideoPlayer(window);
733 const { player, videojs } = buildPlayerHarness(window);
734
735 // JSDOM raf cadence can be inconsistent; force timeout fallback for stable checks.
736 window.requestAnimationFrame = undefined;
737 window.cancelAnimationFrame = undefined;
738
739 player.duration(20);
740
741 window.fetch = jest.fn(async () =>
742 {
743 return new Response(new Uint8Array([137, 80, 78, 71]), {
744 status: 200,
745 headers: {
746 'Content-Type': 'image/png',
747 'X-Subtitle-Frame-Start-Time': '1',
748 'X-Subtitle-Frame-End-Time': '2',
749 'X-Subtitle-Frame-Width': '640',
750 'X-Subtitle-Frame-Height': '80',
751 'X-Subtitle-Frame-Canvas-Width': '1920',
752 'X-Subtitle-Frame-Canvas-Height': '1080',
753 },
754 });
755 });
756
757 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
758 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
759 }, {
760 lookaheadSeconds: 0,
761 initialPrefetchSeconds: 0,
762 buildFrameRequest: ({ currentTime, streamIndex }) => ({
763 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
764 }),
765 });
766
767 await flushAsyncWork(window, 8);
768
769 const overlay = player.el().querySelector('.video-subtitle-overlay');
770 expect(overlay).toBeTruthy();
771
772 player.setCurrentTime(1.2);
773 player.trigger('play');
774 await new Promise((resolve) => window.setTimeout(resolve, 50));
775 await flushAsyncWork(window, 2);
776 expect(overlay.style.display).toBe('block');
777
778 player.setCurrentTime(2.2);
779 await new Promise((resolve) => window.setTimeout(resolve, 50));
780 await flushAsyncWork(window, 2);
781 expect(overlay.style.display).toBe('none');
782
783 controller.detach();
784 await flushAsyncWork(window, 2);
785 window.close();
786 });
787
729 788 test('aborts in-flight prefetch requests when the overlay is detached', async () =>
730 789 {
731 790 const window = createWindow();
@@ -726,6 +726,65 @@ describe('shared image subtitle prefetching', () =>
726 window.close();
726 window.close();
727 });
727 });
728
728
729 test('syncs caption visibility from cache between sparse timeupdate events', async () =>
730 {
731 const window = createWindow();
732 const helper = loadSharedVideoPlayer(window);
733 const { player, videojs } = buildPlayerHarness(window);
734
735 // JSDOM raf cadence can be inconsistent; force timeout fallback for stable checks.
736 window.requestAnimationFrame = undefined;
737 window.cancelAnimationFrame = undefined;
738
739 player.duration(20);
740
741 window.fetch = jest.fn(async () =>
742 {
743 return new Response(new Uint8Array([137, 80, 78, 71]), {
744 status: 200,
745 headers: {
746 'Content-Type': 'image/png',
747 'X-Subtitle-Frame-Start-Time': '1',
748 'X-Subtitle-Frame-End-Time': '2',
749 'X-Subtitle-Frame-Width': '640',
750 'X-Subtitle-Frame-Height': '80',
751 'X-Subtitle-Frame-Canvas-Width': '1920',
752 'X-Subtitle-Frame-Canvas-Height': '1080',
753 },
754 });
755 });
756
757 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
758 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
759 }, {
760 lookaheadSeconds: 0,
761 initialPrefetchSeconds: 0,
762 buildFrameRequest: ({ currentTime, streamIndex }) => ({
763 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
764 }),
765 });
766
767 await flushAsyncWork(window, 8);
768
769 const overlay = player.el().querySelector('.video-subtitle-overlay');
770 expect(overlay).toBeTruthy();
771
772 player.setCurrentTime(1.2);
773 player.trigger('play');
774 await new Promise((resolve) => window.setTimeout(resolve, 50));
775 await flushAsyncWork(window, 2);
776 expect(overlay.style.display).toBe('block');
777
778 player.setCurrentTime(2.2);
779 await new Promise((resolve) => window.setTimeout(resolve, 50));
780 await flushAsyncWork(window, 2);
781 expect(overlay.style.display).toBe('none');
782
783 controller.detach();
784 await flushAsyncWork(window, 2);
785 window.close();
786 });
787
729 test('aborts in-flight prefetch requests when the overlay is detached', async () =>
788 test('aborts in-flight prefetch requests when the overlay is detached', async () =>
730 {
789 {
731 const window = createWindow();
790 const window = createWindow();