BlueGit

timfa filemanager

fixes

timfa Tim Falken · pushed by timfa

Authored 2026-05-30 · 5 months ago

Hash
fd5ad945db582a9d4860ec2e07ee792a234e4278
Parent
d5e89988
7 files changed +149 −21
.github/technical-reference.md +2 −2
@@ -211,7 +211,7 @@
211 211 ## public/shared-video-player.js
212 212 - 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.
213 213 - 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.
214 - 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) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, honours an explicitly saved `off` state (`null` name/index) instead of falling back to stream 0/defaults, retries saved/default selection on early `loadedmetadata`/`loadedplaylist` events while no image track is active yet, 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.
215 215 - 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.
216 216 - 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.
217 217 - bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Double-buffering for smooth rapid-transition captions: maintains two image buffers (primary/secondary), pre-loads next caption on secondary while displaying current on primary, swaps smoothly when transition occurs to eliminate flicker when captions appear in quick succession; tracks which frame is loaded in each buffer (`primaryBufferIndex`, `primaryFrameKey`, `secondaryFrameKey`) so the sync loop can detect pre-loaded frames and swap immediately without re-rendering.
@@ -383,7 +383,7 @@
383 383 - (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
384 384
385 385 ## public/drag-move.css
386 - .file-item.dragging - Lifted style for real dragged tile.
386 - .file-item.dragging - Hides the dragged tile chrome (background/border) so only icon/text appear to move while keeping a soft drop shadow on the visible content.
387 387 - .file-item.drop-target - Glows folder icon when drag hovers over it.
388 388 - .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
389 389 - .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
@@ -211,7 +211,7 @@
211## public/shared-video-player.js
211## public/shared-video-player.js
212- 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- 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.
213- 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- 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.
214- 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) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, honours an explicitly saved `off` state (`null` name/index) instead of falling back to stream 0/defaults, retries saved/default selection on early `loadedmetadata`/`loadedplaylist` events while no image track is active yet, 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.
215- 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.
215- 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.
216- 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.
216- 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.
217- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Double-buffering for smooth rapid-transition captions: maintains two image buffers (primary/secondary), pre-loads next caption on secondary while displaying current on primary, swaps smoothly when transition occurs to eliminate flicker when captions appear in quick succession; tracks which frame is loaded in each buffer (`primaryBufferIndex`, `primaryFrameKey`, `secondaryFrameKey`) so the sync loop can detect pre-loaded frames and swap immediately without re-rendering.
217- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Double-buffering for smooth rapid-transition captions: maintains two image buffers (primary/secondary), pre-loads next caption on secondary while displaying current on primary, swaps smoothly when transition occurs to eliminate flicker when captions appear in quick succession; tracks which frame is loaded in each buffer (`primaryBufferIndex`, `primaryFrameKey`, `secondaryFrameKey`) so the sync loop can detect pre-loaded frames and swap immediately without re-rendering.
@@ -383,7 +383,7 @@
383- (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
383- (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
384
384
385## public/drag-move.css
385## public/drag-move.css
386- .file-item.dragging - Lifted style for real dragged tile.
386- .file-item.dragging - Hides the dragged tile chrome (background/border) so only icon/text appear to move while keeping a soft drop shadow on the visible content.
387- .file-item.drop-target - Glows folder icon when drag hovers over it.
387- .file-item.drop-target - Glows folder icon when drag hovers over it.
388- .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
388- .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
389- .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
389- .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
.github/tests.md +2 −0
@@ -91,6 +91,8 @@
91 91
92 92 ## `test/shared-video-player.test.js`
93 93 - `shared image subtitle prefetching`
94 - `retries saved image subtitle selection when metadata arrives before player ready runs`
95 - `keeps image subtitles off when off was the saved preference`
94 96
95 97 ---
96 98
@@ -91,6 +91,8 @@
91
91
92## `test/shared-video-player.test.js`
92## `test/shared-video-player.test.js`
93- `shared image subtitle prefetching`
93- `shared image subtitle prefetching`
94- `retries saved image subtitle selection when metadata arrives before player ready runs`
95- `keeps image subtitles off when off was the saved preference`
94
96
95---
97---
96
98
public/app.js +10 −0
@@ -5052,6 +5052,7 @@ async function uploadFiles (fileList)
5052 5052 {
5053 5053 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5054 5054 if (!canWrite()) { toast('No write access.', 'err'); return; }
5055 if (!canStartUpload()) return;
5055 5056
5056 5057 const files = Array.from(fileList || []);
5057 5058 if (!files.length) return;
@@ -5127,6 +5128,13 @@ async function uploadFiles (fileList)
5127 5128 }
5128 5129 }
5129 5130
5131 function canStartUpload ()
5132 {
5133 if (!STATE.uploadInProgress) return true;
5134 toast('An upload is already in progress.', 'err');
5135 return false;
5136 }
5137
5130 5138 function createUploadProgressBar (text)
5131 5139 {
5132 5140 const abortSignal = createUploadAbortSignal();
@@ -5311,6 +5319,7 @@ async function uploadFolderInputFiles (fileList)
5311 5319 {
5312 5320 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5313 5321 if (!canWrite()) { toast('No write access.', 'err'); return; }
5322 if (!canStartUpload()) return;
5314 5323 if (!fileList || !fileList.length) return;
5315 5324
5316 5325 const files = Array.from(fileList);
@@ -5453,6 +5462,7 @@ async function uploadEntries (entries)
5453 5462 {
5454 5463 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5455 5464 if (!canWrite()) { toast('No write access.', 'err'); return; }
5465 if (!canStartUpload()) return;
5456 5466
5457 5467 const uploadUi = createUploadProgressBar('Scanning...');
5458 5468 const { wrap, abortSignal } = uploadUi;
@@ -5052,6 +5052,7 @@ async function uploadFiles (fileList)
5052{
5052{
5053 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5053 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5054 if (!canWrite()) { toast('No write access.', 'err'); return; }
5054 if (!canWrite()) { toast('No write access.', 'err'); return; }
5055 if (!canStartUpload()) return;
5055
5056
5056 const files = Array.from(fileList || []);
5057 const files = Array.from(fileList || []);
5057 if (!files.length) return;
5058 if (!files.length) return;
@@ -5127,6 +5128,13 @@ async function uploadFiles (fileList)
5127 }
5128 }
5128}
5129}
5129
5130
5131function canStartUpload ()
5132{
5133 if (!STATE.uploadInProgress) return true;
5134 toast('An upload is already in progress.', 'err');
5135 return false;
5136}
5137
5130function createUploadProgressBar (text)
5138function createUploadProgressBar (text)
5131{
5139{
5132 const abortSignal = createUploadAbortSignal();
5140 const abortSignal = createUploadAbortSignal();
@@ -5311,6 +5319,7 @@ async function uploadFolderInputFiles (fileList)
5311{
5319{
5312 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5320 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5313 if (!canWrite()) { toast('No write access.', 'err'); return; }
5321 if (!canWrite()) { toast('No write access.', 'err'); return; }
5322 if (!canStartUpload()) return;
5314 if (!fileList || !fileList.length) return;
5323 if (!fileList || !fileList.length) return;
5315
5324
5316 const files = Array.from(fileList);
5325 const files = Array.from(fileList);
@@ -5453,6 +5462,7 @@ async function uploadEntries (entries)
5453{
5462{
5454 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5463 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
5455 if (!canWrite()) { toast('No write access.', 'err'); return; }
5464 if (!canWrite()) { toast('No write access.', 'err'); return; }
5465 if (!canStartUpload()) return;
5456
5466
5457 const uploadUi = createUploadProgressBar('Scanning...');
5467 const uploadUi = createUploadProgressBar('Scanning...');
5458 const { wrap, abortSignal } = uploadUi;
5468 const { wrap, abortSignal } = uploadUi;
public/drag-move.css +11 −3
@@ -3,13 +3,21 @@
3 3 ========================================================= */
4 4
5 5 /* Item being actively dragged: lifted shadow + accent border */
6 .file-item.dragging {
7 box-shadow: 0 12px 32px rgba(0, 0, 0, 0.55);
8 border-color: var(--accent, #5b7fff) !important;
6 .file-item.dragging,
7 .file-item.dragging:hover,
8 .file-item.dragging.selected {
9 background: transparent !important;
10 border-color: transparent !important;
11 box-shadow: none;
9 12 z-index: 9999;
10 13 cursor: grabbing !important;
11 14 }
12 15
16 .file-item.dragging .icon,
17 .file-item.dragging .name {
18 filter: drop-shadow(0 10px 18px rgba(0, 0, 0, 0.38));
19 }
20
13 21 /* Folder highlighted while a dragged item hovers over it */
14 22 .file-item.drop-target .icon {
15 23 filter: drop-shadow(0 0 6px var(--accent, #5b7fff)) brightness(1.25);
@@ -3,13 +3,21 @@
3 ========================================================= */
3 ========================================================= */
4
4
5/* Item being actively dragged: lifted shadow + accent border */
5/* Item being actively dragged: lifted shadow + accent border */
6.file-item.dragging {
6.file-item.dragging,
7 box-shadow: 0 12px 32px rgba(0, 0, 0, 0.55);
7.file-item.dragging:hover,
8 border-color: var(--accent, #5b7fff) !important;
8.file-item.dragging.selected {
9 background: transparent !important;
10 border-color: transparent !important;
11 box-shadow: none;
9 z-index: 9999;
12 z-index: 9999;
10 cursor: grabbing !important;
13 cursor: grabbing !important;
11}
14}
12
15
16.file-item.dragging .icon,
17.file-item.dragging .name {
18 filter: drop-shadow(0 10px 18px rgba(0, 0, 0, 0.38));
19}
20
13/* Folder highlighted while a dragged item hovers over it */
21/* Folder highlighted while a dragged item hovers over it */
14.file-item.drop-target .icon {
22.file-item.drop-target .icon {
15 filter: drop-shadow(0 0 6px var(--accent, #5b7fff)) brightness(1.25);
23 filter: drop-shadow(0 0 6px var(--accent, #5b7fff)) brightness(1.25);
public/shared-video-player.js +15 −1
@@ -1938,6 +1938,12 @@
1938 1938
1939 1939 const applySavedTracks = () =>
1940 1940 {
1941 if (prefs.imageSubtitleTrackName === null || prefs.imageSubtitleTrackStreamIndex === null)
1942 {
1943 setSelectedStreamIndex(null, { persist: false });
1944 return;
1945 }
1946
1941 1947 const savedName = normaliseTrackName(prefs.imageSubtitleTrackName);
1942 1948 if (savedName)
1943 1949 {
@@ -1966,6 +1972,12 @@
1966 1972 setSelectedStreamIndex(null, { persist: false });
1967 1973 };
1968 1974
1975 const applySavedTracksIfNeeded = () =>
1976 {
1977 if (selectedStreamIndex !== null || trackDisabled) return;
1978 applySavedTracks();
1979 };
1980
1969 1981 player.imageSubtitleOverlayController = {
1970 1982 toggleMenu,
1971 1983 closeMenu,
@@ -1983,6 +1995,8 @@
1983 1995 player.on('ended', stopPlaybackClockSync);
1984 1996 player.on('ratechange', () => { void refreshFrame(true); });
1985 1997 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
1998 player.on('loadedmetadata', applySavedTracksIfNeeded);
1999 player.on('loadedplaylist', applySavedTracksIfNeeded);
1986 2000 player.on('dispose', dispose);
1987 2001 player.ready(() =>
1988 2002 {
@@ -1991,7 +2005,7 @@
1991 2005 updateMenuState();
1992 2006 updateButtonState();
1993 2007 updateSeekBarMarkers();
1994 applySavedTracks();
2008 applySavedTracksIfNeeded();
1995 2009 if (menuOpen) openMenu();
1996 2010 });
1997 2011
@@ -1938,6 +1938,12 @@
1938
1938
1939 const applySavedTracks = () =>
1939 const applySavedTracks = () =>
1940 {
1940 {
1941 if (prefs.imageSubtitleTrackName === null || prefs.imageSubtitleTrackStreamIndex === null)
1942 {
1943 setSelectedStreamIndex(null, { persist: false });
1944 return;
1945 }
1946
1941 const savedName = normaliseTrackName(prefs.imageSubtitleTrackName);
1947 const savedName = normaliseTrackName(prefs.imageSubtitleTrackName);
1942 if (savedName)
1948 if (savedName)
1943 {
1949 {
@@ -1966,6 +1972,12 @@
1966 setSelectedStreamIndex(null, { persist: false });
1972 setSelectedStreamIndex(null, { persist: false });
1967 };
1973 };
1968
1974
1975 const applySavedTracksIfNeeded = () =>
1976 {
1977 if (selectedStreamIndex !== null || trackDisabled) return;
1978 applySavedTracks();
1979 };
1980
1969 player.imageSubtitleOverlayController = {
1981 player.imageSubtitleOverlayController = {
1970 toggleMenu,
1982 toggleMenu,
1971 closeMenu,
1983 closeMenu,
@@ -1983,6 +1995,8 @@
1983 player.on('ended', stopPlaybackClockSync);
1995 player.on('ended', stopPlaybackClockSync);
1984 player.on('ratechange', () => { void refreshFrame(true); });
1996 player.on('ratechange', () => { void refreshFrame(true); });
1985 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
1997 player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
1998 player.on('loadedmetadata', applySavedTracksIfNeeded);
1999 player.on('loadedplaylist', applySavedTracksIfNeeded);
1986 player.on('dispose', dispose);
2000 player.on('dispose', dispose);
1987 player.ready(() =>
2001 player.ready(() =>
1988 {
2002 {
@@ -1991,7 +2005,7 @@
1991 updateMenuState();
2005 updateMenuState();
1992 updateButtonState();
2006 updateButtonState();
1993 updateSeekBarMarkers();
2007 updateSeekBarMarkers();
1994 applySavedTracks();
2008 applySavedTracksIfNeeded();
1995 if (menuOpen) openMenu();
2009 if (menuOpen) openMenu();
1996 });
2010 });
1997
2011
server/routes/files.js +15 −13
@@ -94,7 +94,20 @@ const storage = {
94 94 {
95 95 if (cleaned) return done(null);
96 96 cleaned = true;
97 unlinkIfExists(tempPath, done);
97
98 const removeTempFile = () => unlinkIfExists(tempPath, done);
99 if (out.closed)
100 {
101 removeTempFile();
102 return;
103 }
104
105 out.once('close', removeTempFile);
106 out.once('error', () =>
107 {
108 // The upload is already failing; close will drive temp-file cleanup.
109 });
110 if (!out.destroyed) out.destroy();
98 111 };
99 112
100 113 const fail = (err) =>
@@ -104,18 +117,7 @@ const storage = {
104 117 stopPiping();
105 118 detach();
106 119
107 const finishFailure = () =>
108 {
109 cleanup((cleanupErr) => cb(cleanupErr || err));
110 };
111
112 if (out.destroyed || out.writableEnded)
113 {
114 finishFailure();
115 return;
116 }
117
118 out.end(finishFailure);
120 cleanup((cleanupErr) => cb(cleanupErr || err));
119 121 };
120 122
121 123 const succeed = () =>
@@ -94,7 +94,20 @@ const storage = {
94 {
94 {
95 if (cleaned) return done(null);
95 if (cleaned) return done(null);
96 cleaned = true;
96 cleaned = true;
97 unlinkIfExists(tempPath, done);
97
98 const removeTempFile = () => unlinkIfExists(tempPath, done);
99 if (out.closed)
100 {
101 removeTempFile();
102 return;
103 }
104
105 out.once('close', removeTempFile);
106 out.once('error', () =>
107 {
108 // The upload is already failing; close will drive temp-file cleanup.
109 });
110 if (!out.destroyed) out.destroy();
98 };
111 };
99
112
100 const fail = (err) =>
113 const fail = (err) =>
@@ -104,18 +117,7 @@ const storage = {
104 stopPiping();
117 stopPiping();
105 detach();
118 detach();
106
119
107 const finishFailure = () =>
120 cleanup((cleanupErr) => cb(cleanupErr || err));
108 {
109 cleanup((cleanupErr) => cb(cleanupErr || err));
110 };
111
112 if (out.destroyed || out.writableEnded)
113 {
114 finishFailure();
115 return;
116 }
117
118 out.end(finishFailure);
119 };
121 };
120
122
121 const succeed = () =>
123 const succeed = () =>
tests/shared-video-player.test.js +94 −2
@@ -14,9 +14,10 @@ function flushAsyncWork (window, rounds = 6)
14 14 return chain;
15 15 }
16 16
17 function buildPlayerHarness (window)
17 function buildPlayerHarness (window, opts = {})
18 18 {
19 19 const registeredComponents = new Map();
20 const autoReady = opts.autoReady !== false;
20 21
21 22 class MockButton
22 23 {
@@ -65,6 +66,7 @@ function buildPlayerHarness (window)
65 66 const progressControlEl = window.document.createElement('div');
66 67 progressControlEl.className = 'vjs-progress-control';
67 68 playerEl.appendChild(progressControlEl);
69 const readyCallbacks = [];
68 70 let currentTime = 0;
69 71 let durationSeconds = 10;
70 72 let bufferedEndSeconds = null;
@@ -72,7 +74,13 @@ function buildPlayerHarness (window)
72 74 const player = {
73 75 ready (cb)
74 76 {
75 if (typeof cb === 'function') cb();
77 if (typeof cb !== 'function') return;
78 if (autoReady)
79 {
80 cb();
81 return;
82 }
83 readyCallbacks.push(cb);
76 84 },
77 85 on (type, fn)
78 86 {
@@ -127,6 +135,14 @@ function buildPlayerHarness (window)
127 135 },
128 136 };
129 137 },
138 flushReady ()
139 {
140 while (readyCallbacks.length)
141 {
142 const callback = readyCallbacks.shift();
143 callback();
144 }
145 },
130 146 };
131 147
132 148 return { player, videojs };
@@ -192,6 +208,82 @@ describe('shared image subtitle prefetching', () =>
192 208 window.close();
193 209 });
194 210
211 test('retries saved image subtitle selection when metadata arrives before player ready runs', async () =>
212 {
213 const window = createWindow();
214 const helper = loadSharedVideoPlayer(window);
215 const { player, videojs } = buildPlayerHarness(window, { autoReady: false });
216 const savedPatches = [];
217
218 window.fetch = jest.fn(async () => new Response(null, {
219 status: 204,
220 headers: { 'X-Subtitle-Frame-Status': 'none' },
221 }));
222
223 const controller = helper.bindImageSubtitleOverlay(player, videojs, {
224 imageSubtitleTrackName: 'PGS English',
225 }, {
226 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: false }],
227 }, {
228 savePrefs: (patch) => savedPatches.push(patch),
229 buildFrameRequest: ({ currentTime, streamIndex }) => ({
230 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
231 }),
232 });
233
234 player.trigger('loadedmetadata');
235 controller.captureSelectedTracks();
236 await flushAsyncWork(window);
237
238 expect(savedPatches).toEqual(expect.arrayContaining([
239 expect.objectContaining({
240 imageSubtitleTrackStreamIndex: 0,
241 imageSubtitleTrackName: 'PGS English',
242 }),
243 ]));
244
245 window.close();
246 });
247
248 test('keeps image subtitles off when off was the saved preference', async () =>
249 {
250 const window = createWindow();
251 const helper = loadSharedVideoPlayer(window);
252 const { player, videojs } = buildPlayerHarness(window);
253 const savedPatches = [];
254
255 window.fetch = jest.fn(async () => new Response(null, {
256 status: 204,
257 headers: { 'X-Subtitle-Frame-Status': 'none' },
258 }));
259
260 const controller = helper.bindImageSubtitleOverlay(player, videojs, {
261 imageSubtitleTrackName: null,
262 imageSubtitleTrackStreamIndex: null,
263 }, {
264 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
265 }, {
266 savePrefs: (patch) => savedPatches.push(patch),
267 buildFrameRequest: ({ currentTime, streamIndex }) => ({
268 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
269 }),
270 });
271
272 controller.captureSelectedTracks();
273 await flushAsyncWork(window);
274
275 expect(savedPatches).toEqual(expect.arrayContaining([
276 expect.objectContaining({
277 imageSubtitleTrackStreamIndex: null,
278 imageSubtitleTrackName: null,
279 }),
280 ]));
281
282 expect(window.fetch).not.toHaveBeenCalled();
283
284 window.close();
285 });
286
195 287 test('prefetches subtitle frames through known video duration even with short lookahead', async () =>
196 288 {
197 289 const window = createWindow();
@@ -14,9 +14,10 @@ function flushAsyncWork (window, rounds = 6)
14 return chain;
14 return chain;
15}
15}
16
16
17function buildPlayerHarness (window)
17function buildPlayerHarness (window, opts = {})
18{
18{
19 const registeredComponents = new Map();
19 const registeredComponents = new Map();
20 const autoReady = opts.autoReady !== false;
20
21
21 class MockButton
22 class MockButton
22 {
23 {
@@ -65,6 +66,7 @@ function buildPlayerHarness (window)
65 const progressControlEl = window.document.createElement('div');
66 const progressControlEl = window.document.createElement('div');
66 progressControlEl.className = 'vjs-progress-control';
67 progressControlEl.className = 'vjs-progress-control';
67 playerEl.appendChild(progressControlEl);
68 playerEl.appendChild(progressControlEl);
69 const readyCallbacks = [];
68 let currentTime = 0;
70 let currentTime = 0;
69 let durationSeconds = 10;
71 let durationSeconds = 10;
70 let bufferedEndSeconds = null;
72 let bufferedEndSeconds = null;
@@ -72,7 +74,13 @@ function buildPlayerHarness (window)
72 const player = {
74 const player = {
73 ready (cb)
75 ready (cb)
74 {
76 {
75 if (typeof cb === 'function') cb();
77 if (typeof cb !== 'function') return;
78 if (autoReady)
79 {
80 cb();
81 return;
82 }
83 readyCallbacks.push(cb);
76 },
84 },
77 on (type, fn)
85 on (type, fn)
78 {
86 {
@@ -127,6 +135,14 @@ function buildPlayerHarness (window)
127 },
135 },
128 };
136 };
129 },
137 },
138 flushReady ()
139 {
140 while (readyCallbacks.length)
141 {
142 const callback = readyCallbacks.shift();
143 callback();
144 }
145 },
130 };
146 };
131
147
132 return { player, videojs };
148 return { player, videojs };
@@ -192,6 +208,82 @@ describe('shared image subtitle prefetching', () =>
192 window.close();
208 window.close();
193 });
209 });
194
210
211 test('retries saved image subtitle selection when metadata arrives before player ready runs', async () =>
212 {
213 const window = createWindow();
214 const helper = loadSharedVideoPlayer(window);
215 const { player, videojs } = buildPlayerHarness(window, { autoReady: false });
216 const savedPatches = [];
217
218 window.fetch = jest.fn(async () => new Response(null, {
219 status: 204,
220 headers: { 'X-Subtitle-Frame-Status': 'none' },
221 }));
222
223 const controller = helper.bindImageSubtitleOverlay(player, videojs, {
224 imageSubtitleTrackName: 'PGS English',
225 }, {
226 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: false }],
227 }, {
228 savePrefs: (patch) => savedPatches.push(patch),
229 buildFrameRequest: ({ currentTime, streamIndex }) => ({
230 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
231 }),
232 });
233
234 player.trigger('loadedmetadata');
235 controller.captureSelectedTracks();
236 await flushAsyncWork(window);
237
238 expect(savedPatches).toEqual(expect.arrayContaining([
239 expect.objectContaining({
240 imageSubtitleTrackStreamIndex: 0,
241 imageSubtitleTrackName: 'PGS English',
242 }),
243 ]));
244
245 window.close();
246 });
247
248 test('keeps image subtitles off when off was the saved preference', async () =>
249 {
250 const window = createWindow();
251 const helper = loadSharedVideoPlayer(window);
252 const { player, videojs } = buildPlayerHarness(window);
253 const savedPatches = [];
254
255 window.fetch = jest.fn(async () => new Response(null, {
256 status: 204,
257 headers: { 'X-Subtitle-Frame-Status': 'none' },
258 }));
259
260 const controller = helper.bindImageSubtitleOverlay(player, videojs, {
261 imageSubtitleTrackName: null,
262 imageSubtitleTrackStreamIndex: null,
263 }, {
264 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
265 }, {
266 savePrefs: (patch) => savedPatches.push(patch),
267 buildFrameRequest: ({ currentTime, streamIndex }) => ({
268 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
269 }),
270 });
271
272 controller.captureSelectedTracks();
273 await flushAsyncWork(window);
274
275 expect(savedPatches).toEqual(expect.arrayContaining([
276 expect.objectContaining({
277 imageSubtitleTrackStreamIndex: null,
278 imageSubtitleTrackName: null,
279 }),
280 ]));
281
282 expect(window.fetch).not.toHaveBeenCalled();
283
284 window.close();
285 });
286
195 test('prefetches subtitle frames through known video duration even with short lookahead', async () =>
287 test('prefetches subtitle frames through known video duration even with short lookahead', async () =>
196 {
288 {
197 const window = createWindow();
289 const window = createWindow();