diff --git a/src/core/services/subsync.test.ts b/src/core/services/subsync.test.ts index 4723003b..48683e7d 100644 --- a/src/core/services/subsync.test.ts +++ b/src/core/services/subsync.test.ts @@ -3089,25 +3089,26 @@ exit 1 test('triggerSubsyncFromConfig keeps sampled misalignment verdict when escalated full audio is unavailable', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-keep-misaligned-')); - const videoPath = path.join(tmpDir, 'ep01.mkv'); - const targetPath = path.join(tmpDir, 'ep01.ja.srt'); - const misalignedExtPath = path.join(tmpDir, 'ep01.en.srt'); - const pcmPath = path.join(tmpDir, 'speech.pcm'); - const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); - const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + try { + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const targetPath = path.join(tmpDir, 'ep01.ja.srt'); + const misalignedExtPath = path.join(tmpDir, 'ep01.en.srt'); + const pcmPath = path.join(tmpDir, 'speech.pcm'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); - fs.writeFileSync(videoPath, 'video'); - // Target and external reference share the same +5.0s offset off the actual audio, - // so an unverified fallback would wrongly align target to the misaligned external ref! - writeSrtFromSpans(targetPath, spans, 5.0); - writeSrtFromSpans(misalignedExtPath, spans, 5.0); - writeSpeechPcmFile(pcmPath, spans, 920); - const originalTarget = fs.readFileSync(targetPath, 'utf8'); + fs.writeFileSync(videoPath, 'video'); + // Target and external reference share the same +5.0s offset off the actual audio, + // so an unverified fallback would wrongly align target to the misaligned external ref! + writeSrtFromSpans(targetPath, spans, 5.0); + writeSrtFromSpans(misalignedExtPath, spans, 5.0); + writeSpeechPcmFile(pcmPath, spans, 920); + const originalTarget = fs.readFileSync(targetPath, 'utf8'); - // Sampled -ss/-t calls return real speech PCM; full-file audio extraction returns silence/empty. - writeExecutableScript( - fakeFfmpeg, - `#!/bin/sh + // Sampled -ss/-t calls return real speech PCM; full-file audio extraction returns silence/empty. + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh ss=0 dur=0 prev="" @@ -3123,99 +3124,103 @@ fi # Full-file pass writes no audio bytes (simulating unavailable full audio) and no usable sub. exit 0 `, - ); + ); - const modalPayloads: SubsyncManualPayload[] = []; - const osd: string[] = []; + const modalPayloads: SubsyncManualPayload[] = []; + 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 2; - 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: true, - external: true, - lang: 'eng', - title: 'English (Bad)', - 'external-filename': misalignedExtPath, - }, - { - id: 3, - type: 'sub', - selected: false, - external: false, - lang: 'eng', - title: 'English (Empty Embedded)', - codec: 'subrip', - 'ff-index': 3, - }, - ]; - } - return null; + 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 2; + 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: true, + external: true, + lang: 'eng', + title: 'English (Bad)', + 'external-filename': misalignedExtPath, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'eng', + title: 'English (Empty Embedded)', + codec: 'subrip', + 'ff-index': 3, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: fakeFfmpeg, + replace: true, + }), + openManualPicker: (payload) => { + modalPayloads.push(payload); + }, + showMpvOsd: (text) => { + osd.push(text); }, }), - getResolvedConfig: () => ({ - mode: 'auto', - alassPath: '/missing/alass', - ffsubsyncPath: '/missing/ffsubsync', - ffmpegPath: fakeFfmpeg, - replace: true, - }), - openManualPicker: (payload) => { - modalPayloads.push(payload); - }, - showMpvOsd: (text) => { - osd.push(text); - }, - }), - ); + ); - assert.equal(fs.readFileSync(targetPath, 'utf8'), originalTarget); - const modalPayload = modalPayloads[0]; - assert.ok(modalPayload !== undefined, `expected guided modal, got OSD: ${osd.join(' | ')}`); - assert.match(modalPayload.guidanceMessage ?? '', /misaligned with the audio/i); + assert.equal(fs.readFileSync(targetPath, 'utf8'), originalTarget); + const modalPayload = modalPayloads[0]; + assert.ok(modalPayload !== undefined, `expected guided modal, got OSD: ${osd.join(' | ')}`); + assert.match(modalPayload.guidanceMessage ?? '', /misaligned with the audio/i); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); test('triggerSubsyncFromConfig escalation extracts embedded tracks individually when combined rip fails', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-escalation-fallback-')); - const videoPath = path.join(tmpDir, 'ep01.mkv'); - const targetPath = path.join(tmpDir, 'ep01.ja.srt'); - const misalignedExtPath = path.join(tmpDir, 'ep01.bad.en.srt'); - const goodEmbeddedPath = path.join(tmpDir, 'fixture-embedded.srt'); - const pcmPath = path.join(tmpDir, 'speech.pcm'); - const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); - const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + try { + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const targetPath = path.join(tmpDir, 'ep01.ja.srt'); + const misalignedExtPath = path.join(tmpDir, 'ep01.bad.en.srt'); + const goodEmbeddedPath = path.join(tmpDir, 'fixture-embedded.srt'); + const pcmPath = path.join(tmpDir, 'speech.pcm'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); - fs.writeFileSync(videoPath, 'video'); - writeSrtFromSpans(targetPath, spans, 2.5); - writeSrtFromSpans(misalignedExtPath, spans, 6.0); - writeSrtFromSpans(goodEmbeddedPath, spans, 0); - writeSpeechPcmFile(pcmPath, spans, 920); + fs.writeFileSync(videoPath, 'video'); + writeSrtFromSpans(targetPath, spans, 2.5); + writeSrtFromSpans(misalignedExtPath, spans, 6.0); + writeSrtFromSpans(goodEmbeddedPath, spans, 0); + writeSpeechPcmFile(pcmPath, spans, 920); - // Sampled -ss/-t calls succeed; combined rip (has pipe:1 + *.srt) fails; full audio-only fails; - // individual embedded extraction (only *.srt, no pipe:1) succeeds for 0:3. - writeExecutableScript( - fakeFfmpeg, - `#!/bin/sh + // Sampled -ss/-t calls succeed; combined rip (has pipe:1 + *.srt) fails; full audio-only fails; + // individual embedded extraction (only *.srt, no pipe:1) succeeds for 0:3. + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh ss=0 dur=0 has_pipe=0 @@ -3245,94 +3250,98 @@ if [ -n "$out_srt" ] && [ "$cur_map" = "0:3" ]; then fi exit 1 `, - ); + ); - let modalOpened = false; - const osd: string[] = []; + 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 2; - 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: true, - external: true, - lang: 'eng', - title: 'English (Bad External)', - 'external-filename': misalignedExtPath, - }, - { - id: 3, - type: 'sub', - selected: false, - external: false, - lang: 'eng', - title: 'English (Embedded)', - codec: 'subrip', - 'ff-index': 3, - }, - ]; - } - return null; + 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 2; + 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: true, + external: true, + lang: 'eng', + title: 'English (Bad External)', + 'external-filename': misalignedExtPath, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'eng', + title: 'English (Embedded)', + 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); }, }), - 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.ok( - osd.some((line) => line.includes('English (Embedded)') && line.includes('-2.5')), - `expected sync via embedded fallback track around -2.5s, got: ${osd.join(' | ')}`, - ); + assert.equal(modalOpened, false); + assert.ok( + osd.some((line) => line.includes('English (Embedded)') && line.includes('-2.5')), + `expected sync via embedded fallback track around -2.5s, got: ${osd.join(' | ')}`, + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); test('triggerSubsyncFromConfig on non-Jellyfin remote stream falls back across lower-ranked embedded tracks when combined pass fails', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-remote-sibling-fallback-')); - const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); - const embeddedSpaPath = path.join(tmpDir, 'embedded-spa.srt'); - const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); - const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + try { + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const embeddedSpaPath = path.join(tmpDir, 'embedded-spa.srt'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); - writeSrtFromSpans(targetPath, spans, 2.1); - writeSrtFromSpans(embeddedSpaPath, spans, 0); + writeSrtFromSpans(targetPath, spans, 2.1); + writeSrtFromSpans(embeddedSpaPath, spans, 0); - // Combined pass (contains 0:2) fails because track 0:2 is corrupt; individual 0:2 fails; - // individual 0:3 succeeds! - writeExecutableScript( - fakeFfmpeg, - `#!/bin/sh + // Combined pass (contains 0:2) fails because track 0:2 is corrupt; individual 0:2 fails; + // individual 0:3 succeeds! + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh has_bad=0 out_srt="" prev="" @@ -3354,156 +3363,482 @@ if [ -n "$out_srt" ] && [ "$cur_map" = "0:3" ]; then fi exit 1 `, - ); + ); - let modalOpened = false; - const osd: string[] = []; + let modalOpened = false; + const osd: string[] = []; - await triggerSubsyncFromConfig( - makeDeps({ - getMpvClient: () => ({ - connected: true, - currentAudioStreamIndex: 1, - send: () => {}, - requestProperty: async (name: string) => { - if (name === 'path') return 'https://media.example.test/episode02.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 (Broken)', - codec: 'subrip', - 'ff-index': 2, - }, - { - id: 3, - type: 'sub', - selected: false, - external: false, - lang: 'spa', - title: 'Spanish (Healthy)', - codec: 'subrip', - 'ff-index': 3, - }, - ]; - } - return null; + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return 'https://media.example.test/episode02.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 (Broken)', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'spa', + title: 'Spanish (Healthy)', + 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); }, }), - 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.ok( - osd.some((line) => line.includes('Spanish (Healthy)') && line.includes('-2.1')), - `expected sync via healthy sibling track around -2.1s, got: ${osd.join(' | ')}`, - ); + assert.equal(modalOpened, false); + assert.ok( + osd.some((line) => line.includes('Spanish (Healthy)') && line.includes('-2.1')), + `expected sync via healthy sibling track around -2.1s, got: ${osd.join(' | ')}`, + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); test('runSubsyncManual alass on Jellyfin stream with external target does not require ffmpeg when reference fetches via HTTP', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-jellyfin-alass-no-ffmpeg-')); - const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); - const engSrtPath = path.join(tmpDir, 'eng.srt'); - const fakeAlass = path.join(tmpDir, 'alass.sh'); - const spans = generateSyntheticSpans(7n, 1442695040888963407n, 200); + try { + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const engSrtPath = path.join(tmpDir, 'eng.srt'); + const fakeAlass = path.join(tmpDir, 'alass.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 200); - writeSrtFromSpans(targetPath, spans, 1.5); - writeSrtFromSpans(engSrtPath, spans, 0); - const engSrtText = fs.readFileSync(engSrtPath, 'utf8'); - writeExecutableScript( - fakeAlass, - `#!/bin/sh + writeSrtFromSpans(targetPath, spans, 1.5); + writeSrtFromSpans(engSrtPath, spans, 0); + const engSrtText = fs.readFileSync(engSrtPath, 'utf8'); + writeExecutableScript( + fakeAlass, + `#!/bin/sh cp "$2" "$3" exit 0 `, - ); + ); - const fakeFetch: typeof fetch = (async () => - new Response(engSrtText, { status: 200 })) as typeof fetch; + const fakeFetch: typeof fetch = (async () => + new Response(engSrtText, { status: 200 })) as typeof fetch; - const result = await runSubsyncManual( - { - engine: 'alass', - 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-12/stream?static=true&ApiKey=secret-token&MediaSourceId=ms-12'; - } - 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; + const result = await runSubsyncManual( + { + engine: 'alass', + 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-12/stream?static=true&ApiKey=secret-token&MediaSourceId=ms-12'; + } + 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: fakeAlass, + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: '/missing/ffmpeg', + replace: false, + }), + }), + ); + + assert.equal(result.ok, true); + assert.match(result.message, /alass/i); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('runSubsyncManual alass with external reference track does not require ffmpeg', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-alass-ext-ref-no-ffmpeg-')); + try { + const targetPath = path.join(tmpDir, 'ep01.ja.srt'); + const refPath = path.join(tmpDir, 'ep01.en.srt'); + const fakeAlass = path.join(tmpDir, 'alass.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 200); + + writeSrtFromSpans(targetPath, spans, 1.5); + writeSrtFromSpans(refPath, spans, 0); + writeExecutableScript( + fakeAlass, + `#!/bin/sh +cp "$2" "$3" +exit 0 +`, + ); + + const result = await runSubsyncManual( + { + engine: 'alass', + referenceMode: 'track', + referenceTrackId: 2, + targetTrackId: 1, + }, + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return path.join(tmpDir, 'ep01.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: true, + lang: 'eng', + title: 'English', + 'external-filename': refPath, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: fakeAlass, + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: '/missing/ffmpeg', + replace: false, + }), + }), + ); + + assert.equal(result.ok, true); + assert.match(result.message, /alass/i); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('triggerSubsyncFromConfig on remote stream retries omitted embedded track when combined pass returns partial map', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-remote-partial-batch-')); + try { + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const unrelatedEngPath = path.join(tmpDir, 'unrelated-eng.srt'); + const goodSpaPath = path.join(tmpDir, 'good-spa.srt'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const targetSpans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + const unrelatedSpans = generateSyntheticSpans(99n, 314159265358979323n, 900); + + writeSrtFromSpans(targetPath, targetSpans, 2.2); + writeSrtFromSpans(unrelatedEngPath, unrelatedSpans, 0); + writeSrtFromSpans(goodSpaPath, targetSpans, 0); + + // Combined pass (2 maps) exits 0 but only writes 0:2 (omitting 0:3); + // individual call for 0:3 writes goodSpaPath. + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +map_count=0 +prev="" +cur_map="" +out_for_2="" +out_for_3="" +for arg in "$@"; do + if [ "$prev" = "-map" ]; then + cur_map="$arg" + map_count=$((map_count + 1)) + fi + case "$arg" in + *.srt) + if [ "$cur_map" = "0:2" ]; then out_for_2="$arg"; fi + if [ "$cur_map" = "0:3" ]; then out_for_3="$arg"; fi + ;; + esac + prev="$arg" +done +if [ "$map_count" -ge 2 ]; then + if [ -n "$out_for_2" ]; then cp "${toShellPath(unrelatedEngPath)}" "$out_for_2"; fi + exit 0 +fi +if [ -n "$out_for_3" ]; then + cp "${toShellPath(goodSpaPath)}" "$out_for_3" + exit 0 +fi +exit 1 +`, + ); + + let modalOpened = false; + const osd: string[] = []; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return 'https://media.example.test/episode03.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 (Wrong Ep)', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'spa', + title: 'Spanish (Omitted From Batch)', + 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); }, }), - getResolvedConfig: () => ({ - mode: 'auto', - alassPath: fakeAlass, - ffsubsyncPath: '/missing/ffsubsync', - ffmpegPath: '/missing/ffmpeg', - replace: false, - }), - }), - ); + ); - assert.equal(result.ok, true); - assert.match(result.message, /alass/i); + assert.equal(modalOpened, false); + assert.ok( + osd.some((line) => line.includes('Spanish (Omitted From Batch)') && line.includes('-2.2')), + `expected sync via omitted sibling track around -2.2s, got: ${osd.join(' | ')}`, + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); + +test('triggerSubsyncFromConfig on remote stream surfaces apply errors during individual embedded fallback', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-remote-apply-error-')); + try { + const targetPath = path.join(tmpDir, 'jimaku.ja.srt'); + const embeddedSpaPath = path.join(tmpDir, 'embedded-spa.srt'); + const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh'); + const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900); + + writeSrtFromSpans(targetPath, spans, 2.0); + writeSrtFromSpans(embeddedSpaPath, spans, 0); + + writeExecutableScript( + fakeFfmpeg, + `#!/bin/sh +has_bad=0 +out_srt="" +prev="" +cur_map="" +for arg in "$@"; do + if [ "$prev" = "-map" ]; then cur_map="$arg"; fi + if [ "$cur_map" = "0:2" ]; then has_bad=1; fi + case "$arg" in + *.srt) out_srt="$arg" ;; + esac + prev="$arg" +done +if [ "$has_bad" = "1" ]; then exit 1; fi +if [ -n "$out_srt" ] && [ "$cur_map" = "0:3" ]; then + cp "${toShellPath(embeddedSpaPath)}" "$out_srt" + exit 0 +fi +exit 1 +`, + ); + + let modalOpened = false; + const osd: string[] = []; + let pathReads = 0; + const mpvClient = { + connected: true, + currentAudioStreamIndex: 1, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') { + pathReads += 1; + // Disconnect right after the pre-write session check passes so loadSyncedSubtitle throws. + if (pathReads >= 2) { + mpvClient.connected = false; + } + return 'https://media.example.test/episode04.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 (Broken)', + codec: 'subrip', + 'ff-index': 2, + }, + { + id: 3, + type: 'sub', + selected: false, + external: false, + lang: 'spa', + title: 'Spanish (Healthy)', + codec: 'subrip', + 'ff-index': 3, + }, + ]; + } + return null; + }, + }; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => mpvClient, + 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.ok( + osd.some((line) => line.startsWith('Subsync failed:')), + `expected Subsync failed OSD when applyAlignment throws, got: ${osd.join(' | ')}`, + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } }); diff --git a/src/core/services/subsync.ts b/src/core/services/subsync.ts index 2f10b85c..4d1678de 100644 --- a/src/core/services/subsync.ts +++ b/src/core/services/subsync.ts @@ -1092,23 +1092,8 @@ async function runBuiltinSubsync( message: 'Reference and out-of-sync subtitles must be different tracks', }; } - 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, + resolved.ffmpegPath, context.videoPath, referenceTrack, context.workingDirectory, @@ -1434,6 +1419,7 @@ export async function runSubsyncManual( resolved, client, targetSlot, + deps.fetchImpl, ); } finally { cleanupTemporaryFile(cleaned); @@ -1448,25 +1434,11 @@ export async function runSubsyncManual( return { ok: false, message: 'Reference and out-of-sync subtitles must be different tracks' }; } - 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 { referenceExtraction = await extractSubtitleTrackToFile( - ffmpegPath, + resolved.ffmpegPath, context.videoPath, referenceTrack, context.workingDirectory, @@ -2039,34 +2011,43 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise includeAudio: false, }); if (singlePass) { - for (const [ffIndex, parsed] of singlePass.embeddedSubtitles) { - remoteExtracted.set(ffIndex, parsed); - } - } else { - // Single-pass failed (e.g. one broken track aborted the combined pass): try - // remaining tracks individually in rank order and stop on the first confident match. - for (const fallbackItem of remainingItems) { - let extraction: FileExtractionResult | null = null; - try { - extraction = await extractSubtitleTrackToFile( - resolved.ffmpegPath, - context.videoPath, - fallbackItem.track, - context.workingDirectory, - deps.fetchImpl, - ); - const parsed = readAndParseSubtitleFile(extraction.path); - if (parsed.events.length === 0) continue; - if (await tryAlignRemoteEmbeddedTrack(fallbackItem, parsed)) { - return; - } - } catch { - // Continue to lower-ranked sibling tracks if this track fails. - } finally { - cleanupTemporaryFile(extraction); + for (const item of remainingItems) { + const parsed = singlePass.embeddedSubtitles.get(item.ffIndex); + if (!parsed) continue; + if (await tryAlignRemoteEmbeddedTrack(item, parsed)) { + return; } } } + + // Retry any ranked track omitted by the combined pass (whether the pass returned null + // or a partial map) individually in rank order, stopping on the first confident match. + const missingItems = remainingItems.filter( + (item) => !remoteExtracted.has(item.ffIndex), + ); + for (const fallbackItem of missingItems) { + let extraction: FileExtractionResult | null = null; + let parsed: ParsedSubtitleFile | null = null; + try { + extraction = await extractSubtitleTrackToFile( + resolved.ffmpegPath, + context.videoPath, + fallbackItem.track, + context.workingDirectory, + deps.fetchImpl, + ); + parsed = readAndParseSubtitleFile(extraction.path); + } catch { + // Continue to lower-ranked sibling tracks if extracting or parsing this track fails. + continue; + } finally { + cleanupTemporaryFile(extraction); + } + if (parsed.events.length === 0) continue; + if (await tryAlignRemoteEmbeddedTrack(fallbackItem, parsed)) { + return; + } + } } if (remoteExtracted.size > 0) {