BlueGit

timfa filemanager

Add subtitle runtime logging

Record live subtitle request timing in the browser console and persist batched diagnostics to capped local cache log files for both authenticated playback and share playback.

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

Hash
b5c1f94d309ee88de97949eaf58bbde2535eda40
Parent
fe80f2a9
12 files changed +680 −4
.github/technical-reference.md +11 −4
@@ -9,6 +9,11 @@
9 9 ## server/logger.js
10 10 - logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
11 11
12 ## server/subtitle-debug-log.js
13 - appendSubtitleDebugEntries({ videoName, entries, context }) - Appends client-side subtitle timing events to a dated per-video text log under the local temp cache (`yyyy-mm-dd-videoname-subtitlelog.txt`), merging static context into each line and pruning the oldest files when the subtitle log cache exceeds 10 MB.
14 - pruneSubtitleDebugLogDir() - Enforces the 10 MB total subtitle-log cache budget by deleting the oldest log files first.
15 - subtitleDebugLogFilePath(videoName, timestampMs) - Resolves the per-day subtitle timing log path for a video name using a filesystem-safe filename.
16
12 17 ## server/image-subtitles.js
13 18 - 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.
14 19 - 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; request/build/render timing counters are tracked for debug diagnostics.
@@ -106,7 +111,8 @@
106 111 - POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
107 112 - POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
108 113 - POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
109 - GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height} to communicate frame placement and dimensions for client-side upscaling; on failures or no active subtitle it returns 204 so the client can stop retrying.
114 - GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height,Start-Time,End-Time} plus X-Subtitle-{Request-Received-At-Ms,Response-Sent-At-Ms} so the client can log subtitle timing against server send time; on failures or no active subtitle it returns 204 so the client can stop retrying.
115 - POST /api/files/video-stream-subtitle-log - Authenticated. Accepts batched client-side subtitle timing events for an authorised file and appends them to the local subtitle debug-log cache with file path, username, and stream session context.
110 116 - DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
111 117 - POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
112 118 - POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
@@ -120,7 +126,8 @@
120 126 - GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
121 127 - GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
122 128 - GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
123 - GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
129 - GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns the same subtitle timing headers as the authenticated route and 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
130 - POST /api/share/video-stream-subtitle-log/:token - Public. Accepts batched client-side subtitle timing events for a valid shared-video token and appends them to the local subtitle debug-log cache with share-token and stream-session context.
124 131 - DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
125 132 - buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
126 133 - buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
@@ -161,7 +168,7 @@
161 168 ## public/shared-video-player.js
162 169 - 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.
163 170 - 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.
164 - 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), aborts stale current/prefetch fetches on seek/track-switch/dispose, and disables the track after the first hard failure.
171 - 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), aborts stale current/prefetch fetches on seek/track-switch/dispose, logs current subtitle request/send/receive/show timing to the browser console and optional batch sink, and disables the track after the first hard failure.
165 172 - configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
166 173 - ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
167 174
@@ -229,7 +236,7 @@
229 236 - setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
230 237 - buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
231 238 - buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
232 - 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), and disables the track after the first failed frame request to avoid repeated polling; reads X-Subtitle-Frame-* headers from server responses and calculates percentage-based sizing (frameWidth / canvasWidth * 100%) to properly upscale downscaled frames while maintaining proportions.
239 - 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.
233 240 - renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, 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.
234 241 - modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
235 242 - loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
@@ -9,6 +9,11 @@
9## server/logger.js
9## server/logger.js
10- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
10- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
11
11
12## server/subtitle-debug-log.js
13- appendSubtitleDebugEntries({ videoName, entries, context }) - Appends client-side subtitle timing events to a dated per-video text log under the local temp cache (`yyyy-mm-dd-videoname-subtitlelog.txt`), merging static context into each line and pruning the oldest files when the subtitle log cache exceeds 10 MB.
14- pruneSubtitleDebugLogDir() - Enforces the 10 MB total subtitle-log cache budget by deleting the oldest log files first.
15- subtitleDebugLogFilePath(videoName, timestampMs) - Resolves the per-day subtitle timing log path for a video name using a filesystem-safe filename.
16
12## server/image-subtitles.js
17## server/image-subtitles.js
13- 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.
18- 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.
14- 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; request/build/render timing counters are tracked for debug diagnostics.
19- 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; request/build/render timing counters are tracked for debug diagnostics.
@@ -106,7 +111,8 @@
106- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
111- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
107- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
112- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
108- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
113- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
109- GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height} to communicate frame placement and dimensions for client-side upscaling; on failures or no active subtitle it returns 204 so the client can stop retrying.
114- GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height,Start-Time,End-Time} plus X-Subtitle-{Request-Received-At-Ms,Response-Sent-At-Ms} so the client can log subtitle timing against server send time; on failures or no active subtitle it returns 204 so the client can stop retrying.
115- POST /api/files/video-stream-subtitle-log - Authenticated. Accepts batched client-side subtitle timing events for an authorised file and appends them to the local subtitle debug-log cache with file path, username, and stream session context.
110- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
116- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
111- POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
117- POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
112- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
118- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
@@ -120,7 +126,8 @@
120- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
126- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
121- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
127- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
122- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
128- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
123- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
129- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns the same subtitle timing headers as the authenticated route and 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
130- POST /api/share/video-stream-subtitle-log/:token - Public. Accepts batched client-side subtitle timing events for a valid shared-video token and appends them to the local subtitle debug-log cache with share-token and stream-session context.
124- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
131- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
125- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
132- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
126- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
133- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
@@ -161,7 +168,7 @@
161## public/shared-video-player.js
168## public/shared-video-player.js
162- 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.
169- 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.
163- 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.
170- 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.
164- 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), aborts stale current/prefetch fetches on seek/track-switch/dispose, and disables the track after the first hard failure.
171- 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), aborts stale current/prefetch fetches on seek/track-switch/dispose, logs current subtitle request/send/receive/show timing to the browser console and optional batch sink, and disables the track after the first hard failure.
165- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
172- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
166- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
173- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
167
174
@@ -229,7 +236,7 @@
229- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
236- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
230- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
237- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
231- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
238- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
232- 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), and disables the track after the first failed frame request to avoid repeated polling; reads X-Subtitle-Frame-* headers from server responses and calculates percentage-based sizing (frameWidth / canvasWidth * 100%) to properly upscale downscaled frames while maintaining proportions.
239- 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.
233- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, 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.
240- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, 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.
234- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
241- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
235- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
242- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
.github/tests.md +5 −0
@@ -89,6 +89,11 @@
89 89
90 90 ---
91 91
92 ## `test/subtitle-debug-log.test.js`
93 - `subtitle debug log writer`
94
95 ---
96
92 97 ## `test/thumbnail-cache.test.js`
93 98 - `thumbnail cache worker`
94 99
@@ -89,6 +89,11 @@
89
89
90---
90---
91
91
92## `test/subtitle-debug-log.test.js`
93- `subtitle debug log writer`
94
95---
96
92## `test/thumbnail-cache.test.js`
97## `test/thumbnail-cache.test.js`
93- `thumbnail cache worker`
98- `thumbnail cache worker`
94
99
public/app.js +23 −0
@@ -400,9 +400,32 @@ function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
400 400 const shared = sharedVideoPlayer();
401 401 if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;
402 402
403 const sendSubtitleLogBatch = (entries) =>
404 {
405 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
406
407 const headers = {
408 ...buildAuthHeaders(),
409 'Content-Type': 'application/json',
410 };
411
412 return fetch('/api/files/video-stream-subtitle-log', {
413 method: 'POST',
414 headers,
415 credentials: 'same-origin',
416 keepalive: true,
417 body: JSON.stringify({
418 filePath: item.path,
419 sessionId: session.sessionId || null,
420 entries,
421 }),
422 }).catch(() => null);
423 };
424
403 425 return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {
404 426 savePrefs: saveUserVideoPrefs,
405 427 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
428 sendSubtitleLogBatch,
406 429 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
407 430 url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,
408 431 headers: buildAuthHeaders(),
@@ -400,9 +400,32 @@ function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
400 const shared = sharedVideoPlayer();
400 const shared = sharedVideoPlayer();
401 if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;
401 if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;
402
402
403 const sendSubtitleLogBatch = (entries) =>
404 {
405 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
406
407 const headers = {
408 ...buildAuthHeaders(),
409 'Content-Type': 'application/json',
410 };
411
412 return fetch('/api/files/video-stream-subtitle-log', {
413 method: 'POST',
414 headers,
415 credentials: 'same-origin',
416 keepalive: true,
417 body: JSON.stringify({
418 filePath: item.path,
419 sessionId: session.sessionId || null,
420 entries,
421 }),
422 }).catch(() => null);
423 };
424
403 return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {
425 return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {
404 savePrefs: saveUserVideoPrefs,
426 savePrefs: saveUserVideoPrefs,
405 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
427 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
428 sendSubtitleLogBatch,
406 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
429 buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
407 url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,
430 url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,
408 headers: buildAuthHeaders(),
431 headers: buildAuthHeaders(),
public/share.html +16 −0
@@ -463,6 +463,22 @@
463 463 ? shared.bindImageSubtitleOverlay(shareVideoPlayer, window.videojs, prefs, data, {
464 464 savePrefs: saveShareVideoPrefs,
465 465 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
466 sendSubtitleLogBatch: (entries) =>
467 {
468 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
469 return fetch(`/api/share/video-stream-subtitle-log/${encodeURIComponent(token)}`, {
470 method: 'POST',
471 credentials: 'same-origin',
472 keepalive: true,
473 headers: {
474 'Content-Type': 'application/json',
475 },
476 body: JSON.stringify({
477 sessionId: data.sessionId || null,
478 entries,
479 }),
480 }).catch(() => null);
481 },
466 482 buildFrameRequest: ({ currentTime, streamIndex, session }) => ({
467 483 url: `/api/share/video-stream-subtitle-frame/${encodeURIComponent(token)}?streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`,
468 484 credentials: 'same-origin',
@@ -463,6 +463,22 @@
463 ? shared.bindImageSubtitleOverlay(shareVideoPlayer, window.videojs, prefs, data, {
463 ? shared.bindImageSubtitleOverlay(shareVideoPlayer, window.videojs, prefs, data, {
464 savePrefs: saveShareVideoPrefs,
464 savePrefs: saveShareVideoPrefs,
465 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
465 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
466 sendSubtitleLogBatch: (entries) =>
467 {
468 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
469 return fetch(`/api/share/video-stream-subtitle-log/${encodeURIComponent(token)}`, {
470 method: 'POST',
471 credentials: 'same-origin',
472 keepalive: true,
473 headers: {
474 'Content-Type': 'application/json',
475 },
476 body: JSON.stringify({
477 sessionId: data.sessionId || null,
478 entries,
479 }),
480 }).catch(() => null);
481 },
466 buildFrameRequest: ({ currentTime, streamIndex, session }) => ({
482 buildFrameRequest: ({ currentTime, streamIndex, session }) => ({
467 url: `/api/share/video-stream-subtitle-frame/${encodeURIComponent(token)}?streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`,
483 url: `/api/share/video-stream-subtitle-frame/${encodeURIComponent(token)}?streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`,
468 credentials: 'same-origin',
484 credentials: 'same-origin',
public/shared-video-player.js +197 −0
@@ -7,10 +7,84 @@
7 7 backgroundOpacity: '0',
8 8 edgeStyle: 'uniform',
9 9 });
10 const SUBTITLE_LOG_BATCH_MAX_ITEMS = 12;
11 const SUBTITLE_LOG_FLUSH_DELAY_MS = 500;
10 12 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15;
11 13 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30;
12 14 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS = 0.5;
13 15
16 function roundLogNumber (value, digits = 3)
17 {
18 const numeric = Number(value);
19 if (!Number.isFinite(numeric)) return null;
20 return Number(numeric.toFixed(digits));
21 }
22
23 function parseHeaderInt (res, name)
24 {
25 if (!res || !res.headers || typeof res.headers.get !== 'function') return null;
26 const value = Number.parseInt(String(res.headers.get(name) || ''), 10);
27 return Number.isFinite(value) ? value : null;
28 }
29
30 function parseHeaderFloat (res, name)
31 {
32 if (!res || !res.headers || typeof res.headers.get !== 'function') return null;
33 const value = Number.parseFloat(String(res.headers.get(name) || ''));
34 return Number.isFinite(value) ? value : null;
35 }
36
37 function diffMilliseconds (later, earlier)
38 {
39 if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null;
40 return Math.round(later - earlier);
41 }
42
43 function diffSeconds (later, earlier)
44 {
45 if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null;
46 return roundLogNumber(later - earlier, 3);
47 }
48
49 function waitForImagePresentation (windowRef, imageEl)
50 {
51 return new Promise((resolve) =>
52 {
53 let settled = false;
54 let fallbackTimer = null;
55 const raf = typeof windowRef.requestAnimationFrame === 'function'
56 ? windowRef.requestAnimationFrame.bind(windowRef)
57 : (fn) => windowRef.setTimeout(fn, 0);
58
59 const cleanup = () =>
60 {
61 imageEl.removeEventListener('load', onLoad);
62 imageEl.removeEventListener('error', onError);
63 if (fallbackTimer !== null) windowRef.clearTimeout(fallbackTimer);
64 };
65
66 const finish = () =>
67 {
68 if (settled) return;
69 settled = true;
70 cleanup();
71 raf(() => resolve(Date.now()));
72 };
73
74 const onLoad = () => finish();
75 const onError = () => finish();
76
77 imageEl.addEventListener('load', onLoad);
78 imageEl.addEventListener('error', onError);
79 fallbackTimer = windowRef.setTimeout(finish, 250);
80
81 if (imageEl.complete && imageEl.currentSrc)
82 {
83 finish();
84 }
85 });
86 }
87
14 88 function normaliseTrackName (name)
15 89 {
16 90 return String(name || '').trim().toLowerCase();
@@ -182,6 +256,7 @@
182 256 const savePrefs = typeof opts.savePrefs === 'function' ? opts.savePrefs : (() => {});
183 257 const buildFrameRequest = typeof opts.buildFrameRequest === 'function' ? opts.buildFrameRequest : null;
184 258 const notifyError = typeof opts.onError === 'function' ? opts.onError : (() => {});
259 const sendSubtitleLogBatch = typeof opts.sendSubtitleLogBatch === 'function' ? opts.sendSubtitleLogBatch : null;
185 260 const requestedLookaheadSeconds = Number(opts.lookaheadSeconds);
186 261 const lookaheadSeconds = Number.isFinite(requestedLookaheadSeconds)
187 262 ? Math.max(0, Math.min(IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX, requestedLookaheadSeconds))
@@ -207,6 +282,66 @@
207 282 let prefetchPromise = null;
208 283 let prefetchTargetTimeSeconds = -1;
209 284 let prefetchedThroughTimeSeconds = -1;
285 let subtitleLogSequence = 0;
286 let subtitleLogQueue = [];
287 let subtitleLogFlushTimer = null;
288
289 const flushSubtitleLogs = () =>
290 {
291 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
292 if (subtitleLogFlushTimer)
293 {
294 window.clearTimeout(subtitleLogFlushTimer);
295 subtitleLogFlushTimer = null;
296 }
297
298 const batch = subtitleLogQueue;
299 subtitleLogQueue = [];
300 Promise.resolve(sendSubtitleLogBatch(batch)).catch(() =>
301 {
302 // Keep subtitle diagnostics best-effort only.
303 });
304 };
305
306 const scheduleSubtitleLogFlush = () =>
307 {
308 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
309 if (subtitleLogQueue.length >= SUBTITLE_LOG_BATCH_MAX_ITEMS)
310 {
311 flushSubtitleLogs();
312 return;
313 }
314 if (subtitleLogFlushTimer) return;
315 subtitleLogFlushTimer = window.setTimeout(() =>
316 {
317 subtitleLogFlushTimer = null;
318 flushSubtitleLogs();
319 }, SUBTITLE_LOG_FLUSH_DELAY_MS);
320 };
321
322 const logSubtitleEvent = (eventType, details = {}) =>
323 {
324 const entry = {
325 seq: ++subtitleLogSequence,
326 loggedAtMs: Date.now(),
327 eventType,
328 sessionId: String(session.sessionId || '').trim() || null,
329 streamIndex: Number.isInteger(selectedStreamIndex) ? selectedStreamIndex : null,
330 playerTimeSeconds: roundLogNumber(player.currentTime()),
331 ...details,
332 };
333 try
334 {
335 console.log('[subtitle-log]', entry);
336 } catch
337 {
338 // Ignore console availability issues.
339 }
340
341 if (!sendSubtitleLogBatch) return;
342 subtitleLogQueue.push(entry);
343 scheduleSubtitleLogFlush();
344 };
210 345
211 346 const createAbortController = () =>
212 347 {
@@ -464,6 +599,8 @@
464 599 if (force) cancelPrefetchRequests({ resetProgress: true });
465 600
466 601 const token = ++currentFrameToken;
602 const requestId = `current-${token}`;
603 const requestStartedAtMs = Date.now();
467 604 const controller = createAbortController();
468 605 currentFrameAbortController = controller;
469 606 const request = buildFrameRequest({
@@ -478,6 +615,14 @@
478 615 return;
479 616 }
480 617
618 logSubtitleEvent('subtitle_png_requested', {
619 requestId,
620 requestKind: 'current',
621 requestUrl: String(request.url || ''),
622 requestedAtMs: requestStartedAtMs,
623 requestedVideoTimeSeconds: roundLogNumber(currentTime),
624 });
625
481 626 try
482 627 {
483 628 const res = await fetch(request.url, {
@@ -489,9 +634,29 @@
489 634
490 635 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
491 636
637 const responseMeta = {
638 requestId,
639 requestKind: 'current',
640 status: res.status,
641 serverRequestReceivedAtMs: parseHeaderInt(res, 'X-Subtitle-Request-Received-At-Ms'),
642 serverResponseSentAtMs: parseHeaderInt(res, 'X-Subtitle-Response-Sent-At-Ms'),
643 shouldShowAtVideoTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'),
644 subtitleEndTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'),
645 responseHeadersReceivedAtMs: Date.now(),
646 };
647 logSubtitleEvent('subtitle_png_sent', {
648 ...responseMeta,
649 serverProcessingMs: diffMilliseconds(responseMeta.serverResponseSentAtMs, responseMeta.serverRequestReceivedAtMs),
650 sentToHeadersReceivedMs: diffMilliseconds(responseMeta.responseHeadersReceivedAtMs, responseMeta.serverResponseSentAtMs),
651 });
652
492 653 if (res.status === 204)
493 654 {
494 655 const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase();
656 logSubtitleEvent('subtitle_png_not_available', {
657 ...responseMeta,
658 frameStatus,
659 });
495 660 hideOverlay();
496 661 if (frameStatus === 'error') disableTrack();
497 662 else queueLookaheadPrefetch(currentTime, { reset: force });
@@ -507,6 +672,15 @@
507 672 const blob = await res.blob();
508 673 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
509 674
675 const receivedAtMs = Date.now();
676 logSubtitleEvent('subtitle_png_received', {
677 ...responseMeta,
678 receivedAtMs,
679 sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs),
680 requestedToReceivedMs: diffMilliseconds(receivedAtMs, requestStartedAtMs),
681 blobBytes: Number(blob && blob.size || 0),
682 });
683
510 684 if (!blob || blob.size === 0)
511 685 {
512 686 disableTrack();
@@ -541,10 +715,32 @@
541 715 overlayEl.style.display = 'block';
542 716 overlayImgEl.style.display = 'block';
543 717
718 void waitForImagePresentation(window, overlayImgEl).then((shownAtMs) =>
719 {
720 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
721 const shownAtVideoTimeSeconds = roundLogNumber(player.currentTime());
722 logSubtitleEvent('subtitle_png_shown', {
723 ...responseMeta,
724 receivedAtMs,
725 shownAtMs,
726 shownAtVideoTimeSeconds,
727 sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs),
728 receivedToShownMs: diffMilliseconds(shownAtMs, receivedAtMs),
729 shouldVsShownDiffSeconds: diffSeconds(shownAtVideoTimeSeconds, responseMeta.shouldShowAtVideoTimeSeconds),
730 });
731 });
732
544 733 queueLookaheadPrefetch(currentTime, { reset: force });
545 734 } catch (error)
546 735 {
547 736 if (isAbortError(error)) return;
737 logSubtitleEvent('subtitle_png_request_failed', {
738 requestId,
739 requestKind: 'current',
740 requestedAtMs: requestStartedAtMs,
741 errorName: error && error.name ? String(error.name) : null,
742 errorMessage: error && error.message ? String(error.message) : String(error || ''),
743 });
548 744 if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack();
549 745 }
550 746 };
@@ -552,6 +748,7 @@
552 748 const dispose = () =>
553 749 {
554 750 resetRequestState();
751 flushSubtitleLogs();
555 752 closeMenu();
556 753 hideOverlay();
557 754 if (overlayEl) overlayEl.remove();
@@ -7,10 +7,84 @@
7 backgroundOpacity: '0',
7 backgroundOpacity: '0',
8 edgeStyle: 'uniform',
8 edgeStyle: 'uniform',
9 });
9 });
10 const SUBTITLE_LOG_BATCH_MAX_ITEMS = 12;
11 const SUBTITLE_LOG_FLUSH_DELAY_MS = 500;
10 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15;
12 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15;
11 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30;
13 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30;
12 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS = 0.5;
14 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS = 0.5;
13
15
16 function roundLogNumber (value, digits = 3)
17 {
18 const numeric = Number(value);
19 if (!Number.isFinite(numeric)) return null;
20 return Number(numeric.toFixed(digits));
21 }
22
23 function parseHeaderInt (res, name)
24 {
25 if (!res || !res.headers || typeof res.headers.get !== 'function') return null;
26 const value = Number.parseInt(String(res.headers.get(name) || ''), 10);
27 return Number.isFinite(value) ? value : null;
28 }
29
30 function parseHeaderFloat (res, name)
31 {
32 if (!res || !res.headers || typeof res.headers.get !== 'function') return null;
33 const value = Number.parseFloat(String(res.headers.get(name) || ''));
34 return Number.isFinite(value) ? value : null;
35 }
36
37 function diffMilliseconds (later, earlier)
38 {
39 if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null;
40 return Math.round(later - earlier);
41 }
42
43 function diffSeconds (later, earlier)
44 {
45 if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null;
46 return roundLogNumber(later - earlier, 3);
47 }
48
49 function waitForImagePresentation (windowRef, imageEl)
50 {
51 return new Promise((resolve) =>
52 {
53 let settled = false;
54 let fallbackTimer = null;
55 const raf = typeof windowRef.requestAnimationFrame === 'function'
56 ? windowRef.requestAnimationFrame.bind(windowRef)
57 : (fn) => windowRef.setTimeout(fn, 0);
58
59 const cleanup = () =>
60 {
61 imageEl.removeEventListener('load', onLoad);
62 imageEl.removeEventListener('error', onError);
63 if (fallbackTimer !== null) windowRef.clearTimeout(fallbackTimer);
64 };
65
66 const finish = () =>
67 {
68 if (settled) return;
69 settled = true;
70 cleanup();
71 raf(() => resolve(Date.now()));
72 };
73
74 const onLoad = () => finish();
75 const onError = () => finish();
76
77 imageEl.addEventListener('load', onLoad);
78 imageEl.addEventListener('error', onError);
79 fallbackTimer = windowRef.setTimeout(finish, 250);
80
81 if (imageEl.complete && imageEl.currentSrc)
82 {
83 finish();
84 }
85 });
86 }
87
14 function normaliseTrackName (name)
88 function normaliseTrackName (name)
15 {
89 {
16 return String(name || '').trim().toLowerCase();
90 return String(name || '').trim().toLowerCase();
@@ -182,6 +256,7 @@
182 const savePrefs = typeof opts.savePrefs === 'function' ? opts.savePrefs : (() => {});
256 const savePrefs = typeof opts.savePrefs === 'function' ? opts.savePrefs : (() => {});
183 const buildFrameRequest = typeof opts.buildFrameRequest === 'function' ? opts.buildFrameRequest : null;
257 const buildFrameRequest = typeof opts.buildFrameRequest === 'function' ? opts.buildFrameRequest : null;
184 const notifyError = typeof opts.onError === 'function' ? opts.onError : (() => {});
258 const notifyError = typeof opts.onError === 'function' ? opts.onError : (() => {});
259 const sendSubtitleLogBatch = typeof opts.sendSubtitleLogBatch === 'function' ? opts.sendSubtitleLogBatch : null;
185 const requestedLookaheadSeconds = Number(opts.lookaheadSeconds);
260 const requestedLookaheadSeconds = Number(opts.lookaheadSeconds);
186 const lookaheadSeconds = Number.isFinite(requestedLookaheadSeconds)
261 const lookaheadSeconds = Number.isFinite(requestedLookaheadSeconds)
187 ? Math.max(0, Math.min(IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX, requestedLookaheadSeconds))
262 ? Math.max(0, Math.min(IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX, requestedLookaheadSeconds))
@@ -207,6 +282,66 @@
207 let prefetchPromise = null;
282 let prefetchPromise = null;
208 let prefetchTargetTimeSeconds = -1;
283 let prefetchTargetTimeSeconds = -1;
209 let prefetchedThroughTimeSeconds = -1;
284 let prefetchedThroughTimeSeconds = -1;
285 let subtitleLogSequence = 0;
286 let subtitleLogQueue = [];
287 let subtitleLogFlushTimer = null;
288
289 const flushSubtitleLogs = () =>
290 {
291 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
292 if (subtitleLogFlushTimer)
293 {
294 window.clearTimeout(subtitleLogFlushTimer);
295 subtitleLogFlushTimer = null;
296 }
297
298 const batch = subtitleLogQueue;
299 subtitleLogQueue = [];
300 Promise.resolve(sendSubtitleLogBatch(batch)).catch(() =>
301 {
302 // Keep subtitle diagnostics best-effort only.
303 });
304 };
305
306 const scheduleSubtitleLogFlush = () =>
307 {
308 if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return;
309 if (subtitleLogQueue.length >= SUBTITLE_LOG_BATCH_MAX_ITEMS)
310 {
311 flushSubtitleLogs();
312 return;
313 }
314 if (subtitleLogFlushTimer) return;
315 subtitleLogFlushTimer = window.setTimeout(() =>
316 {
317 subtitleLogFlushTimer = null;
318 flushSubtitleLogs();
319 }, SUBTITLE_LOG_FLUSH_DELAY_MS);
320 };
321
322 const logSubtitleEvent = (eventType, details = {}) =>
323 {
324 const entry = {
325 seq: ++subtitleLogSequence,
326 loggedAtMs: Date.now(),
327 eventType,
328 sessionId: String(session.sessionId || '').trim() || null,
329 streamIndex: Number.isInteger(selectedStreamIndex) ? selectedStreamIndex : null,
330 playerTimeSeconds: roundLogNumber(player.currentTime()),
331 ...details,
332 };
333 try
334 {
335 console.log('[subtitle-log]', entry);
336 } catch
337 {
338 // Ignore console availability issues.
339 }
340
341 if (!sendSubtitleLogBatch) return;
342 subtitleLogQueue.push(entry);
343 scheduleSubtitleLogFlush();
344 };
210
345
211 const createAbortController = () =>
346 const createAbortController = () =>
212 {
347 {
@@ -464,6 +599,8 @@
464 if (force) cancelPrefetchRequests({ resetProgress: true });
599 if (force) cancelPrefetchRequests({ resetProgress: true });
465
600
466 const token = ++currentFrameToken;
601 const token = ++currentFrameToken;
602 const requestId = `current-${token}`;
603 const requestStartedAtMs = Date.now();
467 const controller = createAbortController();
604 const controller = createAbortController();
468 currentFrameAbortController = controller;
605 currentFrameAbortController = controller;
469 const request = buildFrameRequest({
606 const request = buildFrameRequest({
@@ -478,6 +615,14 @@
478 return;
615 return;
479 }
616 }
480
617
618 logSubtitleEvent('subtitle_png_requested', {
619 requestId,
620 requestKind: 'current',
621 requestUrl: String(request.url || ''),
622 requestedAtMs: requestStartedAtMs,
623 requestedVideoTimeSeconds: roundLogNumber(currentTime),
624 });
625
481 try
626 try
482 {
627 {
483 const res = await fetch(request.url, {
628 const res = await fetch(request.url, {
@@ -489,9 +634,29 @@
489
634
490 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
635 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
491
636
637 const responseMeta = {
638 requestId,
639 requestKind: 'current',
640 status: res.status,
641 serverRequestReceivedAtMs: parseHeaderInt(res, 'X-Subtitle-Request-Received-At-Ms'),
642 serverResponseSentAtMs: parseHeaderInt(res, 'X-Subtitle-Response-Sent-At-Ms'),
643 shouldShowAtVideoTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'),
644 subtitleEndTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'),
645 responseHeadersReceivedAtMs: Date.now(),
646 };
647 logSubtitleEvent('subtitle_png_sent', {
648 ...responseMeta,
649 serverProcessingMs: diffMilliseconds(responseMeta.serverResponseSentAtMs, responseMeta.serverRequestReceivedAtMs),
650 sentToHeadersReceivedMs: diffMilliseconds(responseMeta.responseHeadersReceivedAtMs, responseMeta.serverResponseSentAtMs),
651 });
652
492 if (res.status === 204)
653 if (res.status === 204)
493 {
654 {
494 const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase();
655 const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase();
656 logSubtitleEvent('subtitle_png_not_available', {
657 ...responseMeta,
658 frameStatus,
659 });
495 hideOverlay();
660 hideOverlay();
496 if (frameStatus === 'error') disableTrack();
661 if (frameStatus === 'error') disableTrack();
497 else queueLookaheadPrefetch(currentTime, { reset: force });
662 else queueLookaheadPrefetch(currentTime, { reset: force });
@@ -507,6 +672,15 @@
507 const blob = await res.blob();
672 const blob = await res.blob();
508 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
673 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
509
674
675 const receivedAtMs = Date.now();
676 logSubtitleEvent('subtitle_png_received', {
677 ...responseMeta,
678 receivedAtMs,
679 sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs),
680 requestedToReceivedMs: diffMilliseconds(receivedAtMs, requestStartedAtMs),
681 blobBytes: Number(blob && blob.size || 0),
682 });
683
510 if (!blob || blob.size === 0)
684 if (!blob || blob.size === 0)
511 {
685 {
512 disableTrack();
686 disableTrack();
@@ -541,10 +715,32 @@
541 overlayEl.style.display = 'block';
715 overlayEl.style.display = 'block';
542 overlayImgEl.style.display = 'block';
716 overlayImgEl.style.display = 'block';
543
717
718 void waitForImagePresentation(window, overlayImgEl).then((shownAtMs) =>
719 {
720 if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return;
721 const shownAtVideoTimeSeconds = roundLogNumber(player.currentTime());
722 logSubtitleEvent('subtitle_png_shown', {
723 ...responseMeta,
724 receivedAtMs,
725 shownAtMs,
726 shownAtVideoTimeSeconds,
727 sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs),
728 receivedToShownMs: diffMilliseconds(shownAtMs, receivedAtMs),
729 shouldVsShownDiffSeconds: diffSeconds(shownAtVideoTimeSeconds, responseMeta.shouldShowAtVideoTimeSeconds),
730 });
731 });
732
544 queueLookaheadPrefetch(currentTime, { reset: force });
733 queueLookaheadPrefetch(currentTime, { reset: force });
545 } catch (error)
734 } catch (error)
546 {
735 {
547 if (isAbortError(error)) return;
736 if (isAbortError(error)) return;
737 logSubtitleEvent('subtitle_png_request_failed', {
738 requestId,
739 requestKind: 'current',
740 requestedAtMs: requestStartedAtMs,
741 errorName: error && error.name ? String(error.name) : null,
742 errorMessage: error && error.message ? String(error.message) : String(error || ''),
743 });
548 if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack();
744 if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack();
549 }
745 }
550 };
746 };
@@ -552,6 +748,7 @@
552 const dispose = () =>
748 const dispose = () =>
553 {
749 {
554 resetRequestState();
750 resetRequestState();
751 flushSubtitleLogs();
555 closeMenu();
752 closeMenu();
556 hideOverlay();
753 hideOverlay();
557 if (overlayEl) overlayEl.remove();
754 if (overlayEl) overlayEl.remove();
server/routes/files.js +57 −0
@@ -13,6 +13,7 @@ const { requireAuth } = require('../auth');
13 13 const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14 14 const { logError } = require('../logger');
15 15 const { renderImageSubtitleFrame } = require('../image-subtitles');
16 const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
16 17 const { buildZip } = require('./share');
17 18 const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
18 19
@@ -1553,6 +1554,7 @@ router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1553 1554 // ---------------------------------------------------------------------------
1554 1555 router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1555 1556 {
1557 const requestReceivedAtMs = Date.now();
1556 1558 try
1557 1559 {
1558 1560 const filePath = String(req.query.filePath || '').trim();
@@ -1590,10 +1592,14 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1590 1592
1591 1593 if (!frameData || !frameData.frame)
1592 1594 {
1595 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1596 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1593 1597 res.set('X-Subtitle-Frame-Status', 'none');
1594 1598 return res.status(204).end();
1595 1599 }
1596 1600
1601 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1602 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1597 1603 res.set('X-Subtitle-Frame-Status', 'ok');
1598 1604 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
1599 1605 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
@@ -1601,6 +1607,8 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1601 1607 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
1602 1608 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
1603 1609 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
1610 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
1611 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
1604 1612 res.set('Content-Type', 'image/png');
1605 1613 res.set('Cache-Control', 'private, max-age=3600');
1606 1614 res.send(frameData.frame);
@@ -1611,11 +1619,60 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1611 1619 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1612 1620 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1613 1621 });
1622 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1623 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1614 1624 res.set('X-Subtitle-Frame-Status', 'error');
1615 1625 return res.status(204).end();
1616 1626 }
1617 1627 });
1618 1628
1629 // ---------------------------------------------------------------------------
1630 // POST /api/files/video-stream-subtitle-log
1631 // Authenticated. Persists client-side subtitle timing diagnostics to local cache.
1632 // Body: { filePath, sessionId?, entries[] }
1633 // ---------------------------------------------------------------------------
1634 router.post('/video-stream-subtitle-log', requireAuth, (req, res) =>
1635 {
1636 try
1637 {
1638 const filePath = String(req.body && req.body.filePath || '').trim();
1639 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
1640 const sessionId = String(req.body && req.body.sessionId || '').trim();
1641
1642 if (!filePath || !entries || !entries.length)
1643 {
1644 return res.status(400).json({ error: 'filePath and entries are required.' });
1645 }
1646
1647 const { config, roots } = loadConfigAndRoots();
1648 const info = resolveRootForUser(filePath, roots, req.user, config);
1649 if (!info || !canReadInfo(req.user, info))
1650 {
1651 return res.status(403).json({ error: 'Access denied.' });
1652 }
1653
1654 appendSubtitleDebugEntries({
1655 videoName: path.basename(filePath),
1656 entries,
1657 context: {
1658 source: 'app',
1659 filePath,
1660 sessionId: sessionId || null,
1661 username: String(req.user && req.user.username || '').trim() || null,
1662 },
1663 });
1664
1665 return res.json({ ok: true });
1666 } catch (err)
1667 {
1668 logError('Subtitle debug log write failed', err, {
1669 filePath: String(req.body && req.body.filePath || ''),
1670 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
1671 });
1672 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
1673 }
1674 });
1675
1619 1676 // ---------------------------------------------------------------------------
1620 1677 // GET /api/files/download-zip?dir=<absolute-path>
1621 1678 // Authenticated. Streams a zip of the given directory.
@@ -13,6 +13,7 @@ const { requireAuth } = require('../auth');
13const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
13const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14const { logError } = require('../logger');
14const { logError } = require('../logger');
15const { renderImageSubtitleFrame } = require('../image-subtitles');
15const { renderImageSubtitleFrame } = require('../image-subtitles');
16const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
16const { buildZip } = require('./share');
17const { buildZip } = require('./share');
17const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
18const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
18
19
@@ -1553,6 +1554,7 @@ router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1553// ---------------------------------------------------------------------------
1554// ---------------------------------------------------------------------------
1554router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1555router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1555{
1556{
1557 const requestReceivedAtMs = Date.now();
1556 try
1558 try
1557 {
1559 {
1558 const filePath = String(req.query.filePath || '').trim();
1560 const filePath = String(req.query.filePath || '').trim();
@@ -1590,10 +1592,14 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1590
1592
1591 if (!frameData || !frameData.frame)
1593 if (!frameData || !frameData.frame)
1592 {
1594 {
1595 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1596 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1593 res.set('X-Subtitle-Frame-Status', 'none');
1597 res.set('X-Subtitle-Frame-Status', 'none');
1594 return res.status(204).end();
1598 return res.status(204).end();
1595 }
1599 }
1596
1600
1601 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1602 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1597 res.set('X-Subtitle-Frame-Status', 'ok');
1603 res.set('X-Subtitle-Frame-Status', 'ok');
1598 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
1604 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
1599 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
1605 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
@@ -1601,6 +1607,8 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1601 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
1607 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
1602 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
1608 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
1603 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
1609 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
1610 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
1611 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
1604 res.set('Content-Type', 'image/png');
1612 res.set('Content-Type', 'image/png');
1605 res.set('Cache-Control', 'private, max-age=3600');
1613 res.set('Cache-Control', 'private, max-age=3600');
1606 res.send(frameData.frame);
1614 res.send(frameData.frame);
@@ -1611,11 +1619,60 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1611 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1619 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1612 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1620 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1613 });
1621 });
1622 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1623 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1614 res.set('X-Subtitle-Frame-Status', 'error');
1624 res.set('X-Subtitle-Frame-Status', 'error');
1615 return res.status(204).end();
1625 return res.status(204).end();
1616 }
1626 }
1617});
1627});
1618
1628
1629// ---------------------------------------------------------------------------
1630// POST /api/files/video-stream-subtitle-log
1631// Authenticated. Persists client-side subtitle timing diagnostics to local cache.
1632// Body: { filePath, sessionId?, entries[] }
1633// ---------------------------------------------------------------------------
1634router.post('/video-stream-subtitle-log', requireAuth, (req, res) =>
1635{
1636 try
1637 {
1638 const filePath = String(req.body && req.body.filePath || '').trim();
1639 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
1640 const sessionId = String(req.body && req.body.sessionId || '').trim();
1641
1642 if (!filePath || !entries || !entries.length)
1643 {
1644 return res.status(400).json({ error: 'filePath and entries are required.' });
1645 }
1646
1647 const { config, roots } = loadConfigAndRoots();
1648 const info = resolveRootForUser(filePath, roots, req.user, config);
1649 if (!info || !canReadInfo(req.user, info))
1650 {
1651 return res.status(403).json({ error: 'Access denied.' });
1652 }
1653
1654 appendSubtitleDebugEntries({
1655 videoName: path.basename(filePath),
1656 entries,
1657 context: {
1658 source: 'app',
1659 filePath,
1660 sessionId: sessionId || null,
1661 username: String(req.user && req.user.username || '').trim() || null,
1662 },
1663 });
1664
1665 return res.json({ ok: true });
1666 } catch (err)
1667 {
1668 logError('Subtitle debug log write failed', err, {
1669 filePath: String(req.body && req.body.filePath || ''),
1670 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
1671 });
1672 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
1673 }
1674});
1675
1619// ---------------------------------------------------------------------------
1676// ---------------------------------------------------------------------------
1620// GET /api/files/download-zip?dir=<absolute-path>
1677// GET /api/files/download-zip?dir=<absolute-path>
1621// Authenticated. Streams a zip of the given directory.
1678// Authenticated. Streams a zip of the given directory.
server/routes/share.js +56 −0
@@ -12,6 +12,7 @@ const { requireAuth } = require('../auth');
12 12 const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
13 13 const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
14 14 const { renderImageSubtitleFrame } = require('../image-subtitles');
15 const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
15 16 const { logError } = require('../logger');
16 17
17 18 const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
@@ -366,6 +367,7 @@ router.delete('/video-stream/session/:sessionId', async (req, res, next) =>
366 367 // ---------------------------------------------------------------------------
367 368 router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
368 369 {
370 const requestReceivedAtMs = Date.now();
369 371 try
370 372 {
371 373 const token = String(req.params.token || '').trim();
@@ -402,10 +404,14 @@ router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
402 404
403 405 if (!frameData || !frameData.frame)
404 406 {
407 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
408 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
405 409 res.set('X-Subtitle-Frame-Status', 'none');
406 410 return res.status(204).end();
407 411 }
408 412
413 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
414 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
409 415 res.set('X-Subtitle-Frame-Status', 'ok');
410 416 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
411 417 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
@@ -413,6 +419,8 @@ router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
413 419 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
414 420 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
415 421 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
422 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
423 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
416 424 res.set('Content-Type', 'image/png');
417 425 res.set('Cache-Control', 'private, max-age=3600');
418 426 res.send(frameData.frame);
@@ -423,11 +431,59 @@ router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
423 431 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
424 432 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
425 433 });
434 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
435 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
426 436 res.set('X-Subtitle-Frame-Status', 'error');
427 437 return res.status(204).end();
428 438 }
429 439 });
430 440
441 // ---------------------------------------------------------------------------
442 // POST /api/share/video-stream-subtitle-log/:token
443 // Public. Persists client-side subtitle timing diagnostics for a share playback.
444 // Body: { sessionId?, entries[] }
445 // ---------------------------------------------------------------------------
446 router.post('/video-stream-subtitle-log/:token', express.json(), (req, res) =>
447 {
448 try
449 {
450 const token = String(req.params.token || '').trim();
451 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
452 const sessionId = String(req.body && req.body.sessionId || '').trim();
453
454 if (!token || !entries || !entries.length)
455 {
456 return res.status(400).json({ error: 'token and entries are required.' });
457 }
458
459 const db = getDb();
460 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
461 if (!row) return res.status(404).json({ error: 'Share link not found.' });
462 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
463 if (row.is_dir) return res.status(400).json({ error: 'Cannot log subtitle timing for a directory.' });
464
465 appendSubtitleDebugEntries({
466 videoName: path.basename(row.file_path),
467 entries,
468 context: {
469 source: 'share',
470 filePath: row.file_path,
471 sessionId: sessionId || null,
472 shareToken: token,
473 },
474 });
475
476 return res.json({ ok: true });
477 } catch (err)
478 {
479 logError('Shared subtitle debug log write failed', err, {
480 token: String(req.params.token || ''),
481 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
482 });
483 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
484 }
485 });
486
431 487 // ---------------------------------------------------------------------------
432 488 // GET /api/share/download/:token
433 489 // Public (no auth). Streams the file or a zip of the directory.
@@ -12,6 +12,7 @@ const { requireAuth } = require('../auth');
12const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
12const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
13const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
13const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
14const { renderImageSubtitleFrame } = require('../image-subtitles');
14const { renderImageSubtitleFrame } = require('../image-subtitles');
15const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
15const { logError } = require('../logger');
16const { logError } = require('../logger');
16
17
17const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
18const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
@@ -366,6 +367,7 @@ router.delete('/video-stream/session/:sessionId', async (req, res, next) =>
366// ---------------------------------------------------------------------------
367// ---------------------------------------------------------------------------
367router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
368router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
368{
369{
370 const requestReceivedAtMs = Date.now();
369 try
371 try
370 {
372 {
371 const token = String(req.params.token || '').trim();
373 const token = String(req.params.token || '').trim();
@@ -402,10 +404,14 @@ router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
402
404
403 if (!frameData || !frameData.frame)
405 if (!frameData || !frameData.frame)
404 {
406 {
407 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
408 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
405 res.set('X-Subtitle-Frame-Status', 'none');
409 res.set('X-Subtitle-Frame-Status', 'none');
406 return res.status(204).end();
410 return res.status(204).end();
407 }
411 }
408
412
413 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
414 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
409 res.set('X-Subtitle-Frame-Status', 'ok');
415 res.set('X-Subtitle-Frame-Status', 'ok');
410 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
416 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
411 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
417 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
@@ -413,6 +419,8 @@ router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
413 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
419 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
414 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
420 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
415 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
421 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
422 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
423 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
416 res.set('Content-Type', 'image/png');
424 res.set('Content-Type', 'image/png');
417 res.set('Cache-Control', 'private, max-age=3600');
425 res.set('Cache-Control', 'private, max-age=3600');
418 res.send(frameData.frame);
426 res.send(frameData.frame);
@@ -423,11 +431,59 @@ router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
423 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
431 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
424 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
432 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
425 });
433 });
434 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
435 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
426 res.set('X-Subtitle-Frame-Status', 'error');
436 res.set('X-Subtitle-Frame-Status', 'error');
427 return res.status(204).end();
437 return res.status(204).end();
428 }
438 }
429});
439});
430
440
441// ---------------------------------------------------------------------------
442// POST /api/share/video-stream-subtitle-log/:token
443// Public. Persists client-side subtitle timing diagnostics for a share playback.
444// Body: { sessionId?, entries[] }
445// ---------------------------------------------------------------------------
446router.post('/video-stream-subtitle-log/:token', express.json(), (req, res) =>
447{
448 try
449 {
450 const token = String(req.params.token || '').trim();
451 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
452 const sessionId = String(req.body && req.body.sessionId || '').trim();
453
454 if (!token || !entries || !entries.length)
455 {
456 return res.status(400).json({ error: 'token and entries are required.' });
457 }
458
459 const db = getDb();
460 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
461 if (!row) return res.status(404).json({ error: 'Share link not found.' });
462 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
463 if (row.is_dir) return res.status(400).json({ error: 'Cannot log subtitle timing for a directory.' });
464
465 appendSubtitleDebugEntries({
466 videoName: path.basename(row.file_path),
467 entries,
468 context: {
469 source: 'share',
470 filePath: row.file_path,
471 sessionId: sessionId || null,
472 shareToken: token,
473 },
474 });
475
476 return res.json({ ok: true });
477 } catch (err)
478 {
479 logError('Shared subtitle debug log write failed', err, {
480 token: String(req.params.token || ''),
481 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
482 });
483 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
484 }
485});
486
431// ---------------------------------------------------------------------------
487// ---------------------------------------------------------------------------
432// GET /api/share/download/:token
488// GET /api/share/download/:token
433// Public (no auth). Streams the file or a zip of the directory.
489// Public (no auth). Streams the file or a zip of the directory.
server/subtitle-debug-log.js added +127 −0
@@ -0,0 +1,127 @@
1 'use strict';
2
3 const fs = require('fs');
4 const os = require('os');
5 const path = require('path');
6
7 const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
8 const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024;
9
10 function padNumber (value)
11 {
12 return String(Math.max(0, Number(value) || 0)).padStart(2, '0');
13 }
14
15 function localDateStamp (timestampMs)
16 {
17 const date = new Date(Number.isFinite(timestampMs) ? timestampMs : Date.now());
18 return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`;
19 }
20
21 function sanitiseVideoName (videoName)
22 {
23 const raw = path.basename(String(videoName || '').trim() || 'unknown-video');
24 const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');
25 return cleaned || 'unknown-video';
26 }
27
28 function subtitleDebugLogFilePath (videoName, timestampMs = Date.now())
29 {
30 const fileName = `${localDateStamp(timestampMs)}-${sanitiseVideoName(videoName)}-subtitlelog.txt`;
31 return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName);
32 }
33
34 function ensureSubtitleDebugLogDir ()
35 {
36 fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true });
37 }
38
39 function serialiseLogEntry (entry)
40 {
41 const payload = entry && typeof entry === 'object' ? entry : { value: entry };
42 const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString();
43 return `[${timestamp}] ${JSON.stringify(payload)}\n`;
44 }
45
46 function directoryEntriesWithStats (dirPath)
47 {
48 let entries = [];
49 try
50 {
51 entries = fs.readdirSync(dirPath, { withFileTypes: true });
52 } catch
53 {
54 return [];
55 }
56
57 const out = [];
58 for (const entry of entries)
59 {
60 if (!entry.isFile()) continue;
61 const fullPath = path.join(dirPath, entry.name);
62 try
63 {
64 const stat = fs.statSync(fullPath);
65 out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 });
66 } catch
67 {
68 // Ignore files that disappear mid-scan.
69 }
70 }
71 return out;
72 }
73
74 function pruneSubtitleDebugLogDir ()
75 {
76 ensureSubtitleDebugLogDir();
77 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);
78 let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
79
80 for (const entry of entries)
81 {
82 if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;
83 try
84 {
85 fs.unlinkSync(entry.fullPath);
86 totalBytes = Math.max(0, totalBytes - entry.size);
87 } catch
88 {
89 // Ignore prune failures; logging must remain best-effort.
90 }
91 }
92 }
93
94 function appendSubtitleDebugEntries ({ videoName, entries, context = null })
95 {
96 const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];
97 if (!rows.length) return null;
98
99 const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));
100 const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now());
101
102 try
103 {
104 ensureSubtitleDebugLogDir();
105 const text = rows.map((entry) =>
106 {
107 const payload = context && typeof context === 'object'
108 ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }
109 : entry;
110 return serialiseLogEntry(payload);
111 }).join('');
112 fs.appendFileSync(targetPath, text, 'utf8');
113 pruneSubtitleDebugLogDir();
114 return targetPath;
115 } catch
116 {
117 return null;
118 }
119 }
120
121 module.exports = {
122 SUBTITLE_DEBUG_LOG_DIR,
123 MAX_SUBTITLE_DEBUG_LOG_BYTES,
124 subtitleDebugLogFilePath,
125 pruneSubtitleDebugLogDir,
126 appendSubtitleDebugEntries,
127 };
@@ -0,0 +1,127 @@
1'use strict';
2
3const fs = require('fs');
4const os = require('os');
5const path = require('path');
6
7const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
8const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024;
9
10function padNumber (value)
11{
12 return String(Math.max(0, Number(value) || 0)).padStart(2, '0');
13}
14
15function localDateStamp (timestampMs)
16{
17 const date = new Date(Number.isFinite(timestampMs) ? timestampMs : Date.now());
18 return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`;
19}
20
21function sanitiseVideoName (videoName)
22{
23 const raw = path.basename(String(videoName || '').trim() || 'unknown-video');
24 const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');
25 return cleaned || 'unknown-video';
26}
27
28function subtitleDebugLogFilePath (videoName, timestampMs = Date.now())
29{
30 const fileName = `${localDateStamp(timestampMs)}-${sanitiseVideoName(videoName)}-subtitlelog.txt`;
31 return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName);
32}
33
34function ensureSubtitleDebugLogDir ()
35{
36 fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true });
37}
38
39function serialiseLogEntry (entry)
40{
41 const payload = entry && typeof entry === 'object' ? entry : { value: entry };
42 const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString();
43 return `[${timestamp}] ${JSON.stringify(payload)}\n`;
44}
45
46function directoryEntriesWithStats (dirPath)
47{
48 let entries = [];
49 try
50 {
51 entries = fs.readdirSync(dirPath, { withFileTypes: true });
52 } catch
53 {
54 return [];
55 }
56
57 const out = [];
58 for (const entry of entries)
59 {
60 if (!entry.isFile()) continue;
61 const fullPath = path.join(dirPath, entry.name);
62 try
63 {
64 const stat = fs.statSync(fullPath);
65 out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 });
66 } catch
67 {
68 // Ignore files that disappear mid-scan.
69 }
70 }
71 return out;
72}
73
74function pruneSubtitleDebugLogDir ()
75{
76 ensureSubtitleDebugLogDir();
77 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);
78 let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
79
80 for (const entry of entries)
81 {
82 if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;
83 try
84 {
85 fs.unlinkSync(entry.fullPath);
86 totalBytes = Math.max(0, totalBytes - entry.size);
87 } catch
88 {
89 // Ignore prune failures; logging must remain best-effort.
90 }
91 }
92}
93
94function appendSubtitleDebugEntries ({ videoName, entries, context = null })
95{
96 const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];
97 if (!rows.length) return null;
98
99 const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));
100 const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now());
101
102 try
103 {
104 ensureSubtitleDebugLogDir();
105 const text = rows.map((entry) =>
106 {
107 const payload = context && typeof context === 'object'
108 ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }
109 : entry;
110 return serialiseLogEntry(payload);
111 }).join('');
112 fs.appendFileSync(targetPath, text, 'utf8');
113 pruneSubtitleDebugLogDir();
114 return targetPath;
115 } catch
116 {
117 return null;
118 }
119}
120
121module.exports = {
122 SUBTITLE_DEBUG_LOG_DIR,
123 MAX_SUBTITLE_DEBUG_LOG_BYTES,
124 subtitleDebugLogFilePath,
125 pruneSubtitleDebugLogDir,
126 appendSubtitleDebugEntries,
127};
tests/files.routes.test.js +36 −0
@@ -130,6 +130,10 @@ jest.mock('../server/image-subtitles', () => ({
130 130 }),
131 131 }));
132 132
133 jest.mock('../server/subtitle-debug-log', () => ({
134 appendSubtitleDebugEntries: jest.fn(),
135 }));
136
133 137 const filesRoutes = require('../server/routes/files');
134 138 const { getDb } = require('../server/db');
135 139
@@ -1013,6 +1017,8 @@ describe('video streaming routes', () =>
1013 1017 height: 180,
1014 1018 canvasWidth: 640,
1015 1019 canvasHeight: 360,
1020 startTimeSeconds: 1.5,
1021 endTimeSeconds: 3.2,
1016 1022 };
1017 1023
1018 1024 const { status, headers, body } = await reqRaw(
@@ -1029,9 +1035,39 @@ describe('video streaming routes', () =>
1029 1035 expect(headers['x-subtitle-frame-height']).toBe('180');
1030 1036 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1031 1037 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1038 expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1039 expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1040 expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1041 expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1032 1042 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1033 1043 });
1034 1044
1045 test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1046 {
1047 const filePath = path.join(rootDir, 'movie.mkv');
1048 fs.writeFileSync(filePath, 'video');
1049 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1050
1051 const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1052 filePath,
1053 sessionId: 'sess-123',
1054 entries: [
1055 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1056 ],
1057 });
1058
1059 expect(status).toBe(200);
1060 expect(body).toEqual({ ok: true });
1061 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1062 videoName: 'movie.mkv',
1063 context: expect.objectContaining({
1064 filePath,
1065 sessionId: 'sess-123',
1066 source: 'app',
1067 }),
1068 }));
1069 });
1070
1035 1071 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1036 1072 {
1037 1073 const filePath = path.join(rootDir, 'clip.mkv');
@@ -130,6 +130,10 @@ jest.mock('../server/image-subtitles', () => ({
130 }),
130 }),
131}));
131}));
132
132
133jest.mock('../server/subtitle-debug-log', () => ({
134 appendSubtitleDebugEntries: jest.fn(),
135}));
136
133const filesRoutes = require('../server/routes/files');
137const filesRoutes = require('../server/routes/files');
134const { getDb } = require('../server/db');
138const { getDb } = require('../server/db');
135
139
@@ -1013,6 +1017,8 @@ describe('video streaming routes', () =>
1013 height: 180,
1017 height: 180,
1014 canvasWidth: 640,
1018 canvasWidth: 640,
1015 canvasHeight: 360,
1019 canvasHeight: 360,
1020 startTimeSeconds: 1.5,
1021 endTimeSeconds: 3.2,
1016 };
1022 };
1017
1023
1018 const { status, headers, body } = await reqRaw(
1024 const { status, headers, body } = await reqRaw(
@@ -1029,9 +1035,39 @@ describe('video streaming routes', () =>
1029 expect(headers['x-subtitle-frame-height']).toBe('180');
1035 expect(headers['x-subtitle-frame-height']).toBe('180');
1030 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1036 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1031 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1037 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1038 expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1039 expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1040 expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1041 expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1032 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1042 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1033 });
1043 });
1034
1044
1045 test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1046 {
1047 const filePath = path.join(rootDir, 'movie.mkv');
1048 fs.writeFileSync(filePath, 'video');
1049 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1050
1051 const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1052 filePath,
1053 sessionId: 'sess-123',
1054 entries: [
1055 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1056 ],
1057 });
1058
1059 expect(status).toBe(200);
1060 expect(body).toEqual({ ok: true });
1061 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1062 videoName: 'movie.mkv',
1063 context: expect.objectContaining({
1064 filePath,
1065 sessionId: 'sess-123',
1066 source: 'app',
1067 }),
1068 }));
1069 });
1070
1035 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1071 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1036 {
1072 {
1037 const filePath = path.join(rootDir, 'clip.mkv');
1073 const filePath = path.join(rootDir, 'clip.mkv');
tests/share.routes.test.js +37 −0
@@ -94,6 +94,10 @@ jest.mock('../server/logger', () => ({
94 94 logError: jest.fn(),
95 95 }));
96 96
97 jest.mock('../server/subtitle-debug-log', () => ({
98 appendSubtitleDebugEntries: jest.fn(),
99 }));
100
97 101 const shareRoutes = require('../server/routes/share');
98 102 const { getDb } = require('../server/db');
99 103
@@ -399,6 +403,8 @@ describe('GET /api/share/video-stream/:token', () =>
399 403 height: 180,
400 404 canvasWidth: 640,
401 405 canvasHeight: 360,
406 startTimeSeconds: 1.5,
407 endTimeSeconds: 3.2,
402 408 };
403 409
404 410 const res = await get('/api/share/video-stream-subtitle-frame/stream-subs?streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080');
@@ -412,8 +418,39 @@ describe('GET /api/share/video-stream/:token', () =>
412 418 expect(res.headers.get('x-subtitle-frame-height')).toBe('180');
413 419 expect(res.headers.get('x-subtitle-frame-canvas-width')).toBe('640');
414 420 expect(res.headers.get('x-subtitle-frame-canvas-height')).toBe('360');
421 expect(res.headers.get('x-subtitle-frame-start-time')).toBe('1.5');
422 expect(res.headers.get('x-subtitle-frame-end-time')).toBe('3.2');
423 expect(Number(res.headers.get('x-subtitle-request-received-at-ms'))).toBeGreaterThan(0);
424 expect(Number(res.headers.get('x-subtitle-response-sent-at-ms'))).toBeGreaterThan(0);
415 425 expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from('png-data'))).toBe(true);
416 426 });
427
428 test('persists subtitle debug batches for shared video playback', async () =>
429 {
430 const filePath = path.join(rootDir, 'movie-subs.mkv');
431 fs.writeFileSync(filePath, 'video');
432 insertToken({ token: 'stream-subs-log', filePath });
433 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
434
435 const res = await post('/api/share/video-stream-subtitle-log/stream-subs-log', {
436 sessionId: 'share-sess-1',
437 entries: [
438 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
439 ],
440 });
441
442 expect(res.status).toBe(200);
443 expect(await res.json()).toEqual({ ok: true });
444 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
445 videoName: 'movie-subs.mkv',
446 context: expect.objectContaining({
447 filePath,
448 sessionId: 'share-sess-1',
449 source: 'share',
450 shareToken: 'stream-subs-log',
451 }),
452 }));
453 });
417 454 });
418 455
419 456 // ---------------------------------------------------------------------------
@@ -94,6 +94,10 @@ jest.mock('../server/logger', () => ({
94 logError: jest.fn(),
94 logError: jest.fn(),
95}));
95}));
96
96
97jest.mock('../server/subtitle-debug-log', () => ({
98 appendSubtitleDebugEntries: jest.fn(),
99}));
100
97const shareRoutes = require('../server/routes/share');
101const shareRoutes = require('../server/routes/share');
98const { getDb } = require('../server/db');
102const { getDb } = require('../server/db');
99
103
@@ -399,6 +403,8 @@ describe('GET /api/share/video-stream/:token', () =>
399 height: 180,
403 height: 180,
400 canvasWidth: 640,
404 canvasWidth: 640,
401 canvasHeight: 360,
405 canvasHeight: 360,
406 startTimeSeconds: 1.5,
407 endTimeSeconds: 3.2,
402 };
408 };
403
409
404 const res = await get('/api/share/video-stream-subtitle-frame/stream-subs?streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080');
410 const res = await get('/api/share/video-stream-subtitle-frame/stream-subs?streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080');
@@ -412,8 +418,39 @@ describe('GET /api/share/video-stream/:token', () =>
412 expect(res.headers.get('x-subtitle-frame-height')).toBe('180');
418 expect(res.headers.get('x-subtitle-frame-height')).toBe('180');
413 expect(res.headers.get('x-subtitle-frame-canvas-width')).toBe('640');
419 expect(res.headers.get('x-subtitle-frame-canvas-width')).toBe('640');
414 expect(res.headers.get('x-subtitle-frame-canvas-height')).toBe('360');
420 expect(res.headers.get('x-subtitle-frame-canvas-height')).toBe('360');
421 expect(res.headers.get('x-subtitle-frame-start-time')).toBe('1.5');
422 expect(res.headers.get('x-subtitle-frame-end-time')).toBe('3.2');
423 expect(Number(res.headers.get('x-subtitle-request-received-at-ms'))).toBeGreaterThan(0);
424 expect(Number(res.headers.get('x-subtitle-response-sent-at-ms'))).toBeGreaterThan(0);
415 expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from('png-data'))).toBe(true);
425 expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from('png-data'))).toBe(true);
416 });
426 });
427
428 test('persists subtitle debug batches for shared video playback', async () =>
429 {
430 const filePath = path.join(rootDir, 'movie-subs.mkv');
431 fs.writeFileSync(filePath, 'video');
432 insertToken({ token: 'stream-subs-log', filePath });
433 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
434
435 const res = await post('/api/share/video-stream-subtitle-log/stream-subs-log', {
436 sessionId: 'share-sess-1',
437 entries: [
438 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
439 ],
440 });
441
442 expect(res.status).toBe(200);
443 expect(await res.json()).toEqual({ ok: true });
444 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
445 videoName: 'movie-subs.mkv',
446 context: expect.objectContaining({
447 filePath,
448 sessionId: 'share-sess-1',
449 source: 'share',
450 shareToken: 'stream-subs-log',
451 }),
452 }));
453 });
417});
454});
418
455
419// ---------------------------------------------------------------------------
456// ---------------------------------------------------------------------------
tests/shared-video-player.test.js +55 −0
@@ -224,4 +224,59 @@ describe('shared image subtitle prefetching', () =>
224 224
225 225 window.close();
226 226 });
227
228 test('logs current subtitle request lifecycle events and flushes them on detach', async () =>
229 {
230 const window = createWindow();
231 const helper = loadSharedVideoPlayer(window);
232 const { player, videojs } = buildPlayerHarness(window);
233 const sentBatches = [];
234
235 window.fetch = jest.fn(async () =>
236 {
237 return new Response('png-data', {
238 status: 200,
239 headers: {
240 'Content-Type': 'image/png',
241 'X-Subtitle-Frame-Status': 'ok',
242 'X-Subtitle-Request-Received-At-Ms': '1000',
243 'X-Subtitle-Response-Sent-At-Ms': '1012',
244 'X-Subtitle-Frame-Start-Time': '1.5',
245 'X-Subtitle-Frame-End-Time': '3.2',
246 'X-Subtitle-Frame-Width': '320',
247 'X-Subtitle-Frame-Height': '180',
248 'X-Subtitle-Frame-Canvas-Width': '640',
249 'X-Subtitle-Frame-Canvas-Height': '360',
250 },
251 });
252 });
253
254 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
255 sessionId: 'sess-1',
256 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
257 }, {
258 lookaheadSeconds: 0,
259 sendSubtitleLogBatch: (entries) =>
260 {
261 sentBatches.push(entries);
262 return Promise.resolve();
263 },
264 buildFrameRequest: ({ currentTime, streamIndex }) => ({
265 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
266 }),
267 });
268
269 await flushAsyncWork(window, 8);
270 controller.detach();
271 await flushAsyncWork(window, 4);
272
273 const flattened = sentBatches.flat();
274 expect(flattened.map((entry) => entry.eventType)).toEqual(expect.arrayContaining([
275 'subtitle_png_requested',
276 'subtitle_png_sent',
277 'subtitle_png_received',
278 ]));
279
280 window.close();
281 });
227 282 });
@@ -224,4 +224,59 @@ describe('shared image subtitle prefetching', () =>
224
224
225 window.close();
225 window.close();
226 });
226 });
227
228 test('logs current subtitle request lifecycle events and flushes them on detach', async () =>
229 {
230 const window = createWindow();
231 const helper = loadSharedVideoPlayer(window);
232 const { player, videojs } = buildPlayerHarness(window);
233 const sentBatches = [];
234
235 window.fetch = jest.fn(async () =>
236 {
237 return new Response('png-data', {
238 status: 200,
239 headers: {
240 'Content-Type': 'image/png',
241 'X-Subtitle-Frame-Status': 'ok',
242 'X-Subtitle-Request-Received-At-Ms': '1000',
243 'X-Subtitle-Response-Sent-At-Ms': '1012',
244 'X-Subtitle-Frame-Start-Time': '1.5',
245 'X-Subtitle-Frame-End-Time': '3.2',
246 'X-Subtitle-Frame-Width': '320',
247 'X-Subtitle-Frame-Height': '180',
248 'X-Subtitle-Frame-Canvas-Width': '640',
249 'X-Subtitle-Frame-Canvas-Height': '360',
250 },
251 });
252 });
253
254 const controller = helper.bindImageSubtitleOverlay(player, videojs, {}, {
255 sessionId: 'sess-1',
256 imageSubtitleTracks: [{ label: 'PGS English', streamIndex: 0, default: true }],
257 }, {
258 lookaheadSeconds: 0,
259 sendSubtitleLogBatch: (entries) =>
260 {
261 sentBatches.push(entries);
262 return Promise.resolve();
263 },
264 buildFrameRequest: ({ currentTime, streamIndex }) => ({
265 url: `/subtitle-frame?streamIndex=${streamIndex}&timeSeconds=${currentTime}`,
266 }),
267 });
268
269 await flushAsyncWork(window, 8);
270 controller.detach();
271 await flushAsyncWork(window, 4);
272
273 const flattened = sentBatches.flat();
274 expect(flattened.map((entry) => entry.eventType)).toEqual(expect.arrayContaining([
275 'subtitle_png_requested',
276 'subtitle_png_sent',
277 'subtitle_png_received',
278 ]));
279
280 window.close();
281 });
227});
282});
tests/subtitle-debug-log.test.js added +60 −0
@@ -0,0 +1,60 @@
1 'use strict';
2
3 const fs = require('fs');
4 const os = require('os');
5 const path = require('path');
6
7 describe('subtitle debug log writer', () =>
8 {
9 const modulePath = require.resolve('../server/subtitle-debug-log');
10 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
11
12 beforeEach(() =>
13 {
14 jest.resetModules();
15 fs.rmSync(logDir, { recursive: true, force: true });
16 });
17
18 test('writes dated per-video subtitle log files', () =>
19 {
20 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
21
22 const targetPath = appendSubtitleDebugEntries({
23 videoName: 'My Film.mkv',
24 context: { source: 'app' },
25 entries: [
26 { loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'subtitle_png_requested' },
27 ],
28 });
29
30 expect(targetPath).toContain('2026-05-25-My-Film.mkv-subtitlelog.txt');
31 const text = fs.readFileSync(targetPath, 'utf8');
32 expect(text).toContain('subtitle_png_requested');
33 expect(text).toContain('"source":"app"');
34 });
35
36 test('prunes oldest subtitle log files when cache exceeds 10 MB', () =>
37 {
38 const logModule = require('../server/subtitle-debug-log');
39
40 const oldPath = logModule.appendSubtitleDebugEntries({
41 videoName: 'old-video.mkv',
42 entries: [
43 { loggedAtMs: new Date('2026-05-24T10:00:00Z').getTime(), eventType: 'old-log', payload: 'x'.repeat(6 * 1024 * 1024) },
44 ],
45 });
46 const newPath = logModule.appendSubtitleDebugEntries({
47 videoName: 'new-video.mkv',
48 entries: [
49 { loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'new-log', payload: 'y'.repeat(6 * 1024 * 1024) },
50 ],
51 });
52
53 expect(fs.existsSync(newPath)).toBe(true);
54 expect(fs.existsSync(oldPath)).toBe(false);
55
56 const entries = fs.readdirSync(logDir);
57 expect(entries).toHaveLength(1);
58 expect(entries[0]).toContain('new-video.mkv-subtitlelog.txt');
59 });
60 });
@@ -0,0 +1,60 @@
1'use strict';
2
3const fs = require('fs');
4const os = require('os');
5const path = require('path');
6
7describe('subtitle debug log writer', () =>
8{
9 const modulePath = require.resolve('../server/subtitle-debug-log');
10 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
11
12 beforeEach(() =>
13 {
14 jest.resetModules();
15 fs.rmSync(logDir, { recursive: true, force: true });
16 });
17
18 test('writes dated per-video subtitle log files', () =>
19 {
20 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
21
22 const targetPath = appendSubtitleDebugEntries({
23 videoName: 'My Film.mkv',
24 context: { source: 'app' },
25 entries: [
26 { loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'subtitle_png_requested' },
27 ],
28 });
29
30 expect(targetPath).toContain('2026-05-25-My-Film.mkv-subtitlelog.txt');
31 const text = fs.readFileSync(targetPath, 'utf8');
32 expect(text).toContain('subtitle_png_requested');
33 expect(text).toContain('"source":"app"');
34 });
35
36 test('prunes oldest subtitle log files when cache exceeds 10 MB', () =>
37 {
38 const logModule = require('../server/subtitle-debug-log');
39
40 const oldPath = logModule.appendSubtitleDebugEntries({
41 videoName: 'old-video.mkv',
42 entries: [
43 { loggedAtMs: new Date('2026-05-24T10:00:00Z').getTime(), eventType: 'old-log', payload: 'x'.repeat(6 * 1024 * 1024) },
44 ],
45 });
46 const newPath = logModule.appendSubtitleDebugEntries({
47 videoName: 'new-video.mkv',
48 entries: [
49 { loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'new-log', payload: 'y'.repeat(6 * 1024 * 1024) },
50 ],
51 });
52
53 expect(fs.existsSync(newPath)).toBe(true);
54 expect(fs.existsSync(oldPath)).toBe(false);
55
56 const entries = fs.readdirSync(logDir);
57 expect(entries).toHaveLength(1);
58 expect(entries[0]).toContain('new-video.mkv-subtitlelog.txt');
59 });
60});