diff --git a/src/core/services/subsync-runner.ts b/src/core/services/subsync-runner.ts index 4a8777a1..c1111efd 100644 --- a/src/core/services/subsync-runner.ts +++ b/src/core/services/subsync-runner.ts @@ -74,12 +74,14 @@ export async function openSubsyncManualPickerRuntime(deps: SubsyncRuntimeDeps): } triggerDeps.setSubsyncInProgress(true); try { - await triggerDeps.runWithSubsyncSpinner(() => + const opened = await triggerDeps.runWithSubsyncSpinner(() => openSubsyncManualPicker(triggerDeps, { guidanceMessage: null, }), ); - triggerDeps.showMpvOsd('Subsync: choose engine and subtitles'); + if (opened) { + triggerDeps.showMpvOsd('Subsync: choose engine and subtitles'); + } } catch (error) { triggerDeps.showMpvOsd(`Subsync failed: ${(error as Error).message}`); } finally { diff --git a/src/core/services/subsync.test.ts b/src/core/services/subsync.test.ts index 4081511a..a930395f 100644 --- a/src/core/services/subsync.test.ts +++ b/src/core/services/subsync.test.ts @@ -72,13 +72,20 @@ test('triggerSubsyncFromConfig opens manual picker', async () => { const osd: string[] = []; let payloadTrackCount = 0; let ffsubsyncAvailable: boolean | null = null; + let payloadMediaPath: string | null | undefined = undefined; let inProgressState: boolean | null = null; await triggerSubsyncFromConfig( makeDeps({ + getResolvedConfig: () => ({ + alassPath: process.execPath, + ffsubsyncPath: process.execPath, + ffmpegPath: process.execPath, + }), openManualPicker: (payload) => { payloadTrackCount = payload.subtitleTracks.length; ffsubsyncAvailable = payload.ffsubsyncAvailable; + payloadMediaPath = payload.mediaPath; }, showMpvOsd: (text) => { osd.push(text); @@ -91,6 +98,7 @@ test('triggerSubsyncFromConfig opens manual picker', async () => { assert.equal(payloadTrackCount, 2); assert.equal(ffsubsyncAvailable, true); + assert.equal(payloadMediaPath, '/tmp/video.mkv'); assert.ok(osd.includes('Subsync: choose engine and subtitles')); assert.equal(inProgressState, false); }); @@ -1829,3 +1837,356 @@ test('runSubsyncManual refuses destructive replace when target subtitle encoding assert.match(result.message, /losslessly/i); assert.deepEqual(fs.readFileSync(targetPath), corruptBytes); }); + +test('runSubsyncManual rejects stale submissions when active video changed since picker opened', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-stale-media-')); + const videoA = path.join(tmpDir, 'ep01.mkv'); + const videoB = path.join(tmpDir, 'ep02.mkv'); + const targetB = path.join(tmpDir, 'ep02.ja.srt'); + const original = '1\n00:00:01,000 --> 00:00:03,000\nこんにちは\n'; + fs.writeFileSync(videoA, 'a'); + fs.writeFileSync(videoB, 'b'); + fs.writeFileSync(targetB, original, 'utf8'); + + const result = await runSubsyncManual( + { + engine: 'offset', + mediaPath: videoA, + targetTrackId: 1, + offsetMs: 1000, + }, + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: null, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return videoB; + if (name === 'sid') return 1; + if (name === 'secondary-sid') return null; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': targetB, + }, + ]; + } + return null; + }, + }), + }), + ); + + assert.equal(result.ok, false); + assert.match(result.message, /Active video changed/i); + assert.equal(fs.readFileSync(targetB, 'utf8'), original); +}); + +test('triggerSubsyncFromConfig normalizes file:// video URLs as local media', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-file-url-')); + const videoPath = path.join(tmpDir, 'ep01.mkv'); + fs.writeFileSync(videoPath, 'video'); + const fileUrl = `file://${videoPath}`; + let capturedPayload: SubsyncManualPayload | null = null; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: null, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') return fileUrl; + if (name === 'sid') return 1; + if (name === 'secondary-sid') return null; + if (name === 'track-list') { + return [{ id: 1, type: 'sub', selected: true, lang: 'jpn' }]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'manual', + alassPath: process.execPath, + ffsubsyncPath: process.execPath, + ffmpegPath: process.execPath, + }), + openManualPicker: (payload) => { + capturedPayload = payload; + }, + }), + ); + + assert.ok(capturedPayload); + const resolved = capturedPayload as SubsyncManualPayload; + assert.equal(resolved.videoReferenceAvailable, true); + assert.equal(resolved.ffsubsyncAvailable, true); + assert.equal(resolved.mediaPath, videoPath); +}); + +test('runSubsyncManual allows retiming an unchanged inactive target track', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-inactive-target-')); + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const activeSub = path.join(tmpDir, 'active.srt'); + const inactiveSub = path.join(tmpDir, 'inactive.srt'); + fs.writeFileSync(videoPath, 'video'); + fs.writeFileSync(activeSub, '1\n00:00:01,000 --> 00:00:02,000\nactive\n', 'utf8'); + fs.writeFileSync(inactiveSub, '1\n00:00:05,000 --> 00:00:07,000\ninactive\n', 'utf8'); + + const commands: Array<(string | number)[]> = []; + const result = await runSubsyncManual( + { + engine: 'offset', + mediaPath: videoPath, + targetTrackId: 3, + offsetMs: 1000, + }, + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: null, + send: (payload) => { + commands.push(payload.command); + }, + requestProperty: async (name: string) => { + if (name === 'path') return videoPath; + if (name === 'sid') return 1; + if (name === 'secondary-sid') return null; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + lang: 'jpn', + 'external-filename': activeSub, + }, + { + id: 3, + type: 'sub', + selected: false, + external: true, + lang: 'jpn', + 'external-filename': inactiveSub, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: '/missing/ffmpeg', + replace: true, + }), + }), + ); + + assert.equal(result.ok, true); + assert.ok(fs.readFileSync(inactiveSub, 'utf8').includes('00:00:06,000 --> 00:00:08,000')); + assert.ok(commands.some((cmd) => cmd[0] === 'sub-add' && cmd[1] === inactiveSub)); +}); + +test('triggerSubsyncFromConfig discards auto-sync when user disables target slot mid-sync', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-disabled-slot-')); + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const targetPath = path.join(tmpDir, 'ep01.ja.srt'); + const refPath = path.join(tmpDir, 'ep01.en.srt'); + fs.writeFileSync(videoPath, 'video'); + + const lines: string[] = []; + const targetLines: string[] = []; + for (let i = 0; i < 40; i += 1) { + const start = 10 + i * 5; + const end = start + 2; + const fmt = (sec: number) => { + const m = Math.floor(sec / 60); + const s = sec % 60; + return `00:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},000`; + }; + lines.push(`${i + 1}\n${fmt(start)} --> ${fmt(end)}\nLine ${i + 1}\n`); + targetLines.push(`${i + 1}\n${fmt(start + 3)} --> ${fmt(end + 3)}\nセリフ ${i + 1}\n`); + } + const originalTarget = targetLines.join('\n'); + fs.writeFileSync(refPath, lines.join('\n'), 'utf8'); + fs.writeFileSync(targetPath, originalTarget, 'utf8'); + + let sidCalls = 0; + const sentCommands: Array<(string | number)[]> = []; + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: null, + send: (payload) => { + sentCommands.push(payload.command); + }, + requestProperty: async (name: string) => { + if (name === 'path') return videoPath; + if (name === 'sid') { + sidCalls += 1; + return sidCalls === 1 ? 1 : 'no'; + } + if (name === 'secondary-sid') return 2; + if (name === 'duration') return 400; + 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', + 'external-filename': refPath, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: '/missing/ffmpeg', + replace: true, + }), + }), + ); + + assert.deepEqual(sentCommands, []); + assert.equal(fs.readFileSync(targetPath, 'utf8'), originalTarget); +}); + +test('triggerSubsyncFromConfig skips early extraction fallback picker when playback switches', async () => { + let pathCalls = 0; + let pickerOpened = false; + + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: null, + send: () => {}, + requestProperty: async (name: string) => { + if (name === 'path') { + pathCalls += 1; + return pathCalls === 1 ? '/tmp/videoA.mkv' : '/tmp/videoB.mkv'; + } + if (name === 'sid') return 1; + if (name === 'secondary-sid') return null; + if (name === 'track-list') { + return [{ id: 1, type: 'sub', selected: true, lang: 'jpn' }]; + } + return null; + }, + }), + openManualPicker: () => { + pickerOpened = true; + }, + }), + ); + + assert.equal(pickerOpened, false); +}); + +test('triggerSubsyncFromConfig resets non-zero sub-delay when already in sync without rewriting', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-reset-delay-')); + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const targetPath = path.join(tmpDir, 'ep01.ja.srt'); + const refPath = path.join(tmpDir, 'ep01.en.srt'); + fs.writeFileSync(videoPath, 'video'); + + let t = 5; + const spans: Array<[number, number]> = []; + for (let i = 0; i < 60; i += 1) { + const dur = 1.2 + ((i * 7) % 5) * 0.4; + const gap = 0.6 + ((i * 13) % 7) * 0.7; + spans.push([t, t + dur]); + t += dur + gap; + } + const fmt = (sec: number) => { + const h = Math.floor(sec / 3600); + const m = Math.floor((sec % 3600) / 60); + const s = Math.floor(sec % 60); + const ms = Math.round((sec - Math.floor(sec)) * 1000); + return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},${String(ms).padStart(3, '0')}`; + }; + const srt = spans + .map(([s, e], i) => `${i + 1}\n${fmt(s)} --> ${fmt(e)}\nLine ${i + 1}\n`) + .join('\n'); + fs.writeFileSync(refPath, srt, 'utf8'); + fs.writeFileSync(targetPath, srt, 'utf8'); + const mtimeBefore = fs.statSync(targetPath).mtimeMs; + + const sentCommands: Array<(string | number)[]> = []; + const osd: string[] = []; + await triggerSubsyncFromConfig( + makeDeps({ + getMpvClient: () => ({ + connected: true, + currentAudioStreamIndex: null, + send: (payload) => { + sentCommands.push(payload.command); + }, + requestProperty: async (name: string) => { + if (name === 'path') return videoPath; + if (name === 'sid') return 1; + if (name === 'secondary-sid') return 2; + if (name === 'sub-delay') return 2.5; + if (name === 'duration') return 600; + 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', + 'external-filename': refPath, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + mode: 'auto', + alassPath: '/missing/alass', + ffsubsyncPath: '/missing/ffsubsync', + ffmpegPath: '/missing/ffmpeg', + replace: true, + }), + showMpvOsd: (text) => { + osd.push(text); + }, + }), + ); + + assert.deepEqual(sentCommands, [['set_property', 'sub-delay', 0]]); + assert.equal(fs.statSync(targetPath).mtimeMs, mtimeBefore); + assert.ok(osd.some((line) => line.includes('Reset subtitle delay to 0s'))); +}); diff --git a/src/core/services/subsync.ts b/src/core/services/subsync.ts index ea7685f7..317de220 100644 --- a/src/core/services/subsync.ts +++ b/src/core/services/subsync.ts @@ -12,6 +12,7 @@ import { import { CommandResult, codecToExtension, + extensionToFfmpegMuxer, fileExists, findSubsyncExecutable, formatTrackLabel, @@ -205,7 +206,7 @@ function resolveLocalSubtitlePath( ): string | null { if (!rawPath) return null; let local = rawPath; - if (local.startsWith('file://')) { + if (/^file:\/\//i.test(local)) { try { local = fileURLToPath(local); } catch { @@ -220,6 +221,10 @@ function resolveLocalSubtitlePath( return local; } +function normalizeMediaVideoPath(rawPath: string, workingDirectory?: string | null): string { + return resolveLocalSubtitlePath(rawPath, workingDirectory) ?? rawPath; +} + async function gatherSubsyncContext(client: MpvClientLike): Promise { const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw, workingDirRaw, durationRaw] = await Promise.all([ @@ -238,9 +243,7 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise 0 ? workingDirRaw : null; - const resolvedVideoPath = isRemoteMediaPath(videoPath) - ? videoPath - : (resolveLocalSubtitlePath(videoPath, workingDirectory) ?? videoPath); + const resolvedVideoPath = normalizeMediaVideoPath(videoPath, workingDirectory); const tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : []; const subtitleTracks = tracks.filter((track) => track.type === 'sub'); @@ -345,7 +348,7 @@ async function extractSubtitleTrackToFile( '-map', `0:${ffIndex}`, '-f', - extension, + extensionToFfmpegMuxer(extension), outputPath, ]); @@ -424,27 +427,46 @@ async function isPlaybackSessionUnchanged( if (!client.connected) return false; try { const slotProperty = slot === 'secondary' ? 'secondary-sid' : 'sid'; - const [videoPathRaw, workingDirRaw, slotTrackRaw] = await Promise.all([ + const initialSlotTrackId = + slot === 'secondary' + ? (context.secondaryTrack?.id ?? null) + : (context.primaryTrack.id ?? null); + const needsTrackIdentityCheck = + typeof targetTrack.id === 'number' && targetTrack.id !== initialSlotTrackId; + const [videoPathRaw, workingDirRaw, slotTrackRaw, trackListRaw] = await Promise.all([ client.requestProperty('path'), client.requestProperty('working-directory').catch(() => null), client.requestProperty(slotProperty), + needsTrackIdentityCheck + ? client.requestProperty('track-list').catch(() => null) + : Promise.resolve(null), ]); const currentRawPath = typeof videoPathRaw === 'string' ? videoPathRaw : ''; if (!currentRawPath) return false; const currentWorkingDir = typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null; - const currentVideoPath = isRemoteMediaPath(currentRawPath) - ? currentRawPath - : (resolveLocalSubtitlePath(currentRawPath, currentWorkingDir) ?? currentRawPath); + const currentVideoPath = normalizeMediaVideoPath(currentRawPath, currentWorkingDir); if ( normalizeSubtitlePathForCompare(currentVideoPath) !== normalizeSubtitlePathForCompare(context.videoPath) ) { return false; } - if (typeof targetTrack.id === 'number') { - const currentSlotId = parseTrackId(slotTrackRaw); - if (currentSlotId !== null && currentSlotId !== targetTrack.id) { + const currentSlotId = parseTrackId(slotTrackRaw); + if (currentSlotId !== initialSlotTrackId) { + return false; + } + if (needsTrackIdentityCheck) { + const tracks = Array.isArray(trackListRaw) + ? normalizeTrackIds(trackListRaw as MpvTrack[]) + : []; + const currentTarget = tracks.find( + (track) => track.type === 'sub' && track.id === targetTrack.id, + ); + if ( + !currentTarget || + getSourceTrackIdentity(currentTarget) !== getSourceTrackIdentity(targetTrack) + ) { return false; } } @@ -903,6 +925,7 @@ function buildManualPayload( defaultTargetTrackId: primaryTrackId, videoReferenceAvailable: isLocalMedia, ffsubsyncAvailable, + mediaPath: context.videoPath, guidanceMessage: options.guidanceMessage ?? null, referenceCandidates, defaultReferenceKey: recommendedKey, @@ -1140,6 +1163,10 @@ async function subsyncToReference( }; } + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot))) { + return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; + } + await loadSyncedSubtitle(client, outputPath, slot); return { ok: true, @@ -1205,6 +1232,24 @@ export async function runSubsyncManual( const context = await gatherSubsyncContext(client); const resolved = deps.getResolvedConfig(); + if (request.mediaPath !== undefined && request.mediaPath !== null) { + const trimmedMediaPath = request.mediaPath.trim(); + const expectedVideoPath = trimmedMediaPath + ? normalizeMediaVideoPath(trimmedMediaPath, context.workingDirectory) + : ''; + if ( + !expectedVideoPath || + normalizeSubtitlePathForCompare(expectedVideoPath) !== + normalizeSubtitlePathForCompare(context.videoPath) + ) { + return { + ok: false, + message: + 'Active video changed since the subsync picker opened. Reopen subsync for the current video.', + }; + } + } + const targetTrack = resolveTargetTrack(request, context); if (!targetTrack) { return { ok: false, message: 'Select the out-of-sync subtitle track to retime' }; @@ -1367,7 +1412,11 @@ async function prepareRipCandidatesAndAudio( // 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); + const cachedFull = getCachedAudioSpeechSpans( + context.videoPath, + context.audioStreamIndex, + vadPaths, + ); if (cachedFull) { return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null }; } @@ -1405,7 +1454,7 @@ export async function openSubsyncManualPicker( guidanceMessage?: string | null; skipAudioAnalysis?: boolean; } = {}, -): Promise { +): Promise { const client = getMpvClientForSubsync(deps); const context = await gatherSubsyncContext(client); const resolved = deps.getResolvedConfig(); @@ -1438,6 +1487,9 @@ export async function openSubsyncManualPicker( preExtractedEmbedded: prepared.preExtractedEmbedded, }, ); + if (!(await isPlaybackSessionUnchanged(client, context, context.primaryTrack, 'primary'))) { + return false; + } } const payload = buildManualPayload(context, resolved, deps, { @@ -1446,6 +1498,7 @@ export async function openSubsyncManualPicker( guidanceMessage: options.guidanceMessage ?? null, }); deps.openManualPicker(payload); + return true; } async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise { @@ -1467,6 +1520,9 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise context.workingDirectory, ); } catch (extractError) { + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { + return; + } const payload = buildManualPayload(context, resolved, deps, { guidanceMessage: `Automatic sync could not read the active subtitle track (${(extractError as Error).message}). Choose an engine and subtitle tracks below.`, }); @@ -1478,6 +1534,9 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise const targetInfo = extractSpansFromParsedSubtitle(parsedTarget, { stripSigns: true }); if (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) { + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { + return; + } const payload = buildManualPayload(context, resolved, deps, { guidanceMessage: 'Could not read dialogue cues from the active subtitle track. Choose an engine or reference below.', @@ -1514,6 +1573,14 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise return; } if (isAlreadyInSync(alignment)) { + const delayProperty = targetSlot === 'secondary' ? 'secondary-sub-delay' : 'sub-delay'; + const activeDelayRaw = await client.requestProperty(delayProperty).catch(() => null); + const activeDelay = parseOptionalNumber(activeDelayRaw); + if (activeDelay !== null && Math.abs(activeDelay) > 0.005) { + client.send({ command: ['set_property', delayProperty, 0] }); + deps.showMpvOsd(`Reset subtitle delay to 0s (already in sync with ${sourceLabel})`); + return; + } deps.showMpvOsd(`Subtitles are already in sync (${sourceLabel})`); return; } @@ -1722,8 +1789,10 @@ export async function triggerSubsyncFromConfig(deps: TriggerSubsyncFromConfigDep try { const resolved = deps.getResolvedConfig(); if (resolved.mode === 'manual') { - await openSubsyncManualPicker(deps, { skipAudioAnalysis: true }); - deps.showMpvOsd('Subsync: choose engine and subtitles'); + const opened = await openSubsyncManualPicker(deps, { skipAudioAnalysis: true }); + if (opened) { + deps.showMpvOsd('Subsync: choose engine and subtitles'); + } return; } diff --git a/src/renderer/modals/subsync.test.ts b/src/renderer/modals/subsync.test.ts index 1085889c..3ef5eb1c 100644 --- a/src/renderer/modals/subsync.test.ts +++ b/src/renderer/modals/subsync.test.ts @@ -488,6 +488,7 @@ test('guided subsync modal shows guidance banner, ranked candidates, browse file harness.modal.wireDomEvents(); harness.modal.openSubsyncModal( payloadWith({ + mediaPath: '/tmp/ep01.mkv', guidanceMessage: 'Loaded English track appears +2.4s off audio.', defaultEngine: 'builtin', builtinAvailable: true, @@ -530,6 +531,7 @@ test('guided subsync modal shows guidance banner, ranked candidates, browse file assert.deepEqual(request, { engine: 'builtin', + mediaPath: '/tmp/ep01.mkv', targetTrackId: 1, referenceMode: 'file', referenceTrackId: null, diff --git a/src/renderer/modals/subsync.ts b/src/renderer/modals/subsync.ts index 86307a90..4da51ea3 100644 --- a/src/renderer/modals/subsync.ts +++ b/src/renderer/modals/subsync.ts @@ -443,6 +443,7 @@ export function createSubsyncModal( const request: SubsyncManualRunRequest = { engine, targetTrackId, + ...(currentPayload.mediaPath ? { mediaPath: currentPayload.mediaPath } : {}), }; if (engine === 'builtin' || engine === 'alass') { const parsed = parseReferenceValue(referenceValue); diff --git a/src/shared/ipc/validators.test.ts b/src/shared/ipc/validators.test.ts index a0b57e8b..97294cfc 100644 --- a/src/shared/ipc/validators.test.ts +++ b/src/shared/ipc/validators.test.ts @@ -4,7 +4,11 @@ import test from 'node:test'; import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions'; import { compileSessionBindings } from '../../core/services/session-bindings'; import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config'; -import { parseSessionActionDispatchRequest, parseUnforwardedMpvKeyReport } from './validators'; +import { + parseSessionActionDispatchRequest, + parseSubsyncManualRunRequest, + parseUnforwardedMpvKeyReport, +} from './validators'; // Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the // SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to @@ -46,3 +50,22 @@ test('unforwarded mpv key reports accept known reasons only', () => { assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null); assert.equal(parseUnforwardedMpvKeyReport(null), null); }); + +test('parseSubsyncManualRunRequest validates optional mediaPath', () => { + const parsed = parseSubsyncManualRunRequest({ + engine: 'builtin', + mediaPath: '/tmp/ep01.mkv', + referenceMode: 'track', + referenceTrackId: 2, + targetTrackId: 1, + }); + assert.equal(parsed?.mediaPath, '/tmp/ep01.mkv'); + assert.equal( + parseSubsyncManualRunRequest({ + engine: 'builtin', + mediaPath: 123, + targetTrackId: 1, + }), + null, + ); +}); diff --git a/src/shared/ipc/validators.ts b/src/shared/ipc/validators.ts index dc278f21..1079bc18 100644 --- a/src/shared/ipc/validators.ts +++ b/src/shared/ipc/validators.ts @@ -317,6 +317,7 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe if (!isObject(value)) return null; const { engine, + mediaPath, referenceMode, referenceTrackId, referenceFilePath, @@ -328,6 +329,9 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe if (engine !== 'builtin' && engine !== 'alass' && engine !== 'ffsubsync' && engine !== 'offset') { return null; } + if (mediaPath !== undefined && mediaPath !== null && typeof mediaPath !== 'string') { + return null; + } if ( referenceMode !== undefined && referenceMode !== 'track' && @@ -366,6 +370,7 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe return { engine, + ...(mediaPath !== undefined ? { mediaPath } : {}), referenceMode, referenceTrackId: parsedReferenceTrackId, referenceFilePath: typeof referenceFilePath === 'string' ? referenceFilePath : null, diff --git a/src/subsync/alass-align.test.ts b/src/subsync/alass-align.test.ts index 8f452ce1..1f714f7a 100644 --- a/src/subsync/alass-align.test.ts +++ b/src/subsync/alass-align.test.ts @@ -6,6 +6,7 @@ import { evaluateReferenceAlignmentToAudio, evaluateReferenceAlignmentToSampledAudio, joinSpans, + wrappedCoverage, type SampledAudioWindow, } from './alass-align'; import { @@ -208,3 +209,48 @@ test('evaluateReferenceAlignmentToSampledAudio verifies aligned vs misaligned re const hugeEval = evaluateReferenceAlignmentToSampledAudio(hugeShiftRef, windows); assert.equal(hugeEval.status, 'unverified'); }); + +test('wrappedCoverage counts both fragments of a cue crossing the wrap boundary', () => { + const line = [{ start: 54, end: 58 }]; + const ref = [ + { start: 0, end: 3 }, + { start: 59, end: 60 }, + ]; + // Shifting [54, 58] by +5s in a 60s window wraps to [59, 60] (1s) + [0, 3] (3s) = 4s / 4s = 1.0. + assert.equal(wrappedCoverage(line, 4, ref, 5, 60), 1); + // Also works for shifts larger than the window length and negative shifts. + assert.equal(wrappedCoverage(line, 4, ref, 65, 60), 1); + assert.equal( + wrappedCoverage( + [{ start: 1, end: 5 }], + 4, + [ + { start: 0, end: 2 }, + { start: 58, end: 60 }, + ], + -3, + 60, + ), + 1, + ); +}); + +test('alignSubtitleFileToReferenceSpans rejects broadcast pieces that collapse onto the same reference section', () => { + const actPattern = generateDialogueRhythm(7n, 1442695040888963407n).filter((s) => s.end < 120); + // Two identical target acts separated by a long pause within the standing shift range, + // while the reference only contains one matching section. + const repeatedTarget = [ + ...actPattern, + ...actPattern.map((s) => ({ start: s.start + 150, end: s.end + 150 })), + ]; + const parsedTarget = parseSubtitleFileContent(spansToSrtFile(repeatedTarget), 'dup-acts.ja.srt'); + + const result = alignSubtitleFileToReferenceSpans(parsedTarget, actPattern, { + calibration: 'clean', + lengthSec: 320, + allowSplits: true, + }); + + assert.equal(result.cut, false); + assert.equal(result.confident, false); +}); diff --git a/src/subsync/alass-align.ts b/src/subsync/alass-align.ts index f8ca44ac..dedcf575 100644 --- a/src/subsync/alass-align.ts +++ b/src/subsync/alass-align.ts @@ -421,28 +421,78 @@ function startsStanding( return weakest >= PIECE_Z_MIN ? whole : Math.min(weakest, whole); } -function wrappedCoverage( +function wrapSpansInPeriod( + spans: readonly SubtitleTimeSpan[], + shift: number, + period: number, +): SubtitleTimeSpan[] { + if (period <= 0 || spans.length === 0) return []; + const modShift = ((shift % period) + period) % period; + const out: SubtitleTimeSpan[] = []; + for (let i = 0; i < spans.length; i += 1) { + const line = spans[i]!; + const dur = Math.min(period, line.end - line.start); + if (dur <= 0) continue; + const wStart = (((line.start + modShift) % period) + period) % period; + const wEnd = wStart + dur; + if (wEnd <= period) { + out.push({ start: wStart, end: wEnd }); + } else { + out.push({ start: wStart, end: period }); + out.push({ start: 0, end: wEnd - period }); + } + } + out.sort((a, b) => a.start - b.start); + return out; +} + +export function wrappedCoverage( sortedLines: readonly SubtitleTimeSpan[], total: number, joinedRef: readonly SubtitleTimeSpan[], shift: number, lengthSec: number, ): number { - let covered = 0; - if (shift >= 0) { - let cut = 0; - while (cut < sortedLines.length && sortedLines[cut]!.start + shift < lengthSec) cut += 1; - covered = - coveredAt(sortedLines.slice(0, cut), joinedRef, shift) + - coveredAt(sortedLines.slice(cut), joinedRef, shift - lengthSec); - } else { - let cut = 0; - while (cut < sortedLines.length && sortedLines[cut]!.start + shift < 0) cut += 1; - covered = - coveredAt(sortedLines.slice(0, cut), joinedRef, shift + lengthSec) + - coveredAt(sortedLines.slice(cut), joinedRef, shift); + if (sortedLines.length === 0 || total <= 0 || lengthSec <= 0) return 0; + const modShift = ((shift % lengthSec) + lengthSec) % lengthSec; + const firstStart = sortedLines[0]!.start; + const lastStart = sortedLines[sortedLines.length - 1]!.start; + if (firstStart >= 0 && lastStart < lengthSec) { + const inRange: SubtitleTimeSpan[] = []; + const wrapped: SubtitleTimeSpan[] = []; + const crossingHeads: SubtitleTimeSpan[] = []; + for (let i = 0; i < sortedLines.length; i += 1) { + const line = sortedLines[i]!; + const dur = Math.min(lengthSec, line.end - line.start); + if (dur <= 0) continue; + const shiftedStart = line.start + modShift; + if (shiftedStart < lengthSec) { + const shiftedEnd = shiftedStart + dur; + if (shiftedEnd <= lengthSec) { + inRange.push({ start: shiftedStart, end: shiftedEnd }); + } else { + inRange.push({ start: shiftedStart, end: lengthSec }); + crossingHeads.push({ start: 0, end: shiftedEnd - lengthSec }); + } + } else { + const wStart = shiftedStart - lengthSec; + const wEnd = wStart + dur; + if (wEnd <= lengthSec) { + wrapped.push({ start: wStart, end: wEnd }); + } else { + wrapped.push({ start: wStart, end: lengthSec }); + crossingHeads.push({ start: 0, end: wEnd - lengthSec }); + } + } + } + let covered = 0; + if (inRange.length > 0) covered += coveredAt(inRange, joinedRef, 0); + if (wrapped.length > 0) covered += coveredAt(wrapped, joinedRef, 0); + if (crossingHeads.length > 0) covered += coveredAt(crossingHeads, joinedRef, 0); + return covered / total; } - return covered / total; + const wrapped = wrapSpansInPeriod(sortedLines, modShift, lengthSec); + return coveredAt(wrapped, joinedRef, 0) / total; } export function evaluateStanding( @@ -725,6 +775,29 @@ function alignBroadcastPieces( if (pieces.length < 2 || pieces.length > MAX_PIECES) return null; + // Placed acts must stay in chronological reference order and must not overlap + // onto the same reference interval. + const MAX_PIECE_OVERLAP_SEC = 2.0; + let prevPlacedStart = -Infinity; + let prevPlacedEnd = -Infinity; + for (const p of pieces) { + const placedStart = scaledSorted[p.first]!.start + p.shift; + let maxRawEnd = scaledSorted[p.first]!.end; + for (let i = p.first + 1; i < p.end; i += 1) { + if (scaledSorted[i]!.end > maxRawEnd) maxRawEnd = scaledSorted[i]!.end; + } + const placedEnd = maxRawEnd + p.shift; + if ( + placedStart < prevPlacedStart || + placedEnd <= prevPlacedEnd || + placedStart < prevPlacedEnd - MAX_PIECE_OVERLAP_SEC + ) { + return null; + } + prevPlacedStart = placedStart; + prevPlacedEnd = placedEnd; + } + let weightedZSum = 0; let totalLines = 0; let weakest = Infinity; @@ -851,29 +924,35 @@ export function alignSubtitleFileToReferenceSpans( }; const plain = evaluateRatio(1.0); + const plainScore = scoreStanding(plain.standing, cal); let chosen = plain; // Only test framerate conversions if plain fit isn't already near-perfect or to catch PAL speedup. - const altFits = FRAMERATE_RATIOS.slice(1).map(evaluateRatio); - const bestAltByAbove = altFits.reduce( - (best, cur) => (cur.standing.above > best.standing.above ? cur : best), - altFits[0]!, - ); - const bestAltByStarts = altFits.reduce( - (best, cur) => (cur.standing.starts > best.standing.starts ? cur : best), - altFits[0]!, - ); + // Never replace the plain fit with an alternate that lowers final confidence. + const altFits = FRAMERATE_RATIOS.slice(1) + .map(evaluateRatio) + .filter((alt) => scoreStanding(alt.standing, cal) >= plainScore); + if (altFits.length > 0) { + const bestAltByAbove = altFits.reduce( + (best, cur) => (cur.standing.above > best.standing.above ? cur : best), + altFits[0]!, + ); + const bestAltByStarts = altFits.reduce( + (best, cur) => (cur.standing.starts > best.standing.starts ? cur : best), + altFits[0]!, + ); - if ( - bestAltByAbove.standing.above > plain.standing.above + 2.0 && - bestAltByAbove.standing.above >= Math.max(4.0, cal.cutsFrom) - ) { - chosen = bestAltByAbove; - } else if ( - bestAltByStarts.standing.starts >= STARTS_Z_MIN && - bestAltByStarts.standing.starts > plain.standing.starts + 2.0 - ) { - chosen = bestAltByStarts; + if ( + bestAltByAbove.standing.above > plain.standing.above + 2.0 && + bestAltByAbove.standing.above >= Math.max(4.0, cal.cutsFrom) + ) { + chosen = bestAltByAbove; + } else if ( + bestAltByStarts.standing.starts >= STARTS_Z_MIN && + bestAltByStarts.standing.starts > plain.standing.starts + 2.0 + ) { + chosen = bestAltByStarts; + } } const ratio = chosen.ratio; @@ -1221,14 +1300,7 @@ export function evaluateReferenceAlignmentToSampledAudio( const shiftedWindows = localWindows.map((w) => ({ durationSec: w.durationSec, speechSpans: w.speechSpans, - refSpans: w.refSpans - .map((s) => ({ - start: (((s.start + targetShift) % w.durationSec) + w.durationSec) % w.durationSec, - end: - ((((s.start + targetShift) % w.durationSec) + w.durationSec) % w.durationSec) + - (s.end - s.start), - })) - .sort((a, b) => a.start - b.start), + refSpans: wrapSpansInPeriod(w.refSpans, targetShift, w.durationSec), })); let hereCovered = 0; diff --git a/src/subsync/audio-speech.test.ts b/src/subsync/audio-speech.test.ts index 25e672d7..effa2ae9 100644 --- a/src/subsync/audio-speech.test.ts +++ b/src/subsync/audio-speech.test.ts @@ -1,6 +1,15 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { detectSpeechSpansFromPcm, parseRawSileroVadSegments } from './audio-speech'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { + clearAudioSpeechCache, + detectSpeechSpansFromPcm, + extractAudioSpeechSpans, + getCachedAudioSpeechSpans, + parseRawSileroVadSegments, +} from './audio-speech'; test('detectSpeechSpansFromPcm detects voice-band bursts separated by quiet background', () => { const sampleRate = 8000; @@ -54,3 +63,80 @@ test('parseRawSileroVadSegments parses fine-grained speech segments from whisper { start: 5.105, end: 6.9 }, ]); }); + +test('audio speech cache keys distinguish built-in VAD from Silero VAD config', async () => { + if (process.platform === 'win32') return; + clearAudioSpeechCache(); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-vad-cache-')); + const videoPath = path.join(tmpDir, 'ep01.mkv'); + const modelPath = path.join(tmpDir, 'silero.bin'); + const ffmpegScript = path.join(tmpDir, 'ffmpeg.sh'); + const vadScript = path.join(tmpDir, 'whisper-vad.sh'); + fs.writeFileSync(videoPath, 'video'); + fs.writeFileSync(modelPath, 'model'); + + // Fake ffmpeg outputs silence for pipe:1 (built-in VAD) and a tiny WAV when given an output file (Silero). + fs.writeFileSync( + ffmpegScript, + `#!/bin/sh +last="" +for arg in "$@"; do last="$arg"; done +if [ "$last" = "pipe:1" ]; then + dd if=/dev/zero bs=1600 count=1 2>/dev/null +else + printf 'RIFF....WAVEdata................................................' > "$last" +fi +exit 0 +`, + { mode: 0o755 }, + ); + fs.chmodSync(ffmpegScript, 0o755); + + fs.writeFileSync( + vadScript, + `#!/bin/sh +echo "Speech segment 0: start = 100.00, end = 300.00" +exit 0 +`, + { mode: 0o755 }, + ); + fs.chmodSync(vadScript, 0o755); + + try { + const builtin = await extractAudioSpeechSpans({ + ffmpegPath: ffmpegScript, + videoPath, + audioStreamIndex: 1, + }); + assert.equal(builtin.source, 'builtin-vad'); + assert.equal(builtin.spans.length, 0); + assert.ok(getCachedAudioSpeechSpans(videoPath, 1) !== null); + assert.equal( + getCachedAudioSpeechSpans(videoPath, 1, { + vadExecutablePath: vadScript, + vadModelPath: modelPath, + }), + null, + ); + + const silero = await extractAudioSpeechSpans({ + ffmpegPath: ffmpegScript, + videoPath, + audioStreamIndex: 1, + vadExecutablePath: vadScript, + vadModelPath: modelPath, + }); + assert.equal(silero.source, 'silero-vad'); + assert.deepEqual(silero.spans, [{ start: 1.0, end: 3.0 }]); + assert.equal( + getCachedAudioSpeechSpans(videoPath, 1, { + vadExecutablePath: vadScript, + vadModelPath: modelPath, + })?.source, + 'silero-vad', + ); + } finally { + clearAudioSpeechCache(); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +}); diff --git a/src/subsync/audio-speech.ts b/src/subsync/audio-speech.ts index c4ec56b6..d0b63332 100644 --- a/src/subsync/audio-speech.ts +++ b/src/subsync/audio-speech.ts @@ -9,7 +9,7 @@ import { type ParsedSubtitleFile, type SubtitleTimeSpan, } from './subtitle-lines'; -import { fileExists, resolveCommandInvocation, runCommand } from './utils'; +import { extensionToFfmpegMuxer, fileExists, resolveCommandInvocation, runCommand } from './utils'; const PCM_VAD_SAMPLE_RATE = 8000; const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400'; @@ -73,17 +73,35 @@ function buildFileSignatureKey(videoPath: string): string | null { } } -function buildAudioCacheKey(videoPath: string, audioStreamIndex: number | null): string | null { +function buildVadConfigKey( + vadExecutablePath?: string | null, + vadModelPath?: string | null, +): string { + const exec = vadExecutablePath?.trim() ?? ''; + const model = vadModelPath?.trim() ?? ''; + if (exec.length > 0 && model.length > 0 && fileExists(model)) { + return `silero:${exec}\0${model}`; + } + return 'builtin'; +} + +function buildAudioCacheKey( + videoPath: string, + audioStreamIndex: number | null, + vadConfigKey = 'builtin', +): string | null { const sig = buildFileSignatureKey(videoPath); if (!sig) return null; - return `${sig}\0${audioStreamIndex ?? 'default'}`; + return `${sig}\0${audioStreamIndex ?? 'default'}\0${vadConfigKey}`; } export function getCachedAudioSpeechSpans( videoPath: string, audioStreamIndex: number | null, + vadConfig?: { vadExecutablePath?: string | null; vadModelPath?: string | null } | null, ): AudioSpeechResult | null { - const key = buildAudioCacheKey(videoPath, audioStreamIndex); + const vadKey = buildVadConfigKey(vadConfig?.vadExecutablePath, vadConfig?.vadModelPath); + const key = buildAudioCacheKey(videoPath, audioStreamIndex, vadKey); return key ? (audioSpeechCache.get(key) ?? null) : null; } @@ -295,6 +313,7 @@ function streamFfmpegPcm( const invocation = resolveCommandInvocation(ffmpegPath, args); const child = childProcess.spawn(invocation.command, invocation.args, { stdio: ['ignore', 'pipe', 'pipe'], + ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), }); const chunks: Buffer[] = []; let stderr = ''; @@ -435,7 +454,8 @@ async function trySileroVadSpeech( export async function extractAudioSpeechSpans( options: ExtractAudioSpeechOptions, ): Promise { - const cacheKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex); + const vadKey = buildVadConfigKey(options.vadExecutablePath, options.vadModelPath); + const cacheKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex, vadKey); if (cacheKey) { const cached = audioSpeechCache.get(cacheKey); if (cached) return cached; @@ -479,6 +499,7 @@ function spawnFfmpegWithStdout( const invocation = resolveCommandInvocation(ffmpegPath, args); const child = childProcess.spawn(invocation.command, invocation.args, { stdio: ['ignore', 'pipe', 'pipe'], + ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), }); const chunks: Buffer[] = []; let stderr = ''; @@ -644,7 +665,8 @@ export async function extractSinglePassRipMedia( options: SinglePassRipMediaOptions, ): Promise { const fileKey = buildFileSignatureKey(options.videoPath); - const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex); + const vadKey = buildVadConfigKey(options.vadExecutablePath, options.vadModelPath); + const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex, vadKey); const cachedSubs = (fileKey ? embeddedSubtitlesCache.get(fileKey) : undefined) ?? @@ -683,7 +705,15 @@ export async function extractSinglePassRipMedia( const trackOutputs: Array<{ ffIndex: number; outPath: string }> = []; for (const track of missingTracks) { const outPath = path.join(tempDir, `track_${track.ffIndex}.${track.extension}`); - args.push('-vn', '-an', '-map', `0:${track.ffIndex}`, '-f', track.extension, outPath); + args.push( + '-vn', + '-an', + '-map', + `0:${track.ffIndex}`, + '-f', + extensionToFfmpegMuxer(track.extension), + outPath, + ); trackOutputs.push({ ffIndex: track.ffIndex, outPath }); } diff --git a/src/subsync/subtitle-lines.test.ts b/src/subsync/subtitle-lines.test.ts index 84d08ce2..f7439465 100644 --- a/src/subsync/subtitle-lines.test.ts +++ b/src/subsync/subtitle-lines.test.ts @@ -164,6 +164,15 @@ test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable b const lossy = decodeSubtitleBytesWithStatus(corrupt); assert.equal(lossy.lossless, false); + // Ambiguous bytes valid in both Shift_JIS and EUC-JP (e.g. EUC-JP 'あ' = A4 A2) must not be marked lossless. + const ambiguousEucJp = new Uint8Array([0xa4, 0xa2]); + const ambiguousResult = decodeSubtitleBytesWithStatus(ambiguousEucJp); + assert.equal(ambiguousResult.lossless, false); + + // Unambiguous Shift_JIS bytes (0x82 0xA0 = 'あ', invalid in UTF-8 and EUC-JP) remain lossless. + const unambiguousSjis = new Uint8Array([0x82, 0xa0]); + assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), { text: 'あ', lossless: true }); + const srt = formatSpansAsSrt([ { start: 5.5, end: 7.0 }, { start: 1.25, end: 2.75 }, diff --git a/src/subsync/subtitle-lines.ts b/src/subsync/subtitle-lines.ts index 80071fd3..e8f09078 100644 --- a/src/subsync/subtitle-lines.ts +++ b/src/subsync/subtitle-lines.ts @@ -122,13 +122,19 @@ export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitl return { text: strictUtf8, lossless: true }; } const shiftJis = tryDecode(bytes, 'shift_jis', true); - if (shiftJis !== null) { + const eucJp = tryDecode(bytes, 'euc-jp', true); + if (shiftJis !== null && eucJp === null) { return { text: shiftJis, lossless: true }; } - const eucJp = tryDecode(bytes, 'euc-jp', true); - if (eucJp !== null) { + if (eucJp !== null && shiftJis === null) { return { text: eucJp, lossless: true }; } + if (shiftJis !== null && eucJp !== null) { + if (shiftJis === eucJp) { + return { text: shiftJis, lossless: true }; + } + return { text: eucJp, lossless: false }; + } return { text: new TextDecoder('utf-8').decode(bytes), lossless: false }; } diff --git a/src/subsync/utils.test.ts b/src/subsync/utils.test.ts index 7c923eef..92be812d 100644 --- a/src/subsync/utils.test.ts +++ b/src/subsync/utils.test.ts @@ -3,13 +3,23 @@ import assert from 'node:assert/strict'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { codecToExtension, findSubsyncExecutable, getSubsyncConfig } from './utils'; +import { + candidateExecutableNames, + codecToExtension, + extensionToFfmpegMuxer, + findSubsyncExecutable, + getSubsyncConfig, + resolveCommandInvocation, +} from './utils'; test('codecToExtension maps stream/web formats to ffmpeg extractable extensions', () => { assert.equal(codecToExtension('subrip'), 'srt'); assert.equal(codecToExtension('webvtt'), 'vtt'); assert.equal(codecToExtension('vtt'), 'vtt'); assert.equal(codecToExtension('ttml'), 'ttml'); + assert.equal(extensionToFfmpegMuxer('vtt'), 'webvtt'); + assert.equal(extensionToFfmpegMuxer('srt'), 'srt'); + assert.equal(extensionToFfmpegMuxer('ass'), 'ass'); }); test('codecToExtension returns null for unsupported codecs', () => { @@ -58,3 +68,29 @@ test('findSubsyncExecutable skips non-executable files on POSIX and resolves bar fs.rmSync(dirB, { recursive: true, force: true }); } }); + +test('Windows candidate discovery excludes extensionless shims and escapes cmd.exe batch arguments', () => { + assert.deepEqual(candidateExecutableNames('ffsubsync', 'win32', '.COM;.EXE;.BAT;.CMD'), [ + 'ffsubsync.COM', + 'ffsubsync.EXE', + 'ffsubsync.BAT', + 'ffsubsync.CMD', + ]); + assert.deepEqual(candidateExecutableNames('ffsubsync.exe', 'win32', '.EXE;.CMD'), [ + 'ffsubsync.exe', + ]); + + const invocation = resolveCommandInvocation( + 'C:\\Tools\\ffsubsync.cmd', + ['C:\\Videos\\Show & (Remix) [1080p].mkv', '-i', 'C:\\Subs\\ep1.srt'], + 'win32', + ); + assert.equal(invocation.windowsVerbatimArguments, true); + assert.equal(invocation.args[0], '/d'); + assert.equal(invocation.args[1], '/s'); + assert.equal(invocation.args[2], '/v:off'); + assert.equal(invocation.args[3], '/c'); + assert.ok(invocation.args[4]!.includes('^&')); + assert.ok(invocation.args[4]!.includes('^(')); + assert.ok(invocation.args[4]!.includes('^)')); +}); diff --git a/src/subsync/utils.ts b/src/subsync/utils.ts index ebf17ff7..4375c51a 100644 --- a/src/subsync/utils.ts +++ b/src/subsync/utils.ts @@ -2,6 +2,10 @@ import * as fs from 'fs'; import * as childProcess from 'child_process'; import * as path from 'path'; import { DEFAULT_CONFIG } from '../config'; +import { + buildWindowsShimInvocation, + isWindowsCommandShim, +} from '../core/utils/windows-command-shim'; import { SubsyncConfig, SubsyncMode } from '../types'; export interface MpvTrack { @@ -47,13 +51,18 @@ function isExecutablePath(filePath: string): boolean { } } -function candidateExecutableNames(name: string): string[] { - if (process.platform !== 'win32' || path.extname(name)) return [name]; - const extensions = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT') +export function candidateExecutableNames( + name: string, + platform: NodeJS.Platform = process.platform, + pathExt: string | undefined = process.env.PATHEXT, +): string[] { + if (platform !== 'win32' || path.extname(name)) return [name]; + const extensions = (pathExt ?? '.COM;.EXE;.BAT;.CMD') .split(';') .map((ext) => ext.trim()) .filter((ext) => ext.length > 0 && WINDOWS_RUNNABLE_EXTENSIONS.has(ext.toLowerCase())); - return [name, ...extensions.map((ext) => `${name}${ext}`)]; + const effective = extensions.length > 0 ? extensions : ['.exe', '.com', '.cmd', '.bat']; + return effective.map((ext) => `${name}${ext}`); } /** @@ -117,8 +126,9 @@ export interface CommandResult { export function resolveCommandInvocation( executable: string, args: string[], -): { command: string; args: string[] } { - if (process.platform !== 'win32') { + platform: NodeJS.Platform = process.platform, +): { command: string; args: string[]; windowsVerbatimArguments?: boolean } { + if (platform !== 'win32') { return { command: executable, args }; } @@ -133,10 +143,12 @@ export function resolveCommandInvocation( return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`; }; const extension = path.extname(executable).toLowerCase(); - if (extension === '.cmd' || extension === '.bat') { + if (isWindowsCommandShim(executable)) { + const shim = buildWindowsShimInvocation(executable, args, process.env); return { - command: process.env.ComSpec || 'cmd.exe', - args: ['/d', '/c', executable, ...args], + command: shim.file, + args: shim.args, + windowsVerbatimArguments: true, }; } if (extension === '.ps1') { @@ -233,6 +245,11 @@ export function codecToExtension(codec: string | undefined): string | null { return null; } +export function extensionToFfmpegMuxer(extension: string): string { + if (extension === 'vtt') return 'webvtt'; + return extension; +} + export function runCommand( executable: string, args: string[], @@ -242,6 +259,7 @@ export function runCommand( const invocation = resolveCommandInvocation(executable, args); const child = childProcess.spawn(invocation.command, invocation.args, { stdio: ['ignore', 'pipe', 'pipe'], + ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), }); let stdout = ''; let stderr = ''; diff --git a/src/types/runtime.ts b/src/types/runtime.ts index 7840b74a..280e4e10 100644 --- a/src/types/runtime.ts +++ b/src/types/runtime.ts @@ -124,6 +124,8 @@ export interface SubsyncManualPayload { defaultTargetTrackId: number | null; videoReferenceAvailable: boolean; ffsubsyncAvailable: boolean; + /** Normalized media path this picker payload was built for. */ + mediaPath?: string | null; /** Optional guidance shown when automatic sync hands off to the modal. */ guidanceMessage?: string | null; /** Ranked candidate references (loaded tracks, unloaded tracks, sidecar files, audio). */ @@ -142,6 +144,8 @@ export type SubsyncReferenceMode = 'track' | 'video' | 'file'; export interface SubsyncManualRunRequest { engine: SubsyncEngine; + /** Media path captured when the picker opened, verified against the active video before running. */ + mediaPath?: string | null; /** Reference source: another subtitle track, the loaded video/audio, or a local file on disk. */ referenceMode?: SubsyncReferenceMode; referenceTrackId?: number | null;