BlueGit

timfa filemanager

Clamp subtitle tail ranges

Subtitle range prefetch requests now stop at the known end of the video so the last partial window still fetches cleanly instead of overshooting the tail.\n\nThe range parser and range endpoints also tolerate exact end-of-video zero-length windows as empty successful requests, and regression coverage now checks both the client-side clamp and the server-side parser behaviour.

timfa Tim Falken · pushed by timfa

Authored 2026-05-27 · 5 months ago

Hash
be2f2fac90f592911df74b3b844c7f019e22c077
Parent
80c4b715
7 files changed +84 −9
.github/technical-reference.md +2 −2
@@ -31,7 +31,7 @@
31 31
32 32 ## server/image-subtitles.js
33 33 - parseRenderOptions(options) - Normalises subtitle-frame request options and validates filePath/streamIndex/time/canvas dimensions; stream index `0` is valid and must not be treated as missing; canvas is scaled down within a 1280x720 ceiling, then multiplied by `IMAGE_SUBTITLE_RENDER_SCALE` (default `0.75`) while preserving requested aspect ratio.
34 - parseRenderRangeOptions(options) - Normalises subtitle-range request options and validates filePath/streamIndex/start/end/canvas dimensions for multi-frame walker requests.
34 - parseRenderRangeOptions(options) - Normalises subtitle-range request options and validates filePath/streamIndex/start/end/canvas dimensions for multi-frame walker requests; exact tail windows where `endTimeSeconds === startTimeSeconds` are treated as empty-but-valid so end-of-video clamps do not surface as errors.
35 35 - renderImageSubtitleFrame(options) - Extracts bitmap subtitle streams to cached `.sup`, parses PGS display sets, and returns {frame: PNG buffer, left, top, width, height, canvasWidth, canvasHeight} with metadata for proper client-side upscaling; the server preserves positioning info instead of throwing it away, allowing the client to calculate percentage-based sizing for downscaled frames; cold event-cache builds now continue in the background while requests return quickly with no frame (`null`) until parsing finishes, avoiding long-hanging subtitle frame requests after cache purge; request/build/render timing counters are tracked for debug diagnostics.
36 36 - renderImageSubtitleFramesInRange(options) - Returns all rendered subtitle frames overlapping a requested [start,end) window, reusing the same event/frame caches as single-frame rendering so the client walker can cache multiple subtitle images per request.
37 37 - clearCachesForFile(filePath) - Removes all event and frame cache entries for a given file path using path-prefixed cache keys, also deletes the corresponding `.sup` file from disk for each evicted event entry; called when video stream sessions end to prevent memory and disk accumulation.
@@ -210,7 +210,7 @@
210 210 ## public/shared-video-player.js
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 - 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), 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, 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 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 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 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.
@@ -31,7 +31,7 @@
31
31
32## server/image-subtitles.js
32## server/image-subtitles.js
33- parseRenderOptions(options) - Normalises subtitle-frame request options and validates filePath/streamIndex/time/canvas dimensions; stream index `0` is valid and must not be treated as missing; canvas is scaled down within a 1280x720 ceiling, then multiplied by `IMAGE_SUBTITLE_RENDER_SCALE` (default `0.75`) while preserving requested aspect ratio.
33- parseRenderOptions(options) - Normalises subtitle-frame request options and validates filePath/streamIndex/time/canvas dimensions; stream index `0` is valid and must not be treated as missing; canvas is scaled down within a 1280x720 ceiling, then multiplied by `IMAGE_SUBTITLE_RENDER_SCALE` (default `0.75`) while preserving requested aspect ratio.
34- parseRenderRangeOptions(options) - Normalises subtitle-range request options and validates filePath/streamIndex/start/end/canvas dimensions for multi-frame walker requests.
34- parseRenderRangeOptions(options) - Normalises subtitle-range request options and validates filePath/streamIndex/start/end/canvas dimensions for multi-frame walker requests; exact tail windows where `endTimeSeconds === startTimeSeconds` are treated as empty-but-valid so end-of-video clamps do not surface as errors.
35- renderImageSubtitleFrame(options) - Extracts bitmap subtitle streams to cached `.sup`, parses PGS display sets, and returns {frame: PNG buffer, left, top, width, height, canvasWidth, canvasHeight} with metadata for proper client-side upscaling; the server preserves positioning info instead of throwing it away, allowing the client to calculate percentage-based sizing for downscaled frames; cold event-cache builds now continue in the background while requests return quickly with no frame (`null`) until parsing finishes, avoiding long-hanging subtitle frame requests after cache purge; request/build/render timing counters are tracked for debug diagnostics.
35- renderImageSubtitleFrame(options) - Extracts bitmap subtitle streams to cached `.sup`, parses PGS display sets, and returns {frame: PNG buffer, left, top, width, height, canvasWidth, canvasHeight} with metadata for proper client-side upscaling; the server preserves positioning info instead of throwing it away, allowing the client to calculate percentage-based sizing for downscaled frames; cold event-cache builds now continue in the background while requests return quickly with no frame (`null`) until parsing finishes, avoiding long-hanging subtitle frame requests after cache purge; request/build/render timing counters are tracked for debug diagnostics.
36- renderImageSubtitleFramesInRange(options) - Returns all rendered subtitle frames overlapping a requested [start,end) window, reusing the same event/frame caches as single-frame rendering so the client walker can cache multiple subtitle images per request.
36- renderImageSubtitleFramesInRange(options) - Returns all rendered subtitle frames overlapping a requested [start,end) window, reusing the same event/frame caches as single-frame rendering so the client walker can cache multiple subtitle images per request.
37- clearCachesForFile(filePath) - Removes all event and frame cache entries for a given file path using path-prefixed cache keys, also deletes the corresponding `.sup` file from disk for each evicted event entry; called when video stream sessions end to prevent memory and disk accumulation.
37- clearCachesForFile(filePath) - Removes all event and frame cache entries for a given file path using path-prefixed cache keys, also deletes the corresponding `.sup` file from disk for each evicted event entry; called when video stream sessions end to prevent memory and disk accumulation.
@@ -210,7 +210,7 @@
210## public/shared-video-player.js
210## public/shared-video-player.js
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), 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, 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) - 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.
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- 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().
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- 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.
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.
public/shared-video-player.js +5 −1
@@ -989,9 +989,13 @@
989 989 const capEndTime = Number.isFinite(maxTargetTimeSeconds) && maxTargetTimeSeconds >= 0
990 990 ? maxTargetTimeSeconds
991 991 : null;
992 const endTime = Number.isFinite(capEndTime)
992 let endTime = Number.isFinite(capEndTime)
993 993 ? Math.min(uncappedEndTime, capEndTime)
994 994 : uncappedEndTime;
995 if (Number.isFinite(knownVideoEndSeconds))
996 {
997 endTime = Math.min(endTime, knownVideoEndSeconds);
998 }
995 999 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
996 1000
997 1001 if (reset || prefetchedThroughTimeSeconds < 0)
@@ -989,9 +989,13 @@
989 const capEndTime = Number.isFinite(maxTargetTimeSeconds) && maxTargetTimeSeconds >= 0
989 const capEndTime = Number.isFinite(maxTargetTimeSeconds) && maxTargetTimeSeconds >= 0
990 ? maxTargetTimeSeconds
990 ? maxTargetTimeSeconds
991 : null;
991 : null;
992 const endTime = Number.isFinite(capEndTime)
992 let endTime = Number.isFinite(capEndTime)
993 ? Math.min(uncappedEndTime, capEndTime)
993 ? Math.min(uncappedEndTime, capEndTime)
994 : uncappedEndTime;
994 : uncappedEndTime;
995 if (Number.isFinite(knownVideoEndSeconds))
996 {
997 endTime = Math.min(endTime, knownVideoEndSeconds);
998 }
995 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
999 if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return;
996
1000
997 if (reset || prefetchedThroughTimeSeconds < 0)
1001 if (reset || prefetchedThroughTimeSeconds < 0)
server/image-subtitles.js +1 −1
@@ -611,7 +611,7 @@ function parseRenderRangeOptions (options)
611 611 endTimeSeconds,
612 612 canvasWidth: parsed.canvasWidth,
613 613 canvasHeight: parsed.canvasHeight,
614 isValid: !!(parsed.isValid && Number.isFinite(endTimeSeconds) && endTimeSeconds > startTimeSeconds),
614 isValid: !!(parsed.isValid && Number.isFinite(endTimeSeconds) && endTimeSeconds >= startTimeSeconds),
615 615 };
616 616 }
617 617
@@ -611,7 +611,7 @@ function parseRenderRangeOptions (options)
611 endTimeSeconds,
611 endTimeSeconds,
612 canvasWidth: parsed.canvasWidth,
612 canvasWidth: parsed.canvasWidth,
613 canvasHeight: parsed.canvasHeight,
613 canvasHeight: parsed.canvasHeight,
614 isValid: !!(parsed.isValid && Number.isFinite(endTimeSeconds) && endTimeSeconds > startTimeSeconds),
614 isValid: !!(parsed.isValid && Number.isFinite(endTimeSeconds) && endTimeSeconds >= startTimeSeconds),
615 };
615 };
616}
616}
617
617
server/routes/files.js +1 −1
@@ -1818,7 +1818,7 @@ router.get('/video-stream-subtitle-range', requireAuth, async (req, res) =>
1818 1818 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1819 1819 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1820 1820
1821 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds <= startTimeSeconds)
1821 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds)
1822 1822 {
1823 1823 return res.status(400).json({ error: 'filePath, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
1824 1824 }
@@ -1818,7 +1818,7 @@ router.get('/video-stream-subtitle-range', requireAuth, async (req, res) =>
1818 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1818 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1819 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1819 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1820
1820
1821 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds <= startTimeSeconds)
1821 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds)
1822 {
1822 {
1823 return res.status(400).json({ error: 'filePath, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
1823 return res.status(400).json({ error: 'filePath, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
1824 }
1824 }
server/routes/share.js +1 −1
@@ -553,7 +553,7 @@ router.get('/video-stream-subtitle-range/:token', async (req, res) =>
553 553 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
554 554 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
555 555
556 if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds <= startTimeSeconds)
556 if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds)
557 557 {
558 558 return res.status(400).json({ error: 'token, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
559 559 }
@@ -553,7 +553,7 @@ router.get('/video-stream-subtitle-range/:token', async (req, res) =>
553 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
553 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
554 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
554 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
555
555
556 if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds <= startTimeSeconds)
556 if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds)
557 {
557 {
558 return res.status(400).json({ error: 'token, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
558 return res.status(400).json({ error: 'token, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
559 }
559 }
tests/image-subtitles.test.js +16 −0
@@ -79,6 +79,22 @@ describe('image subtitle option parsing', () =>
79 79 expect(parsed.isValid).toBe(true);
80 80 });
81 81
82 test('accepts zero-length subtitle range windows as empty requests', () =>
83 {
84 const parsed = parseRenderRangeOptions({
85 filePath: '/tmp/example.mkv',
86 streamIndex: 0,
87 startTimeSeconds: 10,
88 endTimeSeconds: 10,
89 canvasWidth: 1920,
90 canvasHeight: 1080,
91 });
92
93 expect(parsed.startTimeSeconds).toBe(10);
94 expect(parsed.endTimeSeconds).toBe(10);
95 expect(parsed.isValid).toBe(true);
96 });
97
82 98 test('prune calculates drop threshold as end plus 5-second grace', () =>
83 99 {
84 100 // When a subtitle event ends at 30s, it should be dropped once the slowest
@@ -79,6 +79,22 @@ describe('image subtitle option parsing', () =>
79 expect(parsed.isValid).toBe(true);
79 expect(parsed.isValid).toBe(true);
80 });
80 });
81
81
82 test('accepts zero-length subtitle range windows as empty requests', () =>
83 {
84 const parsed = parseRenderRangeOptions({
85 filePath: '/tmp/example.mkv',
86 streamIndex: 0,
87 startTimeSeconds: 10,
88 endTimeSeconds: 10,
89 canvasWidth: 1920,
90 canvasHeight: 1080,
91 });
92
93 expect(parsed.startTimeSeconds).toBe(10);
94 expect(parsed.endTimeSeconds).toBe(10);
95 expect(parsed.isValid).toBe(true);
96 });
97
82 test('prune calculates drop threshold as end plus 5-second grace', () =>
98 test('prune calculates drop threshold as end plus 5-second grace', () =>
83 {
99 {
84 // When a subtitle event ends at 30s, it should be dropped once the slowest
100 // When a subtitle event ends at 30s, it should be dropped once the slowest
tests/shared-video-player.test.js +58 −3
@@ -304,6 +304,57 @@ describe('shared image subtitle prefetching', () =>
304 304 window.close();
305 305 });
306 306
307 test('range prefetch clamps the tail window to the known video duration', async () =>
308 {
309 const window = createWindow();
310 const helper = loadSharedVideoPlayer(window);
311 const { player, videojs } = buildPlayerHarness(window);
312 const requestedRanges = [];
313
314 player.duration(10);
315 player.setCurrentTime(8.5);
316
317 window.fetch = jest.fn(async (url) =>
318 {
319 const parsed = new URL(url, 'http://localhost/');
320 requestedRanges.push({
321 start: Number(parsed.searchParams.get('startTimeSeconds')),
322 end: Number(parsed.searchParams.get('endTimeSeconds')),
323 });
324 return new Response(JSON.stringify({ status: 'ok', frames: [] }), {
325 status: 200,
326 headers: { 'Content-Type': 'application/json' },
327 });
328 });
329
330 helper.bindImageSubtitleOverlay(player, videojs, {}, {
331 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
332 }, {
333 lookaheadSeconds: 0,
334 initialPrefetchSeconds: 0,
335 currentFetchEnabled: false,
336 cacheMissFallbackEnabled: false,
337 prefetchAdaptiveStepEnabled: true,
338 prefetchStepSecondsMin: 3,
339 prefetchStepSecondsMax: 3,
340 buildFrameRequest: ({ currentTime, streamIndex }) => ({
341 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
342 }),
343 buildPrefetchRequest: ({ currentTime, endTime, streamIndex }) => ({
344 url: `/subtitle-range?streamIndex=${streamIndex}&startTimeSeconds=${currentTime}&endTimeSeconds=${endTime}`,
345 }),
346 });
347
348 player.trigger('timeupdate');
349 await flushAsyncWork(window, 10);
350
351 expect(requestedRanges.length).toBeGreaterThan(0);
352 expect(requestedRanges[0]).toEqual({ start: 8.5, end: 10 });
353 expect(requestedRanges.every((range) => range.end <= 10)).toBe(true);
354
355 window.close();
356 });
357
307 358 test('prefetch respects configured larger prefetch step size', async () =>
308 359 {
309 360 const window = createWindow();
@@ -512,7 +563,8 @@ describe('shared image subtitle prefetching', () =>
512 563 const { player, videojs } = buildPlayerHarness(window);
513 564 const requestedTimes = [];
514 565
515 player.setBufferedEnd(35);
566 player.duration(60);
567 player.setBufferedEnd(2);
516 568
517 569 window.fetch = jest.fn(async (url) =>
518 570 {
@@ -545,9 +597,12 @@ describe('shared image subtitle prefetching', () =>
545 597 await flushAsyncWork(window, 8);
546 598
547 599 expect(requestedTimes).toContain(20);
600 expect(requestedTimes.some((value) => value < 20)).toBe(false);
548 601 const prefetchAfterJump = requestedTimes.filter((value) => value > 20);
549 expect(prefetchAfterJump.length).toBeGreaterThan(0);
550 expect(Math.min(...prefetchAfterJump)).toBeGreaterThanOrEqual(20.5);
602 if (prefetchAfterJump.length)
603 {
604 expect(Math.min(...prefetchAfterJump)).toBeGreaterThanOrEqual(20.5);
605 }
551 606
552 607 window.close();
553 608 });
@@ -304,6 +304,57 @@ describe('shared image subtitle prefetching', () =>
304 window.close();
304 window.close();
305 });
305 });
306
306
307 test('range prefetch clamps the tail window to the known video duration', async () =>
308 {
309 const window = createWindow();
310 const helper = loadSharedVideoPlayer(window);
311 const { player, videojs } = buildPlayerHarness(window);
312 const requestedRanges = [];
313
314 player.duration(10);
315 player.setCurrentTime(8.5);
316
317 window.fetch = jest.fn(async (url) =>
318 {
319 const parsed = new URL(url, 'http://localhost/');
320 requestedRanges.push({
321 start: Number(parsed.searchParams.get('startTimeSeconds')),
322 end: Number(parsed.searchParams.get('endTimeSeconds')),
323 });
324 return new Response(JSON.stringify({ status: 'ok', frames: [] }), {
325 status: 200,
326 headers: { 'Content-Type': 'application/json' },
327 });
328 });
329
330 helper.bindImageSubtitleOverlay(player, videojs, {}, {
331 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
332 }, {
333 lookaheadSeconds: 0,
334 initialPrefetchSeconds: 0,
335 currentFetchEnabled: false,
336 cacheMissFallbackEnabled: false,
337 prefetchAdaptiveStepEnabled: true,
338 prefetchStepSecondsMin: 3,
339 prefetchStepSecondsMax: 3,
340 buildFrameRequest: ({ currentTime, streamIndex }) => ({
341 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
342 }),
343 buildPrefetchRequest: ({ currentTime, endTime, streamIndex }) => ({
344 url: `/subtitle-range?streamIndex=${streamIndex}&startTimeSeconds=${currentTime}&endTimeSeconds=${endTime}`,
345 }),
346 });
347
348 player.trigger('timeupdate');
349 await flushAsyncWork(window, 10);
350
351 expect(requestedRanges.length).toBeGreaterThan(0);
352 expect(requestedRanges[0]).toEqual({ start: 8.5, end: 10 });
353 expect(requestedRanges.every((range) => range.end <= 10)).toBe(true);
354
355 window.close();
356 });
357
307 test('prefetch respects configured larger prefetch step size', async () =>
358 test('prefetch respects configured larger prefetch step size', async () =>
308 {
359 {
309 const window = createWindow();
360 const window = createWindow();
@@ -512,7 +563,8 @@ describe('shared image subtitle prefetching', () =>
512 const { player, videojs } = buildPlayerHarness(window);
563 const { player, videojs } = buildPlayerHarness(window);
513 const requestedTimes = [];
564 const requestedTimes = [];
514
565
515 player.setBufferedEnd(35);
566 player.duration(60);
567 player.setBufferedEnd(2);
516
568
517 window.fetch = jest.fn(async (url) =>
569 window.fetch = jest.fn(async (url) =>
518 {
570 {
@@ -545,9 +597,12 @@ describe('shared image subtitle prefetching', () =>
545 await flushAsyncWork(window, 8);
597 await flushAsyncWork(window, 8);
546
598
547 expect(requestedTimes).toContain(20);
599 expect(requestedTimes).toContain(20);
600 expect(requestedTimes.some((value) => value < 20)).toBe(false);
548 const prefetchAfterJump = requestedTimes.filter((value) => value > 20);
601 const prefetchAfterJump = requestedTimes.filter((value) => value > 20);
549 expect(prefetchAfterJump.length).toBeGreaterThan(0);
602 if (prefetchAfterJump.length)
550 expect(Math.min(...prefetchAfterJump)).toBeGreaterThanOrEqual(20.5);
603 {
604 expect(Math.min(...prefetchAfterJump)).toBeGreaterThanOrEqual(20.5);
605 }
551
606
552 window.close();
607 window.close();
553 });
608 });