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) {
|
} catch (extractError) {
|
||||||
if (
|
if (
|
||||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
!(await isPlaybackSessionUnchanged(
|
||||||
|
client,
|
||||||
|
context,
|
||||||
|
targetTrack,
|
||||||
|
targetSlot,
|
||||||
|
deps.signal,
|
||||||
|
)) ||
|
||||||
!isMediaFileUnchanged()
|
!isMediaFileUnchanged()
|
||||||
) {
|
) {
|
||||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
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 (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) {
|
||||||
if (
|
if (
|
||||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
!(await isPlaybackSessionUnchanged(
|
||||||
|
client,
|
||||||
|
context,
|
||||||
|
targetTrack,
|
||||||
|
targetSlot,
|
||||||
|
deps.signal,
|
||||||
|
)) ||
|
||||||
!isMediaFileUnchanged()
|
!isMediaFileUnchanged()
|
||||||
) {
|
) {
|
||||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||||
@@ -163,7 +175,13 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
|||||||
? parseOptionalNumber(await client.requestProperty(delayProperty).catch(() => null))
|
? parseOptionalNumber(await client.requestProperty(delayProperty).catch(() => null))
|
||||||
: null;
|
: null;
|
||||||
if (
|
if (
|
||||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
!(await isPlaybackSessionUnchanged(
|
||||||
|
client,
|
||||||
|
context,
|
||||||
|
targetTrack,
|
||||||
|
targetSlot,
|
||||||
|
deps.signal,
|
||||||
|
)) ||
|
||||||
!isMediaFileUnchanged()
|
!isMediaFileUnchanged()
|
||||||
) {
|
) {
|
||||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||||
@@ -186,7 +204,7 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis
|
|||||||
replacesSource: replaceTarget,
|
replacesSource: replaceTarget,
|
||||||
sourceStamp: parsedTarget.stamp,
|
sourceStamp: parsedTarget.stamp,
|
||||||
});
|
});
|
||||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack, deps.signal);
|
||||||
deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment));
|
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.');
|
reasons.push('Pick a reference, browse a subtitle file, or adjust sync options below.');
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot, deps.signal)) ||
|
||||||
!isMediaFileUnchanged()
|
!isMediaFileUnchanged()
|
||||||
) {
|
) {
|
||||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||||
|
|||||||
@@ -526,7 +526,8 @@ export async function prepareRipCandidatesAndAudio(
|
|||||||
});
|
});
|
||||||
if (rip) {
|
if (rip) {
|
||||||
return {
|
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,
|
sampledAudioWindows: null,
|
||||||
preExtractedEmbedded: rip.embeddedSubtitles,
|
preExtractedEmbedded: rip.embeddedSubtitles,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -175,6 +175,18 @@ export async function isPlaybackSessionUnchanged(
|
|||||||
context: SubsyncContext,
|
context: SubsyncContext,
|
||||||
targetTrack: MpvTrack,
|
targetTrack: MpvTrack,
|
||||||
slot: SubtitleSlot,
|
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> {
|
): Promise<boolean> {
|
||||||
if (!client.connected) return false;
|
if (!client.connected) return false;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -230,8 +230,13 @@ export function pruneRetainedSubsyncTempDirs(
|
|||||||
for (const name of entries) {
|
for (const name of entries) {
|
||||||
if (!name.startsWith(SUBSYNC_TEMP_DIR_PREFIX)) continue;
|
if (!name.startsWith(SUBSYNC_TEMP_DIR_PREFIX)) continue;
|
||||||
const dir = path.join(tmpRoot, name);
|
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)) continue;
|
||||||
if (retainedSubsyncTempDirs.has(dir) || isReferenced(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 {
|
try {
|
||||||
const stat = fs.statSync(dir);
|
const stat = fs.statSync(dir);
|
||||||
if (stat.isDirectory() && now - stat.mtimeMs > STALE_SUBSYNC_TEMP_DIR_MS) {
|
if (stat.isDirectory() && now - stat.mtimeMs > STALE_SUBSYNC_TEMP_DIR_MS) {
|
||||||
@@ -348,9 +353,18 @@ export function installRetimedFile(
|
|||||||
try {
|
try {
|
||||||
fs.renameSync(stagedPath, targetPath);
|
fs.renameSync(stagedPath, targetPath);
|
||||||
} catch (error) {
|
} 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;
|
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);
|
fs.unlinkSync(stagedPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -470,6 +484,7 @@ export async function loadSyncedSubtitle(
|
|||||||
pathToLoad: string,
|
pathToLoad: string,
|
||||||
slot: SubtitleSlot,
|
slot: SubtitleSlot,
|
||||||
sourceTrack: MpvTrack,
|
sourceTrack: MpvTrack,
|
||||||
|
signal?: AbortSignal,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (!client.connected) {
|
if (!client.connected) {
|
||||||
throw new Error('MPV disconnected while loading subtitle');
|
throw new Error('MPV disconnected while loading subtitle');
|
||||||
@@ -478,16 +493,19 @@ export async function loadSyncedSubtitle(
|
|||||||
if (slot === 'secondary') {
|
if (slot === 'secondary') {
|
||||||
// Keep the primary track untouched: load without selecting, then point
|
// Keep the primary track untouched: load without selecting, then point
|
||||||
// secondary-sid at the freshly added track.
|
// 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(
|
const knownTrackIds = new Set(
|
||||||
(await readSubtitleTracks(client).catch(() => [])).flatMap((track) =>
|
(await readSubtitleTracks(client)).flatMap((track) =>
|
||||||
typeof track.id === 'number' ? [track.id] : [],
|
typeof track.id === 'number' ? [track.id] : [],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
signal?.throwIfAborted();
|
||||||
client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) });
|
client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) });
|
||||||
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds);
|
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad, knownTrackIds);
|
||||||
if (addedTrackId === null) {
|
if (addedTrackId === null) {
|
||||||
throw new Error('Synchronized subtitle did not appear in the mpv track list');
|
throw new Error('Synchronized subtitle did not appear in the mpv track list');
|
||||||
}
|
}
|
||||||
|
signal?.throwIfAborted();
|
||||||
client.send({ command: ['set_property', 'secondary-sid', addedTrackId] });
|
client.send({ command: ['set_property', 'secondary-sid', addedTrackId] });
|
||||||
// The retimed file carries the timing now; only drop the old delay once it is selected.
|
// The retimed file carries the timing now; only drop the old delay once it is selected.
|
||||||
client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
|
client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
|
||||||
|
|||||||
@@ -178,7 +178,9 @@ async function runBuiltinSubsync(
|
|||||||
lengthSec,
|
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 };
|
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +188,7 @@ async function runBuiltinSubsync(
|
|||||||
replacesSource: replaceTarget,
|
replacesSource: replaceTarget,
|
||||||
sourceStamp: parsedTarget.stamp,
|
sourceStamp: parsedTarget.stamp,
|
||||||
});
|
});
|
||||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack, deps.signal);
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
message: formatAlignmentSummary(referenceLabel, alignment),
|
message: formatAlignmentSummary(referenceLabel, alignment),
|
||||||
@@ -226,14 +228,14 @@ async function runManualOffsetSubsync(
|
|||||||
const allIndices = parsedTarget.events.map((_, idx) => idx);
|
const allIndices = parsedTarget.events.map((_, idx) => idx);
|
||||||
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, io.signal))) {
|
||||||
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
||||||
}
|
}
|
||||||
writeRetimedContent(outputPath, rewritten, {
|
writeRetimedContent(outputPath, rewritten, {
|
||||||
replacesSource: replaceTarget,
|
replacesSource: replaceTarget,
|
||||||
sourceStamp: parsedTarget.stamp,
|
sourceStamp: parsedTarget.stamp,
|
||||||
});
|
});
|
||||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack, io.signal);
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`,
|
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 };
|
return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,7 +310,7 @@ async function subsyncToReference(
|
|||||||
replacesSource: replaceTarget,
|
replacesSource: replaceTarget,
|
||||||
sourceStamp,
|
sourceStamp,
|
||||||
});
|
});
|
||||||
await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
|
await loadSyncedSubtitle(client, outputPath, slot, targetTrack, io.signal);
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
message: `Subtitle synchronized with ${engine}`,
|
message: `Subtitle synchronized with ${engine}`,
|
||||||
@@ -521,7 +523,13 @@ export async function openSubsyncManualPicker(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (
|
if (
|
||||||
!(await isPlaybackSessionUnchanged(client, context, context.primaryTrack, 'primary')) ||
|
!(await isPlaybackSessionUnchanged(
|
||||||
|
client,
|
||||||
|
context,
|
||||||
|
context.primaryTrack,
|
||||||
|
'primary',
|
||||||
|
deps.signal,
|
||||||
|
)) ||
|
||||||
(!isRemote && getMediaFileSignature(context.videoPath) !== initialMediaSignature)
|
(!isRemote && getMediaFileSignature(context.videoPath) !== initialMediaSignature)
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import type { Worker } from 'node:worker_threads';
|
import { Worker } from 'node:worker_threads';
|
||||||
import { createLogger } from '../logger';
|
import { createLogger } from '../logger';
|
||||||
import {
|
import {
|
||||||
alignSubtitleFileToReferenceSpans,
|
alignSubtitleFileToReferenceSpans,
|
||||||
@@ -84,8 +84,8 @@ class AlignWorkerRuntime {
|
|||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
): Promise<AlignTaskResult<K>> {
|
): Promise<AlignTaskResult<K>> {
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
const worker = await this.getWorker();
|
// Synchronous startup: no await between picking the worker and posting to it.
|
||||||
signal?.throwIfAborted();
|
const worker = this.getWorker();
|
||||||
if (!worker) return runAlignTask(kind, args) as AlignTaskResult<K>;
|
if (!worker) return runAlignTask(kind, args) as AlignTaskResult<K>;
|
||||||
|
|
||||||
const id = this.nextId++;
|
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.worker) return this.worker;
|
||||||
if (this.workerUnavailable || process.env[DISABLE_WORKER_ENV] === '1') return null;
|
if (this.workerUnavailable || process.env[DISABLE_WORKER_ENV] === '1') return null;
|
||||||
const workerPath = resolveAlignWorkerPath();
|
const workerPath = resolveAlignWorkerPath();
|
||||||
@@ -114,8 +114,7 @@ class AlignWorkerRuntime {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const { Worker: WorkerCtor } = await import('node:worker_threads');
|
const worker = new Worker(workerPath);
|
||||||
const worker = new WorkerCtor(workerPath);
|
|
||||||
let online = false;
|
let online = false;
|
||||||
worker.unref();
|
worker.unref();
|
||||||
worker.once('online', () => {
|
worker.once('online', () => {
|
||||||
|
|||||||
Reference in new issue
Block a user