BlueGit

timfa filemanager

Fix subtitle seek-back deadlock

Image subtitles no longer stall after seeking backwards.\n\nThis fixes a deadlock in current subtitle request cleanup after force-seek aborts, so subtitle refresh continues normally after rewinding. It also adds regression coverage for the force-seek abort path and updates the technical reference to document the behaviour.

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

Hash
afd05e405dc283dbb295d90f58ce9fa5b617981b
Parent
2618c4ac
3 files changed +68 −4
.github/technical-reference.md +1 −1
@@ -182,7 +182,7 @@
182 182 ## public/shared-video-player.js
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 - 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), 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, 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), 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 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 187 - clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188 188
@@ -182,7 +182,7 @@
182## public/shared-video-player.js
182## public/shared-video-player.js
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), 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, 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), 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- 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.
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- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
187- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188
188
public/shared-video-player.js +6 −3
@@ -1075,7 +1075,7 @@
1075 1075 requestedVideoTimeSeconds: roundLogNumber(currentTime),
1076 1076 });
1077 1077
1078 currentFramePromise = (async () =>
1078 const frameRequestPromise = (async () =>
1079 1079 {
1080 1080 let currentTimedOut = false;
1081 1081 const timeoutId = armRequestTimeout(controller, currentRequestTimeoutMs, () =>
@@ -1201,9 +1201,12 @@
1201 1201 });
1202 1202 if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack();
1203 1203 }
1204 })().finally(() =>
1204 })();
1205
1206 currentFramePromise = frameRequestPromise;
1207 frameRequestPromise.finally(() =>
1205 1208 {
1206 if (token !== currentFrameToken) return;
1209 if (currentFramePromise !== frameRequestPromise) return;
1207 1210 currentFrameAbortController = null;
1208 1211 currentFramePromise = null;
1209 1212 if (!queuedCurrentRefresh) return;
@@ -1075,7 +1075,7 @@
1075 requestedVideoTimeSeconds: roundLogNumber(currentTime),
1075 requestedVideoTimeSeconds: roundLogNumber(currentTime),
1076 });
1076 });
1077
1077
1078 currentFramePromise = (async () =>
1078 const frameRequestPromise = (async () =>
1079 {
1079 {
1080 let currentTimedOut = false;
1080 let currentTimedOut = false;
1081 const timeoutId = armRequestTimeout(controller, currentRequestTimeoutMs, () =>
1081 const timeoutId = armRequestTimeout(controller, currentRequestTimeoutMs, () =>
@@ -1201,9 +1201,12 @@
1201 });
1201 });
1202 if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack();
1202 if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack();
1203 }
1203 }
1204 })().finally(() =>
1204 })();
1205
1206 currentFramePromise = frameRequestPromise;
1207 frameRequestPromise.finally(() =>
1205 {
1208 {
1206 if (token !== currentFrameToken) return;
1209 if (currentFramePromise !== frameRequestPromise) return;
1207 currentFrameAbortController = null;
1210 currentFrameAbortController = null;
1208 currentFramePromise = null;
1211 currentFramePromise = null;
1209 if (!queuedCurrentRefresh) return;
1212 if (!queuedCurrentRefresh) return;
tests/shared-video-player.test.js +61 −0
@@ -705,6 +705,67 @@ describe('shared image subtitle prefetching', () =>
705 705 window.close();
706 706 });
707 707
708 test('continues current subtitle refreshes after a force-seek aborts the in-flight request', async () =>
709 {
710 const window = createWindow();
711 const helper = loadSharedVideoPlayer(window);
712 const { player, videojs } = buildPlayerHarness(window);
713 const requestedTimes = [];
714
715 window.fetch = jest.fn((url, init = {}) =>
716 {
717 const parsed = new URL(url, 'http://localhost/');
718 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
719 requestedTimes.push(timeSeconds);
720
721 if (requestedTimes.length === 1)
722 {
723 return new Promise((resolve, reject) =>
724 {
725 if (init.signal && typeof init.signal.addEventListener === 'function')
726 {
727 init.signal.addEventListener('abort', () =>
728 {
729 reject(new window.DOMException('Aborted', 'AbortError'));
730 }, { once: true });
731 }
732 });
733 }
734
735 return Promise.resolve(new Response(null, {
736 status: 204,
737 headers: {
738 'X-Subtitle-Frame-Status': 'none',
739 },
740 }));
741 });
742
743 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
744 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
745 }, {
746 lookaheadSeconds: 0,
747 currentRequestTimeoutMs: 300,
748 logToConsole: false,
749 buildFrameRequest: ({ currentTime, streamIndex }) => ({
750 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
751 }),
752 });
753
754 await flushAsyncWork(window, 4);
755 expect(window.fetch).toHaveBeenCalledTimes(1);
756
757 player.setCurrentTime(5);
758 player.trigger('seeking');
759 await flushAsyncWork(window, 20);
760
761 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
762 expect(requestedTimes).toEqual(expect.arrayContaining([0, 5]));
763
764 controller.detach();
765 await flushAsyncWork(window, 2);
766 window.close();
767 });
768
708 769 test('recovers when a current subtitle request hangs and times out', async () =>
709 770 {
710 771 const window = createWindow();
@@ -705,6 +705,67 @@ describe('shared image subtitle prefetching', () =>
705 window.close();
705 window.close();
706 });
706 });
707
707
708 test('continues current subtitle refreshes after a force-seek aborts the in-flight request', async () =>
709 {
710 const window = createWindow();
711 const helper = loadSharedVideoPlayer(window);
712 const { player, videojs } = buildPlayerHarness(window);
713 const requestedTimes = [];
714
715 window.fetch = jest.fn((url, init = {}) =>
716 {
717 const parsed = new URL(url, 'http://localhost/');
718 const timeSeconds = Number(parsed.searchParams.get('timeSeconds'));
719 requestedTimes.push(timeSeconds);
720
721 if (requestedTimes.length === 1)
722 {
723 return new Promise((resolve, reject) =>
724 {
725 if (init.signal && typeof init.signal.addEventListener === 'function')
726 {
727 init.signal.addEventListener('abort', () =>
728 {
729 reject(new window.DOMException('Aborted', 'AbortError'));
730 }, { once: true });
731 }
732 });
733 }
734
735 return Promise.resolve(new Response(null, {
736 status: 204,
737 headers: {
738 'X-Subtitle-Frame-Status': 'none',
739 },
740 }));
741 });
742
743 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
744 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
745 }, {
746 lookaheadSeconds: 0,
747 currentRequestTimeoutMs: 300,
748 logToConsole: false,
749 buildFrameRequest: ({ currentTime, streamIndex }) => ({
750 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
751 }),
752 });
753
754 await flushAsyncWork(window, 4);
755 expect(window.fetch).toHaveBeenCalledTimes(1);
756
757 player.setCurrentTime(5);
758 player.trigger('seeking');
759 await flushAsyncWork(window, 20);
760
761 expect(window.fetch.mock.calls.length).toBeGreaterThanOrEqual(2);
762 expect(requestedTimes).toEqual(expect.arrayContaining([0, 5]));
763
764 controller.detach();
765 await flushAsyncWork(window, 2);
766 window.close();
767 });
768
708 test('recovers when a current subtitle request hangs and times out', async () =>
769 test('recovers when a current subtitle request hangs and times out', async () =>
709 {
770 {
710 const window = createWindow();
771 const window = createWindow();