diff --git a/src/core/services/subsync-context.ts b/src/core/services/subsync-context.ts index 8341b5f9..76153d8d 100644 --- a/src/core/services/subsync-context.ts +++ b/src/core/services/subsync-context.ts @@ -195,8 +195,9 @@ async function isPlaybackSessionUnchangedNow( slot === 'secondary' ? (context.secondaryTrack?.id ?? null) : (context.primaryTrack.id ?? null); - const needsTrackIdentityCheck = - typeof targetTrack.id === 'number' && targetTrack.id !== initialSlotTrackId; + // Always compare the target's source too: mpv reuses the highest freed id, so a track + // removed and replaced mid-sync can keep the same id (and the same slot id). + const needsTrackIdentityCheck = typeof targetTrack.id === 'number'; const [videoPathRaw, workingDirRaw, slotTrackRaw, trackListRaw] = await Promise.all([ client.requestProperty('path'), client.requestProperty('working-directory').catch(() => null), diff --git a/src/core/services/subsync-files.ts b/src/core/services/subsync-files.ts index 43e42c47..2af41957 100644 --- a/src/core/services/subsync-files.ts +++ b/src/core/services/subsync-files.ts @@ -275,11 +275,14 @@ export function buildRetimedPath(subPath: string, replace: boolean): string { export const LOSSY_REWRITE_ERROR_MESSAGE = 'Cannot safely rewrite subtitle file because its text encoding could not be decoded unambiguously and losslessly. Convert the file to UTF-8 and retry.'; -/** Size + mtime of a subtitle file, compared before an in-place rewrite to catch edits made mid-sync. */ +/** + * Identity (device + inode, through symlinks) plus size and mtime of a subtitle file, compared + * before an in-place rewrite to catch edits or a retargeted symlink mid-sync. + */ export function readSubtitleFileStamp(filePath: string): string | null { try { const stat = fs.statSync(filePath); - return `${stat.size}\0${stat.mtimeMs}`; + return `${stat.dev}:${stat.ino}\0${stat.size}\0${stat.mtimeMs}`; } catch { return null; } @@ -499,6 +502,7 @@ export async function loadSyncedSubtitle( typeof track.id === 'number' ? [track.id] : [], ), ); + const secondaryBeforeAdd = await client.requestProperty('secondary-sid'); signal?.throwIfAborted(); client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) }); const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds); @@ -506,6 +510,13 @@ export async function loadSyncedSubtitle( throw new Error('Synchronized subtitle did not appear in the mpv track list'); } signal?.throwIfAborted(); + // The lookup polls for a while; if the user picked another secondary track meanwhile, + // keep their choice (and delay) rather than overriding it. + if ((await client.requestProperty('secondary-sid')) !== secondaryBeforeAdd) { + throw new Error( + `Secondary subtitle changed while loading; saved the synced file at ${pathToLoad} without selecting it.`, + ); + } client.send({ command: ['set_property', 'secondary-sid', addedTrackId] }); // The retimed file carries the timing now; only drop the old delay once it is selected. client.send({ command: ['set_property', 'secondary-sub-delay', 0] }); diff --git a/src/core/services/subsync-manual.ts b/src/core/services/subsync-manual.ts index 83336e51..fcb8092e 100644 --- a/src/core/services/subsync-manual.ts +++ b/src/core/services/subsync-manual.ts @@ -301,6 +301,13 @@ async function subsyncToReference( message: `${engine} synchronization failed: ${details}`, }; } + // A zero exit is not proof of a usable file; never replace a subtitle with an empty one. + if (readAndParseSubtitleFile(stagedOutputPath).events.length === 0) { + return { + ok: false, + message: `${engine} synchronization failed: it wrote no readable subtitle cues; the original was kept.`, + }; + } if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot, io.signal))) { return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }; diff --git a/src/core/services/subsync.test.ts b/src/core/services/subsync.test.ts index 963d4f21..1ce3b5a0 100644 --- a/src/core/services/subsync.test.ts +++ b/src/core/services/subsync.test.ts @@ -471,6 +471,59 @@ function fromShellPath(filePath: string): string { .replace(/\//g, '\\'); } +test('runSubsyncManual keeps the original when an external engine writes an empty file', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-empty-engine-output-')); + const ffsubsyncPath = path.join(tmpDir, 'ffsubsync.sh'); + const videoPath = path.join(tmpDir, 'video.mkv'); + const primaryPath = path.join(tmpDir, 'primary.srt'); + const original = '1\n00:00:05,000 --> 00:00:06,000\noriginal\n'; + fs.writeFileSync(videoPath, 'video'); + fs.writeFileSync(primaryPath, original); + writeExecutableScript( + ffsubsyncPath, + `#!/bin/sh\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\n: > "$out"\nexit 0\n`, + ); + const sentCommands: Array> = []; + const deps = 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 null; + if (name === 'track-list') { + return [ + { + id: 1, + type: 'sub', + selected: true, + external: true, + 'external-filename': primaryPath, + }, + ]; + } + return null; + }, + }), + getResolvedConfig: () => ({ + alassPath: '/missing/alass', + ffsubsyncPath, + ffmpegPath: '/missing/ffmpeg', + replace: true, + }), + }); + + const result = await runSubsyncManual({ engine: 'ffsubsync' }, deps); + assert.equal(result.ok, false); + assert.match(result.message, /no readable subtitle cues/); + assert.equal(fs.readFileSync(primaryPath, 'utf8'), original); + assert.equal(sentCommands.length, 0); +}); + test('runSubsyncManual ignores the ff-index of an external audio track', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-external-audio-')); const ffsubsyncLogPath = path.join(tmpDir, 'ffsubsync-args.log'); @@ -481,7 +534,7 @@ test('runSubsyncManual ignores the ff-index of an external audio track', async ( fs.writeFileSync(primaryPath, 'sub'); writeExecutableScript( ffsubsyncPath, - `#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then : > "$out"; fi\nexit 0\n`, + `#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then printf "1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n" > "$out"; fi\nexit 0\n`, ); const deps = makeDeps({ @@ -544,7 +597,7 @@ test('runSubsyncManual constructs ffsubsync command and returns success', async writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript( ffsubsyncPath, - `#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=\"\"\nprev=\"\"\nfor arg in \"$@\"; do\n if [ \"$prev\" = \"-o\" ]; then out=\"$arg\"; fi\n prev=\"$arg\"\ndone\nif [ -n \"$out\" ]; then : > \"$out\"; fi\nexit 0\n`, + `#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=\"\"\nprev=\"\"\nfor arg in \"$@\"; do\n if [ \"$prev\" = \"-o\" ]; then out=\"$arg\"; fi\n prev=\"$arg\"\ndone\nif [ -n \"$out\" ]; then printf \"1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n\" > \"$out\"; fi\nexit 0\n`, ); const sentCommands: Array> = []; @@ -617,7 +670,7 @@ test('runSubsyncManual writes deterministic _retimed filename when replace is fa writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript( ffsubsyncPath, - `#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=\"\"\nprev=\"\"\nfor arg in \"$@\"; do\n if [ \"$prev\" = \"-o\" ]; then out=\"$arg\"; fi\n prev=\"$arg\"\ndone\nif [ -n \"$out\" ]; then : > \"$out\"; fi\nexit 0\n`, + `#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=\"\"\nprev=\"\"\nfor arg in \"$@\"; do\n if [ \"$prev\" = \"-o\" ]; then out=\"$arg\"; fi\n prev=\"$arg\"\ndone\nif [ -n \"$out\" ]; then printf \"1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n\" > \"$out\"; fi\nexit 0\n`, ); const deps = makeDeps({ @@ -807,7 +860,7 @@ function makeAlassSelectionDeps(tmpDir: string): { writeExecutableScript(ffsubsyncPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript( alassPath, - `#!/bin/sh\n: > "${toShellPath(alassLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(alassLogPath)}"; done\n: > "$3"\nexit 0\n`, + `#!/bin/sh\n: > "${toShellPath(alassLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(alassLogPath)}"; done\nprintf "1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n" > "$3"\nexit 0\n`, ); const trackList: Array> = [ @@ -895,7 +948,10 @@ test('runSubsyncManual keeps a retimed secondary track in the secondary slot', a fs.writeFileSync(secondaryPath, 'en'); writeExecutableScript(ffmpegPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(ffsubsyncPath, '#!/bin/sh\nexit 0\n'); - writeExecutableScript(alassPath, '#!/bin/sh\n: > "$3"\nexit 0\n'); + writeExecutableScript( + alassPath, + '#!/bin/sh\nprintf "1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n" > "$3"\nexit 0\n', + ); const trackList: Array> = [ { id: 1, type: 'sub', selected: true, external: true, 'external-filename': primaryPath }, @@ -971,11 +1027,11 @@ test('runSubsyncManual keeps internal alass source file alive until sync finishe writeExecutableScript(ffsubsyncPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript( ffmpegPath, - '#!/bin/sh\nout=""\nfor arg in "$@"; do out="$arg"; done\nif [ -n "$out" ]; then : > "$out"; fi\nexit 0\n', + '#!/bin/sh\nout=""\nfor arg in "$@"; do out="$arg"; done\nif [ -n "$out" ]; then printf "1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n" > "$out"; fi\nexit 0\n', ); writeExecutableScript( alassPath, - '#!/bin/sh\nsleep 0.2\nif [ ! -f "$1" ]; then echo "missing reference subtitle" >&2; exit 1; fi\nif [ ! -f "$2" ]; then echo "missing input subtitle" >&2; exit 1; fi\n: > "$3"\nexit 0\n', + '#!/bin/sh\nsleep 0.2\nif [ ! -f "$1" ]; then echo "missing reference subtitle" >&2; exit 1; fi\nif [ ! -f "$2" ]; then echo "missing input subtitle" >&2; exit 1; fi\nprintf "1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n" > "$3"\nexit 0\n', ); const sentCommands: Array> = []; @@ -1042,7 +1098,7 @@ test('runSubsyncManual resolves string sid values from mpv stream properties', a writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript( ffsubsyncPath, - `#!/bin/sh\nmkdir -p "${toShellPath(tmpDir)}"\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nprev=""\nout=""\nfor arg in "$@"; do\n if [ "$prev" = "--reference-stream" ]; then :; fi\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then : > "$out"; fi`, + `#!/bin/sh\nmkdir -p "${toShellPath(tmpDir)}"\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nprev=""\nout=""\nfor arg in "$@"; do\n if [ "$prev" = "--reference-stream" ]; then :; fi\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then printf "1\\n00:00:01,000 --> 00:00:02,000\\nhi\\n" > "$out"; fi`, ); const deps = makeDeps({ @@ -1086,7 +1142,7 @@ test('runSubsyncManual resolves string sid values from mpv stream properties', a assert.equal(typeof outputPath, 'string'); assert.ok(outputPath!.length > 0); assert.equal(fs.existsSync(fromShellPath(outputPath!)), false); - assert.equal(fs.readFileSync(primaryPath, 'utf8'), ''); + assert.match(fs.readFileSync(primaryPath, 'utf8'), /00:00:01,000 --> 00:00:02,000/); }); function generateSyntheticSpans( @@ -2479,7 +2535,7 @@ test('runSubsyncManual stages external engine output and preserves original when writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript( ffsubsyncPath, - '#!/bin/sh\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then printf "overwritten" > "$out"; fi\nexit 0\n', + '#!/bin/sh\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then printf "1\\n00:00:01,000 --> 00:00:02,000\\noverwritten\\n" > "$out"; fi\nexit 0\n', ); let pathCalls = 0; diff --git a/src/subsync/alass-align.test.ts b/src/subsync/alass-align.test.ts index 7318d55b..c39abfa4 100644 --- a/src/subsync/alass-align.test.ts +++ b/src/subsync/alass-align.test.ts @@ -6,6 +6,8 @@ import { evaluateReferenceAlignmentToAudio, evaluateReferenceAlignmentToSampledAudio, joinSpans, + scoreStanding, + CALIBRATION_CLEAN, wrappedCoverage, type SampledAudioWindow, } from './alass-align'; @@ -318,3 +320,11 @@ test('alignSubtitleFileToReferenceSpans rejects broadcast pieces that collapse o assert.equal(result.cut, false); assert.equal(result.confident, false); }); + +test('scoreStanding caps a weak-quarter fit unless every quarter agrees on line starts', () => { + const strongCoverage = { above: 14, alone: 5, weakestPart: 0.5 }; + // One quarter does not fit and starts do not agree everywhere: below the 0.65 auto bar. + assert.ok(scoreStanding({ ...strongCoverage, starts: 0 }, CALIBRATION_CLEAN) <= 0.6); + // Every quarter agrees line for line (starts is the weakest quarter's z): not a partial fit. + assert.ok(scoreStanding({ ...strongCoverage, starts: 9 }, CALIBRATION_CLEAN) > 0.65); +}); diff --git a/src/subsync/alass-align.ts b/src/subsync/alass-align.ts index e159426d..14094768 100644 --- a/src/subsync/alass-align.ts +++ b/src/subsync/alass-align.ts @@ -655,6 +655,10 @@ export function scoreStanding(z: AlignmentStanding, cal: SyncCalibration): numbe if (z.weakestPart !== undefined && z.weakestPart < PART_COVERAGE_Z_MIN) { covered = Math.min(covered, PARTIAL_FIT_SCORE_CAP); } + // Intended override of the weak-quarter cap: `starts` is itself the weakest quarter's + // line-start agreement, so clearing STARTS_Z_MIN means every quarter matches line for line + // (a partial fit cannot). Coverage alone can dip in one quarter for benign reasons, such as + // VAD over a music-heavy stretch. const started = z.starts >= STARTS_Z_MIN ? Math.max( @@ -1128,8 +1132,15 @@ export function alignSubtitleFileToReferenceSpans( end: targetSpans[idx]!.end * ratio + shift, }); } - const zSplit = evaluateStanding(splitSpans, joinedRef, sortedRefStarts, lengthSec); - if (zSplit.above > zOne.above + 0.3) { + // splitSpans follow the original start order; a cut that makes a later line start + // before an earlier one reorders dialogue, which no real edit does. + const keepsLineOrder = splitSpans.every( + (span, i) => i === 0 || span.start >= splitSpans[i - 1]!.start, + ); + const zSplit = keepsLineOrder + ? evaluateStanding(splitSpans, joinedRef, sortedRefStarts, lengthSec) + : null; + if (zSplit && zSplit.above > zOne.above + 0.3) { finalStanding = zSplit; finalScore = scoreStanding(zSplit, cal); finalSegments = jumps + 1; diff --git a/src/subsync/audio-speech.test.ts b/src/subsync/audio-speech.test.ts index 72241410..914ce114 100644 --- a/src/subsync/audio-speech.test.ts +++ b/src/subsync/audio-speech.test.ts @@ -241,3 +241,59 @@ exit 0 fs.rmSync(tmpDir, { recursive: true, force: true }); } }); + +test('a built-in fallback after a Silero failure does not block retrying Silero', async () => { + if (process.platform === 'win32') return; + clearAudioSpeechCache(); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-vad-retry-')); + 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'); + const vadBrokenFlag = path.join(tmpDir, 'vad-broken'); + fs.writeFileSync(videoPath, 'video'); + fs.writeFileSync(modelPath, 'model'); + fs.writeFileSync(vadBrokenFlag, ''); + 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 }, + ); + // Fails while the flag file exists (e.g. a timeout), then recovers. + fs.writeFileSync( + vadScript, + `#!/bin/sh +if [ -f "${vadBrokenFlag}" ]; then exit 1; fi +echo "Speech segment 0: start = 100.00, end = 300.00" +exit 0 +`, + { mode: 0o755 }, + ); + const options = { + ffmpegPath: ffmpegScript, + videoPath, + audioStreamIndex: 1, + vadExecutablePath: vadScript, + vadModelPath: modelPath, + }; + + try { + assert.equal((await extractAudioSpeechSpans(options)).source, 'builtin-vad'); + assert.equal(getCachedAudioSpeechSpans(videoPath, 1, options), null); + + fs.rmSync(vadBrokenFlag); + assert.equal((await extractAudioSpeechSpans(options)).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 686d30b3..67cd8f16 100644 --- a/src/subsync/audio-speech.ts +++ b/src/subsync/audio-speech.ts @@ -1,4 +1,3 @@ -import * as childProcess from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -14,8 +13,8 @@ import { extensionToFfmpegMuxer, fileExists, killProcessTree, - resolveCommandInvocation, runCommand, + spawnTool, } from './utils'; const PCM_VAD_SAMPLE_RATE = 8000; @@ -356,11 +355,12 @@ function streamFfmpegPcm( 'pipe:1', ); - const invocation = resolveCommandInvocation(ffmpegPath, args); - const child = childProcess.spawn(invocation.command, invocation.args, { - stdio: ['ignore', 'pipe', 'pipe'], - ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), - }); + // Checked before spawning: nothing below is set up yet for an already-aborted run. + if (signal?.aborted) { + reject(new Error('Audio extraction aborted')); + return; + } + const child = spawnTool(ffmpegPath, args); const chunks: Buffer[] = []; let stderr = ''; let settled = false; @@ -378,10 +378,6 @@ function streamFfmpegPcm( finishError(new Error('Audio extraction aborted')); }; - if (signal?.aborted) { - onAbort(); - return; - } signal?.addEventListener('abort', onAbort, { once: true }); const timer = setTimeout(() => { @@ -522,6 +518,16 @@ export async function extractAudioSpeechSpans( return silero; } + // Built-in results live under the built-in key, never the Silero one, so a later run still + // retries Silero (e.g. after a timeout) while reusing this fallback meanwhile. + const builtinKey = buildAudioCacheKey( + options.videoPath, + options.audioStreamIndex, + buildVadConfigKey(null, null), + ); + const cachedBuiltin = builtinKey ? audioSpeechCache.get(builtinKey) : undefined; + if (cachedBuiltin) return cachedBuiltin; + // Tier 2: Built-in voice-band PCM speech detector via ffmpeg (zero extra dependencies). const pcmBuffer = await streamFfmpegPcm( options.ffmpegPath, @@ -539,7 +545,7 @@ export async function extractAudioSpeechSpans( calibration: 'noisy', source: 'builtin-vad', }; - rememberAudioSpeech(cacheKey, result); + rememberAudioSpeech(builtinKey, result); return result; } @@ -550,11 +556,12 @@ function spawnFfmpegWithStdout( signal?: AbortSignal, ): Promise { return new Promise((resolve, reject) => { - const invocation = resolveCommandInvocation(ffmpegPath, args); - const child = childProcess.spawn(invocation.command, invocation.args, { - stdio: ['ignore', 'pipe', 'pipe'], - ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), - }); + // Checked before spawning: nothing below is set up yet for an already-aborted run. + if (signal?.aborted) { + reject(new Error('ffmpeg operation aborted')); + return; + } + const child = spawnTool(ffmpegPath, args); const chunks: Buffer[] = []; let stderr = ''; let settled = false; @@ -572,10 +579,6 @@ function spawnFfmpegWithStdout( finishError(new Error('ffmpeg operation aborted')); }; - if (signal?.aborted) { - onAbort(); - return; - } signal?.addEventListener('abort', onAbort, { once: true }); const timer = setTimeout(() => { diff --git a/src/subsync/utils.ts b/src/subsync/utils.ts index 143cad5e..d7d0b086 100644 --- a/src/subsync/utils.ts +++ b/src/subsync/utils.ts @@ -1,6 +1,7 @@ import * as fs from 'fs'; import * as childProcess from 'child_process'; import * as path from 'path'; +import type { Readable } from 'stream'; import { DEFAULT_CONFIG } from '../config'; import { buildWindowsShimInvocation, @@ -329,7 +330,11 @@ export function killProcessTree(child: childProcess.ChildProcess): void { stdio: 'ignore', windowsHide: true, }) - .on('error', () => child.kill()); + .on('error', () => child.kill()) + // taskkill can start yet fail (e.g. access denied); fall back to killing the tool itself. + .on('close', (code: number | null) => { + if (code !== 0) child.kill(); + }); return; } if (processGroupLeaders.has(child)) { @@ -362,6 +367,26 @@ function trackProcessGroup(child: childProcess.ChildProcess): void { }); } +/** + * Spawn a tool with piped stdout/stderr. On POSIX it leads its own process group, so + * `killProcessTree` also reaches anything it started (a wrapper script running ffmpeg, + * ffsubsync's ffmpeg); still-running groups are killed when the app exits. + */ +export function spawnTool( + executable: string, + args: string[], +): childProcess.ChildProcessByStdio { + const invocation = resolveCommandInvocation(executable, args); + const ownGroup = process.platform !== 'win32'; + const child = childProcess.spawn(invocation.command, invocation.args, { + stdio: ['ignore', 'pipe', 'pipe'], + ...(ownGroup ? { detached: true } : {}), + ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), + }); + if (ownGroup) trackProcessGroup(child); + return child; +} + /** Run a tool to completion; an abort or the timeout kills it and resolves with `ok: false`. */ export function runCommand( executable: string, @@ -373,15 +398,7 @@ export function runCommand( return Promise.resolve({ ok: false, code: null, stderr: '', stdout: '', error: 'aborted' }); } return new Promise((resolve) => { - const invocation = resolveCommandInvocation(executable, args); - const ownGroup = process.platform !== 'win32'; - const child = childProcess.spawn(invocation.command, invocation.args, { - stdio: ['ignore', 'pipe', 'pipe'], - // POSIX: own process group so killProcessTree reaches grandchildren too. - ...(ownGroup ? { detached: true } : {}), - ...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), - }); - if (ownGroup) trackProcessGroup(child); + const child = spawnTool(executable, args); let stdout = ''; let stderr = ''; const onAbort = (): void => killProcessTree(child);