From cde9362ee572027882af6f0a7b64f759124a1a57 Mon Sep 17 00:00:00 2001 From: sudacode Date: Sat, 28 Nov 2026 03:53:12 -0800 Subject: [PATCH] fix(subsync): address CodeRabbit review of cancellation, cleanup, and writes - kill a tool's whole POSIX process group on cancel (orphaned children held the pipes open, so the run never finished); kill running groups on exit - refuse an in-place rewrite when the subtitle changed on disk mid-sync - pick only a freshly added track for the secondary slot, and reset its delay only after selecting it - pass cancellation to the video-reference alass and ffsubsync runs, and never open a picker for media the user already left - treat a failed media-path baseline read as unknown instead of null - align worker: honor aborts during startup and finish queued calls on the main thread when the worker fails to start - temp dirs: keep failed removals registered, never sweep a dir mpv still plays from, and clean up when writing a cleaned reference fails - an empty cached audio result means no usable audio, as on a fresh decode - compare external track paths case-sensitively on POSIX - decode ffmpeg stderr as a stream; coverage lane for subtitle tests - make the cancellation test wait for the tool to start --- package.json | 2 +- src/core/services/subsync-auto.ts | 5 +- src/core/services/subsync-candidates.ts | 8 +- src/core/services/subsync-context.ts | 2 +- src/core/services/subsync-files.test.ts | 15 ++-- src/core/services/subsync-files.ts | 110 +++++++++++++++++++----- src/core/services/subsync-manual.ts | 21 ++++- src/core/services/subsync.test.ts | 36 ++++++-- src/core/services/subsync.ts | 10 ++- src/subsync/align-worker.ts | 37 +++++++- src/subsync/audio-speech.ts | 12 ++- src/subsync/utils.ts | 43 ++++++++- 12 files changed, 244 insertions(+), 57 deletions(-) diff --git a/package.json b/package.json index 21389f63..0359b27b 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "test:immersion:sqlite": "bun run tsc && bun run test:immersion:sqlite:dist", "test:src": "bun run build:yomitan && bun scripts/run-test-lane.mjs bun-src-full", "test:coverage:src": "bun run build:yomitan && bun run scripts/run-coverage-lane.ts bun-src-full --coverage-dir coverage/test-src", - "test:coverage:subtitle:src": "bun test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir coverage/test-subtitle src/core/services/subsync.test.ts src/subsync/utils.test.ts", + "test:coverage:subtitle:src": "bun run scripts/run-coverage-lane.ts subtitle --coverage-dir coverage/test-subtitle", "test:launcher:unit:src": "bun scripts/run-test-lane.mjs bun-launcher-unit", "test:scripts": "bun scripts/run-test-lane.mjs scripts", "test:stats": "bun scripts/run-test-lane.mjs stats", diff --git a/src/core/services/subsync-auto.ts b/src/core/services/subsync-auto.ts index 43fb6761..76624092 100644 --- a/src/core/services/subsync-auto.ts +++ b/src/core/services/subsync-auto.ts @@ -182,7 +182,10 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis deps.showMpvOsd(`Subsync failed: ${LOSSY_REWRITE_ERROR_MESSAGE}`); return; } - writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget); + writeRetimedContent(outputPath, alignment.rewrittenContent, { + replacesSource: replaceTarget, + sourceStamp: parsedTarget.stamp, + }); await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack); deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment)); }; diff --git a/src/core/services/subsync-candidates.ts b/src/core/services/subsync-candidates.ts index 956b0e3d..02d5dcec 100644 --- a/src/core/services/subsync-candidates.ts +++ b/src/core/services/subsync-candidates.ts @@ -541,7 +541,13 @@ export async function prepareRipCandidatesAndAudio( } if (cachedFull) { - return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null }; + // An empty cached result stays cached (no re-decode) but means "no usable audio" here, + // matching resolveAudioSpeechForContext. + return { + audioSpeech: cachedFull.spans.length > 0 ? cachedFull : null, + sampledAudioWindows: null, + preExtractedEmbedded: null, + }; } const audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps); diff --git a/src/core/services/subsync-context.ts b/src/core/services/subsync-context.ts index e023b19f..f36f7dba 100644 --- a/src/core/services/subsync-context.ts +++ b/src/core/services/subsync-context.ts @@ -46,7 +46,7 @@ function getSourceTrackIdentity(track: MpvTrack): string { typeof track['external-filename'] === 'string' && track['external-filename'].length > 0 ) { - return `external:${track['external-filename'].toLowerCase()}`; + return `external:${normalizeSubtitlePathForCompare(track['external-filename'])}`; } if (typeof track.id === 'number') { return `id:${track.id}`; diff --git a/src/core/services/subsync-files.test.ts b/src/core/services/subsync-files.test.ts index 5f3df881..4f9e413a 100644 --- a/src/core/services/subsync-files.test.ts +++ b/src/core/services/subsync-files.test.ts @@ -7,8 +7,6 @@ import { cleanupTemporaryFile, pruneRetainedSubsyncTempDirs } from './subsync-fi test('synced embedded-track temp dirs keep only the loaded file and go away once mpv drops it', () => { const isolatedTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-files-test-')); - const previousTmpDir = process.env.TMPDIR; - process.env.TMPDIR = isolatedTmp; try { // Left behind by a crashed session two days ago. const staleDir = fs.mkdtempSync(path.join(isolatedTmp, 'subminer-subsync-')); @@ -25,15 +23,20 @@ test('synced embedded-track temp dirs keep only the loaded file and go away once cleanupTemporaryFile({ path: extractedPath, temporary: true }); assert.deepEqual(fs.readdirSync(runDir), ['track_2_retimed.ass']); - pruneRetainedSubsyncTempDirs([retimedPath]); + // An old dir whose file mpv still plays survives the sweep. + const playingDir = fs.mkdtempSync(path.join(isolatedTmp, 'subminer-subsync-')); + const playingPath = path.join(playingDir, 'track_4_retimed.srt'); + fs.writeFileSync(playingPath, 'still loaded'); + fs.utimesSync(playingDir, twoDaysAgo, twoDaysAgo); + + pruneRetainedSubsyncTempDirs([retimedPath, playingPath], { tmpRoot: isolatedTmp }); assert.equal(fs.existsSync(runDir), true, 'mpv still lists the retimed file'); assert.equal(fs.existsSync(staleDir), false, 'stale dirs from old sessions are swept'); + assert.equal(fs.existsSync(playingDir), true, 'stale but referenced dirs are kept'); - pruneRetainedSubsyncTempDirs(['/media/ep02.ja.srt']); + pruneRetainedSubsyncTempDirs(['/media/ep02.ja.srt'], { tmpRoot: isolatedTmp }); assert.equal(fs.existsSync(runDir), false, 'dropped once mpv no longer lists it'); } finally { - if (previousTmpDir === undefined) delete process.env.TMPDIR; - else process.env.TMPDIR = previousTmpDir; fs.rmSync(isolatedTmp, { recursive: true, force: true }); } }); diff --git a/src/core/services/subsync-files.ts b/src/core/services/subsync-files.ts index 960fd678..f82dec0b 100644 --- a/src/core/services/subsync-files.ts +++ b/src/core/services/subsync-files.ts @@ -205,17 +205,22 @@ export function cleanupTemporaryFile(extraction: FileExtractionResult | null): v */ export function pruneRetainedSubsyncTempDirs( referencedPaths: readonly string[], - now: number = Date.now(), + options: { now?: number; tmpRoot?: string } = {}, ): void { - for (const dir of retainedSubsyncTempDirs) { + const isReferenced = (dir: string): boolean => { const prefix = `${dir}${path.sep}`; - if (referencedPaths.some((filePath) => filePath.startsWith(prefix))) continue; + return referencedPaths.some((filePath) => filePath.startsWith(prefix)); + }; + for (const dir of retainedSubsyncTempDirs) { + if (isReferenced(dir)) continue; removeDirQuietly(dir); - retainedSubsyncTempDirs.delete(dir); + // Keep failed removals registered so the next prune or exit cleanup retries them. + if (!fs.existsSync(dir)) retainedSubsyncTempDirs.delete(dir); } if (staleSweepDone) return; staleSweepDone = true; - const tmpRoot = os.tmpdir(); + const tmpRoot = options.tmpRoot ?? os.tmpdir(); + const now = options.now ?? Date.now(); let entries: string[] = []; try { entries = fs.readdirSync(tmpRoot); @@ -225,7 +230,8 @@ export function pruneRetainedSubsyncTempDirs( for (const name of entries) { if (!name.startsWith(SUBSYNC_TEMP_DIR_PREFIX)) continue; const dir = path.join(tmpRoot, name); - if (retainedSubsyncTempDirs.has(dir)) continue; + // mpv may still play a file from an old dir (e.g. the app restarted under a running mpv). + if (retainedSubsyncTempDirs.has(dir) || isReferenced(dir)) continue; try { const stat = fs.statSync(dir); if (stat.isDirectory() && now - stat.mtimeMs > STALE_SUBSYNC_TEMP_DIR_MS) { @@ -264,15 +270,42 @@ 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.'; -export function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile { +/** Size + mtime of a subtitle file, compared before an in-place rewrite to catch edits made mid-sync. */ +export function readSubtitleFileStamp(filePath: string): string | null { + try { + const stat = fs.statSync(filePath); + return `${stat.size}\0${stat.mtimeMs}`; + } catch { + return null; + } +} + +export type ReadSubtitleFile = ParsedSubtitleFile & { + /** `readSubtitleFileStamp` taken before reading, for `RetimedWrite.sourceStamp`. */ + stamp: string | null; +}; + +export function readAndParseSubtitleFile(filePath: string): ReadSubtitleFile { + const stamp = readSubtitleFileStamp(filePath); const bytes = fs.readFileSync(filePath); const decoded = decodeSubtitleBytesWithStatus(bytes); return { ...parseSubtitleFileContent(decoded.text, filePath), lossless: decoded.lossless, + stamp, }; } +export interface RetimedWrite { + /** In-place `subsync.replace` rewrite of the user's subtitle (backup + source-change check). */ + replacesSource: boolean; + /** Stamp of the source when it was read; a different stamp now means it was edited mid-sync. */ + sourceStamp?: string | null; +} + +const SOURCE_CHANGED_MESSAGE = + 'The subtitle file changed on disk while syncing; discarded the result. Run subsync again.'; + /** Suffix for the one-time backup of a replaced subtitle; not a subtitle extension, so mpv and sidecar discovery ignore it. */ const SUBSYNC_BACKUP_SUFFIX = '.orig'; @@ -292,9 +325,16 @@ function resolveRealPathOrSelf(filePath: string): string { export function installRetimedFile( stagedPath: string, outputPath: string, - replacesSource: boolean, + { replacesSource, sourceStamp }: RetimedWrite, ): void { const targetPath = resolveRealPathOrSelf(outputPath); + if ( + replacesSource && + sourceStamp !== undefined && + readSubtitleFileStamp(targetPath) !== sourceStamp + ) { + throw new Error(SOURCE_CHANGED_MESSAGE); + } const existing = fs.existsSync(targetPath) ? fs.statSync(targetPath) : null; if (existing) { if (replacesSource) { @@ -326,7 +366,7 @@ export function removeIfExists(filePath: string): void { export function writeRetimedContent( outputPath: string, content: string, - replacesSource: boolean, + write: RetimedWrite, ): void { const dir = path.dirname(resolveRealPathOrSelf(outputPath)); const tmpPath = path.join( @@ -335,7 +375,7 @@ export function writeRetimedContent( ); try { fs.writeFileSync(tmpPath, content, 'utf8'); - installRetimedFile(tmpPath, outputPath, replacesSource); + installRetimedFile(tmpPath, outputPath, write); } catch (error) { removeIfExists(tmpPath); throw error; @@ -367,30 +407,43 @@ export async function runFfsubsyncSync( return runCommand(ffsubsyncPath, args, undefined, signal); } +async function readSubtitleTracks(client: MpvClientLike): Promise { + const trackListRaw = await client.requestProperty('track-list'); + return Array.isArray(trackListRaw) + ? normalizeTrackIds(trackListRaw as MpvTrack[]).filter((track) => track.type === 'sub') + : []; +} + +/** + * Find the track `sub-add` created for `pathToLoad`. Only ids missing from `knownTrackIds` + * (the list before the add) count, so an older track for the same file is never picked. + */ async function findAddedSubtitleTrackId( client: MpvClientLike, pathToLoad: string, + knownTrackIds: ReadonlySet, ): Promise { const wanted = normalizeSubtitlePathForCompare(pathToLoad); // sub-add is queued, so the track may not appear in the first track-list reply. for (let attempt = 0; attempt < SYNCED_TRACK_LOOKUP_ATTEMPTS; attempt += 1) { let tracks: MpvTrack[] = []; try { - const trackListRaw = await client.requestProperty('track-list'); - tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : []; + tracks = await readSubtitleTracks(client); } catch { return null; } - // Re-adding a file mpv already knows appends a duplicate entry; the newest - // one holds the retimed content, so prefer the last match. - const matches = tracks.filter((track) => { - if (track.type !== 'sub') return false; + const added = tracks.filter((track) => { const filename = track['external-filename']; - return typeof filename === 'string' && normalizeSubtitlePathForCompare(filename) === wanted; + return ( + typeof track.id === 'number' && + !knownTrackIds.has(track.id) && + typeof filename === 'string' && + normalizeSubtitlePathForCompare(filename) === wanted + ); }); - const added = matches[matches.length - 1]; - if (added && typeof added.id === 'number') { - return added.id; + const newest = added[added.length - 1]; + if (newest && typeof newest.id === 'number') { + return newest.id; } if (attempt < SYNCED_TRACK_LOOKUP_ATTEMPTS - 1) { await delay(SYNCED_TRACK_LOOKUP_RETRY_MS); @@ -425,13 +478,19 @@ export async function loadSyncedSubtitle( if (slot === 'secondary') { // Keep the primary track untouched: load without selecting, then point // secondary-sid at the freshly added track. + const knownTrackIds = new Set( + (await readSubtitleTracks(client).catch(() => [])).flatMap((track) => + typeof track.id === 'number' ? [track.id] : [], + ), + ); client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) }); - client.send({ command: ['set_property', 'secondary-sub-delay', 0] }); - const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad); + const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds); if (addedTrackId === null) { throw new Error('Synchronized subtitle did not appear in the mpv track list'); } 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] }); return; } @@ -460,7 +519,12 @@ export function maybeWriteCleanedReferenceSrt( } const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-cleanref-')); const cleanPath = path.join(tempDir, 'clean_ref.srt'); - fs.writeFileSync(cleanPath, formatSpansAsSrt(extracted.spans), 'utf8'); + try { + fs.writeFileSync(cleanPath, formatSpansAsSrt(extracted.spans), 'utf8'); + } catch (error) { + removeDirQuietly(tempDir); + throw error; + } return { path: cleanPath, temporary: true }; } catch { return null; diff --git a/src/core/services/subsync-manual.ts b/src/core/services/subsync-manual.ts index 8e99ec73..cc7721a4 100644 --- a/src/core/services/subsync-manual.ts +++ b/src/core/services/subsync-manual.ts @@ -44,6 +44,7 @@ import { runFfsubsyncSync, validateFfsubsyncReference, writeRetimedContent, + readSubtitleFileStamp, } from './subsync-files'; import { AUDIO_SPEECH_LEAD_SEC, @@ -181,7 +182,10 @@ async function runBuiltinSubsync( return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }; } - writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget); + writeRetimedContent(outputPath, alignment.rewrittenContent, { + replacesSource: replaceTarget, + sourceStamp: parsedTarget.stamp, + }); await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack); return { ok: true, @@ -225,7 +229,10 @@ async function runManualOffsetSubsync( if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }; } - writeRetimedContent(outputPath, rewritten, replaceTarget); + writeRetimedContent(outputPath, rewritten, { + replacesSource: replaceTarget, + sourceStamp: parsedTarget.stamp, + }); await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack); return { ok: true, @@ -255,6 +262,7 @@ async function subsyncToReference( ); const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); + const sourceStamp = readSubtitleFileStamp(targetExtraction.path); const parsedOutput = path.parse(outputPath); const stagedOutputPath = path.join( parsedOutput.dir, @@ -296,7 +304,10 @@ async function subsyncToReference( return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }; } - installRetimedFile(stagedOutputPath, outputPath, replaceTarget); + installRetimedFile(stagedOutputPath, outputPath, { + replacesSource: replaceTarget, + sourceStamp, + }); await loadSyncedSubtitle(client, outputPath, slot, targetTrack); return { ok: true, @@ -377,6 +388,7 @@ export async function runSubsyncManualUnguarded( resolved, client, targetSlot, + deps, ); } @@ -396,6 +408,7 @@ export async function runSubsyncManualUnguarded( resolved, client, targetSlot, + deps, ); } @@ -520,6 +533,8 @@ export async function openSubsyncManualPicker( audioSpeechAvailable, guidanceMessage: options.guidanceMessage ?? null, }); + // A cancelled run (media changed) must not open a picker for the old media. + if (deps.signal?.aborted) return false; deps.openManualPicker(payload); return true; } diff --git a/src/core/services/subsync.test.ts b/src/core/services/subsync.test.ts index bb3e6ab8..963d4f21 100644 --- a/src/core/services/subsync.test.ts +++ b/src/core/services/subsync.test.ts @@ -941,8 +941,9 @@ test('runSubsyncManual keeps a retimed secondary track in the secondary slot', a assert.equal(result.ok, true); assert.deepEqual(sentCommands[0], ['sub-add', retimedPath, 'auto']); - assert.deepEqual(sentCommands[1], ['set_property', 'secondary-sub-delay', 0]); - assert.deepEqual(sentCommands[2], ['set_property', 'secondary-sid', 3]); + // The old delay is only dropped once the retimed track is selected. + assert.deepEqual(sentCommands[1], ['set_property', 'secondary-sid', 3]); + assert.deepEqual(sentCommands[2], ['set_property', 'secondary-sub-delay', 0]); assert.equal( sentCommands.some((command) => command[1] === 'sub-delay'), false, @@ -1556,9 +1557,14 @@ test('runSubsyncManual kills a running tool and reports cancellation when the me fs.writeFileSync(videoPath, 'video'); fs.writeFileSync(targetPath, '1\n00:00:01,000 --> 00:00:02,000\nhi\n'); fs.writeFileSync(refPath, '1\n00:00:01,000 --> 00:00:02,000\nhi\n'); - writeExecutableScript(alassPath, `#!/bin/sh\necho $$ > "${pidPath}"\nexec sleep 30\n`); + const childPidPath = path.join(tmpDir, 'alass-child.pid'); + // Like ffsubsync (Python running ffmpeg): the tool itself starts a long-running child. + writeExecutableScript( + alassPath, + `#!/bin/sh\nsleep 30 &\necho $! > "${childPidPath}"\necho $$ > "${pidPath}"\nwait\n`, + ); - const startedAt = Date.now(); + let switchedAt: number | null = null; const deps = makeDeps({ getMpvClient: () => ({ connected: true, @@ -1566,7 +1572,9 @@ test('runSubsyncManual kills a running tool and reports cancellation when the me send: () => {}, requestProperty: async (name: string) => { if (name === 'path') { - return Date.now() - startedAt < 700 ? videoPath : path.join(tmpDir, 'ep02.mkv'); + // Switch episodes only once the tool is running, however slow the machine is. + if (switchedAt === null && fs.existsSync(pidPath)) switchedAt = Date.now(); + return switchedAt === null ? videoPath : path.join(tmpDir, 'ep02.mkv'); } if (name === 'sid') return 1; if (name === 'secondary-sid') return null; @@ -1592,9 +1600,21 @@ test('runSubsyncManual kills a running tool and reports cancellation when the me assert.equal(result.ok, false); assert.match(result.message, /Playback changed/); - assert.ok(Date.now() - startedAt < 5000, 'run should stop well before the tool would finish'); - const pid = Number(fs.readFileSync(pidPath, 'utf8').trim()); - assert.throws(() => process.kill(pid, 0), 'the external tool should have been killed'); + assert.ok(switchedAt !== null && Date.now() - switchedAt < 5000, 'stops soon after the switch'); + const isAlive = (pidFile: string): boolean => { + try { + process.kill(Number(fs.readFileSync(pidFile, 'utf8').trim()), 0); + return true; + } catch { + return false; + } + }; + assert.equal(isAlive(pidPath), false, 'the external tool should have been killed'); + // The orphaned child is reaped asynchronously by init; give it a moment. + for (let attempt = 0; attempt < 20 && isAlive(childPidPath); attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 50)); + } + assert.equal(isAlive(childPidPath), false, "the tool's own child should have been killed"); }); test('in-place replacement keeps a one-time .orig backup, the file mode, and symlinks', async () => { diff --git a/src/core/services/subsync.ts b/src/core/services/subsync.ts index 8d557d97..9a2acdbb 100644 --- a/src/core/services/subsync.ts +++ b/src/core/services/subsync.ts @@ -73,9 +73,10 @@ export async function runWithMediaChangeAbort( task: (deps: D) => Promise, ): Promise { const client = deps.getMpvClient(); - const initialPath = client?.connected - ? await client.requestProperty('path').catch(() => null) - : null; + // `undefined` = baseline not read yet (failed request); the first successful poll sets it. + let baselinePath: unknown = client?.connected + ? await client.requestProperty('path').catch(() => undefined) + : undefined; const controller = new AbortController(); let polling = false; const timer = setInterval(() => { @@ -90,7 +91,8 @@ export async function runWithMediaChangeAbort( .requestProperty('path') .then( (currentPath) => { - if (currentPath !== initialPath) controller.abort(); + if (baselinePath === undefined) baselinePath = currentPath; + else if (currentPath !== baselinePath) controller.abort(); }, () => {}, ) diff --git a/src/subsync/align-worker.ts b/src/subsync/align-worker.ts index 6cc35baa..654e9dd0 100644 --- a/src/subsync/align-worker.ts +++ b/src/subsync/align-worker.ts @@ -64,7 +64,12 @@ function resolveAlignWorkerPath(): string | null { return fs.existsSync(workerPath) ? workerPath : null; } -type Pending = { resolve: (value: unknown) => void; reject: (reason: Error) => void }; +type Pending = { + kind: AlignTaskKind; + args: unknown[]; + resolve: (value: unknown) => void; + reject: (reason: Error) => void; +}; class AlignWorkerRuntime { private worker: Worker | null = null; @@ -80,12 +85,13 @@ class AlignWorkerRuntime { ): Promise> { signal?.throwIfAborted(); const worker = await this.getWorker(); + signal?.throwIfAborted(); if (!worker) return runAlignTask(kind, args) as AlignTaskResult; const id = this.nextId++; this.clearIdleTimer(); const result = new Promise((resolve, reject) => { - this.pending.set(id, { resolve, reject }); + this.pending.set(id, { kind, args, resolve, reject }); }); const onAbort = (): void => this.reset(signal?.reason ?? new Error('aborted')); signal?.addEventListener('abort', onAbort, { once: true }); @@ -110,10 +116,20 @@ class AlignWorkerRuntime { try { const { Worker: WorkerCtor } = await import('node:worker_threads'); const worker = new WorkerCtor(workerPath); + let online = false; worker.unref(); + worker.once('online', () => { + online = true; + }); worker.on('message', (message: AlignWorkerResponse) => this.handleMessage(message)); worker.on('error', (error: Error) => { - this.markUnavailable(error); + // Failing to start (e.g. the module cannot load) is not the task's fault: finish the + // queued calls on this thread and stop using the worker. + if (!online) { + this.markUnavailable(error); + this.runPendingInThread(); + return; + } this.reset(error); }); worker.on('exit', (code) => { @@ -139,6 +155,21 @@ class AlignWorkerRuntime { else pending.reject(new Error(message.error)); } + private runPendingInThread(): void { + const worker = this.worker; + this.worker = null; + if (worker) void worker.terminate().catch(() => undefined); + const queued = [...this.pending.values()]; + this.pending.clear(); + for (const pending of queued) { + try { + pending.resolve(runAlignTask(pending.kind, pending.args)); + } catch (error) { + pending.reject(error instanceof Error ? error : new Error(String(error))); + } + } + } + /** Stop the worker (and any computation in it) and fail every in-flight call. */ private reset(reason: unknown): void { const error = reason instanceof Error ? reason : new Error(String(reason)); diff --git a/src/subsync/audio-speech.ts b/src/subsync/audio-speech.ts index fc8f184b..686d30b3 100644 --- a/src/subsync/audio-speech.ts +++ b/src/subsync/audio-speech.ts @@ -145,8 +145,8 @@ export function getCachedEmbeddedSubtitles( // ffmpeg stderr only feeds error messages; a corrupt file can spam megabytes of it. const STDERR_TAIL_LIMIT = 64 * 1024; -function appendStderrTail(current: string, chunk: Buffer): string { - const next = current + chunk.toString(); +function appendStderrTail(current: string, chunk: string): string { + const next = current + chunk; return next.length > STDERR_TAIL_LIMIT ? next.slice(-STDERR_TAIL_LIMIT) : next; } @@ -392,7 +392,9 @@ function streamFfmpegPcm( child.stdout.on('data', (chunk: Buffer) => { chunks.push(chunk); }); - child.stderr.on('data', (chunk: Buffer) => { + // Decode as a stream so multi-byte characters split across chunks survive. + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk: string) => { stderr = appendStderrTail(stderr, chunk); }); child.on('error', (error: Error) => { @@ -584,7 +586,9 @@ function spawnFfmpegWithStdout( child.stdout.on('data', (chunk: Buffer) => { chunks.push(chunk); }); - child.stderr.on('data', (chunk: Buffer) => { + // Decode as a stream so multi-byte characters split across chunks survive. + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk: string) => { stderr = appendStderrTail(stderr, chunk); }); child.on('error', (error: Error) => { diff --git a/src/subsync/utils.ts b/src/subsync/utils.ts index dac06323..143cad5e 100644 --- a/src/subsync/utils.ts +++ b/src/subsync/utils.ts @@ -313,9 +313,17 @@ export function buildJellyfinEmbeddedSubtitleUrl( return subtitleUrl.toString(); } -/** Kill a spawned tool. On Windows a `.cmd`/`.bat` shim is cmd.exe, so the whole tree must go. */ +/** + * Kill a spawned tool and what it started. On Windows a `.cmd`/`.bat` shim is cmd.exe, so the + * tree goes via taskkill. On POSIX a child spawned with `detached: true` leads its own process + * group (ffsubsync is Python running ffmpeg), so the whole group is signalled. + */ export function killProcessTree(child: childProcess.ChildProcess): void { - if (process.platform === 'win32' && child.pid !== undefined) { + if (child.pid === undefined) { + child.kill('SIGKILL'); + return; + } + if (process.platform === 'win32') { childProcess .spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', @@ -324,9 +332,36 @@ export function killProcessTree(child: childProcess.ChildProcess): void { .on('error', () => child.kill()); return; } + if (processGroupLeaders.has(child)) { + try { + // Negative pid = the child's own group; never ours, since the child was detached. + process.kill(-child.pid, 'SIGKILL'); + return; + } catch { + // Group already gone; fall through to the direct kill. + } + } child.kill('SIGKILL'); } +/** Children spawned by runCommand as leaders of their own POSIX process group. */ +const processGroupLeaders = new WeakSet(); +/** Running detached groups: they no longer get the terminal's Ctrl+C, so exit kills them. */ +const runningProcessGroups = new Set(); +let processGroupExitHookInstalled = false; + +function trackProcessGroup(child: childProcess.ChildProcess): void { + processGroupLeaders.add(child); + runningProcessGroups.add(child); + child.once('close', () => runningProcessGroups.delete(child)); + child.once('error', () => runningProcessGroups.delete(child)); + if (processGroupExitHookInstalled) return; + processGroupExitHookInstalled = true; + process.once('exit', () => { + for (const running of runningProcessGroups) killProcessTree(running); + }); +} + /** Run a tool to completion; an abort or the timeout kills it and resolves with `ok: false`. */ export function runCommand( executable: string, @@ -339,10 +374,14 @@ export function runCommand( } 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); let stdout = ''; let stderr = ''; const onAbort = (): void => killProcessTree(child);