mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
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:
8 files changed
+379
-75
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import { redactUrlCredentials } from './subtitle-generation-process';
|
||||
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 {
|
||||
decodeSubtitleBytesWithStatus,
|
||||
@@ -45,8 +45,8 @@ import {
|
||||
getMpvClientForSubsync,
|
||||
isAlreadyInSync,
|
||||
isExecutableAvailable,
|
||||
yieldToEventLoop,
|
||||
} from './subsync-shared';
|
||||
import { alignSubtitleOffThread } from '../../subsync/align-worker';
|
||||
|
||||
export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
|
||||
const client = getMpvClientForSubsync(deps);
|
||||
@@ -179,14 +179,18 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES,
|
||||
);
|
||||
for (const candidate of fastAligned) {
|
||||
await yieldToEventLoop(deps.signal);
|
||||
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: 'clean',
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD,
|
||||
});
|
||||
const alignment = await alignSubtitleOffThread(
|
||||
deps.signal,
|
||||
parsedTarget,
|
||||
candidate.dialogueSpans,
|
||||
{
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: 'clean',
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD,
|
||||
},
|
||||
);
|
||||
if (alignment.confident) {
|
||||
await applyAlignment(alignment, candidate.evaluated.label);
|
||||
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!).
|
||||
for (const candidate of alignedCandidates) {
|
||||
await yieldToEventLoop(deps.signal);
|
||||
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: 'clean',
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD,
|
||||
});
|
||||
const alignment = await alignSubtitleOffThread(
|
||||
deps.signal,
|
||||
parsedTarget,
|
||||
candidate.dialogueSpans,
|
||||
{
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: 'clean',
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD,
|
||||
},
|
||||
);
|
||||
if (alignment.confident) {
|
||||
await applyAlignment(alignment, candidate.evaluated.label);
|
||||
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
|
||||
// reference subtitles are shifted off the audio): sync directly to video audio speech!
|
||||
if (audioSpeech && audioSpeech.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) {
|
||||
await yieldToEventLoop(deps.signal);
|
||||
const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, {
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: audioSpeech.calibration,
|
||||
leadSec: AUDIO_SPEECH_LEAD_SEC,
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_AUDIO_CONFIDENCE_THRESHOLD,
|
||||
});
|
||||
const audioAlignment = await alignSubtitleOffThread(
|
||||
deps.signal,
|
||||
parsedTarget,
|
||||
audioSpeech.spans,
|
||||
{
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
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';
|
||||
if (audioAlignment.confident) {
|
||||
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.
|
||||
if (!audioSpeech) {
|
||||
for (const candidate of unverifiedDialogueCandidates) {
|
||||
await yieldToEventLoop(deps.signal);
|
||||
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: 'clean',
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD,
|
||||
});
|
||||
const alignment = await alignSubtitleOffThread(
|
||||
deps.signal,
|
||||
parsedTarget,
|
||||
candidate.dialogueSpans,
|
||||
{
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
calibration: 'clean',
|
||||
lengthSec,
|
||||
confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD,
|
||||
},
|
||||
);
|
||||
if (alignment.confident) {
|
||||
await applyAlignment(alignment, candidate.evaluated.label);
|
||||
return;
|
||||
@@ -331,8 +347,8 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
|
||||
const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
|
||||
if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) return false;
|
||||
await yieldToEventLoop(deps.signal);
|
||||
const alignment = alignSubtitleFileToReferenceSpans(
|
||||
const alignment = await alignSubtitleOffThread(
|
||||
deps.signal,
|
||||
parsedTarget,
|
||||
extractedSpans.spans,
|
||||
{
|
||||
@@ -473,8 +489,8 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
(item) => item.key === candidate.evaluated.key,
|
||||
);
|
||||
if (matchedItem && triedRemoteEmbedded.has(matchedItem.ffIndex)) continue;
|
||||
await yieldToEventLoop(deps.signal);
|
||||
const alignment = alignSubtitleFileToReferenceSpans(
|
||||
const alignment = await alignSubtitleOffThread(
|
||||
deps.signal,
|
||||
parsedTarget,
|
||||
candidate.dialogueSpans,
|
||||
{
|
||||
|
||||
@@ -8,11 +8,7 @@ import {
|
||||
SubsyncContext,
|
||||
SubsyncResolvedConfig,
|
||||
} from '../../subsync/utils';
|
||||
import {
|
||||
evaluateReferenceAlignmentToAudio,
|
||||
evaluateReferenceAlignmentToSampledAudio,
|
||||
type SampledAudioWindow,
|
||||
} from '../../subsync/alass-align';
|
||||
import { type SampledAudioWindow } from '../../subsync/alass-align';
|
||||
import {
|
||||
cacheEmbeddedSubtitleTrack,
|
||||
extractAudioSpeechSpans,
|
||||
@@ -52,8 +48,11 @@ import {
|
||||
MIN_REFERENCE_DIALOGUE_LINES,
|
||||
type SubsyncCoreDeps,
|
||||
isExecutableAvailable,
|
||||
yieldToEventLoop,
|
||||
} from './subsync-shared';
|
||||
import {
|
||||
evaluateToAudioOffThread,
|
||||
evaluateToSampledAudioOffThread,
|
||||
} from '../../subsync/align-worker';
|
||||
|
||||
async function resolveAudioSpeechForContext(
|
||||
context: SubsyncContext,
|
||||
@@ -139,13 +138,13 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
}
|
||||
}
|
||||
|
||||
const evaluateParsedCandidate = (
|
||||
const evaluateParsedCandidate = async (
|
||||
meta: Omit<
|
||||
EvaluatedSubtitleReference,
|
||||
'dialogueCount' | 'signCount' | 'audioStatus' | 'audioOffsetMs' | 'audioConfidence'
|
||||
>,
|
||||
parsed: ParsedSubtitleFile | null,
|
||||
): CandidateWithSpans => {
|
||||
): Promise<CandidateWithSpans> => {
|
||||
const stripped = parsed
|
||||
? extractSpansFromParsedSubtitle(parsed, { stripSigns: true })
|
||||
: { spans: [], dialogueCount: 0, signCount: 0 };
|
||||
@@ -163,16 +162,22 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
|
||||
if (!effectiveSignsOnly && stripped.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) {
|
||||
if (audioSpeech && audioSpeech.spans.length > 0) {
|
||||
const audioEval = evaluateReferenceAlignmentToAudio(stripped.spans, audioSpeech.spans, {
|
||||
lengthSec: context.durationSec ?? audioSpeech.durationSec,
|
||||
audioCalibration: audioSpeech.calibration,
|
||||
audioLeadSec: AUDIO_SPEECH_LEAD_SEC,
|
||||
});
|
||||
const audioEval = await evaluateToAudioOffThread(
|
||||
options.signal,
|
||||
stripped.spans,
|
||||
audioSpeech.spans,
|
||||
{
|
||||
lengthSec: context.durationSec ?? audioSpeech.durationSec,
|
||||
audioCalibration: audioSpeech.calibration,
|
||||
audioLeadSec: AUDIO_SPEECH_LEAD_SEC,
|
||||
},
|
||||
);
|
||||
audioStatus = audioEval.status;
|
||||
audioOffsetMs = audioEval.offsetMs;
|
||||
audioConfidence = audioEval.confidence;
|
||||
} else if (sampledWindows && sampledWindows.length >= 2) {
|
||||
const sampleEval = evaluateReferenceAlignmentToSampledAudio(
|
||||
const sampleEval = await evaluateToSampledAudioOffThread(
|
||||
options.signal,
|
||||
stripped.spans,
|
||||
sampledWindows,
|
||||
{ audioLeadSec: AUDIO_SPEECH_LEAD_SEC },
|
||||
@@ -229,21 +234,20 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
};
|
||||
|
||||
if (isEmbedded && skipSignsEmbedded && isSignsTrack) {
|
||||
results.push(evaluateParsedCandidate(baseMeta, null));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, null));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') {
|
||||
const preParsed = preExtracted.get(track['ff-index']);
|
||||
if (preParsed && preParsed.events.length > 0) {
|
||||
await yieldToEventLoop(options.signal);
|
||||
results.push(evaluateParsedCandidate(baseMeta, preParsed));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, preParsed));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (isEmbedded && skipEmbeddedExtraction) {
|
||||
results.push(evaluateParsedCandidate(baseMeta, null));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, null));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -257,7 +261,7 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
(!isRemoteMediaPath(context.videoPath) &&
|
||||
!canFfmpegExtractSubtitleExtension(embeddedExtension)))
|
||||
) {
|
||||
results.push(evaluateParsedCandidate(baseMeta, null));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, null));
|
||||
continue;
|
||||
}
|
||||
const preExtractSignature =
|
||||
@@ -275,7 +279,7 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
if (isEmbedded && !isRemoteMediaPath(context.videoPath)) {
|
||||
const postExtractSignature = getMediaFileSignature(context.videoPath);
|
||||
if (postExtractSignature !== preExtractSignature) {
|
||||
results.push(evaluateParsedCandidate(baseMeta, null));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, null));
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
@@ -291,10 +295,9 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
);
|
||||
}
|
||||
}
|
||||
await yieldToEventLoop(options.signal);
|
||||
results.push(evaluateParsedCandidate(baseMeta, parsed));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, parsed));
|
||||
} catch {
|
||||
results.push(evaluateParsedCandidate(baseMeta, null));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, null));
|
||||
} finally {
|
||||
cleanupTemporaryFile(extraction);
|
||||
}
|
||||
@@ -322,8 +325,7 @@ export async function discoverAndEvaluateSubtitleCandidates(
|
||||
};
|
||||
try {
|
||||
const parsed = readAndParseSubtitleFile(sidecar.path);
|
||||
await yieldToEventLoop(options.signal);
|
||||
results.push(evaluateParsedCandidate(baseMeta, parsed));
|
||||
results.push(await evaluateParsedCandidate(baseMeta, parsed));
|
||||
} catch {
|
||||
// Ignore unreadable sidecars.
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
SubsyncContext,
|
||||
SubsyncResolvedConfig,
|
||||
} from '../../subsync/utils';
|
||||
import { alignSubtitleFileToReferenceSpans } from '../../subsync/alass-align';
|
||||
import { extractAudioSpeechSpans, getMediaFileSignature } from '../../subsync/audio-speech';
|
||||
import { buildTrackReferenceLabel } from '../../subsync/reference-discovery';
|
||||
import {
|
||||
@@ -63,6 +62,7 @@ import {
|
||||
isExecutableAvailable,
|
||||
summarizeCommandFailure,
|
||||
} from './subsync-shared';
|
||||
import { alignSubtitleOffThread } from '../../subsync/align-worker';
|
||||
|
||||
async function runBuiltinSubsync(
|
||||
request: SubsyncManualRunRequest,
|
||||
@@ -170,7 +170,7 @@ async function runBuiltinSubsync(
|
||||
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,
|
||||
allowSplits,
|
||||
calibration,
|
||||
|
||||
@@ -38,14 +38,6 @@ export const JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS = 15_000;
|
||||
|
||||
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
|
||||
// stream tokens: ffmpeg echoes input URLs, and Jellyfin URLs carry ApiKey.
|
||||
function summarizeCommandOutput(text: string): string {
|
||||
|
||||
Reference in new issue
Block a user