feat(subsync): cancel running syncs when playback moves to other media

Every run now carries an AbortSignal that fires when mpv's path changes or mpv
disconnects. Spawned ffmpeg, VAD, alass, and ffsubsync are killed (whole tree
on Windows so .cmd shims do not leave the real process behind), candidate loops
and alignment yields stop at the next stage, and the subsync lock is released
right away instead of after minutes of stale work.
This commit is contained in:
sudacode committed 2026-11-28 03:23:06 -08:00
1 parent 3b3c6581f4
commit 480c8582d8
7 files changed
+274 -81

No files matched your search

+1
View File
@@ -4,3 +4,4 @@ area: subsync
- Integrated built-in alass-based subtitle syncing with sign/song stripping, framerate and scene-cut/ad-break handling, audio alignment verification across all loaded/embedded/sidecar tracks, and built-in speech-activity audio fallback. - Integrated built-in alass-based subtitle syncing with sign/song stripping, framerate and scene-cut/ad-break handling, audio alignment verification across all loaded/embedded/sidecar tracks, and built-in speech-activity audio fallback.
- Added one-click automatic syncing via the subtitle sidebar Sync button and `Ctrl+Alt+S` (`subsync.mode: "auto"`), automatically opening the guided Subtitle Sync modal with diagnostics, file browsing, external engine fallbacks, and manual offset only when guidance is needed. - Added one-click automatic syncing via the subtitle sidebar Sync button and `Ctrl+Alt+S` (`subsync.mode: "auto"`), automatically opening the guided Subtitle Sync modal with diagnostics, file browsing, external engine fallbacks, and manual offset only when guidance is needed.
- In-place sync (`subsync.replace`, on by default) keeps the untouched original next to the subtitle as `<file>.orig` on the first overwrite. - In-place sync (`subsync.replace`, on by default) keeps the untouched original next to the subtitle as `<file>.orig` on the first overwrite.
- Switching to other media while a sync is running cancels it right away instead of finishing in the background and blocking the next sync.
+1 -1
View File
@@ -35,7 +35,7 @@ Update checks and startup launcher migration share a serialized update-state sto
- `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative. - `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative.
- Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments. - Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments.
- `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps. - `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps.
- `src/subsync/` and `src/core/services/subsync*.ts` own built-in subtitle synchronization: format-preserving SRT/VTT/ASS parsing and sign/song/karaoke stripping (`subtitle-lines.ts`), pure-TypeScript alass-based single-shift, framerate-ratio, Viterbi piecewise, and broadcast multi-piece alignment with statistical standing/start-agreement scoring (`alass-align.ts`), cached local audio speech detection preferring Silero VAD when available with a built-in ffmpeg voice-band PCM VAD fallback, single-pass multi-track `ffmpeg` demuxing for embedded tracks, and fast parallel seeked-window audio verification for external-only references (`audio-speech.ts`), plus sidecar/track candidate discovery and audio-alignment verification (`reference-discovery.ts`). Triggering subsync in default `auto` mode evaluates all available tracks and sidecars (skipping signs/songs-tagged embedded tracks), verifies references against audio on local media so misaligned secondary tracks are skipped in favor of better-aligned tracks or audio speech, applies confident syncs automatically, and opens the guided modal (supporting built-in, external `alass`/`ffsubsync`, file browse, sign/split toggles, and manual offset) whenever automatic sync cannot finish cleanly. - `src/subsync/` and `src/core/services/subsync*.ts` own built-in subtitle synchronization: format-preserving SRT/VTT/ASS parsing and sign/song/karaoke stripping (`subtitle-lines.ts`), pure-TypeScript alass-based single-shift, framerate-ratio, Viterbi piecewise, and broadcast multi-piece alignment with statistical standing/start-agreement scoring (`alass-align.ts`), cached local audio speech detection preferring Silero VAD when available with a built-in ffmpeg voice-band PCM VAD fallback, single-pass multi-track `ffmpeg` demuxing for embedded tracks, and fast parallel seeked-window audio verification for external-only references (`audio-speech.ts`), plus sidecar/track candidate discovery and audio-alignment verification (`reference-discovery.ts`). Triggering subsync in default `auto` mode evaluates all available tracks and sidecars (skipping signs/songs-tagged embedded tracks), verifies references against audio on local media so misaligned secondary tracks are skipped in favor of better-aligned tracks or audio speech, applies confident syncs automatically, and opens the guided modal (supporting built-in, external `alass`/`ffsubsync`, file browse, sign/split toggles, and manual offset) whenever automatic sync cannot finish cleanly. Every run goes through `runWithMediaChangeAbort`: when mpv's `path` changes it aborts the run's signal, which kills spawned ffmpeg/VAD/alass/ffsubsync (process tree on Windows) and stops at the next stage boundary, so the global subsync lock is released immediately. In-place rewrites keep a one-time `<file>.orig` backup.
- `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry. - `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry.
- `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes. - `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes.
- `src/core/services/plugins/` owns user plugins: discovery from `<config dir>/plugins/<id>/plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `src/main/assemblies/plugins.ts` builds the host. The playback assembly attaches each new mpv client so plugin listeners survive client replacement, the startup assembly starts plugins from the app-ready path after logging is configured, and the `will-quit` cleanup unloads them first, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open. - `src/core/services/plugins/` owns user plugins: discovery from `<config dir>/plugins/<id>/plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `src/main/assemblies/plugins.ts` builds the host. The playback assembly attaches each new mpv client so plugin listeners survive client replacement, the startup assembly starts plugins from the app-ready path after logging is configured, and the `will-quit` cleanup unloads them first, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open.
+10 -2
View File
@@ -2,10 +2,12 @@ import { SubsyncManualPayload, SubsyncManualRunRequest, SubsyncResult } from '..
import { SubsyncResolvedConfig } from '../../subsync/utils'; import { SubsyncResolvedConfig } from '../../subsync/utils';
import { runSubsyncManualFromIpc } from './ipc-command'; import { runSubsyncManualFromIpc } from './ipc-command';
import { import {
SubsyncCancelledError,
SubsyncVadPaths, SubsyncVadPaths,
TriggerSubsyncFromConfigDeps, TriggerSubsyncFromConfigDeps,
openSubsyncManualPicker, openSubsyncManualPicker,
runSubsyncManual, runSubsyncManual,
runWithMediaChangeAbort,
triggerSubsyncFromConfig, triggerSubsyncFromConfig,
} from './subsync'; } from './subsync';
@@ -75,15 +77,21 @@ export async function openSubsyncManualPickerRuntime(deps: SubsyncRuntimeDeps):
triggerDeps.setSubsyncInProgress(true); triggerDeps.setSubsyncInProgress(true);
try { try {
const opened = await triggerDeps.runWithSubsyncSpinner(() => const opened = await triggerDeps.runWithSubsyncSpinner(() =>
openSubsyncManualPicker(triggerDeps, { runWithMediaChangeAbort(triggerDeps, (runDeps) =>
openSubsyncManualPicker(runDeps, {
guidanceMessage: null, guidanceMessage: null,
}), }),
),
); );
if (opened) { if (opened) {
triggerDeps.showMpvOsd('Subsync: choose engine and subtitles'); triggerDeps.showMpvOsd('Subsync: choose engine and subtitles');
} }
} catch (error) { } catch (error) {
triggerDeps.showMpvOsd(`Subsync failed: ${(error as Error).message}`); triggerDeps.showMpvOsd(
error instanceof SubsyncCancelledError
? error.message
: `Subsync failed: ${(error as Error).message}`,
);
} finally { } finally {
triggerDeps.setSubsyncInProgress(false); triggerDeps.setSubsyncInProgress(false);
} }
+58 -3
View File
@@ -1545,6 +1545,58 @@ test('runSubsyncManual supports built-in file reference and manual offset engine
assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s'); assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s');
}); });
test('runSubsyncManual kills a running tool and reports cancellation when the media changes', async () => {
if (process.platform === 'win32') return;
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-cancel-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const refPath = path.join(tmpDir, 'ref.srt');
const alassPath = path.join(tmpDir, 'alass.sh');
const pidPath = path.join(tmpDir, 'alass.pid');
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 startedAt = Date.now();
const deps = makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') {
return Date.now() - startedAt < 700 ? videoPath : path.join(tmpDir, 'ep02.mkv');
}
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': targetPath },
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath,
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
}),
});
const result = await runSubsyncManual(
{ engine: 'alass', referenceMode: 'file', referenceFilePath: refPath, stripSigns: false },
deps,
);
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');
});
test('in-place replacement keeps a one-time .orig backup, the file mode, and symlinks', async () => { test('in-place replacement keeps a one-time .orig backup, the file mode, and symlinks', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-backup-')); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-backup-'));
const videoPath = path.join(tmpDir, 'ep01.mkv'); const videoPath = path.join(tmpDir, 'ep01.mkv');
@@ -1937,7 +1989,8 @@ test('triggerSubsyncFromConfig discards stale result when playback switches to a
if (name === 'path') { if (name === 'path') {
pathCalls += 1; pathCalls += 1;
// First call sees ep01, subsequent staleness check sees ep02. // First call sees ep01, subsequent staleness check sees ep02.
return pathCalls === 1 ? videoA : videoB; // 1: media-change watcher baseline, 2: context gather; later reads see the switch
return pathCalls <= 2 ? videoA : videoB;
} }
if (name === 'sid') return 1; if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2; if (name === 'secondary-sid') return 2;
@@ -2283,7 +2336,8 @@ test('triggerSubsyncFromConfig skips early extraction fallback picker when playb
requestProperty: async (name: string) => { requestProperty: async (name: string) => {
if (name === 'path') { if (name === 'path') {
pathCalls += 1; pathCalls += 1;
return pathCalls === 1 ? '/tmp/videoA.mkv' : '/tmp/videoB.mkv'; // 1: media-change watcher baseline, 2: context gather; later reads see the switch
return pathCalls <= 2 ? '/tmp/videoA.mkv' : '/tmp/videoB.mkv';
} }
if (name === 'sid') return 1; if (name === 'sid') return 1;
if (name === 'secondary-sid') return null; if (name === 'secondary-sid') return null;
@@ -2422,7 +2476,8 @@ test('runSubsyncManual stages external engine output and preserves original when
requestProperty: async (name: string) => { requestProperty: async (name: string) => {
if (name === 'path') { if (name === 'path') {
pathCalls += 1; pathCalls += 1;
return pathCalls === 1 ? videoA : videoB; // 1: media-change watcher baseline, 2: context gather; later reads see the switch
return pathCalls <= 2 ? videoA : videoB;
} }
if (name === 'sid') return 1; if (name === 'sid') return 1;
if (name === 'secondary-sid') return null; if (name === 'secondary-sid') return null;
+162 -52
View File
@@ -86,8 +86,10 @@ const COMMAND_OUTPUT_SUMMARY_CHARS = 300;
// Alignment and candidate scoring are synchronous CPU work (100ms to 1s each on long media). // Alignment and candidate scoring are synchronous CPU work (100ms to 1s each on long media).
// Yield between them so mpv IPC, the overlay, and other main-process work keep flowing. // Yield between them so mpv IPC, the overlay, and other main-process work keep flowing.
function yieldToEventLoop(): Promise<void> { // Also the cancellation point between those stages.
return new Promise((resolve) => setImmediate(resolve)); async function yieldToEventLoop(signal?: AbortSignal): Promise<void> {
await new Promise((resolve) => setImmediate(resolve));
signal?.throwIfAborted();
} }
// Keep the tail of tool output (errors come last; alass prints progress first) and strip // Keep the tail of tool output (errors come last; alass prints progress first) and strip
@@ -131,8 +133,13 @@ interface SubsyncCoreDeps {
getVadPaths?: () => SubsyncVadPaths; getVadPaths?: () => SubsyncVadPaths;
canPickReferenceFile?: () => boolean; canPickReferenceFile?: () => boolean;
fetchImpl?: typeof fetch; fetchImpl?: typeof fetch;
/** Aborts the run (media changed); kills spawned tools and stops between stages. */
signal?: AbortSignal;
} }
/** Network and cancellation handles threaded into extraction helpers. */
type SubsyncIo = Pick<SubsyncCoreDeps, 'fetchImpl' | 'signal'>;
function parseTrackId(value: unknown): number | null { function parseTrackId(value: unknown): number | null {
if (typeof value === 'number') { if (typeof value === 'number') {
return Number.isInteger(value) ? value : null; return Number.isInteger(value) ? value : null;
@@ -335,23 +342,22 @@ async function tryFetchJellyfinSubtitleBytes(
videoPath: string, videoPath: string,
ffIndex: number, ffIndex: number,
extension: string, extension: string,
fetchImpl: typeof fetch = globalThis.fetch, io: SubsyncIo = {},
): Promise<Uint8Array | null> { ): Promise<Uint8Array | null> {
const subtitleUrl = buildJellyfinEmbeddedSubtitleUrl(videoPath, ffIndex, extension); const subtitleUrl = buildJellyfinEmbeddedSubtitleUrl(videoPath, ffIndex, extension);
const fetchImpl = io.fetchImpl ?? globalThis.fetch;
if (!subtitleUrl || typeof fetchImpl !== 'function') return null; if (!subtitleUrl || typeof fetchImpl !== 'function') return null;
const controller = new AbortController(); const timeoutSignal = AbortSignal.timeout(JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS);
const timeout = setTimeout(() => controller.abort(), JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS); const signal = io.signal ? AbortSignal.any([timeoutSignal, io.signal]) : timeoutSignal;
try { try {
const response = await fetchImpl(subtitleUrl, { signal: controller.signal }); const response = await fetchImpl(subtitleUrl, { signal });
if (!response.ok) return null; if (!response.ok) return null;
const buffer = await response.arrayBuffer(); const buffer = await response.arrayBuffer();
if (buffer.byteLength === 0) return null; if (buffer.byteLength === 0) return null;
return new Uint8Array(buffer); return new Uint8Array(buffer);
} catch { } catch {
return null; return null;
} finally {
clearTimeout(timeout);
} }
} }
@@ -360,7 +366,7 @@ async function extractSubtitleTrackToFile(
videoPath: string, videoPath: string,
track: MpvTrack, track: MpvTrack,
workingDirectory?: string | null, workingDirectory?: string | null,
fetchImpl?: typeof fetch, io: SubsyncIo = {},
): Promise<FileExtractionResult> { ): Promise<FileExtractionResult> {
if (track.external) { if (track.external) {
const externalPath = track['external-filename']; const externalPath = track['external-filename'];
@@ -384,12 +390,7 @@ async function extractSubtitleTrackToFile(
} }
if (isRemoteMediaPath(videoPath)) { if (isRemoteMediaPath(videoPath)) {
const fetchedBytes = await tryFetchJellyfinSubtitleBytes( const fetchedBytes = await tryFetchJellyfinSubtitleBytes(videoPath, ffIndex, extension, io);
videoPath,
ffIndex,
extension,
fetchImpl,
);
if (fetchedBytes) { if (fetchedBytes) {
const decoded = decodeSubtitleBytesWithStatus(fetchedBytes); const decoded = decodeSubtitleBytesWithStatus(fetchedBytes);
const parsed = parseSubtitleFileContent(decoded.text, `track_${ffIndex}.${extension}`); const parsed = parseSubtitleFileContent(decoded.text, `track_${ffIndex}.${extension}`);
@@ -416,7 +417,9 @@ async function extractSubtitleTrackToFile(
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-')); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-'));
const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`); const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`);
try { try {
const extraction = await runCommand(resolvedFfmpegPath, [ const extraction = await runCommand(
resolvedFfmpegPath,
[
'-hide_banner', '-hide_banner',
'-nostdin', '-nostdin',
'-y', '-y',
@@ -431,7 +434,10 @@ async function extractSubtitleTrackToFile(
'-f', '-f',
extensionToFfmpegMuxer(extension), extensionToFfmpegMuxer(extension),
outputPath, outputPath,
]); ],
undefined,
io.signal,
);
if (!extraction.ok || !fileExists(outputPath)) { if (!extraction.ok || !fileExists(outputPath)) {
throw new Error( throw new Error(
@@ -624,8 +630,9 @@ async function runAlassSync(
referenceFile: string, referenceFile: string,
inputSubtitlePath: string, inputSubtitlePath: string,
outputPath: string, outputPath: string,
signal?: AbortSignal,
): Promise<CommandResult> { ): Promise<CommandResult> {
return runCommand(alassPath, [referenceFile, inputSubtitlePath, outputPath]); return runCommand(alassPath, [referenceFile, inputSubtitlePath, outputPath], undefined, signal);
} }
async function runFfsubsyncSync( async function runFfsubsyncSync(
@@ -634,12 +641,13 @@ async function runFfsubsyncSync(
inputSubtitlePath: string, inputSubtitlePath: string,
outputPath: string, outputPath: string,
audioStreamIndex: number | null, audioStreamIndex: number | null,
signal?: AbortSignal,
): Promise<CommandResult> { ): Promise<CommandResult> {
const args = [videoPath, '-i', inputSubtitlePath, '-o', outputPath]; const args = [videoPath, '-i', inputSubtitlePath, '-o', outputPath];
if (audioStreamIndex !== null) { if (audioStreamIndex !== null) {
args.push('--reference-stream', `0:${audioStreamIndex}`); args.push('--reference-stream', `0:${audioStreamIndex}`);
} }
return runCommand(ffsubsyncPath, args); return runCommand(ffsubsyncPath, args, undefined, signal);
} }
function delay(ms: number): Promise<void> { function delay(ms: number): Promise<void> {
@@ -775,6 +783,7 @@ async function resolveAudioSpeechForContext(
ffmpegPath: resolved.ffmpegPath, ffmpegPath: resolved.ffmpegPath,
videoPath: context.videoPath, videoPath: context.videoPath,
audioStreamIndex: context.audioStreamIndex, audioStreamIndex: context.audioStreamIndex,
signal: deps.signal,
vadExecutablePath: vadPaths?.vadExecutablePath ?? null, vadExecutablePath: vadPaths?.vadExecutablePath ?? null,
vadModelPath: vadPaths?.vadModelPath ?? null, vadModelPath: vadPaths?.vadModelPath ?? null,
}); });
@@ -826,6 +835,7 @@ async function discoverAndEvaluateSubtitleCandidates(
skipSignsEmbeddedExtraction?: boolean; skipSignsEmbeddedExtraction?: boolean;
skipEmbeddedExtraction?: boolean; skipEmbeddedExtraction?: boolean;
fetchImpl?: typeof fetch; fetchImpl?: typeof fetch;
signal?: AbortSignal;
} = {}, } = {},
): Promise<CandidateWithSpans[]> { ): Promise<CandidateWithSpans[]> {
const results: CandidateWithSpans[] = []; const results: CandidateWithSpans[] = [];
@@ -907,6 +917,7 @@ async function discoverAndEvaluateSubtitleCandidates(
// 1. Evaluate all mpv subtitle tracks other than target. // 1. Evaluate all mpv subtitle tracks other than target.
for (const track of context.subtitleTracks) { for (const track of context.subtitleTracks) {
options.signal?.throwIfAborted();
if (typeof track.id !== 'number' || track.id === targetTrack.id) continue; if (typeof track.id !== 'number' || track.id === targetTrack.id) continue;
const isSecondary = context.secondaryTrack !== null && track.id === context.secondaryTrack.id; const isSecondary = context.secondaryTrack !== null && track.id === context.secondaryTrack.id;
const isEmbedded = !track.external; const isEmbedded = !track.external;
@@ -942,7 +953,7 @@ async function discoverAndEvaluateSubtitleCandidates(
if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') { if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') {
const preParsed = preExtracted.get(track['ff-index']); const preParsed = preExtracted.get(track['ff-index']);
if (preParsed && preParsed.events.length > 0) { if (preParsed && preParsed.events.length > 0) {
await yieldToEventLoop(); await yieldToEventLoop(options.signal);
results.push(evaluateParsedCandidate(baseMeta, preParsed)); results.push(evaluateParsedCandidate(baseMeta, preParsed));
continue; continue;
} }
@@ -975,7 +986,7 @@ async function discoverAndEvaluateSubtitleCandidates(
context.videoPath, context.videoPath,
track, track,
context.workingDirectory, context.workingDirectory,
options.fetchImpl, options,
); );
const parsed = readAndParseSubtitleFile(extraction.path); const parsed = readAndParseSubtitleFile(extraction.path);
if (isEmbedded && !isRemoteMediaPath(context.videoPath)) { if (isEmbedded && !isRemoteMediaPath(context.videoPath)) {
@@ -997,7 +1008,7 @@ async function discoverAndEvaluateSubtitleCandidates(
); );
} }
} }
await yieldToEventLoop(); await yieldToEventLoop(options.signal);
results.push(evaluateParsedCandidate(baseMeta, parsed)); results.push(evaluateParsedCandidate(baseMeta, parsed));
} catch { } catch {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(evaluateParsedCandidate(baseMeta, null));
@@ -1010,6 +1021,7 @@ async function discoverAndEvaluateSubtitleCandidates(
if (!isRemoteMediaPath(context.videoPath) && fileExists(context.videoPath)) { if (!isRemoteMediaPath(context.videoPath) && fileExists(context.videoPath)) {
const sidecars = discoverSidecarReferenceFiles(context.videoPath, loadedPaths); const sidecars = discoverSidecarReferenceFiles(context.videoPath, loadedPaths);
for (const sidecar of sidecars) { for (const sidecar of sidecars) {
options.signal?.throwIfAborted();
const baseMeta = { const baseMeta = {
key: `file:${sidecar.path}`, key: `file:${sidecar.path}`,
kind: 'sidecar' as const, kind: 'sidecar' as const,
@@ -1027,7 +1039,7 @@ async function discoverAndEvaluateSubtitleCandidates(
}; };
try { try {
const parsed = readAndParseSubtitleFile(sidecar.path); const parsed = readAndParseSubtitleFile(sidecar.path);
await yieldToEventLoop(); await yieldToEventLoop(options.signal);
results.push(evaluateParsedCandidate(baseMeta, parsed)); results.push(evaluateParsedCandidate(baseMeta, parsed));
} catch { } catch {
// Ignore unreadable sidecars. // Ignore unreadable sidecars.
@@ -1161,7 +1173,7 @@ async function runBuiltinSubsync(
context.videoPath, context.videoPath,
targetTrack, targetTrack,
context.workingDirectory, context.workingDirectory,
deps.fetchImpl, deps,
); );
const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const replaceTarget = resolved.replace !== false && !targetExtraction.temporary;
const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget);
@@ -1197,6 +1209,7 @@ async function runBuiltinSubsync(
ffmpegPath, ffmpegPath,
videoPath: context.videoPath, videoPath: context.videoPath,
audioStreamIndex: context.audioStreamIndex, audioStreamIndex: context.audioStreamIndex,
signal: deps.signal,
vadExecutablePath: vadPaths?.vadExecutablePath ?? null, vadExecutablePath: vadPaths?.vadExecutablePath ?? null,
vadModelPath: vadPaths?.vadModelPath ?? null, vadModelPath: vadPaths?.vadModelPath ?? null,
}); });
@@ -1235,7 +1248,7 @@ async function runBuiltinSubsync(
context.videoPath, context.videoPath,
referenceTrack, referenceTrack,
context.workingDirectory, context.workingDirectory,
deps.fetchImpl, deps,
); );
const parsedRef = readAndParseSubtitleFile(refExtraction.path); const parsedRef = readAndParseSubtitleFile(refExtraction.path);
referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans; referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans;
@@ -1258,7 +1271,7 @@ async function runBuiltinSubsync(
}); });
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
} }
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget); writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
@@ -1285,14 +1298,14 @@ async function runManualOffsetSubsync(
context: SubsyncContext, context: SubsyncContext,
resolved: SubsyncResolvedConfig, resolved: SubsyncResolvedConfig,
client: MpvClientLike, client: MpvClientLike,
fetchImpl?: typeof fetch, io: SubsyncIo = {},
): Promise<SubsyncResult> { ): Promise<SubsyncResult> {
const targetExtraction = await extractSubtitleTrackToFile( const targetExtraction = await extractSubtitleTrackToFile(
resolved.ffmpegPath, resolved.ffmpegPath,
context.videoPath, context.videoPath,
targetTrack, targetTrack,
context.workingDirectory, context.workingDirectory,
fetchImpl, io,
); );
const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const replaceTarget = resolved.replace !== false && !targetExtraction.temporary;
const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget);
@@ -1310,7 +1323,7 @@ async function runManualOffsetSubsync(
const moves = new Array<number>(allIndices.length).fill(offsetMs / 1000); const moves = new Array<number>(allIndices.length).fill(offsetMs / 1000);
const rewritten = applyTimingToSubtitleFile(parsedTarget, allIndices, moves, 1.0); const rewritten = applyTimingToSubtitleFile(parsedTarget, allIndices, moves, 1.0);
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
} }
writeRetimedContent(outputPath, rewritten, replaceTarget); writeRetimedContent(outputPath, rewritten, replaceTarget);
if (targetExtraction.temporary) { if (targetExtraction.temporary) {
@@ -1336,14 +1349,14 @@ async function subsyncToReference(
resolved: SubsyncResolvedConfig, resolved: SubsyncResolvedConfig,
client: MpvClientLike, client: MpvClientLike,
slot: SubtitleSlot, slot: SubtitleSlot,
fetchImpl?: typeof fetch, io: SubsyncIo = {},
): Promise<SubsyncResult> { ): Promise<SubsyncResult> {
const targetExtraction = await extractSubtitleTrackToFile( const targetExtraction = await extractSubtitleTrackToFile(
resolved.ffmpegPath, resolved.ffmpegPath,
context.videoPath, context.videoPath,
targetTrack, targetTrack,
context.workingDirectory, context.workingDirectory,
fetchImpl, io,
); );
const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const replaceTarget = resolved.replace !== false && !targetExtraction.temporary;
const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget);
@@ -1362,6 +1375,7 @@ async function subsyncToReference(
referenceFilePath, referenceFilePath,
targetExtraction.path, targetExtraction.path,
stagedOutputPath, stagedOutputPath,
io.signal,
); );
} else { } else {
const ffsubsyncPath = ensureExecutablePath(resolved.ffsubsyncPath, 'ffsubsync'); const ffsubsyncPath = ensureExecutablePath(resolved.ffsubsyncPath, 'ffsubsync');
@@ -1371,6 +1385,7 @@ async function subsyncToReference(
targetExtraction.path, targetExtraction.path,
stagedOutputPath, stagedOutputPath,
context.audioStreamIndex, context.audioStreamIndex,
io.signal,
); );
} }
@@ -1383,7 +1398,7 @@ async function subsyncToReference(
} }
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot))) { if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot))) {
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
} }
installRetimedFile(stagedOutputPath, outputPath, replaceTarget); installRetimedFile(stagedOutputPath, outputPath, replaceTarget);
@@ -1445,9 +1460,30 @@ function maybeWriteCleanedReferenceSrt(
} }
} }
/** Manual (modal) run, cancelled when playback moves to other media. */
export async function runSubsyncManual( export async function runSubsyncManual(
request: SubsyncManualRunRequest, request: SubsyncManualRunRequest,
deps: SubsyncCoreDeps, deps: SubsyncCoreDeps,
): Promise<SubsyncResult> {
try {
return await runWithMediaChangeAbort(deps, async (runDeps) => {
const result = await runSubsyncManualUnguarded(request, runDeps);
// Tools killed by the abort report generic failures; say what actually happened.
return !result.ok && runDeps.signal?.aborted
? { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }
: result;
});
} catch (error) {
if (error instanceof SubsyncCancelledError) {
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
}
throw error;
}
}
async function runSubsyncManualUnguarded(
request: SubsyncManualRunRequest,
deps: SubsyncCoreDeps,
): Promise<SubsyncResult> { ): Promise<SubsyncResult> {
const client = getMpvClientForSubsync(deps); const client = getMpvClientForSubsync(deps);
const context = await gatherSubsyncContext(client); const context = await gatherSubsyncContext(client);
@@ -1489,7 +1525,7 @@ export async function runSubsyncManual(
context, context,
resolved, resolved,
client, client,
deps.fetchImpl, deps,
); );
} }
@@ -1554,7 +1590,7 @@ export async function runSubsyncManual(
resolved, resolved,
client, client,
targetSlot, targetSlot,
deps.fetchImpl, deps,
); );
} finally { } finally {
cleanupTemporaryFile(cleaned); cleanupTemporaryFile(cleaned);
@@ -1577,7 +1613,7 @@ export async function runSubsyncManual(
context.videoPath, context.videoPath,
referenceTrack, referenceTrack,
context.workingDirectory, context.workingDirectory,
deps.fetchImpl, deps,
); );
cleanedRef = maybeWriteCleanedReferenceSrt( cleanedRef = maybeWriteCleanedReferenceSrt(
referenceExtraction.path, referenceExtraction.path,
@@ -1591,7 +1627,7 @@ export async function runSubsyncManual(
resolved, resolved,
client, client,
targetSlot, targetSlot,
deps.fetchImpl, deps,
); );
} finally { } finally {
cleanupTemporaryFile(cleanedRef); cleanupTemporaryFile(cleanedRef);
@@ -1661,6 +1697,7 @@ async function prepareRipCandidatesAndAudio(
ffmpegPath: resolved.ffmpegPath, ffmpegPath: resolved.ffmpegPath,
videoPath: context.videoPath, videoPath: context.videoPath,
audioStreamIndex: context.audioStreamIndex, audioStreamIndex: context.audioStreamIndex,
signal: deps.signal,
durationSec: context.durationSec, durationSec: context.durationSec,
}); });
if (sampled && sampled.length >= 2) { if (sampled && sampled.length >= 2) {
@@ -1675,6 +1712,7 @@ async function prepareRipCandidatesAndAudio(
ffmpegPath: resolved.ffmpegPath, ffmpegPath: resolved.ffmpegPath,
videoPath: context.videoPath, videoPath: context.videoPath,
audioStreamIndex: context.audioStreamIndex, audioStreamIndex: context.audioStreamIndex,
signal: deps.signal,
vadExecutablePath: vadPaths?.vadExecutablePath ?? null, vadExecutablePath: vadPaths?.vadExecutablePath ?? null,
vadModelPath: vadPaths?.vadModelPath ?? null, vadModelPath: vadPaths?.vadModelPath ?? null,
embeddedTracks: embeddedSpecs, embeddedTracks: embeddedSpecs,
@@ -1788,6 +1826,7 @@ export async function openSubsyncManualPicker(
allowSampledAudioFastPath: true, allowSampledAudioFastPath: true,
}, },
); );
deps.signal?.throwIfAborted();
audioSpeechAvailable = audioSpeechAvailable =
prepared.audioSpeech !== null || prepared.audioSpeech !== null ||
prepared.sampledAudioWindows !== null || prepared.sampledAudioWindows !== null ||
@@ -1803,6 +1842,7 @@ export async function openSubsyncManualPicker(
// Never stream a remote video over HTTP or full-read a local MKV during sampled fast-path just to populate the picker. // Never stream a remote video over HTTP or full-read a local MKV during sampled fast-path just to populate the picker.
skipEmbeddedExtraction: isRemote || prepared.sampledAudioWindows !== null, skipEmbeddedExtraction: isRemote || prepared.sampledAudioWindows !== null,
fetchImpl: deps.fetchImpl, fetchImpl: deps.fetchImpl,
signal: deps.signal,
}, },
); );
if ( if (
@@ -1822,6 +1862,66 @@ export async function openSubsyncManualPicker(
return true; return true;
} }
const PLAYBACK_CHANGED_RESULT_MESSAGE = 'Playback changed while syncing; discarded stale result.';
const MEDIA_CHANGE_POLL_MS = 500;
/** Thrown when a run was cancelled because playback moved to other media. */
export class SubsyncCancelledError extends Error {
constructor() {
super(PLAYBACK_CHANGED_RESULT_MESSAGE);
this.name = 'SubsyncCancelledError';
}
}
/**
* Run a subsync task with `deps.signal` aborting once mpv leaves the media the run started on
* (polls `path`; mpv disconnecting also aborts). Aborting kills spawned ffmpeg/VAD/alass and
* stops at the next stage boundary, so switching episodes frees the subsync lock right away.
* A failure caused by the abort surfaces as `SubsyncCancelledError`.
*/
export async function runWithMediaChangeAbort<D extends SubsyncCoreDeps, T>(
deps: D,
task: (deps: D) => Promise<T>,
): Promise<T> {
const client = deps.getMpvClient();
const initialPath = client?.connected
? await client.requestProperty('path').catch(() => null)
: null;
const controller = new AbortController();
let polling = false;
const timer = setInterval(() => {
if (polling || controller.signal.aborted) return;
const current = deps.getMpvClient();
if (!current?.connected) {
controller.abort();
return;
}
polling = true;
current
.requestProperty('path')
.then(
(currentPath) => {
if (currentPath !== initialPath) controller.abort();
},
() => {},
)
.finally(() => {
polling = false;
});
}, MEDIA_CHANGE_POLL_MS);
const signal = deps.signal
? AbortSignal.any([deps.signal, controller.signal])
: controller.signal;
try {
return await task({ ...deps, signal });
} catch (error) {
if (signal.aborted) throw new SubsyncCancelledError();
throw error;
} finally {
clearInterval(timer);
}
}
const STALE_AUTO_RESULT_MESSAGE = 'Subsync: playback changed while syncing; discarded result'; const STALE_AUTO_RESULT_MESSAGE = 'Subsync: playback changed while syncing; discarded result';
async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> { async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
@@ -1845,7 +1945,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
context.videoPath, context.videoPath,
targetTrack, targetTrack,
context.workingDirectory, context.workingDirectory,
deps.fetchImpl, deps,
); );
} catch (extractError) { } catch (extractError) {
if ( if (
@@ -1885,6 +1985,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
const prepared = await prepareRipCandidatesAndAudio(context, targetTrack, resolved, deps, { const prepared = await prepareRipCandidatesAndAudio(context, targetTrack, resolved, deps, {
allowSampledAudioFastPath: true, allowSampledAudioFastPath: true,
}); });
deps.signal?.throwIfAborted();
let audioSpeech = prepared.audioSpeech; let audioSpeech = prepared.audioSpeech;
let evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( let evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates(
context, context,
@@ -1898,6 +1999,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// local sampled-audio fast path (try external/sidecar tracks before full MKV demux). // local sampled-audio fast path (try external/sidecar tracks before full MKV demux).
skipEmbeddedExtraction: isRemote || prepared.sampledAudioWindows !== null, skipEmbeddedExtraction: isRemote || prepared.sampledAudioWindows !== null,
fetchImpl: deps.fetchImpl, fetchImpl: deps.fetchImpl,
signal: deps.signal,
}, },
); );
@@ -1953,7 +2055,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES,
); );
for (const candidate of fastAligned) { for (const candidate of fastAligned) {
await yieldToEventLoop(); await yieldToEventLoop(deps.signal);
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -1973,6 +2075,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
const escalated = await prepareRipCandidatesAndAudio(context, targetTrack, resolved, deps, { const escalated = await prepareRipCandidatesAndAudio(context, targetTrack, resolved, deps, {
allowSampledAudioFastPath: false, allowSampledAudioFastPath: false,
}); });
deps.signal?.throwIfAborted();
audioSpeech = escalated.audioSpeech; audioSpeech = escalated.audioSpeech;
lengthSec = context.durationSec ?? audioSpeech?.durationSec ?? lengthSec; lengthSec = context.durationSec ?? audioSpeech?.durationSec ?? lengthSec;
evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates(
@@ -1985,6 +2088,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
sampledAudioWindows: audioSpeech ? null : prepared.sampledAudioWindows, sampledAudioWindows: audioSpeech ? null : prepared.sampledAudioWindows,
preExtractedEmbedded: escalated.preExtractedEmbedded, preExtractedEmbedded: escalated.preExtractedEmbedded,
fetchImpl: deps.fetchImpl, fetchImpl: deps.fetchImpl,
signal: deps.signal,
}, },
); );
} }
@@ -2013,7 +2117,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// 1. Best path: an audio-verified aligned dialogue subtitle reference (loaded or unloaded!). // 1. Best path: an audio-verified aligned dialogue subtitle reference (loaded or unloaded!).
for (const candidate of alignedCandidates) { for (const candidate of alignedCandidates) {
await yieldToEventLoop(); await yieldToEventLoop(deps.signal);
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -2037,7 +2141,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// 2. Fallback when no subtitle track is audio-aligned (none exist, only signs/songs, or all // 2. Fallback when no subtitle track is audio-aligned (none exist, only signs/songs, or all
// reference subtitles are shifted off the audio): sync directly to video audio speech! // reference subtitles are shifted off the audio): sync directly to video audio speech!
if (audioSpeech && audioSpeech.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) { if (audioSpeech && audioSpeech.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) {
await yieldToEventLoop(); await yieldToEventLoop(deps.signal);
const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, { const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -2064,7 +2168,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// try already-loaded external dialogue tracks first with a stricter confidence bar. // try already-loaded external dialogue tracks first with a stricter confidence bar.
if (!audioSpeech) { if (!audioSpeech) {
for (const candidate of unverifiedDialogueCandidates) { for (const candidate of unverifiedDialogueCandidates) {
await yieldToEventLoop(); await yieldToEventLoop(deps.signal);
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -2103,7 +2207,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true }); const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) return false; if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) return false;
await yieldToEventLoop(); await yieldToEventLoop(deps.signal);
const alignment = alignSubtitleFileToReferenceSpans( const alignment = alignSubtitleFileToReferenceSpans(
parsedTarget, parsedTarget,
extractedSpans.spans, extractedSpans.spans,
@@ -2139,7 +2243,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
context.videoPath, context.videoPath,
item.ffIndex, item.ffIndex,
item.extension, item.extension,
deps.fetchImpl, deps,
); );
if (!bytes) continue; if (!bytes) continue;
const decoded = decodeSubtitleBytesWithStatus(bytes); const decoded = decodeSubtitleBytesWithStatus(bytes);
@@ -2166,6 +2270,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
ffmpegPath: resolved.ffmpegPath, ffmpegPath: resolved.ffmpegPath,
videoPath: context.videoPath, videoPath: context.videoPath,
audioStreamIndex: context.audioStreamIndex, audioStreamIndex: context.audioStreamIndex,
signal: deps.signal,
embeddedTracks: remainingSpecs, embeddedTracks: remainingSpecs,
includeAudio: false, includeAudio: false,
}); });
@@ -2193,7 +2298,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
context.videoPath, context.videoPath,
fallbackItem.track, fallbackItem.track,
context.workingDirectory, context.workingDirectory,
deps.fetchImpl, deps,
); );
parsed = readAndParseSubtitleFile(extraction.path); parsed = readAndParseSubtitleFile(extraction.path);
} catch { } catch {
@@ -2219,6 +2324,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
preExtractedEmbedded: remoteExtracted, preExtractedEmbedded: remoteExtracted,
skipEmbeddedExtraction: true, skipEmbeddedExtraction: true,
fetchImpl: deps.fetchImpl, fetchImpl: deps.fetchImpl,
signal: deps.signal,
}, },
); );
misalignedCandidates = evaluatedCandidates.filter( misalignedCandidates = evaluatedCandidates.filter(
@@ -2243,7 +2349,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
(item) => item.key === candidate.evaluated.key, (item) => item.key === candidate.evaluated.key,
); );
if (matchedItem && triedRemoteEmbedded.has(matchedItem.ffIndex)) continue; if (matchedItem && triedRemoteEmbedded.has(matchedItem.ffIndex)) continue;
await yieldToEventLoop(); await yieldToEventLoop(deps.signal);
const alignment = alignSubtitleFileToReferenceSpans( const alignment = alignSubtitleFileToReferenceSpans(
parsedTarget, parsedTarget,
candidate.dialogueSpans, candidate.dialogueSpans,
@@ -2333,18 +2439,22 @@ export async function triggerSubsyncFromConfig(deps: TriggerSubsyncFromConfigDep
deps.setSubsyncInProgress(true); deps.setSubsyncInProgress(true);
try { try {
const resolved = deps.getResolvedConfig(); await runWithMediaChangeAbort(deps, async (runDeps) => {
if (resolved.mode === 'manual') { if (runDeps.getResolvedConfig().mode === 'manual') {
const opened = await openSubsyncManualPicker(deps, { skipAudioAnalysis: true }); const opened = await openSubsyncManualPicker(runDeps, { skipAudioAnalysis: true });
if (opened) { if (opened) {
deps.showMpvOsd('Subsync: choose engine and subtitles'); runDeps.showMpvOsd('Subsync: choose engine and subtitles');
} }
return; return;
} }
await runDeps.runWithSubsyncSpinner(() => runAutoSubsync(runDeps));
await deps.runWithSubsyncSpinner(() => runAutoSubsync(deps)); });
} catch (error) { } catch (error) {
deps.showMpvOsd(`Subsync failed: ${(error as Error).message}`); deps.showMpvOsd(
error instanceof SubsyncCancelledError
? STALE_AUTO_RESULT_MESSAGE
: `Subsync failed: ${(error as Error).message}`,
);
} finally { } finally {
deps.setSubsyncInProgress(false); deps.setSubsyncInProgress(false);
} }
+13 -5
View File
@@ -13,6 +13,7 @@ import {
canFfmpegExtractSubtitleExtension, canFfmpegExtractSubtitleExtension,
extensionToFfmpegMuxer, extensionToFfmpegMuxer,
fileExists, fileExists,
killProcessTree,
resolveCommandInvocation, resolveCommandInvocation,
runCommand, runCommand,
} from './utils'; } from './utils';
@@ -373,7 +374,7 @@ function streamFfmpegPcm(
}; };
const onAbort = (): void => { const onAbort = (): void => {
child.kill('SIGKILL'); killProcessTree(child);
finishError(new Error('Audio extraction aborted')); finishError(new Error('Audio extraction aborted'));
}; };
@@ -384,7 +385,7 @@ function streamFfmpegPcm(
signal?.addEventListener('abort', onAbort, { once: true }); signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(() => { const timer = setTimeout(() => {
child.kill('SIGKILL'); killProcessTree(child);
finishError(new Error('Timed out while reading video audio with ffmpeg')); finishError(new Error('Timed out while reading video audio with ffmpeg'));
}, AUDIO_EXTRACT_TIMEOUT_MS); }, AUDIO_EXTRACT_TIMEOUT_MS);
@@ -447,7 +448,12 @@ async function trySileroVadSpeech(
} }
ffmpegArgs.push('-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', wavPath); ffmpegArgs.push('-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', wavPath);
const wavRes = await runCommand(options.ffmpegPath, ffmpegArgs, AUDIO_EXTRACT_TIMEOUT_MS); const wavRes = await runCommand(
options.ffmpegPath,
ffmpegArgs,
AUDIO_EXTRACT_TIMEOUT_MS,
options.signal,
);
if (!wavRes.ok || !fileExists(wavPath)) return null; if (!wavRes.ok || !fileExists(wavPath)) return null;
const wavStats = fs.statSync(wavPath); const wavStats = fs.statSync(wavPath);
@@ -471,6 +477,7 @@ async function trySileroVadSpeech(
'-np', '-np',
], ],
AUDIO_EXTRACT_TIMEOUT_MS, AUDIO_EXTRACT_TIMEOUT_MS,
options.signal,
); );
if (!vadRes.ok) return null; if (!vadRes.ok) return null;
@@ -559,7 +566,7 @@ function spawnFfmpegWithStdout(
}; };
const onAbort = (): void => { const onAbort = (): void => {
child.kill('SIGKILL'); killProcessTree(child);
finishError(new Error('ffmpeg operation aborted')); finishError(new Error('ffmpeg operation aborted'));
}; };
@@ -570,7 +577,7 @@ function spawnFfmpegWithStdout(
signal?.addEventListener('abort', onAbort, { once: true }); signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(() => { const timer = setTimeout(() => {
child.kill('SIGKILL'); killProcessTree(child);
finishError(new Error('ffmpeg operation timed out')); finishError(new Error('ffmpeg operation timed out'));
}, timeoutMs); }, timeoutMs);
@@ -851,6 +858,7 @@ export async function extractSinglePassRipMedia(
'-np', '-np',
], ],
AUDIO_EXTRACT_TIMEOUT_MS, AUDIO_EXTRACT_TIMEOUT_MS,
options.signal,
); );
if (vadRes.ok) { if (vadRes.ok) {
const spans = parseRawSileroVadSegments(`${vadRes.stdout}\n${vadRes.stderr}`); const spans = parseRawSileroVadSegments(`${vadRes.stdout}\n${vadRes.stderr}`);
+29 -18
View File
@@ -313,11 +313,30 @@ export function buildJellyfinEmbeddedSubtitleUrl(
return subtitleUrl.toString(); return subtitleUrl.toString();
} }
/** Kill a spawned tool. On Windows a `.cmd`/`.bat` shim is cmd.exe, so the whole tree must go. */
export function killProcessTree(child: childProcess.ChildProcess): void {
if (process.platform === 'win32' && child.pid !== undefined) {
childProcess
.spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
stdio: 'ignore',
windowsHide: true,
})
.on('error', () => child.kill());
return;
}
child.kill('SIGKILL');
}
/** 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,
args: string[], args: string[],
timeoutMs = 120000, timeoutMs = 120000,
signal?: AbortSignal,
): Promise<CommandResult> { ): Promise<CommandResult> {
if (signal?.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 invocation = resolveCommandInvocation(executable, args);
const child = childProcess.spawn(invocation.command, invocation.args, { const child = childProcess.spawn(invocation.command, invocation.args, {
@@ -326,9 +345,14 @@ export function runCommand(
}); });
let stdout = ''; let stdout = '';
let stderr = ''; let stderr = '';
const timeout = setTimeout(() => { const onAbort = (): void => killProcessTree(child);
child.kill('SIGKILL'); const timeout = setTimeout(onAbort, timeoutMs);
}, timeoutMs); signal?.addEventListener('abort', onAbort, { once: true });
const settle = (result: CommandResult): void => {
clearTimeout(timeout);
signal?.removeEventListener('abort', onAbort);
resolve(signal?.aborted ? { ...result, ok: false, error: 'aborted' } : result);
};
child.stdout.on('data', (chunk: Buffer) => { child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString(); stdout += chunk.toString();
@@ -337,23 +361,10 @@ export function runCommand(
stderr += chunk.toString(); stderr += chunk.toString();
}); });
child.on('error', (error: Error) => { child.on('error', (error: Error) => {
clearTimeout(timeout); settle({ ok: false, code: null, stderr, stdout, error: error.message });
resolve({
ok: false,
code: null,
stderr,
stdout,
error: error.message,
});
}); });
child.on('close', (code: number | null) => { child.on('close', (code: number | null) => {
clearTimeout(timeout); settle({ ok: code === 0, code, stderr, stdout });
resolve({
ok: code === 0,
code,
stderr,
stdout,
});
}); });
}); });
} }