fix(subsync): address PR review of track identity, tool output, and cancellation

- check the active target's source identity too (mpv reuses freed track ids)
- include device and inode in the source stamp so a retargeted symlink is caught
- reject external-engine output with no readable cues instead of installing it
- leave the user's secondary track alone if they changed it during the lookup
- reject scene-cut splits that would reorder dialogue lines
- document that full line-start agreement overrides the weak-quarter cap
- spawn ffmpeg launchers in their own process group and check aborts before
  spawning (an aborted signal hit a TDZ ReferenceError)
- cache the built-in VAD fallback under its own key so Silero is retried
- kill the tool directly when taskkill exits nonzero
This commit is contained in:
sudacode committed 2026-11-28 04:23:39 -08:00
1 parent bd3fe3140d
commit d6d541e51b
9 files changed
+219 -47

No files matched your search

+3 -2
View File
@@ -195,8 +195,9 @@ async function isPlaybackSessionUnchangedNow(
slot === 'secondary' slot === 'secondary'
? (context.secondaryTrack?.id ?? null) ? (context.secondaryTrack?.id ?? null)
: (context.primaryTrack.id ?? null); : (context.primaryTrack.id ?? null);
const needsTrackIdentityCheck = // Always compare the target's source too: mpv reuses the highest freed id, so a track
typeof targetTrack.id === 'number' && targetTrack.id !== initialSlotTrackId; // 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([ const [videoPathRaw, workingDirRaw, slotTrackRaw, trackListRaw] = await Promise.all([
client.requestProperty('path'), client.requestProperty('path'),
client.requestProperty('working-directory').catch(() => null), client.requestProperty('working-directory').catch(() => null),
+13 -2
View File
@@ -275,11 +275,14 @@ export function buildRetimedPath(subPath: string, replace: boolean): string {
export const LOSSY_REWRITE_ERROR_MESSAGE = 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.'; '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 { export function readSubtitleFileStamp(filePath: string): string | null {
try { try {
const stat = fs.statSync(filePath); const stat = fs.statSync(filePath);
return `${stat.size}\0${stat.mtimeMs}`; return `${stat.dev}:${stat.ino}\0${stat.size}\0${stat.mtimeMs}`;
} catch { } catch {
return null; return null;
} }
@@ -499,6 +502,7 @@ export async function loadSyncedSubtitle(
typeof track.id === 'number' ? [track.id] : [], typeof track.id === 'number' ? [track.id] : [],
), ),
); );
const secondaryBeforeAdd = await client.requestProperty('secondary-sid');
signal?.throwIfAborted(); signal?.throwIfAborted();
client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) }); client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) });
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds); 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'); throw new Error('Synchronized subtitle did not appear in the mpv track list');
} }
signal?.throwIfAborted(); 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] }); client.send({ command: ['set_property', 'secondary-sid', addedTrackId] });
// The retimed file carries the timing now; only drop the old delay once it is selected. // 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] }); client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
+7
View File
@@ -301,6 +301,13 @@ async function subsyncToReference(
message: `${engine} synchronization failed: ${details}`, 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))) { if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot, io.signal))) {
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }; return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
+66 -10
View File
@@ -471,6 +471,59 @@ function fromShellPath(filePath: string): string {
.replace(/\//g, '\\'); .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<Array<string | number>> = [];
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 () => { test('runSubsyncManual ignores the ff-index of an external audio track', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-external-audio-')); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-external-audio-'));
const ffsubsyncLogPath = path.join(tmpDir, 'ffsubsync-args.log'); 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'); fs.writeFileSync(primaryPath, 'sub');
writeExecutableScript( writeExecutableScript(
ffsubsyncPath, 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({ const deps = makeDeps({
@@ -544,7 +597,7 @@ test('runSubsyncManual constructs ffsubsync command and returns success', async
writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript( writeExecutableScript(
ffsubsyncPath, 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<Array<string | number>> = []; const sentCommands: Array<Array<string | number>> = [];
@@ -617,7 +670,7 @@ test('runSubsyncManual writes deterministic _retimed filename when replace is fa
writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript( writeExecutableScript(
ffsubsyncPath, 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({ const deps = makeDeps({
@@ -807,7 +860,7 @@ function makeAlassSelectionDeps(tmpDir: string): {
writeExecutableScript(ffsubsyncPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(ffsubsyncPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript( writeExecutableScript(
alassPath, 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<Record<string, unknown>> = [ const trackList: Array<Record<string, unknown>> = [
@@ -895,7 +948,10 @@ test('runSubsyncManual keeps a retimed secondary track in the secondary slot', a
fs.writeFileSync(secondaryPath, 'en'); fs.writeFileSync(secondaryPath, 'en');
writeExecutableScript(ffmpegPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(ffmpegPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript(ffsubsyncPath, '#!/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<Record<string, unknown>> = [ const trackList: Array<Record<string, unknown>> = [
{ id: 1, type: 'sub', selected: true, external: true, 'external-filename': primaryPath }, { 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(ffsubsyncPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript( writeExecutableScript(
ffmpegPath, 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( writeExecutableScript(
alassPath, 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<Array<string | number>> = []; const sentCommands: Array<Array<string | number>> = [];
@@ -1042,7 +1098,7 @@ test('runSubsyncManual resolves string sid values from mpv stream properties', a
writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript( writeExecutableScript(
ffsubsyncPath, 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({ const deps = makeDeps({
@@ -1086,7 +1142,7 @@ test('runSubsyncManual resolves string sid values from mpv stream properties', a
assert.equal(typeof outputPath, 'string'); assert.equal(typeof outputPath, 'string');
assert.ok(outputPath!.length > 0); assert.ok(outputPath!.length > 0);
assert.equal(fs.existsSync(fromShellPath(outputPath!)), false); 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( function generateSyntheticSpans(
@@ -2479,7 +2535,7 @@ test('runSubsyncManual stages external engine output and preserves original when
writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n'); writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript( writeExecutableScript(
ffsubsyncPath, 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; let pathCalls = 0;
+10
View File
@@ -6,6 +6,8 @@ import {
evaluateReferenceAlignmentToAudio, evaluateReferenceAlignmentToAudio,
evaluateReferenceAlignmentToSampledAudio, evaluateReferenceAlignmentToSampledAudio,
joinSpans, joinSpans,
scoreStanding,
CALIBRATION_CLEAN,
wrappedCoverage, wrappedCoverage,
type SampledAudioWindow, type SampledAudioWindow,
} from './alass-align'; } from './alass-align';
@@ -318,3 +320,11 @@ test('alignSubtitleFileToReferenceSpans rejects broadcast pieces that collapse o
assert.equal(result.cut, false); assert.equal(result.cut, false);
assert.equal(result.confident, 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);
});
+13 -2
View File
@@ -655,6 +655,10 @@ export function scoreStanding(z: AlignmentStanding, cal: SyncCalibration): numbe
if (z.weakestPart !== undefined && z.weakestPart < PART_COVERAGE_Z_MIN) { if (z.weakestPart !== undefined && z.weakestPart < PART_COVERAGE_Z_MIN) {
covered = Math.min(covered, PARTIAL_FIT_SCORE_CAP); 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 = const started =
z.starts >= STARTS_Z_MIN z.starts >= STARTS_Z_MIN
? Math.max( ? Math.max(
@@ -1128,8 +1132,15 @@ export function alignSubtitleFileToReferenceSpans(
end: targetSpans[idx]!.end * ratio + shift, end: targetSpans[idx]!.end * ratio + shift,
}); });
} }
const zSplit = evaluateStanding(splitSpans, joinedRef, sortedRefStarts, lengthSec); // splitSpans follow the original start order; a cut that makes a later line start
if (zSplit.above > zOne.above + 0.3) { // 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; finalStanding = zSplit;
finalScore = scoreStanding(zSplit, cal); finalScore = scoreStanding(zSplit, cal);
finalSegments = jumps + 1; finalSegments = jumps + 1;
+56
View File
@@ -241,3 +241,59 @@ exit 0
fs.rmSync(tmpDir, { recursive: true, force: true }); 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 });
}
});
+24 -21
View File
@@ -1,4 +1,3 @@
import * as childProcess from 'node:child_process';
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import * as os from 'node:os'; import * as os from 'node:os';
import * as path from 'node:path'; import * as path from 'node:path';
@@ -14,8 +13,8 @@ import {
extensionToFfmpegMuxer, extensionToFfmpegMuxer,
fileExists, fileExists,
killProcessTree, killProcessTree,
resolveCommandInvocation,
runCommand, runCommand,
spawnTool,
} from './utils'; } from './utils';
const PCM_VAD_SAMPLE_RATE = 8000; const PCM_VAD_SAMPLE_RATE = 8000;
@@ -356,11 +355,12 @@ function streamFfmpegPcm(
'pipe:1', 'pipe:1',
); );
const invocation = resolveCommandInvocation(ffmpegPath, args); // Checked before spawning: nothing below is set up yet for an already-aborted run.
const child = childProcess.spawn(invocation.command, invocation.args, { if (signal?.aborted) {
stdio: ['ignore', 'pipe', 'pipe'], reject(new Error('Audio extraction aborted'));
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), return;
}); }
const child = spawnTool(ffmpegPath, args);
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let stderr = ''; let stderr = '';
let settled = false; let settled = false;
@@ -378,10 +378,6 @@ function streamFfmpegPcm(
finishError(new Error('Audio extraction aborted')); finishError(new Error('Audio extraction aborted'));
}; };
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener('abort', onAbort, { once: true }); signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(() => { const timer = setTimeout(() => {
@@ -522,6 +518,16 @@ export async function extractAudioSpeechSpans(
return silero; 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). // Tier 2: Built-in voice-band PCM speech detector via ffmpeg (zero extra dependencies).
const pcmBuffer = await streamFfmpegPcm( const pcmBuffer = await streamFfmpegPcm(
options.ffmpegPath, options.ffmpegPath,
@@ -539,7 +545,7 @@ export async function extractAudioSpeechSpans(
calibration: 'noisy', calibration: 'noisy',
source: 'builtin-vad', source: 'builtin-vad',
}; };
rememberAudioSpeech(cacheKey, result); rememberAudioSpeech(builtinKey, result);
return result; return result;
} }
@@ -550,11 +556,12 @@ function spawnFfmpegWithStdout(
signal?: AbortSignal, signal?: AbortSignal,
): Promise<Buffer> { ): Promise<Buffer> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const invocation = resolveCommandInvocation(ffmpegPath, args); // Checked before spawning: nothing below is set up yet for an already-aborted run.
const child = childProcess.spawn(invocation.command, invocation.args, { if (signal?.aborted) {
stdio: ['ignore', 'pipe', 'pipe'], reject(new Error('ffmpeg operation aborted'));
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}), return;
}); }
const child = spawnTool(ffmpegPath, args);
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let stderr = ''; let stderr = '';
let settled = false; let settled = false;
@@ -572,10 +579,6 @@ function spawnFfmpegWithStdout(
finishError(new Error('ffmpeg operation aborted')); finishError(new Error('ffmpeg operation aborted'));
}; };
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener('abort', onAbort, { once: true }); signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(() => { const timer = setTimeout(() => {
+27 -10
View File
@@ -1,6 +1,7 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import * as path from 'path'; import * as path from 'path';
import type { Readable } from 'stream';
import { DEFAULT_CONFIG } from '../config'; import { DEFAULT_CONFIG } from '../config';
import { import {
buildWindowsShimInvocation, buildWindowsShimInvocation,
@@ -329,7 +330,11 @@ export function killProcessTree(child: childProcess.ChildProcess): void {
stdio: 'ignore', stdio: 'ignore',
windowsHide: true, 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; return;
} }
if (processGroupLeaders.has(child)) { 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<null, Readable, Readable> {
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`. */ /** Run a tool to completion; an abort or the timeout kills it and resolves with `ok: false`. */
export function runCommand( export function runCommand(
executable: string, executable: string,
@@ -373,15 +398,7 @@ export function runCommand(
return Promise.resolve({ ok: false, code: null, stderr: '', stdout: '', error: 'aborted' }); return Promise.resolve({ ok: false, code: null, stderr: '', stdout: '', error: 'aborted' });
} }
return new Promise((resolve) => { return new Promise((resolve) => {
const invocation = resolveCommandInvocation(executable, args); const child = spawnTool(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 stdout = '';
let stderr = ''; let stderr = '';
const onAbort = (): void => killProcessTree(child); const onAbort = (): void => killProcessTree(child);