From 584dfa360890af0c58ec51da0528fb66b894d2d9 Mon Sep 17 00:00:00 2001 From: sudacode Date: Thu, 26 Nov 2026 22:07:13 -0800 Subject: [PATCH] perf(subsync): avoid streaming remote media for embedded references - Fetch embedded Jellyfin subtitle tracks through the Subtitles Stream endpoint instead of running ffmpeg over the HTTP stream - Try external references before extracting embedded tracks on remote streams, and skip embedded extraction when opening the picker - Run the sampled-audio fast path before the full MKV demux when a non-signs external or sidecar reference exists - Escalate to a single-pass embedded and audio rip only when sampled verification is inconclusive --- src/core/services/subsync.test.ts | 602 ++++++++++++++++++++++++++++++ src/core/services/subsync.ts | 456 +++++++++++++++++++--- src/subsync/utils.test.ts | 41 ++ src/subsync/utils.ts | 57 +++ 4 files changed, 1106 insertions(+), 50 deletions(-) diff --git a/src/core/services/subsync.test.ts b/src/core/services/subsync.test.ts index f1e16550..7f2e022c 100644 --- a/src/core/services/subsync.test.ts +++ b/src/core/services/subsync.test.ts @@ -6,6 +6,7 @@ import * as path from 'path'; import { pathToFileURL } from 'url'; import { TriggerSubsyncFromConfigDeps, + openSubsyncManualPicker, runSubsyncManual, triggerSubsyncFromConfig, } from './subsync'; @@ -2484,3 +2485,604 @@ test('triggerSubsyncFromConfig checks playback session after reading sub-delay w assert.equal(switched, true); assert.deepEqual(sentCommands, []); }); + +test('triggerSubsyncFromConfig on Jellyfin remote stream uses preloaded external reference without calling ffmpeg on embedded tracks', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-remote-external-first-')); + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const preloadedEngPath = path.join(tmpDir, 'jellyfin-eng.srt'); + const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + + writeSrtFromSpans(targetPath, spans, 2.4); + writeSrtFromSpans(preloadedEngPath, spans, 0); + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}" +exit 1 +`, + ); + + const osd: string[] = []; + let modalOpened = false; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') { + return 'http://pve-main:8096/Videos/item-1/stream?static=true&ApiKey=secret-token&MediaSourceId=ms-1'; + } + if (name === 'sid') return 1; + if (name === 'secondary-sid') return 4; + if (name === 'duration') return 1420; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetPath, + }, + { + id: 2, + type: 'sub', + selected: false, + external: false, + lang: 'eng', + title: 'English', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'spa', + title: 'Spanish', + codec: 'subrip', + 'ff-index': 3, + }, + { + id: 4, + type: 'sub', + selected: true, + external: true, + lang: 'eng', + title: 'English', + 'external-filename': preloadedEngPath, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: false, + }), + openManualPicker: () => { + modalOpened = true; + }, + showMpvOsd: (text) => { + osd.push(text); + }, + }), + ); + + assert.equal(modalOpened, false); + assert.equal( + fs.existsSync(ffmpegCallsLog), + false, + `expected zero ffmpeg calls on remote stream when external reference succeeds, got: ${fs.existsSync(ffmpegCallsLog) ? fs.readFileSync(ffmpegCallsLog, 'utf8') : ''}`, + ); + assert.ok( + osd.some((line) => line.startsWith('Synced via') && line.includes('-2.4')), + `expected sync around -2.4s, got: ${osd.join(' | ')}`, + ); +}); + +test('triggerSubsyncFromConfig on non-Jellyfin remote stream extracts embedded candidates in a single ffmpeg pass', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-remote-single-pass-')); + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const embeddedEngPath = path.join(tmpDir, 'embedded-eng.srt'); + const embeddedSpaPath = path.join(tmpDir, 'embedded-spa.srt'); + const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + + writeSrtFromSpans(targetPath, spans, 2.8); + writeSrtFromSpans(embeddedEngPath, spans, 0); + writeSrtFromSpans(embeddedSpaPath, spans, 0); + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}" +prev="" +cur_map="" +for arg in "$@"; do + if [ "$prev" = "-map" ]; then cur_map="$arg"; fi + case "$arg" in + *.srt) + if [ "$cur_map" = "0:2" ]; then cp "${toShellPath(embeddedEngPath)}" "$arg"; fi + if [ "$cur_map" = "0:3" ]; then cp "${toShellPath(embeddedSpaPath)}" "$arg"; fi + ;; + esac + prev="$arg" +done +exit 0 +`, + ); + + const osd: string[] = []; + let modalOpened = false; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return 'https://media.example.test/episode01.mkv'; + if (name === 'sid') return 1; + if (name === 'secondary-sid') return 2; + if (name === 'duration') return 1420; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetPath, + }, + { + id: 2, + type: 'sub', + selected: true, + external: false, + lang: 'eng', + title: 'English', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'spa', + title: 'Spanish', + codec: 'subrip', + 'ff-index': 3, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: false, + }), + openManualPicker: () => { + modalOpened = true; + }, + showMpvOsd: (text) => { + osd.push(text); + }, + }), + ); + + assert.equal(modalOpened, false); + const calls = fs.readFileSync(ffmpegCallsLog, 'utf8').trim().split('\n'); + assert.equal( + calls.length, + 1, + `expected single ffmpeg pass on remote stream, got ${calls.length}: ${calls.join(' | ')}`, + ); + assert.ok( + osd.some((line) => line.startsWith('Synced via') && line.includes('-2.8')), + `expected sync around -2.8s, got: ${osd.join(' | ')}`, + ); +}); + +test('triggerSubsyncFromConfig on local MKV with external reference and embedded track uses sampled audio fast path first', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-local-mixed-fastpath-')); + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const targetPath = path.join(tmpDir, 'ep01.ja.srt'); + const externalRefPath = path.join(tmpDir, 'ep01.en.srt'); + const pcmPath = path.join(tmpDir, 'speech.pcm'); + const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + + fs.writeFileSync(videoPath, 'video'); + writeSrtFromSpans(targetPath, spans, 2.6); + writeSrtFromSpans(externalRefPath, spans, 0); + writeSpeechPcmFile(pcmPath, spans, 920); + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}" +ss=0 +dur=0 +prev="" +for arg in "$@"; do + if [ "$prev" = "-ss" ]; then ss="$arg"; fi + if [ "$prev" = "-t" ]; then dur="$arg"; fi + prev="$arg" +done +if [ "$dur" -gt 0 ] 2>/dev/null; then + dd if="${toShellPath(pcmPath)}" bs=16000 skip="$ss" count="$dur" 2>/dev/null +else + cat "${toShellPath(pcmPath)}" +fi +exit 0 +`, + ); + + let modalOpened = false; + const osd: string[] = []; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return videoPath; + if (name === 'sid') return 1; + if (name === 'secondary-sid') return 3; + if (name === 'duration') return 920; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetPath, + }, + { + id: 2, + type: 'sub', + selected: false, + external: false, + lang: 'eng', + title: 'English (Embedded)', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: true, + external: true, + lang: 'eng', + title: 'English (External)', + 'external-filename': externalRefPath, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: false, + }), + openManualPicker: () => { + modalOpened = true; + }, + showMpvOsd: (text) => { + osd.push(text); + }, + }), + ); + + assert.equal(modalOpened, false); + const calls = fs.readFileSync(ffmpegCallsLog, 'utf8').trim().split('\n'); + assert.ok( + calls.length >= 2 && calls.every((line) => line.includes('-ss ') && line.includes('-t 60')), + `expected only sampled -ss/-t 60 calls without full MKV rip, got: ${calls.join(' | ')}`, + ); + assert.ok( + osd.some((line) => line.startsWith('Synced via') && line.includes('-2.6')), + `expected sync around -2.6s, got: ${osd.join(' | ')}`, + ); +}); + +test('triggerSubsyncFromConfig on Jellyfin remote stream with embedded-only references fetches via Jellyfin subtitle endpoint without ffmpeg', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-jellyfin-embedded-http-')); + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const engSrtPath = path.join(tmpDir, 'eng.srt'); + const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + + writeSrtFromSpans(targetPath, spans, 2.3); + writeSrtFromSpans(engSrtPath, spans, 0); + const engSrtText = fs.readFileSync(engSrtPath, 'utf8'); + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}" +exit 1 +`, + ); + + const fetchedUrls: string[] = []; + const fakeFetch: typeof fetch = (async (input: string | URL | Request) => { + const url = String(input); + fetchedUrls.push(url); + if (url.includes('/Subtitles/2/Stream.srt')) { + return new Response(engSrtText, { status: 200 }); + } + return new Response('not found', { status: 404 }); + }) as typeof fetch; + + const osd: string[] = []; + let modalOpened = false; + + await triggerSubsyncFromConfig( + makeDeps({ + fetchImpl: fakeFetch, + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') { + return 'http://pve-main:8096/Videos/item-9/stream?static=true&ApiKey=secret-token&MediaSourceId=ms-9'; + } + if (name === 'sid') return 1; + if (name === 'secondary-sid') return null; + if (name === 'duration') return 1420; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetPath, + }, + { + id: 2, + type: 'sub', + selected: false, + external: false, + lang: 'eng', + title: 'English (Full)', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'spa', + title: 'Spanish', + codec: 'subrip', + 'ff-index': 3, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: false, + }), + openManualPicker: () => { + modalOpened = true; + }, + showMpvOsd: (text) => { + osd.push(text); + }, + }), + ); + + assert.equal(modalOpened, false); + assert.equal(fs.existsSync(ffmpegCallsLog), false, 'expected zero ffmpeg calls'); + assert.deepEqual(fetchedUrls, [ + 'http://pve-main:8096/Videos/item-9/ms-9/Subtitles/2/Stream.srt?ApiKey=secret-token', + ]); + assert.ok( + osd.some((line) => line.startsWith('Synced via') && line.includes('-2.3')), + `expected sync around -2.3s, got: ${osd.join(' | ')}`, + ); +}); + +test('openSubsyncManualPicker on remote stream skips ffmpeg extraction of embedded tracks', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-remote-picker-')); + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 200); + + writeSrtFromSpans(targetPath, spans, 0); + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}" +exit 1 +`, + ); + + const receivedPayloads: SubsyncManualPayload[] = []; + const opened = await openSubsyncManualPicker( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') { + return 'http://pve-main:8096/Videos/item-10/stream?static=true&ApiKey=secret-token&MediaSourceId=ms-10'; + } + if (name === 'sid') return 1; + if (name === 'secondary-sid') return 2; + if (name === 'duration') return 1420; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetPath, + }, + { + id: 2, + type: 'sub', + selected: true, + external: false, + lang: 'eng', + title: 'English', + codec: 'subrip', + 'ff-index': 2, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: false, + }), + openManualPicker: (nextPayload) => { + receivedPayloads.push(nextPayload); + }, + }), + ); + + assert.equal(opened, true); + assert.equal(fs.existsSync(ffmpegCallsLog), false, 'expected zero ffmpeg calls opening picker'); + const payload = receivedPayloads[0]; + assert.ok(payload !== undefined); + assert.equal( + payload.referenceCandidates?.some((c) => c.trackId === 2), + true, + ); +}); + +test('runSubsyncManual builtin on Jellyfin stream fetches embedded reference via Jellyfin endpoint without ffmpeg', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-jellyfin-manual-http-')); + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const engSrtPath = path.join(tmpDir, 'eng.srt'); + const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + + writeSrtFromSpans(targetPath, spans, 1.8); + writeSrtFromSpans(engSrtPath, spans, 0); + const engSrtText = fs.readFileSync(engSrtPath, 'utf8'); + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}" +exit 1 +`, + ); + + const fetchedUrls: string[] = []; + const fakeFetch: typeof fetch = (async (input: string | URL | Request) => { + fetchedUrls.push(String(input)); + return new Response(engSrtText, { status: 200 }); + }) as typeof fetch; + + const result = await runSubsyncManual( + { + engine: 'builtin', + referenceMode: 'track', + referenceTrackId: 2, + targetTrackId: 1, + }, + makeDeps({ + fetchImpl: fakeFetch, + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') { + return 'http://pve-main:8096/Videos/item-11/stream?static=true&ApiKey=secret-token&MediaSourceId=ms-11'; + } + if (name === 'sid') return 1; + if (name === 'secondary-sid') return 2; + if (name === 'duration') return 1420; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetPath, + }, + { + id: 2, + type: 'sub', + selected: true, + external: false, + lang: 'eng', + title: 'English', + codec: 'subrip', + 'ff-index': 2, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: false, + }), + }), + ); + + assert.equal(result.ok, true); + assert.equal(fs.existsSync(ffmpegCallsLog), false, 'expected zero ffmpeg calls'); + assert.deepEqual(fetchedUrls, [ + 'http://pve-main:8096/Videos/item-11/ms-11/Subtitles/2/Stream.srt?ApiKey=secret-token', + ]); + assert.match(result.message, /-1\.80s/); +}); diff --git a/src/core/services/subsync.ts b/src/core/services/subsync.ts index ac41dde5..cfd2c018 100644 --- a/src/core/services/subsync.ts +++ b/src/core/services/subsync.ts @@ -10,6 +10,7 @@ import { SubsyncResult, } from '../../types'; import { + buildJellyfinEmbeddedSubtitleUrl, CommandResult, codecToExtension, extensionToFfmpegMuxer, @@ -74,6 +75,7 @@ const AUTO_SUBTITLE_CONFIDENCE_THRESHOLD = 0.65; const AUTO_REMOTE_CONFIDENCE_THRESHOLD = 0.7; const AUTO_AUDIO_CONFIDENCE_THRESHOLD = 0.65; const AUDIO_SPEECH_LEAD_SEC = 0.1; +const JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS = 15_000; function summarizeCommandFailure(command: string, result: CommandResult): string { const parts = [ @@ -106,6 +108,7 @@ interface SubsyncCoreDeps { getResolvedConfig: () => SubsyncResolvedConfig; getVadPaths?: () => SubsyncVadPaths; canPickReferenceFile?: () => boolean; + fetchImpl?: typeof fetch; } function parseTrackId(value: unknown): number | null { @@ -306,11 +309,36 @@ function isExecutableAvailable(configuredPath: string, names: readonly string[]) return findSubsyncExecutable(configuredPath, names) !== null; } +async function tryFetchJellyfinSubtitleBytes( + videoPath: string, + ffIndex: number, + extension: string, + fetchImpl: typeof fetch = globalThis.fetch, +): Promise { + const subtitleUrl = buildJellyfinEmbeddedSubtitleUrl(videoPath, ffIndex, extension); + if (!subtitleUrl || typeof fetchImpl !== 'function') return null; + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS); + try { + const response = await fetchImpl(subtitleUrl, { signal: controller.signal }); + if (!response.ok) return null; + const buffer = await response.arrayBuffer(); + if (buffer.byteLength === 0) return null; + return new Uint8Array(buffer); + } catch { + return null; + } finally { + clearTimeout(timeout); + } +} + async function extractSubtitleTrackToFile( ffmpegPath: string, videoPath: string, track: MpvTrack, workingDirectory?: string | null, + fetchImpl?: typeof fetch, ): Promise { if (track.external) { const externalPath = track['external-filename']; @@ -333,9 +361,29 @@ async function extractSubtitleTrackToFile( throw new Error(`Unsupported subtitle codec: ${track.codec ?? 'unknown'}`); } + if (isRemoteMediaPath(videoPath)) { + const fetchedBytes = await tryFetchJellyfinSubtitleBytes( + videoPath, + ffIndex, + extension, + fetchImpl, + ); + if (fetchedBytes) { + const decoded = decodeSubtitleBytesWithStatus(fetchedBytes); + const parsed = parseSubtitleFileContent(decoded.text, `track_${ffIndex}.${extension}`); + if (parsed.events.length > 0) { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-')); + const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`); + fs.writeFileSync(outputPath, fetchedBytes); + return { path: outputPath, temporary: true }; + } + } + } + + const resolvedFfmpegPath = ensureExecutablePath(ffmpegPath, 'ffmpeg'); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-')); const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`); - const extraction = await runCommand(ffmpegPath, [ + const extraction = await runCommand(resolvedFfmpegPath, [ '-hide_banner', '-nostdin', '-y', @@ -661,6 +709,8 @@ async function discoverAndEvaluateSubtitleCandidates( sampledAudioWindows?: SampledAudioWindow[] | null; preExtractedEmbedded?: ReadonlyMap | null; skipSignsEmbeddedExtraction?: boolean; + skipEmbeddedExtraction?: boolean; + fetchImpl?: typeof fetch; } = {}, ): Promise { const results: CandidateWithSpans[] = []; @@ -669,6 +719,7 @@ async function discoverAndEvaluateSubtitleCandidates( const sampledWindows = options.sampledAudioWindows ?? null; const preExtracted = options.preExtractedEmbedded ?? null; const skipSignsEmbedded = options.skipSignsEmbeddedExtraction !== false; + const skipEmbeddedExtraction = options.skipEmbeddedExtraction === true; for (const track of context.subtitleTracks) { if (track.external && track['external-filename']) { @@ -781,6 +832,11 @@ async function discoverAndEvaluateSubtitleCandidates( } } + if (isEmbedded && skipEmbeddedExtraction) { + results.push(evaluateParsedCandidate(baseMeta, null)); + continue; + } + let extraction: FileExtractionResult | null = null; try { if (isEmbedded && (!ffmpegAvailable || !codecToExtension(track.codec))) { @@ -792,6 +848,7 @@ async function discoverAndEvaluateSubtitleCandidates( context.videoPath, track, context.workingDirectory, + options.fetchImpl, ); const parsed = readAndParseSubtitleFile(extraction.path); results.push(evaluateParsedCandidate(baseMeta, parsed)); @@ -956,6 +1013,7 @@ async function runBuiltinSubsync( context.videoPath, targetTrack, context.workingDirectory, + deps.fetchImpl, ); const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); @@ -1024,14 +1082,27 @@ async function runBuiltinSubsync( message: 'Reference and out-of-sync subtitles must be different tracks', }; } - const ffmpegPath = referenceTrack.external - ? resolved.ffmpegPath - : ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); + const referenceExtension = codecToExtension(referenceTrack.codec); + const canTryJellyfinHttp = + !referenceTrack.external && + isRemoteMediaPath(context.videoPath) && + typeof referenceTrack['ff-index'] === 'number' && + referenceExtension !== null && + buildJellyfinEmbeddedSubtitleUrl( + context.videoPath, + referenceTrack['ff-index'], + referenceExtension, + ) !== null; + const ffmpegPath = + referenceTrack.external || canTryJellyfinHttp + ? resolved.ffmpegPath + : ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); refExtraction = await extractSubtitleTrackToFile( ffmpegPath, context.videoPath, referenceTrack, context.workingDirectory, + deps.fetchImpl, ); const parsedRef = readAndParseSubtitleFile(refExtraction.path); referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans; @@ -1081,12 +1152,14 @@ async function runManualOffsetSubsync( context: SubsyncContext, resolved: SubsyncResolvedConfig, client: MpvClientLike, + fetchImpl?: typeof fetch, ): Promise { const targetExtraction = await extractSubtitleTrackToFile( resolved.ffmpegPath, context.videoPath, targetTrack, context.workingDirectory, + fetchImpl, ); const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); @@ -1130,6 +1203,7 @@ async function subsyncToReference( resolved: SubsyncResolvedConfig, client: MpvClientLike, slot: SubtitleSlot, + fetchImpl?: typeof fetch, ): Promise { const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); const targetExtraction = await extractSubtitleTrackToFile( @@ -1137,6 +1211,7 @@ async function subsyncToReference( context.videoPath, targetTrack, context.workingDirectory, + fetchImpl, ); const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); @@ -1281,7 +1356,15 @@ export async function runSubsyncManual( if (!Number.isFinite(offsetMs) || offsetMs === 0) { return { ok: false, message: 'Enter a non-zero offset in milliseconds' }; } - return runManualOffsetSubsync(offsetMs, targetTrack, targetSlot, context, resolved, client); + return runManualOffsetSubsync( + offsetMs, + targetTrack, + targetSlot, + context, + resolved, + client, + deps.fetchImpl, + ); } if (request.engine === 'builtin') { @@ -1356,7 +1439,20 @@ export async function runSubsyncManual( return { ok: false, message: 'Reference and out-of-sync subtitles must be different tracks' }; } - const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); + const referenceExtension = codecToExtension(referenceTrack.codec); + const canTryJellyfinHttp = + !referenceTrack.external && + isRemoteMediaPath(context.videoPath) && + typeof referenceTrack['ff-index'] === 'number' && + referenceExtension !== null && + buildJellyfinEmbeddedSubtitleUrl( + context.videoPath, + referenceTrack['ff-index'], + referenceExtension, + ) !== null; + const ffmpegPath = canTryJellyfinHttp + ? resolved.ffmpegPath + : ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); let referenceExtraction: FileExtractionResult | null = null; let cleanedRef: FileExtractionResult | null = null; try { @@ -1365,6 +1461,7 @@ export async function runSubsyncManual( context.videoPath, referenceTrack, context.workingDirectory, + deps.fetchImpl, ); cleanedRef = maybeWriteCleanedReferenceSrt( referenceExtraction.path, @@ -1378,6 +1475,7 @@ export async function runSubsyncManual( resolved, client, targetSlot, + deps.fetchImpl, ); } finally { cleanupTemporaryFile(cleanedRef); @@ -1404,6 +1502,55 @@ async function prepareRipCandidatesAndAudio( const embeddedSpecs = collectExtractableEmbeddedRefTracks(context, targetTrack); const vadPaths = deps.getVadPaths?.(); + const cachedFull = getCachedAudioSpeechSpans( + context.videoPath, + context.audioStreamIndex, + vadPaths, + ); + + // Fast path: when a non-signs external or sidecar reference already exists and + // full audio is not cached yet, sample 4 seeked 60s windows (~0.3s local / ~3s NAS) + // before ever streaming the full container over disk/NFS for embedded tracks or full VAD. + const loadedExternalPaths: string[] = []; + for (const track of context.subtitleTracks) { + if (track.external && track['external-filename']) { + const resolvedPath = resolveLocalSubtitlePath( + track['external-filename'], + context.workingDirectory, + ); + if (resolvedPath) loadedExternalPaths.push(resolvedPath); + } + } + const hasExternalOrSidecarHint = + context.subtitleTracks.some( + (t) => + typeof t.id === 'number' && + t.id !== targetTrack.id && + t.external && + !isSignsOrSongsTrackMeta(t), + ) || + discoverSidecarReferenceFiles(context.videoPath, loadedExternalPaths).some( + (s) => !s.isSignsOnly, + ); + + if ( + options.allowSampledAudioFastPath && + !cachedFull && + hasExternalOrSidecarHint && + context.durationSec !== null && + context.durationSec !== undefined && + context.durationSec >= 300 + ) { + const sampled = await extractSampledAudioWindows({ + ffmpegPath: resolved.ffmpegPath, + videoPath: context.videoPath, + audioStreamIndex: context.audioStreamIndex, + durationSec: context.durationSec, + }); + if (sampled && sampled.length >= 2) { + return { audioSpeech: null, sampledAudioWindows: sampled, preExtractedEmbedded: null }; + } + } // Single-pass demux when 1+ non-signs embedded tracks exist: reads the MKV ONCE // for all embedded subtitle tracks + full audio simultaneously. @@ -1429,45 +1576,72 @@ async function prepareRipCandidatesAndAudio( return { audioSpeech, sampledAudioWindows: null, preExtractedEmbedded: null }; } - // External-only reference fast path: reuse cached full audio if already available, - // otherwise sample 4 seeked 60s windows (~0.2-0.5s) to verify external subtitle - // references before ever decoding the full video audio. - const cachedFull = getCachedAudioSpeechSpans( - context.videoPath, - context.audioStreamIndex, - vadPaths, - ); if (cachedFull) { return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null }; } - const hasExternalOrSidecarHint = - context.subtitleTracks.some( - (t) => typeof t.id === 'number' && t.id !== targetTrack.id && t.external, - ) || discoverSidecarReferenceFiles(context.videoPath, []).length > 0; - - if ( - options.allowSampledAudioFastPath && - hasExternalOrSidecarHint && - context.durationSec !== null && - context.durationSec !== undefined && - context.durationSec >= 300 - ) { - const sampled = await extractSampledAudioWindows({ - ffmpegPath: resolved.ffmpegPath, - videoPath: context.videoPath, - audioStreamIndex: context.audioStreamIndex, - durationSec: context.durationSec, - }); - if (sampled && sampled.length >= 2) { - return { audioSpeech: null, sampledAudioWindows: sampled, preExtractedEmbedded: null }; - } - } - const audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps); return { audioSpeech, sampledAudioWindows: null, preExtractedEmbedded: null }; } +function collectRankedRemoteEmbeddedTracks( + context: SubsyncContext, + targetTrack: MpvTrack, +): Array<{ track: MpvTrack; ffIndex: number; extension: string; key: string; label: string }> { + const metadataEvaluated: Array<{ + evaluated: EvaluatedSubtitleReference; + track: MpvTrack; + ffIndex: number; + extension: string; + }> = []; + + for (const track of context.subtitleTracks) { + if (typeof track.id !== 'number' || track.id === targetTrack.id) continue; + if (track.external || isSignsOrSongsTrackMeta(track)) continue; + const ffIndex = track['ff-index']; + const extension = codecToExtension(track.codec); + if (typeof ffIndex !== 'number' || !Number.isInteger(ffIndex) || ffIndex < 0 || !extension) { + continue; + } + const isSecondary = context.secondaryTrack !== null && track.id === context.secondaryTrack.id; + metadataEvaluated.push({ + track, + ffIndex, + extension, + evaluated: { + key: `track:${track.id}`, + kind: 'track', + trackId: track.id, + filePath: null, + label: buildTrackReferenceLabel(track, isSecondary), + isSecondary, + isEmbedded: true, + isEnglish: isEnglishReferenceMeta({ lang: track.lang, title: track.title }), + isFullDialogueHint: isFullDialogueHintMeta({ title: track.title }), + isSignsOnly: false, + dialogueCount: MIN_REFERENCE_DIALOGUE_LINES + 5, + signCount: 0, + audioStatus: 'unverified', + audioOffsetMs: null, + audioConfidence: 0, + }, + }); + } + + const rankedKeys = rankReferenceCandidates(metadataEvaluated.map((item) => item.evaluated)); + const byKey = new Map(metadataEvaluated.map((item) => [item.evaluated.key, item])); + return rankedKeys.map((ev) => { + const item = byKey.get(ev.key)!; + return { + track: item.track, + ffIndex: item.ffIndex, + extension: item.extension, + key: ev.key, + label: ev.label, + }; + }); +} + export async function openSubsyncManualPicker( deps: TriggerSubsyncFromConfigDeps, options: { @@ -1478,6 +1652,7 @@ export async function openSubsyncManualPicker( const client = getMpvClientForSubsync(deps); const context = await gatherSubsyncContext(client); const resolved = deps.getResolvedConfig(); + const isRemote = isRemoteMediaPath(context.videoPath); let evaluatedCandidates: CandidateWithSpans[] | undefined; let audioSpeechAvailable: boolean | undefined; @@ -1495,8 +1670,7 @@ export async function openSubsyncManualPicker( audioSpeechAvailable = prepared.audioSpeech !== null || prepared.sampledAudioWindows !== null || - (!isRemoteMediaPath(context.videoPath) && - isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg'])); + (!isRemote && isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg'])); evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( context, context.primaryTrack, @@ -1505,6 +1679,12 @@ export async function openSubsyncManualPicker( { sampledAudioWindows: prepared.sampledAudioWindows, preExtractedEmbedded: prepared.preExtractedEmbedded, + // Never stream a remote video over HTTP or full-read a local MKV during sampled fast-path just to populate the picker. + skipEmbeddedExtraction: + isRemote || + prepared.sampledAudioWindows !== null || + prepared.preExtractedEmbedded !== null, + fetchImpl: deps.fetchImpl, }, ); if (!(await isPlaybackSessionUnchanged(client, context, context.primaryTrack, 'primary'))) { @@ -1525,6 +1705,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise const client = getMpvClientForSubsync(deps); const context = await gatherSubsyncContext(client); const resolved = deps.getResolvedConfig(); + const isRemote = isRemoteMediaPath(context.videoPath); const targetTrack = context.primaryTrack; const targetSlot = resolveTargetSlot(targetTrack, context); @@ -1538,6 +1719,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise context.videoPath, targetTrack, context.workingDirectory, + deps.fetchImpl, ); } catch (extractError) { if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { @@ -1578,6 +1760,13 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise { sampledAudioWindows: prepared.sampledAudioWindows, preExtractedEmbedded: prepared.preExtractedEmbedded, + // Defer embedded extraction on remote streams (try external tracks first) and on + // local sampled-audio fast path (try external/sidecar tracks before full MKV demux). + skipEmbeddedExtraction: + isRemote || + prepared.sampledAudioWindows !== null || + prepared.preExtractedEmbedded !== null, + fetchImpl: deps.fetchImpl, }, ); @@ -1620,7 +1809,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise // Fast path: if sampled audio already verified a clean aligned subtitle reference // and target alignment succeeds with high confidence, finish immediately without - // reading the full video audio! + // reading the full video audio or embedded container tracks! if (!audioSpeech && prepared.sampledAudioWindows) { const fastAligned = evaluatedCandidates.filter( (c) => @@ -1643,31 +1832,38 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise } // Sampled verification did not yield a confident aligned subtitle sync (e.g. all - // references were misaligned or sampled windows were inconclusive). Escalate - // to full-episode audio extraction for complete verification and audio VAD sync. - audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps); - if (audioSpeech) { - lengthSec = context.durationSec ?? audioSpeech.durationSec; + // external references were misaligned or sampled windows were inconclusive). Escalate + // to a single full-episode pass for embedded tracks + complete audio verification. + const escalated = await prepareRipCandidatesAndAudio(context, targetTrack, resolved, deps, { + allowSampledAudioFastPath: false, + }); + audioSpeech = escalated.audioSpeech; + if (audioSpeech || escalated.preExtractedEmbedded) { + lengthSec = context.durationSec ?? audioSpeech?.durationSec ?? lengthSec; evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( context, targetTrack, resolved, audioSpeech, - { preExtractedEmbedded: prepared.preExtractedEmbedded }, + { + preExtractedEmbedded: escalated.preExtractedEmbedded, + skipEmbeddedExtraction: escalated.preExtractedEmbedded !== null, + fetchImpl: deps.fetchImpl, + }, ); } } - const misalignedCandidates = evaluatedCandidates.filter( + let misalignedCandidates = evaluatedCandidates.filter( (c) => c.evaluated.audioStatus === 'misaligned' && !c.evaluated.isSignsOnly, ); - const alignedCandidates = evaluatedCandidates.filter( + let alignedCandidates = evaluatedCandidates.filter( (c) => c.evaluated.audioStatus === 'aligned' && !c.evaluated.isSignsOnly && c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, ); - const unverifiedDialogueCandidates = evaluatedCandidates.filter( + let unverifiedDialogueCandidates = evaluatedCandidates.filter( (c) => c.evaluated.audioStatus === 'unverified' && !c.evaluated.isSignsOnly && @@ -1728,7 +1924,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise } // 3. When audio verification wasn't available (e.g. remote stream or no ffmpeg): - // try the highest-ranked clean dialogue subtitle track with a stricter confidence bar. + // try already-loaded external dialogue tracks first with a stricter confidence bar. if (!audioSpeech) { for (const candidate of unverifiedDialogueCandidates) { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { @@ -1750,6 +1946,166 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise }; } } + + // 3b. On remote streams where no external reference succeeded, fetch embedded tracks + // via Jellyfin's subtitle endpoint first (KB instead of GB), or fall back to a + // single ffmpeg pass across embedded candidates instead of N sequential downloads. + if (isRemote) { + const rankedEmbedded = collectRankedRemoteEmbeddedTracks(context, targetTrack); + if (rankedEmbedded.length > 0) { + const remoteExtracted = new Map(); + const triedViaJellyfin = new Set(); + + for (const item of rankedEmbedded) { + if ( + !buildJellyfinEmbeddedSubtitleUrl(context.videoPath, item.ffIndex, item.extension) + ) { + break; + } + const bytes = await tryFetchJellyfinSubtitleBytes( + context.videoPath, + item.ffIndex, + item.extension, + deps.fetchImpl, + ); + if (!bytes) continue; + const decoded = decodeSubtitleBytesWithStatus(bytes); + const parsed = parseSubtitleFileContent( + decoded.text, + `track_${item.ffIndex}.${item.extension}`, + ); + if (parsed.events.length === 0) continue; + remoteExtracted.set(item.ffIndex, parsed); + triedViaJellyfin.add(item.ffIndex); + + const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true }); + if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) continue; + const alignment = alignSubtitleFileToReferenceSpans( + parsedTarget, + extractedSpans.spans, + { + stripSigns: true, + allowSplits: true, + calibration: 'clean', + lengthSec, + confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD, + }, + ); + if (alignment.confident) { + await applyAlignment(alignment, item.label); + return; + } + if (!bestAttempt || alignment.confidence > bestAttempt.alignment.confidence) { + bestAttempt = { + alignment, + sourceLabel: item.label, + referenceKey: item.key, + }; + } + } + + const remainingSpecs = rankedEmbedded + .filter((item) => !remoteExtracted.has(item.ffIndex)) + .map((item) => ({ ffIndex: item.ffIndex, extension: item.extension })); + + if (remainingSpecs.length > 0 && isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg'])) { + const singlePass = await extractSinglePassRipMedia({ + ffmpegPath: resolved.ffmpegPath, + videoPath: context.videoPath, + audioStreamIndex: context.audioStreamIndex, + embeddedTracks: remainingSpecs, + includeAudio: false, + }); + if (singlePass) { + for (const [ffIndex, parsed] of singlePass.embeddedSubtitles) { + remoteExtracted.set(ffIndex, parsed); + } + } else { + // Single-pass failed: fall back to at most the single top-ranked embedded track. + const topFallback = rankedEmbedded.find((item) => !remoteExtracted.has(item.ffIndex)); + if (topFallback) { + let extraction: FileExtractionResult | null = null; + try { + extraction = await extractSubtitleTrackToFile( + resolved.ffmpegPath, + context.videoPath, + topFallback.track, + context.workingDirectory, + deps.fetchImpl, + ); + remoteExtracted.set( + topFallback.ffIndex, + readAndParseSubtitleFile(extraction.path), + ); + } catch { + // Ignore failed remote extraction and let guided picker open. + } finally { + cleanupTemporaryFile(extraction); + } + } + } + } + + if (remoteExtracted.size > 0) { + evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( + context, + targetTrack, + resolved, + null, + { + preExtractedEmbedded: remoteExtracted, + skipEmbeddedExtraction: true, + fetchImpl: deps.fetchImpl, + }, + ); + misalignedCandidates = evaluatedCandidates.filter( + (c) => c.evaluated.audioStatus === 'misaligned' && !c.evaluated.isSignsOnly, + ); + alignedCandidates = evaluatedCandidates.filter( + (c) => + c.evaluated.audioStatus === 'aligned' && + !c.evaluated.isSignsOnly && + c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, + ); + unverifiedDialogueCandidates = evaluatedCandidates.filter( + (c) => + c.evaluated.audioStatus === 'unverified' && + !c.evaluated.isSignsOnly && + c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, + ); + + for (const candidate of unverifiedDialogueCandidates) { + if (!candidate.evaluated.isEmbedded) continue; + const matchedItem = rankedEmbedded.find( + (item) => item.key === candidate.evaluated.key, + ); + if (matchedItem && triedViaJellyfin.has(matchedItem.ffIndex)) continue; + const alignment = alignSubtitleFileToReferenceSpans( + parsedTarget, + candidate.dialogueSpans, + { + stripSigns: true, + allowSplits: true, + calibration: 'clean', + lengthSec, + confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD, + }, + ); + if (alignment.confident) { + await applyAlignment(alignment, candidate.evaluated.label); + return; + } + if (!bestAttempt || alignment.confidence > bestAttempt.alignment.confidence) { + bestAttempt = { + alignment, + sourceLabel: candidate.evaluated.label, + referenceKey: candidate.evaluated.key, + }; + } + } + } + } + } } // 4. Automatic sync could not finish with high confidence -> open guided modal with explanation! diff --git a/src/subsync/utils.test.ts b/src/subsync/utils.test.ts index 92be812d..df7febd6 100644 --- a/src/subsync/utils.test.ts +++ b/src/subsync/utils.test.ts @@ -4,6 +4,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { + buildJellyfinEmbeddedSubtitleUrl, candidateExecutableNames, codecToExtension, extensionToFfmpegMuxer, @@ -94,3 +95,43 @@ test('Windows candidate discovery excludes extensionless shims and escapes cmd.e assert.ok(invocation.args[4]!.includes('^(')); assert.ok(invocation.args[4]!.includes('^)')); }); + +test('buildJellyfinEmbeddedSubtitleUrl derives direct-play subtitle endpoints and rejects non-direct URLs', () => { + assert.equal( + buildJellyfinEmbeddedSubtitleUrl( + 'http://pve-main:8096/Videos/item-1/stream?static=true&ApiKey=tok123&MediaSourceId=ms-1', + 2, + 'ass', + ), + 'http://pve-main:8096/Videos/item-1/ms-1/Subtitles/2/Stream.ass?ApiKey=tok123', + ); + assert.equal( + buildJellyfinEmbeddedSubtitleUrl( + 'https://media.example.test/jellyfin/Videos/item-2/stream.mkv?Static=True&api_key=tok456&mediaSourceId=ms-2', + 4, + 'ttml', + ), + 'https://media.example.test/jellyfin/Videos/item-2/ms-2/Subtitles/4/Stream.srt?ApiKey=tok456', + ); + // Transcoded or non-static streams must not assume container ff-index matches Jellyfin stream index. + assert.equal( + buildJellyfinEmbeddedSubtitleUrl( + 'http://pve-main:8096/Videos/item-1/main.m3u8?ApiKey=tok123&MediaSourceId=ms-1', + 2, + 'srt', + ), + null, + ); + assert.equal( + buildJellyfinEmbeddedSubtitleUrl( + 'http://pve-main:8096/Videos/item-1/stream?ApiKey=tok123&MediaSourceId=ms-1', + 2, + 'srt', + ), + null, + ); + assert.equal( + buildJellyfinEmbeddedSubtitleUrl('https://cdn.example.test/episode.mkv', 2, 'srt'), + null, + ); +}); diff --git a/src/subsync/utils.ts b/src/subsync/utils.ts index 4375c51a..1ca05d26 100644 --- a/src/subsync/utils.ts +++ b/src/subsync/utils.ts @@ -250,6 +250,63 @@ export function extensionToFfmpegMuxer(extension: string): string { return extension; } +/** + * Derive Jellyfin's direct subtitle delivery endpoint for an embedded track on a + * direct-play stream URL (`.../Videos/{itemId}/stream?static=true&MediaSourceId=...&ApiKey=...`). + * Returns null for non-Jellyfin or transcoded URLs where stream indices may not match. + */ +export function buildJellyfinEmbeddedSubtitleUrl( + videoPath: string, + ffIndex: number, + extension: string, +): string | null { + if (!Number.isInteger(ffIndex) || ffIndex < 0 || !extension) return null; + let url: URL; + try { + url = new URL(videoPath); + } catch { + return null; + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + + const findParam = (pattern: RegExp): string | null => { + for (const [key, value] of url.searchParams) { + if (pattern.test(key) && value.trim().length > 0) { + return value.trim(); + } + } + return null; + }; + + if (findParam(/^static$/i)?.toLowerCase() !== 'true') return null; + + const apiKey = findParam(/^api_?key$/i); + const mediaSourceId = findParam(/^mediasourceid$/i); + if (!apiKey || !mediaSourceId) return null; + + const match = /^(.*)\/videos\/([^/]+)\/stream(?:\.[^/]+)?$/i.exec(url.pathname); + if (!match) return null; + + const basePath = match[1] ?? ''; + const rawItemId = match[2] ?? ''; + if (!rawItemId) return null; + + let itemId = rawItemId; + try { + itemId = decodeURIComponent(rawItemId); + } catch { + // Keep raw segment if it contains malformed percent escapes. + } + + const deliveryExt = extension === 'ttml' ? 'srt' : extension; + const subtitleUrl = new URL( + `${basePath}/Videos/${encodeURIComponent(itemId)}/${encodeURIComponent(mediaSourceId)}/Subtitles/${ffIndex}/Stream.${deliveryExt}`, + `${url.origin}/`, + ); + subtitleUrl.searchParams.set('ApiKey', apiKey); + return subtitleUrl.toString(); +} + export function runCommand( executable: string, args: string[],