mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
fix(subsync): close remaining cancellation and install races from review
- treat a cancelled run as a changed session at every commit point (writes, delay resets, track loads, picker), so nothing lands after a media switch - fail the secondary track load when the baseline track list cannot be read - keep the cross-filesystem install atomic by staging next to the target - register old temp dirs mpv still plays from so they are pruned later - no detected speech in the combined pass means no audio reference - start the align worker synchronously so a call cannot post to a stale worker
This commit is contained in:
6 files changed
+80
-24
No files matched your search
@@ -95,7 +95,13 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
);
|
||||
} catch (extractError) {
|
||||
if (
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!(await isPlaybackSessionUnchanged(
|
||||
client,
|
||||
context,
|
||||
targetTrack,
|
||||
targetSlot,
|
||||
deps.signal,
|
||||
)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
@@ -113,7 +119,13 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
|
||||
if (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) {
|
||||
if (
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!(await isPlaybackSessionUnchanged(
|
||||
client,
|
||||
context,
|
||||
targetTrack,
|
||||
targetSlot,
|
||||
deps.signal,
|
||||
)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
@@ -163,7 +175,13 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
? parseOptionalNumber(await client.requestProperty(delayProperty).catch(() => null))
|
||||
: null;
|
||||
if (
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!(await isPlaybackSessionUnchanged(
|
||||
client,
|
||||
context,
|
||||
targetTrack,
|
||||
targetSlot,
|
||||
deps.signal,
|
||||
)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
@@ -186,7 +204,7 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
replacesSource: replaceTarget,
|
||||
sourceStamp: parsedTarget.stamp,
|
||||
});
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack, deps.signal);
|
||||
deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment));
|
||||
};
|
||||
|
||||
@@ -477,7 +495,7 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
||||
reasons.push('Pick a reference, browse a subtitle file, or adjust sync options below.');
|
||||
|
||||
if (
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot, deps.signal)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
|
||||
@@ -526,7 +526,8 @@ export async function prepareRipCandidatesAndAudio(
|
||||
});
|
||||
if (rip) {
|
||||
return {
|
||||
audioSpeech: rip.audioSpeech,
|
||||
// No detected speech means no usable audio reference (keeps the no-audio fallbacks).
|
||||
audioSpeech: rip.audioSpeech && rip.audioSpeech.spans.length > 0 ? rip.audioSpeech : null,
|
||||
sampledAudioWindows: null,
|
||||
preExtractedEmbedded: rip.embeddedSubtitles,
|
||||
};
|
||||
|
||||
@@ -175,6 +175,18 @@ export async function isPlaybackSessionUnchanged(
|
||||
context: SubsyncContext,
|
||||
targetTrack: MpvTrack,
|
||||
slot: SubtitleSlot,
|
||||
signal?: AbortSignal,
|
||||
): Promise<boolean> {
|
||||
const unchanged = await isPlaybackSessionUnchangedNow(client, context, targetTrack, slot);
|
||||
// Checked after the awaits: a run cancelled meanwhile must not commit anything.
|
||||
return unchanged && !signal?.aborted;
|
||||
}
|
||||
|
||||
async function isPlaybackSessionUnchangedNow(
|
||||
client: MpvClientLike,
|
||||
context: SubsyncContext,
|
||||
targetTrack: MpvTrack,
|
||||
slot: SubtitleSlot,
|
||||
): Promise<boolean> {
|
||||
if (!client.connected) return false;
|
||||
try {
|
||||
|
||||
@@ -230,8 +230,13 @@ export function pruneRetainedSubsyncTempDirs(
|
||||
for (const name of entries) {
|
||||
if (!name.startsWith(SUBSYNC_TEMP_DIR_PREFIX)) continue;
|
||||
const dir = path.join(tmpRoot, name);
|
||||
// mpv may still play a file from an old dir (e.g. the app restarted under a running mpv).
|
||||
if (retainedSubsyncTempDirs.has(dir) || isReferenced(dir)) continue;
|
||||
if (retainedSubsyncTempDirs.has(dir)) continue;
|
||||
// mpv may still play a file from an old dir (e.g. the app restarted under a running mpv):
|
||||
// keep it until mpv drops the file, then the regular prune removes it.
|
||||
if (isReferenced(dir)) {
|
||||
retainSubsyncTempDir(dir);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const stat = fs.statSync(dir);
|
||||
if (stat.isDirectory() && now - stat.mtimeMs > STALE_SUBSYNC_TEMP_DIR_MS) {
|
||||
@@ -348,9 +353,18 @@ export function installRetimedFile(
|
||||
try {
|
||||
fs.renameSync(stagedPath, targetPath);
|
||||
} catch (error) {
|
||||
// A staged file next to a symlink can sit on another filesystem than the link target.
|
||||
// A staged file next to a symlink can sit on another filesystem than the link target:
|
||||
// copy it next to the target first so the final swap is still an atomic rename.
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;
|
||||
fs.copyFileSync(stagedPath, targetPath);
|
||||
const localStaged = `${targetPath}.subminer-subsync-${process.pid}-${Date.now()}.tmp`;
|
||||
try {
|
||||
fs.copyFileSync(stagedPath, localStaged);
|
||||
if (existing) fs.chmodSync(localStaged, existing.mode & 0o7777);
|
||||
fs.renameSync(localStaged, targetPath);
|
||||
} catch (copyError) {
|
||||
removeIfExists(localStaged);
|
||||
throw copyError;
|
||||
}
|
||||
fs.unlinkSync(stagedPath);
|
||||
}
|
||||
}
|
||||
@@ -470,6 +484,7 @@ export async function loadSyncedSubtitle(
|
||||
pathToLoad: string,
|
||||
slot: SubtitleSlot,
|
||||
sourceTrack: MpvTrack,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (!client.connected) {
|
||||
throw new Error('MPV disconnected while loading subtitle');
|
||||
@@ -478,16 +493,19 @@ export async function loadSyncedSubtitle(
|
||||
if (slot === 'secondary') {
|
||||
// Keep the primary track untouched: load without selecting, then point
|
||||
// secondary-sid at the freshly added track.
|
||||
// Without a baseline an older track for the same file could pass as the new one.
|
||||
const knownTrackIds = new Set(
|
||||
(await readSubtitleTracks(client).catch(() => [])).flatMap((track) =>
|
||||
(await readSubtitleTracks(client)).flatMap((track) =>
|
||||
typeof track.id === 'number' ? [track.id] : [],
|
||||
),
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) });
|
||||
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds);
|
||||
if (addedTrackId === null) {
|
||||
throw new Error('Synchronized subtitle did not appear in the mpv track list');
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
client.send({ command: ['set_property', 'secondary-sid', addedTrackId] });
|
||||
// The retimed file carries the timing now; only drop the old delay once it is selected.
|
||||
client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
|
||||
|
||||
@@ -178,7 +178,9 @@ async function runBuiltinSubsync(
|
||||
lengthSec,
|
||||
});
|
||||
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
|
||||
if (
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot, deps.signal))
|
||||
) {
|
||||
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
||||
}
|
||||
|
||||
@@ -186,7 +188,7 @@ async function runBuiltinSubsync(
|
||||
replacesSource: replaceTarget,
|
||||
sourceStamp: parsedTarget.stamp,
|
||||
});
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack, deps.signal);
|
||||
return {
|
||||
ok: true,
|
||||
message: formatAlignmentSummary(referenceLabel, alignment),
|
||||
@@ -226,14 +228,14 @@ async function runManualOffsetSubsync(
|
||||
const allIndices = parsedTarget.events.map((_, idx) => idx);
|
||||
const moves = new Array<number>(allIndices.length).fill(offsetMs / 1000);
|
||||
const rewritten = applyTimingToSubtitleFile(parsedTarget, allIndices, moves, 1.0);
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot, io.signal))) {
|
||||
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
||||
}
|
||||
writeRetimedContent(outputPath, rewritten, {
|
||||
replacesSource: replaceTarget,
|
||||
sourceStamp: parsedTarget.stamp,
|
||||
});
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack, io.signal);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`,
|
||||
@@ -300,7 +302,7 @@ async function subsyncToReference(
|
||||
};
|
||||
}
|
||||
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot))) {
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot, io.signal))) {
|
||||
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
||||
}
|
||||
|
||||
@@ -308,7 +310,7 @@ async function subsyncToReference(
|
||||
replacesSource: replaceTarget,
|
||||
sourceStamp,
|
||||
});
|
||||
await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
|
||||
await loadSyncedSubtitle(client, outputPath, slot, targetTrack, io.signal);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Subtitle synchronized with ${engine}`,
|
||||
@@ -521,7 +523,13 @@ export async function openSubsyncManualPicker(
|
||||
},
|
||||
);
|
||||
if (
|
||||
!(await isPlaybackSessionUnchanged(client, context, context.primaryTrack, 'primary')) ||
|
||||
!(await isPlaybackSessionUnchanged(
|
||||
client,
|
||||
context,
|
||||
context.primaryTrack,
|
||||
'primary',
|
||||
deps.signal,
|
||||
)) ||
|
||||
(!isRemote && getMediaFileSignature(context.videoPath) !== initialMediaSignature)
|
||||
) {
|
||||
return false;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Worker } from 'node:worker_threads';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { createLogger } from '../logger';
|
||||
import {
|
||||
alignSubtitleFileToReferenceSpans,
|
||||
@@ -84,8 +84,8 @@ class AlignWorkerRuntime {
|
||||
signal?: AbortSignal,
|
||||
): Promise<AlignTaskResult<K>> {
|
||||
signal?.throwIfAborted();
|
||||
const worker = await this.getWorker();
|
||||
signal?.throwIfAborted();
|
||||
// Synchronous startup: no await between picking the worker and posting to it.
|
||||
const worker = this.getWorker();
|
||||
if (!worker) return runAlignTask(kind, args) as AlignTaskResult<K>;
|
||||
|
||||
const id = this.nextId++;
|
||||
@@ -105,7 +105,7 @@ class AlignWorkerRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
private async getWorker(): Promise<Worker | null> {
|
||||
private getWorker(): Worker | null {
|
||||
if (this.worker) return this.worker;
|
||||
if (this.workerUnavailable || process.env[DISABLE_WORKER_ENV] === '1') return null;
|
||||
const workerPath = resolveAlignWorkerPath();
|
||||
@@ -114,8 +114,7 @@ class AlignWorkerRuntime {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const { Worker: WorkerCtor } = await import('node:worker_threads');
|
||||
const worker = new WorkerCtor(workerPath);
|
||||
const worker = new Worker(workerPath);
|
||||
let online = false;
|
||||
worker.unref();
|
||||
worker.once('online', () => {
|
||||
|
||||
Reference in new issue
Block a user