BlueGit

timfa filemanager

Harden client walker lifecycle on preview switch

Video preview initialisation now uses a lifecycle token so stale async setup from a previously closed preview is discarded and cleaned up immediately. This prevents old preview instances from leaving behind active client walkers or stream sessions when users switch videos quickly.\n\nImage subtitle prefetching now also extends to the known video end as soon as duration metadata arrives, even before playback advances, so subtitle cache filling continues towards full coverage without relying on current playback position.

timfa Tim Falken · pushed by timfa

Authored 2026-05-27 · 5 months ago

Hash
89ff5a0fc76b790bf2ef04d213362111abcf73b7
Parent
1f2d6982
4 files changed +93 −5
.github/technical-reference.md +2 −2
@@ -207,7 +207,7 @@
207 207 - 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.
208 208 - 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.
209 209 - 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.
210 - 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, and fallback fetches preserve prefetch progress so repeated cache misses do not keep resetting subtitle lookahead.
210 - 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.
211 211 - 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().
212 212 - 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.
213 213 - 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.
@@ -295,7 +295,7 @@
295 295 - buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
296 296 - 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.
297 297 - 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.
298 - 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.
298 - 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, releases the backend stream session on close/unload, and uses a preview initialisation token guard so stale async player/walker setup from a previously closed preview is discarded immediately.
299 299 - modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
300 300 - loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
301 301 - modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
@@ -207,7 +207,7 @@
207- 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.
207- 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.
208- 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.
208- 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.
209- 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.
209- 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.
210- 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, and fallback fetches preserve prefetch progress so repeated cache misses do not keep resetting subtitle lookahead.
210- 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.
211- 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().
211- 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().
212- 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.
212- 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.
213- 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.
213- 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.
@@ -295,7 +295,7 @@
295- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
295- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
296- 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.
296- 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.
297- 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.
297- 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.
298- 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.
298- 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, releases the backend stream session on close/unload, and uses a preview initialisation token guard so stale async player/walker setup from a previously closed preview is discarded immediately.
299- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
299- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
300- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
300- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
301- modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
301- modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
public/app.js +33 −1
@@ -55,6 +55,7 @@ const STATE = {
55 55 previewCleanup: null,
56 56 previewDownloadAction: null,
57 57 previewVideoStreamSessionId: null,
58 previewStreamInitToken: 0,
58 59 previewSourceEl: null, // SVG element that triggered the preview
59 60 previewClosing: false, // guard to prevent double-close during animation
60 61 previewExpandState: null, // in-place expanded tile preview state
@@ -4002,6 +4003,7 @@ function highlightCode (raw, lang)
4002 4003
4003 4004 function clearPreviewObjectUrl ()
4004 4005 {
4006 STATE.previewStreamInitToken += 1;
4005 4007 if (typeof STATE.previewCleanup === 'function')
4006 4008 {
4007 4009 try { STATE.previewCleanup(); } catch { /* ignore */ }
@@ -4125,11 +4127,33 @@ async function preparePreviewDownload (item)
4125 4127
4126 4128 async function renderStreamedVideoPreview (item, targetEl)
4127 4129 {
4130 const streamInitToken = ++STATE.previewStreamInitToken;
4131 const isStaleInit = () =>
4132 streamInitToken !== STATE.previewStreamInitToken
4133 || !targetEl
4134 || !targetEl.isConnected;
4135
4128 4136 const videojs = await ensureVideoJsLoaded();
4137 if (isStaleInit()) return;
4129 4138 await enableVideoStreamClientCache();
4139 if (isStaleInit()) return;
4130 4140 const session = await createVideoStreamSessionForItem(item);
4141 if (isStaleInit())
4142 {
4143 void releaseVideoStreamSession(session && session.sessionId, { keepalive: true });
4144 return;
4145 }
4146
4131 4147 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
4132 4148 const streamAheadPrefetch = bindStreamAheadPrefetch(sessionPlaylistUrl);
4149 if (isStaleInit())
4150 {
4151 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4152 void clearVideoStreamClientCache(sessionPlaylistUrl);
4153 void releaseVideoStreamSession(session && session.sessionId, { keepalive: true });
4154 return;
4155 }
4156
4133 4157 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
4134 4158 const prefs = loadUserVideoPrefs();
4135 4159 applyUserVideoTextTrackPrefs();
@@ -4251,7 +4275,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4251 4275 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
4252 4276 });
4253 4277
4254 STATE.previewCleanup = () =>
4278 const cleanupPreviewPlayer = () =>
4255 4279 {
4256 4280 if (imageSubtitleController)
4257 4281 {
@@ -4267,6 +4291,14 @@ async function renderStreamedVideoPreview (item, targetEl)
4267 4291 try { trackPrefs.detach(); } catch { /* ignore */ }
4268 4292 try { player.dispose(); } catch { /* ignore */ }
4269 4293 };
4294
4295 if (isStaleInit())
4296 {
4297 cleanupPreviewPlayer();
4298 return;
4299 }
4300
4301 STATE.previewCleanup = cleanupPreviewPlayer;
4270 4302 }
4271 4303
4272 4304 function fileAccentColor (name)
@@ -55,6 +55,7 @@ const STATE = {
55 previewCleanup: null,
55 previewCleanup: null,
56 previewDownloadAction: null,
56 previewDownloadAction: null,
57 previewVideoStreamSessionId: null,
57 previewVideoStreamSessionId: null,
58 previewStreamInitToken: 0,
58 previewSourceEl: null, // SVG element that triggered the preview
59 previewSourceEl: null, // SVG element that triggered the preview
59 previewClosing: false, // guard to prevent double-close during animation
60 previewClosing: false, // guard to prevent double-close during animation
60 previewExpandState: null, // in-place expanded tile preview state
61 previewExpandState: null, // in-place expanded tile preview state
@@ -4002,6 +4003,7 @@ function highlightCode (raw, lang)
4002
4003
4003function clearPreviewObjectUrl ()
4004function clearPreviewObjectUrl ()
4004{
4005{
4006 STATE.previewStreamInitToken += 1;
4005 if (typeof STATE.previewCleanup === 'function')
4007 if (typeof STATE.previewCleanup === 'function')
4006 {
4008 {
4007 try { STATE.previewCleanup(); } catch { /* ignore */ }
4009 try { STATE.previewCleanup(); } catch { /* ignore */ }
@@ -4125,11 +4127,33 @@ async function preparePreviewDownload (item)
4125
4127
4126async function renderStreamedVideoPreview (item, targetEl)
4128async function renderStreamedVideoPreview (item, targetEl)
4127{
4129{
4130 const streamInitToken = ++STATE.previewStreamInitToken;
4131 const isStaleInit = () =>
4132 streamInitToken !== STATE.previewStreamInitToken
4133 || !targetEl
4134 || !targetEl.isConnected;
4135
4128 const videojs = await ensureVideoJsLoaded();
4136 const videojs = await ensureVideoJsLoaded();
4137 if (isStaleInit()) return;
4129 await enableVideoStreamClientCache();
4138 await enableVideoStreamClientCache();
4139 if (isStaleInit()) return;
4130 const session = await createVideoStreamSessionForItem(item);
4140 const session = await createVideoStreamSessionForItem(item);
4141 if (isStaleInit())
4142 {
4143 void releaseVideoStreamSession(session && session.sessionId, { keepalive: true });
4144 return;
4145 }
4146
4131 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
4147 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
4132 const streamAheadPrefetch = bindStreamAheadPrefetch(sessionPlaylistUrl);
4148 const streamAheadPrefetch = bindStreamAheadPrefetch(sessionPlaylistUrl);
4149 if (isStaleInit())
4150 {
4151 try { streamAheadPrefetch && streamAheadPrefetch.stop(); } catch { /* ignore */ }
4152 void clearVideoStreamClientCache(sessionPlaylistUrl);
4153 void releaseVideoStreamSession(session && session.sessionId, { keepalive: true });
4154 return;
4155 }
4156
4133 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
4157 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
4134 const prefs = loadUserVideoPrefs();
4158 const prefs = loadUserVideoPrefs();
4135 applyUserVideoTextTrackPrefs();
4159 applyUserVideoTextTrackPrefs();
@@ -4251,7 +4275,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4251 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
4275 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
4252 });
4276 });
4253
4277
4254 STATE.previewCleanup = () =>
4278 const cleanupPreviewPlayer = () =>
4255 {
4279 {
4256 if (imageSubtitleController)
4280 if (imageSubtitleController)
4257 {
4281 {
@@ -4267,6 +4291,14 @@ async function renderStreamedVideoPreview (item, targetEl)
4267 try { trackPrefs.detach(); } catch { /* ignore */ }
4291 try { trackPrefs.detach(); } catch { /* ignore */ }
4268 try { player.dispose(); } catch { /* ignore */ }
4292 try { player.dispose(); } catch { /* ignore */ }
4269 };
4293 };
4294
4295 if (isStaleInit())
4296 {
4297 cleanupPreviewPlayer();
4298 return;
4299 }
4300
4301 STATE.previewCleanup = cleanupPreviewPlayer;
4270}
4302}
4271
4303
4272function fileAccentColor (name)
4304function fileAccentColor (name)
public/shared-video-player.js +16 −2
@@ -1529,8 +1529,22 @@
1529 1529 if (menuOpen) openMenu();
1530 1530 });
1531 1531
1532 player.on('durationchange', () => { ensureSeekBarMarkers(); updateSeekBarMarkers(); });
1533 player.on('loadedmetadata', () => { ensureSeekBarMarkers(); updateSeekBarMarkers(); });
1532 const onDurationHints = () =>
1533 {
1534 ensureSeekBarMarkers();
1535 updateSeekBarMarkers();
1536
1537 if (selectedStreamIndex === null || trackDisabled) return;
1538 const currentTime = Number(player.currentTime());
1539 if (!Number.isFinite(currentTime) || currentTime < 0) return;
1540
1541 queueLookaheadPrefetch(currentTime, {
1542 includeCurrentTime: true,
1543 });
1544 };
1545
1546 player.on('durationchange', onDurationHints);
1547 player.on('loadedmetadata', onDurationHints);
1534 1548
1535 1549 return player.imageSubtitleOverlayController;
1536 1550 }
@@ -1529,8 +1529,22 @@
1529 if (menuOpen) openMenu();
1529 if (menuOpen) openMenu();
1530 });
1530 });
1531
1531
1532 player.on('durationchange', () => { ensureSeekBarMarkers(); updateSeekBarMarkers(); });
1532 const onDurationHints = () =>
1533 player.on('loadedmetadata', () => { ensureSeekBarMarkers(); updateSeekBarMarkers(); });
1533 {
1534 ensureSeekBarMarkers();
1535 updateSeekBarMarkers();
1536
1537 if (selectedStreamIndex === null || trackDisabled) return;
1538 const currentTime = Number(player.currentTime());
1539 if (!Number.isFinite(currentTime) || currentTime < 0) return;
1540
1541 queueLookaheadPrefetch(currentTime, {
1542 includeCurrentTime: true,
1543 });
1544 };
1545
1546 player.on('durationchange', onDurationHints);
1547 player.on('loadedmetadata', onDurationHints);
1534
1548
1535 return player.imageSubtitleOverlayController;
1549 return player.imageSubtitleOverlayController;
1536 }
1550 }
tests/shared-video-player.test.js +42 −0
@@ -227,6 +227,48 @@ describe('shared image subtitle prefetching', () =>
227 227 window.close();
228 228 });
229 229
230 test('prefetch expands to video end when duration metadata appears later', async () =>
231 {
232 const window = createWindow();
233 const helper = loadSharedVideoPlayer(window);
234 const { player, videojs } = buildPlayerHarness(window);
235 const requestedTimes = [];
236
237 player.duration(Number.NaN);
238
239 window.fetch = jest.fn(async (url) =>
240 {
241 const parsed = new URL(url, 'http://localhost/');
242 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
243 return new Response(null, {
244 status: 204,
245 headers: { 'X-Subtitle-Frame-Status': 'none' },
246 });
247 });
248
249 helper.bindImageSubtitleOverlay(player, videojs, {}, {
250 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
251 }, {
252 lookaheadSeconds: 0.5,
253 initialPrefetchSeconds: 0,
254 buildFrameRequest: ({ currentTime, streamIndex }) => ({
255 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
256 }),
257 });
258
259 await flushAsyncWork(window, 6);
260 expect(requestedTimes).toContain(0);
261
262 requestedTimes.length = 0;
263 player.duration(4);
264 player.trigger('durationchange');
265 await flushAsyncWork(window, 14);
266
267 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]));
268
269 window.close();
270 });
271
230 272 test('prefetches at least through the buffered video end', async () =>
231 273 {
232 274 const window = createWindow();
@@ -227,6 +227,48 @@ describe('shared image subtitle prefetching', () =>
227 window.close();
227 window.close();
228 });
228 });
229
229
230 test('prefetch expands to video end when duration metadata appears later', async () =>
231 {
232 const window = createWindow();
233 const helper = loadSharedVideoPlayer(window);
234 const { player, videojs } = buildPlayerHarness(window);
235 const requestedTimes = [];
236
237 player.duration(Number.NaN);
238
239 window.fetch = jest.fn(async (url) =>
240 {
241 const parsed = new URL(url, 'http://localhost/');
242 requestedTimes.push(Number(parsed.searchParams.get('timeSeconds')));
243 return new Response(null, {
244 status: 204,
245 headers: { 'X-Subtitle-Frame-Status': 'none' },
246 });
247 });
248
249 helper.bindImageSubtitleOverlay(player, videojs, {}, {
250 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
251 }, {
252 lookaheadSeconds: 0.5,
253 initialPrefetchSeconds: 0,
254 buildFrameRequest: ({ currentTime, streamIndex }) => ({
255 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
256 }),
257 });
258
259 await flushAsyncWork(window, 6);
260 expect(requestedTimes).toContain(0);
261
262 requestedTimes.length = 0;
263 player.duration(4);
264 player.trigger('durationchange');
265 await flushAsyncWork(window, 14);
266
267 expect(requestedTimes).toEqual(expect.arrayContaining([0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]));
268
269 window.close();
270 });
271
230 test('prefetches at least through the buffered video end', async () =>
272 test('prefetches at least through the buffered video end', async () =>
231 {
273 {
232 const window = createWindow();
274 const window = createWindow();