perf(subsync): run alignment in a worker thread

Alignment and candidate scoring take up to ~1s per call on long media and an
auto run makes several, which stalled mpv IPC and the overlay on the main
process. They now run in a reusable worker (src/subsync/align-worker.ts) that
idles out after 30s and falls back to the main thread if it cannot start.
Aborting a run terminates the worker, so cancellation no longer waits for an
in-flight alignment.
This commit is contained in:
sudacode committed 2026-11-28 03:30:32 -08:00
1 parent 241aab087f
commit 935cc1a20f
8 files changed
+379 -75

No files matched your search

+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. 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/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. The service is split into `subsync.ts` (entry points) over `subsync-context`, `subsync-files`, `subsync-candidates`, `subsync-manual`, `subsync-auto`, and `subsync-shared`. Alignment and candidate scoring run in a reusable worker thread (`src/subsync/align-worker.ts`, falling back to the main thread if the worker cannot start), so long movies do not stall mpv IPC or the overlay. 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 terminates the align worker, 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.
+55 -39
View File
@@ -1,6 +1,6 @@
import { redactUrlCredentials } from './subtitle-generation-process'; import { redactUrlCredentials } from './subtitle-generation-process';
import { buildJellyfinEmbeddedSubtitleUrl } from '../../subsync/utils'; import { buildJellyfinEmbeddedSubtitleUrl } from '../../subsync/utils';
import { alignSubtitleFileToReferenceSpans, type AlignmentResult } from '../../subsync/alass-align'; import type { AlignmentResult } from '../../subsync/alass-align';
import { extractSinglePassRipMedia, getMediaFileSignature } from '../../subsync/audio-speech'; import { extractSinglePassRipMedia, getMediaFileSignature } from '../../subsync/audio-speech';
import { import {
decodeSubtitleBytesWithStatus, decodeSubtitleBytesWithStatus,
@@ -45,8 +45,8 @@ import {
getMpvClientForSubsync, getMpvClientForSubsync,
isAlreadyInSync, isAlreadyInSync,
isExecutableAvailable, isExecutableAvailable,
yieldToEventLoop,
} from './subsync-shared'; } from './subsync-shared';
import { alignSubtitleOffThread } from '../../subsync/align-worker';
export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> { export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
const client = getMpvClientForSubsync(deps); const client = getMpvClientForSubsync(deps);
@@ -179,14 +179,18 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
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(deps.signal); const alignment = await alignSubtitleOffThread(
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { deps.signal,
stripSigns: true, parsedTarget,
allowSplits: true, candidate.dialogueSpans,
calibration: 'clean', {
lengthSec, stripSigns: true,
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD, allowSplits: true,
}); calibration: 'clean',
lengthSec,
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD,
},
);
if (alignment.confident) { if (alignment.confident) {
await applyAlignment(alignment, candidate.evaluated.label); await applyAlignment(alignment, candidate.evaluated.label);
return; return;
@@ -241,14 +245,18 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
// 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(deps.signal); const alignment = await alignSubtitleOffThread(
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { deps.signal,
stripSigns: true, parsedTarget,
allowSplits: true, candidate.dialogueSpans,
calibration: 'clean', {
lengthSec, stripSigns: true,
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD, allowSplits: true,
}); calibration: 'clean',
lengthSec,
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD,
},
);
if (alignment.confident) { if (alignment.confident) {
await applyAlignment(alignment, candidate.evaluated.label); await applyAlignment(alignment, candidate.evaluated.label);
return; return;
@@ -265,15 +273,19 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
// 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(deps.signal); const audioAlignment = await alignSubtitleOffThread(
const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, { deps.signal,
stripSigns: true, parsedTarget,
allowSplits: true, audioSpeech.spans,
calibration: audioSpeech.calibration, {
leadSec: AUDIO_SPEECH_LEAD_SEC, stripSigns: true,
lengthSec, allowSplits: true,
confidenceThreshold: AUTO_AUDIO_CONFIDENCE_THRESHOLD, calibration: audioSpeech.calibration,
}); leadSec: AUDIO_SPEECH_LEAD_SEC,
lengthSec,
confidenceThreshold: AUTO_AUDIO_CONFIDENCE_THRESHOLD,
},
);
const audioLabel = audioSpeech.source === 'silero-vad' ? 'audio (Silero VAD)' : 'video audio'; const audioLabel = audioSpeech.source === 'silero-vad' ? 'audio (Silero VAD)' : 'video audio';
if (audioAlignment.confident) { if (audioAlignment.confident) {
await applyAlignment(audioAlignment, audioLabel); await applyAlignment(audioAlignment, audioLabel);
@@ -292,14 +304,18 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
// 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(deps.signal); const alignment = await alignSubtitleOffThread(
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { deps.signal,
stripSigns: true, parsedTarget,
allowSplits: true, candidate.dialogueSpans,
calibration: 'clean', {
lengthSec, stripSigns: true,
confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD, allowSplits: true,
}); calibration: 'clean',
lengthSec,
confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD,
},
);
if (alignment.confident) { if (alignment.confident) {
await applyAlignment(alignment, candidate.evaluated.label); await applyAlignment(alignment, candidate.evaluated.label);
return; return;
@@ -331,8 +347,8 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
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(deps.signal); const alignment = await alignSubtitleOffThread(
const alignment = alignSubtitleFileToReferenceSpans( deps.signal,
parsedTarget, parsedTarget,
extractedSpans.spans, extractedSpans.spans,
{ {
@@ -473,8 +489,8 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
(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(deps.signal); const alignment = await alignSubtitleOffThread(
const alignment = alignSubtitleFileToReferenceSpans( deps.signal,
parsedTarget, parsedTarget,
candidate.dialogueSpans, candidate.dialogueSpans,
{ {
+27 -25
View File
@@ -8,11 +8,7 @@ import {
SubsyncContext, SubsyncContext,
SubsyncResolvedConfig, SubsyncResolvedConfig,
} from '../../subsync/utils'; } from '../../subsync/utils';
import { import { type SampledAudioWindow } from '../../subsync/alass-align';
evaluateReferenceAlignmentToAudio,
evaluateReferenceAlignmentToSampledAudio,
type SampledAudioWindow,
} from '../../subsync/alass-align';
import { import {
cacheEmbeddedSubtitleTrack, cacheEmbeddedSubtitleTrack,
extractAudioSpeechSpans, extractAudioSpeechSpans,
@@ -52,8 +48,11 @@ import {
MIN_REFERENCE_DIALOGUE_LINES, MIN_REFERENCE_DIALOGUE_LINES,
type SubsyncCoreDeps, type SubsyncCoreDeps,
isExecutableAvailable, isExecutableAvailable,
yieldToEventLoop,
} from './subsync-shared'; } from './subsync-shared';
import {
evaluateToAudioOffThread,
evaluateToSampledAudioOffThread,
} from '../../subsync/align-worker';
async function resolveAudioSpeechForContext( async function resolveAudioSpeechForContext(
context: SubsyncContext, context: SubsyncContext,
@@ -139,13 +138,13 @@ export async function discoverAndEvaluateSubtitleCandidates(
} }
} }
const evaluateParsedCandidate = ( const evaluateParsedCandidate = async (
meta: Omit< meta: Omit<
EvaluatedSubtitleReference, EvaluatedSubtitleReference,
'dialogueCount' | 'signCount' | 'audioStatus' | 'audioOffsetMs' | 'audioConfidence' 'dialogueCount' | 'signCount' | 'audioStatus' | 'audioOffsetMs' | 'audioConfidence'
>, >,
parsed: ParsedSubtitleFile | null, parsed: ParsedSubtitleFile | null,
): CandidateWithSpans => { ): Promise<CandidateWithSpans> => {
const stripped = parsed const stripped = parsed
? extractSpansFromParsedSubtitle(parsed, { stripSigns: true }) ? extractSpansFromParsedSubtitle(parsed, { stripSigns: true })
: { spans: [], dialogueCount: 0, signCount: 0 }; : { spans: [], dialogueCount: 0, signCount: 0 };
@@ -163,16 +162,22 @@ export async function discoverAndEvaluateSubtitleCandidates(
if (!effectiveSignsOnly && stripped.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) { if (!effectiveSignsOnly && stripped.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) {
if (audioSpeech && audioSpeech.spans.length > 0) { if (audioSpeech && audioSpeech.spans.length > 0) {
const audioEval = evaluateReferenceAlignmentToAudio(stripped.spans, audioSpeech.spans, { const audioEval = await evaluateToAudioOffThread(
lengthSec: context.durationSec ?? audioSpeech.durationSec, options.signal,
audioCalibration: audioSpeech.calibration, stripped.spans,
audioLeadSec: AUDIO_SPEECH_LEAD_SEC, audioSpeech.spans,
}); {
lengthSec: context.durationSec ?? audioSpeech.durationSec,
audioCalibration: audioSpeech.calibration,
audioLeadSec: AUDIO_SPEECH_LEAD_SEC,
},
);
audioStatus = audioEval.status; audioStatus = audioEval.status;
audioOffsetMs = audioEval.offsetMs; audioOffsetMs = audioEval.offsetMs;
audioConfidence = audioEval.confidence; audioConfidence = audioEval.confidence;
} else if (sampledWindows && sampledWindows.length >= 2) { } else if (sampledWindows && sampledWindows.length >= 2) {
const sampleEval = evaluateReferenceAlignmentToSampledAudio( const sampleEval = await evaluateToSampledAudioOffThread(
options.signal,
stripped.spans, stripped.spans,
sampledWindows, sampledWindows,
{ audioLeadSec: AUDIO_SPEECH_LEAD_SEC }, { audioLeadSec: AUDIO_SPEECH_LEAD_SEC },
@@ -229,21 +234,20 @@ export async function discoverAndEvaluateSubtitleCandidates(
}; };
if (isEmbedded && skipSignsEmbedded && isSignsTrack) { if (isEmbedded && skipSignsEmbedded && isSignsTrack) {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(await evaluateParsedCandidate(baseMeta, null));
continue; continue;
} }
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(options.signal); results.push(await evaluateParsedCandidate(baseMeta, preParsed));
results.push(evaluateParsedCandidate(baseMeta, preParsed));
continue; continue;
} }
} }
if (isEmbedded && skipEmbeddedExtraction) { if (isEmbedded && skipEmbeddedExtraction) {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(await evaluateParsedCandidate(baseMeta, null));
continue; continue;
} }
@@ -257,7 +261,7 @@ export async function discoverAndEvaluateSubtitleCandidates(
(!isRemoteMediaPath(context.videoPath) && (!isRemoteMediaPath(context.videoPath) &&
!canFfmpegExtractSubtitleExtension(embeddedExtension))) !canFfmpegExtractSubtitleExtension(embeddedExtension)))
) { ) {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(await evaluateParsedCandidate(baseMeta, null));
continue; continue;
} }
const preExtractSignature = const preExtractSignature =
@@ -275,7 +279,7 @@ export async function discoverAndEvaluateSubtitleCandidates(
if (isEmbedded && !isRemoteMediaPath(context.videoPath)) { if (isEmbedded && !isRemoteMediaPath(context.videoPath)) {
const postExtractSignature = getMediaFileSignature(context.videoPath); const postExtractSignature = getMediaFileSignature(context.videoPath);
if (postExtractSignature !== preExtractSignature) { if (postExtractSignature !== preExtractSignature) {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(await evaluateParsedCandidate(baseMeta, null));
continue; continue;
} }
if ( if (
@@ -291,10 +295,9 @@ export async function discoverAndEvaluateSubtitleCandidates(
); );
} }
} }
await yieldToEventLoop(options.signal); results.push(await evaluateParsedCandidate(baseMeta, parsed));
results.push(evaluateParsedCandidate(baseMeta, parsed));
} catch { } catch {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(await evaluateParsedCandidate(baseMeta, null));
} finally { } finally {
cleanupTemporaryFile(extraction); cleanupTemporaryFile(extraction);
} }
@@ -322,8 +325,7 @@ export async function discoverAndEvaluateSubtitleCandidates(
}; };
try { try {
const parsed = readAndParseSubtitleFile(sidecar.path); const parsed = readAndParseSubtitleFile(sidecar.path);
await yieldToEventLoop(options.signal); results.push(await evaluateParsedCandidate(baseMeta, parsed));
results.push(evaluateParsedCandidate(baseMeta, parsed));
} catch { } catch {
// Ignore unreadable sidecars. // Ignore unreadable sidecars.
} }
+2 -2
View File
@@ -8,7 +8,6 @@ import {
SubsyncContext, SubsyncContext,
SubsyncResolvedConfig, SubsyncResolvedConfig,
} from '../../subsync/utils'; } from '../../subsync/utils';
import { alignSubtitleFileToReferenceSpans } from '../../subsync/alass-align';
import { extractAudioSpeechSpans, getMediaFileSignature } from '../../subsync/audio-speech'; import { extractAudioSpeechSpans, getMediaFileSignature } from '../../subsync/audio-speech';
import { buildTrackReferenceLabel } from '../../subsync/reference-discovery'; import { buildTrackReferenceLabel } from '../../subsync/reference-discovery';
import { import {
@@ -63,6 +62,7 @@ import {
isExecutableAvailable, isExecutableAvailable,
summarizeCommandFailure, summarizeCommandFailure,
} from './subsync-shared'; } from './subsync-shared';
import { alignSubtitleOffThread } from '../../subsync/align-worker';
async function runBuiltinSubsync( async function runBuiltinSubsync(
request: SubsyncManualRunRequest, request: SubsyncManualRunRequest,
@@ -170,7 +170,7 @@ async function runBuiltinSubsync(
return { ok: false, message: 'Selected reference has no usable dialogue timestamps.' }; return { ok: false, message: 'Selected reference has no usable dialogue timestamps.' };
} }
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, referenceSpans, { const alignment = await alignSubtitleOffThread(deps.signal, parsedTarget, referenceSpans, {
stripSigns, stripSigns,
allowSplits, allowSplits,
calibration, calibration,
-8
View File
@@ -38,14 +38,6 @@ export const JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS = 15_000;
const COMMAND_OUTPUT_SUMMARY_CHARS = 300; const COMMAND_OUTPUT_SUMMARY_CHARS = 300;
// 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.
// Also the cancellation point between those stages.
export 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
// stream tokens: ffmpeg echoes input URLs, and Jellyfin URLs carry ApiKey. // stream tokens: ffmpeg echoes input URLs, and Jellyfin URLs carry ApiKey.
function summarizeCommandOutput(text: string): string { function summarizeCommandOutput(text: string): string {
+24
View File
@@ -0,0 +1,24 @@
import { parentPort } from 'node:worker_threads';
import { runAlignTask, type AlignWorkerRequest, type AlignWorkerResponse } from './align-worker';
// Worker entry for align-worker.ts: runs one alignment task per message.
if (!parentPort) {
throw new Error('subsync align worker missing parent port');
}
const port = parentPort;
port.on('message', (message: AlignWorkerRequest) => {
let response: AlignWorkerResponse;
try {
const result = runAlignTask(message.kind, message.args);
response = { id: message.id, ok: true, result };
} catch (error) {
response = {
id: message.id,
ok: false,
error: error instanceof Error ? error.message : String(error),
};
}
port.postMessage(response);
});
+70
View File
@@ -0,0 +1,70 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { alignSubtitleFileToReferenceSpans } from './alass-align';
import { alignSubtitleOffThread } from './align-worker';
import {
formatSrtTimestamp,
parseSubtitleFileContent,
type SubtitleTimeSpan,
} from './subtitle-lines';
// Deterministic dialogue-like spans (same LCG as alass-align.test.ts).
function rhythm(untilSec: number): SubtitleTimeSpan[] {
const out: SubtitleTimeSpan[] = [];
let seed = 7n;
const mask = (1n << 64n) - 1n;
let t = 5;
while (t < untilSec) {
seed = (seed * 6364136223846793005n + 1442695040888963407n) & mask;
const len = 0.8 + (Number(seed >> 33n) / Number(1n << 31n)) * 3;
const gap = 0.4 + (Number((seed >> 13n) & 0xffffn) / 65536) * 4;
out.push({ start: t, end: t + len });
t += len + gap;
}
return out;
}
function srtShiftedBy(spans: readonly SubtitleTimeSpan[], shiftSec: number): string {
return spans
.map(
(s, i) =>
`${i + 1}\n${formatSrtTimestamp(s.start + shiftSec)} --> ${formatSrtTimestamp(s.end + shiftSec)}\nline ${i + 1}\n`,
)
.join('\n');
}
test('alignSubtitleOffThread returns the same alignment as the in-thread aligner', async () => {
const reference = rhythm(1300);
const target = parseSubtitleFileContent(srtShiftedBy(reference, 2.5), 'target.srt');
const offThread = await alignSubtitleOffThread(undefined, target, reference, {});
assert.deepEqual(offThread, alignSubtitleFileToReferenceSpans(target, reference, {}));
assert.equal(offThread.offsetMs, -2500);
});
test('aborting alignSubtitleOffThread stops a long alignment without waiting for it', async () => {
// A 2.5 h film takes most of a second to align; an abort can only win if it runs off-thread.
const reference = rhythm(9000);
const target = parseSubtitleFileContent(srtShiftedBy(reference, 4), 'movie.srt');
const startedAt = Date.now();
const inThreadMs = (() => {
alignSubtitleFileToReferenceSpans(target, reference, {});
return Date.now() - startedAt;
})();
const controller = new AbortController();
const abortedAt = Date.now();
setTimeout(() => controller.abort(new Error('media changed')), 20);
await assert.rejects(
alignSubtitleOffThread(controller.signal, target, reference, {}),
/media changed/,
);
assert.ok(
Date.now() - abortedAt < inThreadMs,
`abort took ${Date.now() - abortedAt}ms, in-thread alignment takes ${inThreadMs}ms`,
);
// The next call starts a fresh worker.
const after = await alignSubtitleOffThread(undefined, target, reference, {});
assert.equal(after.offsetMs, -4000);
});
+200
View File
@@ -0,0 +1,200 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Worker } from 'node:worker_threads';
import { createLogger } from '../logger';
import {
alignSubtitleFileToReferenceSpans,
evaluateReferenceAlignmentToAudio,
evaluateReferenceAlignmentToSampledAudio,
} from './alass-align';
/**
* Off-main-thread alignment. The alass-style aligner is pure CPU work (up to ~1s per call on
* a long movie, several calls per auto run), so subsync runs it in a reusable worker thread to
* keep mpv IPC and the overlay responsive. Aborting a call terminates the worker (stopping the
* computation mid-way); the next call starts a fresh one. If the worker cannot start, calls run
* on the current thread instead.
*/
type AlignTasks = {
alignSubtitle: typeof alignSubtitleFileToReferenceSpans;
evaluateToAudio: typeof evaluateReferenceAlignmentToAudio;
evaluateToSampledAudio: typeof evaluateReferenceAlignmentToSampledAudio;
};
export type AlignTaskKind = keyof AlignTasks;
type AlignTaskArgs<K extends AlignTaskKind> = Parameters<AlignTasks[K]>;
type AlignTaskResult<K extends AlignTaskKind> = ReturnType<AlignTasks[K]>;
export interface AlignWorkerRequest {
id: number;
kind: AlignTaskKind;
args: unknown[];
}
export type AlignWorkerResponse =
| { id: number; ok: true; result: unknown }
| { id: number; ok: false; error: string };
/**
* Run one alignment task synchronously. Untyped because it sits on the worker message
* boundary (shared by the worker thread and the fallback path); the exported `*OffThread`
* wrappers keep callers type-checked.
*/
export function runAlignTask(kind: AlignTaskKind, args: unknown[]): unknown {
switch (kind) {
case 'alignSubtitle':
return alignSubtitleFileToReferenceSpans(...(args as AlignTaskArgs<'alignSubtitle'>));
case 'evaluateToAudio':
return evaluateReferenceAlignmentToAudio(...(args as AlignTaskArgs<'evaluateToAudio'>));
case 'evaluateToSampledAudio':
return evaluateReferenceAlignmentToSampledAudio(
...(args as AlignTaskArgs<'evaluateToSampledAudio'>),
);
}
}
const logger = createLogger('main:subsync:align-worker');
const DISABLE_WORKER_ENV = 'SUBMINER_DISABLE_SUBSYNC_ALIGN_WORKER';
const IDLE_TERMINATE_MS = 30_000;
function resolveAlignWorkerPath(): string | null {
const fileName = __filename.endsWith('.ts') ? 'align-worker-thread.ts' : 'align-worker-thread.js';
const workerPath = path.join(__dirname, fileName);
return fs.existsSync(workerPath) ? workerPath : null;
}
type Pending = { resolve: (value: unknown) => void; reject: (reason: Error) => void };
class AlignWorkerRuntime {
private worker: Worker | null = null;
private workerUnavailable = false;
private nextId = 1;
private readonly pending = new Map<number, Pending>();
private idleTimer: ReturnType<typeof setTimeout> | null = null;
async run<K extends AlignTaskKind>(
kind: K,
args: AlignTaskArgs<K>,
signal?: AbortSignal,
): Promise<AlignTaskResult<K>> {
signal?.throwIfAborted();
const worker = await this.getWorker();
if (!worker) return runAlignTask(kind, args) as AlignTaskResult<K>;
const id = this.nextId++;
this.clearIdleTimer();
const result = new Promise<unknown>((resolve, reject) => {
this.pending.set(id, { resolve, reject });
});
const onAbort = (): void => this.reset(signal?.reason ?? new Error('aborted'));
signal?.addEventListener('abort', onAbort, { once: true });
const request: AlignWorkerRequest = { id, kind, args };
worker.postMessage(request);
try {
return (await result) as AlignTaskResult<K>;
} finally {
signal?.removeEventListener('abort', onAbort);
if (this.pending.size === 0) this.scheduleIdleTerminate();
}
}
private async getWorker(): Promise<Worker | null> {
if (this.worker) return this.worker;
if (this.workerUnavailable || process.env[DISABLE_WORKER_ENV] === '1') return null;
const workerPath = resolveAlignWorkerPath();
if (!workerPath) {
this.markUnavailable(new Error('align worker module not found'));
return null;
}
try {
const { Worker: WorkerCtor } = await import('node:worker_threads');
const worker = new WorkerCtor(workerPath);
worker.unref();
worker.on('message', (message: AlignWorkerResponse) => this.handleMessage(message));
worker.on('error', (error: Error) => {
this.markUnavailable(error);
this.reset(error);
});
worker.on('exit', (code) => {
if (this.worker !== worker) return;
this.worker = null;
if (this.pending.size > 0) {
this.reset(new Error(`subsync align worker exited with code ${code}`));
}
});
this.worker = worker;
return worker;
} catch (error) {
this.markUnavailable(error as Error);
return null;
}
}
private handleMessage(message: AlignWorkerResponse): void {
const pending = this.pending.get(message.id);
if (!pending) return;
this.pending.delete(message.id);
if (message.ok) pending.resolve(message.result);
else pending.reject(new Error(message.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));
const worker = this.worker;
this.worker = null;
this.clearIdleTimer();
if (worker) void worker.terminate().catch(() => undefined);
for (const pending of this.pending.values()) pending.reject(error);
this.pending.clear();
}
private markUnavailable(error: Error): void {
if (!this.workerUnavailable) {
logger.warn(
`Subsync align worker unavailable, aligning on the main thread: ${error.message}`,
);
}
this.workerUnavailable = true;
}
private scheduleIdleTerminate(): void {
this.clearIdleTimer();
this.idleTimer = setTimeout(() => {
if (this.pending.size === 0) this.reset(new Error('idle'));
}, IDLE_TERMINATE_MS);
this.idleTimer.unref?.();
}
private clearIdleTimer(): void {
if (this.idleTimer) clearTimeout(this.idleTimer);
this.idleTimer = null;
}
}
const runtime = new AlignWorkerRuntime();
/** `alignSubtitleFileToReferenceSpans` off the main thread; rejects promptly when `signal` aborts. */
export function alignSubtitleOffThread(
signal: AbortSignal | undefined,
...args: AlignTaskArgs<'alignSubtitle'>
): Promise<AlignTaskResult<'alignSubtitle'>> {
return runtime.run('alignSubtitle', args, signal);
}
/** `evaluateReferenceAlignmentToAudio` off the main thread. */
export function evaluateToAudioOffThread(
signal: AbortSignal | undefined,
...args: AlignTaskArgs<'evaluateToAudio'>
): Promise<AlignTaskResult<'evaluateToAudio'>> {
return runtime.run('evaluateToAudio', args, signal);
}
/** `evaluateReferenceAlignmentToSampledAudio` off the main thread. */
export function evaluateToSampledAudioOffThread(
signal: AbortSignal | undefined,
...args: AlignTaskArgs<'evaluateToSampledAudio'>
): Promise<AlignTaskResult<'evaluateToSampledAudio'>> {
return runtime.run('evaluateToSampledAudio', args, signal);
}