fix(subsync): address PR review findings and deterministic CI check

This commit is contained in:
sudacode committed 2026-11-25 20:17:25 -08:00
1 parent 8e3d9e21e0
commit fc113cfbca
16 files changed
+852 -82

No files matched your search

+4 -2
View File
@@ -74,12 +74,14 @@ export async function openSubsyncManualPickerRuntime(deps: SubsyncRuntimeDeps):
}
triggerDeps.setSubsyncInProgress(true);
try {
await triggerDeps.runWithSubsyncSpinner(() =>
const opened = await triggerDeps.runWithSubsyncSpinner(() =>
openSubsyncManualPicker(triggerDeps, {
guidanceMessage: null,
}),
);
triggerDeps.showMpvOsd('Subsync: choose engine and subtitles');
if (opened) {
triggerDeps.showMpvOsd('Subsync: choose engine and subtitles');
}
} catch (error) {
triggerDeps.showMpvOsd(`Subsync failed: ${(error as Error).message}`);
} finally {
+361
View File
@@ -72,13 +72,20 @@ test('triggerSubsyncFromConfig opens manual picker', async () => {
const osd: string[] = [];
let payloadTrackCount = 0;
let ffsubsyncAvailable: boolean | null = null;
let payloadMediaPath: string | null | undefined = undefined;
let inProgressState: boolean | null = null;
await triggerSubsyncFromConfig(
makeDeps({
getResolvedConfig: () => ({
alassPath: process.execPath,
ffsubsyncPath: process.execPath,
ffmpegPath: process.execPath,
}),
openManualPicker: (payload) => {
payloadTrackCount = payload.subtitleTracks.length;
ffsubsyncAvailable = payload.ffsubsyncAvailable;
payloadMediaPath = payload.mediaPath;
},
showMpvOsd: (text) => {
osd.push(text);
@@ -91,6 +98,7 @@ test('triggerSubsyncFromConfig opens manual picker', async () => {
assert.equal(payloadTrackCount, 2);
assert.equal(ffsubsyncAvailable, true);
assert.equal(payloadMediaPath, '/tmp/video.mkv');
assert.ok(osd.includes('Subsync: choose engine and subtitles'));
assert.equal(inProgressState, false);
});
@@ -1829,3 +1837,356 @@ test('runSubsyncManual refuses destructive replace when target subtitle encoding
assert.match(result.message, /losslessly/i);
assert.deepEqual(fs.readFileSync(targetPath), corruptBytes);
});
test('runSubsyncManual rejects stale submissions when active video changed since picker opened', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-stale-media-'));
const videoA = path.join(tmpDir, 'ep01.mkv');
const videoB = path.join(tmpDir, 'ep02.mkv');
const targetB = path.join(tmpDir, 'ep02.ja.srt');
const original = '1\n00:00:01,000 --> 00:00:03,000\nこんにちは\n';
fs.writeFileSync(videoA, 'a');
fs.writeFileSync(videoB, 'b');
fs.writeFileSync(targetB, original, 'utf8');
const result = await runSubsyncManual(
{
engine: 'offset',
mediaPath: videoA,
targetTrackId: 1,
offsetMs: 1000,
},
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoB;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetB,
},
];
}
return null;
},
}),
}),
);
assert.equal(result.ok, false);
assert.match(result.message, /Active video changed/i);
assert.equal(fs.readFileSync(targetB, 'utf8'), original);
});
test('triggerSubsyncFromConfig normalizes file:// video URLs as local media', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-file-url-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
fs.writeFileSync(videoPath, 'video');
const fileUrl = `file://${videoPath}`;
let capturedPayload: SubsyncManualPayload | null = null;
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return fileUrl;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [{ id: 1, type: 'sub', selected: true, lang: 'jpn' }];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'manual',
alassPath: process.execPath,
ffsubsyncPath: process.execPath,
ffmpegPath: process.execPath,
}),
openManualPicker: (payload) => {
capturedPayload = payload;
},
}),
);
assert.ok(capturedPayload);
const resolved = capturedPayload as SubsyncManualPayload;
assert.equal(resolved.videoReferenceAvailable, true);
assert.equal(resolved.ffsubsyncAvailable, true);
assert.equal(resolved.mediaPath, videoPath);
});
test('runSubsyncManual allows retiming an unchanged inactive target track', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-inactive-target-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const activeSub = path.join(tmpDir, 'active.srt');
const inactiveSub = path.join(tmpDir, 'inactive.srt');
fs.writeFileSync(videoPath, 'video');
fs.writeFileSync(activeSub, '1\n00:00:01,000 --> 00:00:02,000\nactive\n', 'utf8');
fs.writeFileSync(inactiveSub, '1\n00:00:05,000 --> 00:00:07,000\ninactive\n', 'utf8');
const commands: Array<(string | number)[]> = [];
const result = await runSubsyncManual(
{
engine: 'offset',
mediaPath: videoPath,
targetTrackId: 3,
offsetMs: 1000,
},
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: (payload) => {
commands.push(payload.command);
},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': activeSub,
},
{
id: 3,
type: 'sub',
selected: false,
external: true,
lang: 'jpn',
'external-filename': inactiveSub,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: true,
}),
}),
);
assert.equal(result.ok, true);
assert.ok(fs.readFileSync(inactiveSub, 'utf8').includes('00:00:06,000 --> 00:00:08,000'));
assert.ok(commands.some((cmd) => cmd[0] === 'sub-add' && cmd[1] === inactiveSub));
});
test('triggerSubsyncFromConfig discards auto-sync when user disables target slot mid-sync', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-disabled-slot-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const refPath = path.join(tmpDir, 'ep01.en.srt');
fs.writeFileSync(videoPath, 'video');
const lines: string[] = [];
const targetLines: string[] = [];
for (let i = 0; i < 40; i += 1) {
const start = 10 + i * 5;
const end = start + 2;
const fmt = (sec: number) => {
const m = Math.floor(sec / 60);
const s = sec % 60;
return `00:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},000`;
};
lines.push(`${i + 1}\n${fmt(start)} --> ${fmt(end)}\nLine ${i + 1}\n`);
targetLines.push(`${i + 1}\n${fmt(start + 3)} --> ${fmt(end + 3)}\nセリフ ${i + 1}\n`);
}
const originalTarget = targetLines.join('\n');
fs.writeFileSync(refPath, lines.join('\n'), 'utf8');
fs.writeFileSync(targetPath, originalTarget, 'utf8');
let sidCalls = 0;
const sentCommands: Array<(string | number)[]> = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: (payload) => {
sentCommands.push(payload.command);
},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') {
sidCalls += 1;
return sidCalls === 1 ? 1 : 'no';
}
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 400;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': refPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: true,
}),
}),
);
assert.deepEqual(sentCommands, []);
assert.equal(fs.readFileSync(targetPath, 'utf8'), originalTarget);
});
test('triggerSubsyncFromConfig skips early extraction fallback picker when playback switches', async () => {
let pathCalls = 0;
let pickerOpened = false;
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') {
pathCalls += 1;
return pathCalls === 1 ? '/tmp/videoA.mkv' : '/tmp/videoB.mkv';
}
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [{ id: 1, type: 'sub', selected: true, lang: 'jpn' }];
}
return null;
},
}),
openManualPicker: () => {
pickerOpened = true;
},
}),
);
assert.equal(pickerOpened, false);
});
test('triggerSubsyncFromConfig resets non-zero sub-delay when already in sync without rewriting', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-reset-delay-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const refPath = path.join(tmpDir, 'ep01.en.srt');
fs.writeFileSync(videoPath, 'video');
let t = 5;
const spans: Array<[number, number]> = [];
for (let i = 0; i < 60; i += 1) {
const dur = 1.2 + ((i * 7) % 5) * 0.4;
const gap = 0.6 + ((i * 13) % 7) * 0.7;
spans.push([t, t + dur]);
t += dur + gap;
}
const fmt = (sec: number) => {
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = Math.floor(sec % 60);
const ms = Math.round((sec - Math.floor(sec)) * 1000);
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},${String(ms).padStart(3, '0')}`;
};
const srt = spans
.map(([s, e], i) => `${i + 1}\n${fmt(s)} --> ${fmt(e)}\nLine ${i + 1}\n`)
.join('\n');
fs.writeFileSync(refPath, srt, 'utf8');
fs.writeFileSync(targetPath, srt, 'utf8');
const mtimeBefore = fs.statSync(targetPath).mtimeMs;
const sentCommands: Array<(string | number)[]> = [];
const osd: string[] = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: (payload) => {
sentCommands.push(payload.command);
},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'sub-delay') return 2.5;
if (name === 'duration') return 600;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': refPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: true,
}),
showMpvOsd: (text) => {
osd.push(text);
},
}),
);
assert.deepEqual(sentCommands, [['set_property', 'sub-delay', 0]]);
assert.equal(fs.statSync(targetPath).mtimeMs, mtimeBefore);
assert.ok(osd.some((line) => line.includes('Reset subtitle delay to 0s')));
});
+85 -16
View File
@@ -12,6 +12,7 @@ import {
import {
CommandResult,
codecToExtension,
extensionToFfmpegMuxer,
fileExists,
findSubsyncExecutable,
formatTrackLabel,
@@ -205,7 +206,7 @@ function resolveLocalSubtitlePath(
): string | null {
if (!rawPath) return null;
let local = rawPath;
if (local.startsWith('file://')) {
if (/^file:\/\//i.test(local)) {
try {
local = fileURLToPath(local);
} catch {
@@ -220,6 +221,10 @@ function resolveLocalSubtitlePath(
return local;
}
function normalizeMediaVideoPath(rawPath: string, workingDirectory?: string | null): string {
return resolveLocalSubtitlePath(rawPath, workingDirectory) ?? rawPath;
}
async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncContext> {
const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw, workingDirRaw, durationRaw] =
await Promise.all([
@@ -238,9 +243,7 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncConte
const workingDirectory =
typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null;
const resolvedVideoPath = isRemoteMediaPath(videoPath)
? videoPath
: (resolveLocalSubtitlePath(videoPath, workingDirectory) ?? videoPath);
const resolvedVideoPath = normalizeMediaVideoPath(videoPath, workingDirectory);
const tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : [];
const subtitleTracks = tracks.filter((track) => track.type === 'sub');
@@ -345,7 +348,7 @@ async function extractSubtitleTrackToFile(
'-map',
`0:${ffIndex}`,
'-f',
extension,
extensionToFfmpegMuxer(extension),
outputPath,
]);
@@ -424,27 +427,46 @@ async function isPlaybackSessionUnchanged(
if (!client.connected) return false;
try {
const slotProperty = slot === 'secondary' ? 'secondary-sid' : 'sid';
const [videoPathRaw, workingDirRaw, slotTrackRaw] = await Promise.all([
const initialSlotTrackId =
slot === 'secondary'
? (context.secondaryTrack?.id ?? null)
: (context.primaryTrack.id ?? null);
const needsTrackIdentityCheck =
typeof targetTrack.id === 'number' && targetTrack.id !== initialSlotTrackId;
const [videoPathRaw, workingDirRaw, slotTrackRaw, trackListRaw] = await Promise.all([
client.requestProperty('path'),
client.requestProperty('working-directory').catch(() => null),
client.requestProperty(slotProperty),
needsTrackIdentityCheck
? client.requestProperty('track-list').catch(() => null)
: Promise.resolve(null),
]);
const currentRawPath = typeof videoPathRaw === 'string' ? videoPathRaw : '';
if (!currentRawPath) return false;
const currentWorkingDir =
typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null;
const currentVideoPath = isRemoteMediaPath(currentRawPath)
? currentRawPath
: (resolveLocalSubtitlePath(currentRawPath, currentWorkingDir) ?? currentRawPath);
const currentVideoPath = normalizeMediaVideoPath(currentRawPath, currentWorkingDir);
if (
normalizeSubtitlePathForCompare(currentVideoPath) !==
normalizeSubtitlePathForCompare(context.videoPath)
) {
return false;
}
if (typeof targetTrack.id === 'number') {
const currentSlotId = parseTrackId(slotTrackRaw);
if (currentSlotId !== null && currentSlotId !== targetTrack.id) {
const currentSlotId = parseTrackId(slotTrackRaw);
if (currentSlotId !== initialSlotTrackId) {
return false;
}
if (needsTrackIdentityCheck) {
const tracks = Array.isArray(trackListRaw)
? normalizeTrackIds(trackListRaw as MpvTrack[])
: [];
const currentTarget = tracks.find(
(track) => track.type === 'sub' && track.id === targetTrack.id,
);
if (
!currentTarget ||
getSourceTrackIdentity(currentTarget) !== getSourceTrackIdentity(targetTrack)
) {
return false;
}
}
@@ -903,6 +925,7 @@ function buildManualPayload(
defaultTargetTrackId: primaryTrackId,
videoReferenceAvailable: isLocalMedia,
ffsubsyncAvailable,
mediaPath: context.videoPath,
guidanceMessage: options.guidanceMessage ?? null,
referenceCandidates,
defaultReferenceKey: recommendedKey,
@@ -1140,6 +1163,10 @@ async function subsyncToReference(
};
}
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, slot))) {
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
}
await loadSyncedSubtitle(client, outputPath, slot);
return {
ok: true,
@@ -1205,6 +1232,24 @@ export async function runSubsyncManual(
const context = await gatherSubsyncContext(client);
const resolved = deps.getResolvedConfig();
if (request.mediaPath !== undefined && request.mediaPath !== null) {
const trimmedMediaPath = request.mediaPath.trim();
const expectedVideoPath = trimmedMediaPath
? normalizeMediaVideoPath(trimmedMediaPath, context.workingDirectory)
: '';
if (
!expectedVideoPath ||
normalizeSubtitlePathForCompare(expectedVideoPath) !==
normalizeSubtitlePathForCompare(context.videoPath)
) {
return {
ok: false,
message:
'Active video changed since the subsync picker opened. Reopen subsync for the current video.',
};
}
}
const targetTrack = resolveTargetTrack(request, context);
if (!targetTrack) {
return { ok: false, message: 'Select the out-of-sync subtitle track to retime' };
@@ -1367,7 +1412,11 @@ async function prepareRipCandidatesAndAudio(
// External-only reference fast path: reuse cached full audio if already available,
// otherwise sample 4 seeked 60s windows (~0.2-0.5s) to verify external subtitle
// references before ever decoding the full video audio.
const cachedFull = getCachedAudioSpeechSpans(context.videoPath, context.audioStreamIndex);
const cachedFull = getCachedAudioSpeechSpans(
context.videoPath,
context.audioStreamIndex,
vadPaths,
);
if (cachedFull) {
return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null };
}
@@ -1405,7 +1454,7 @@ export async function openSubsyncManualPicker(
guidanceMessage?: string | null;
skipAudioAnalysis?: boolean;
} = {},
): Promise<void> {
): Promise<boolean> {
const client = getMpvClientForSubsync(deps);
const context = await gatherSubsyncContext(client);
const resolved = deps.getResolvedConfig();
@@ -1438,6 +1487,9 @@ export async function openSubsyncManualPicker(
preExtractedEmbedded: prepared.preExtractedEmbedded,
},
);
if (!(await isPlaybackSessionUnchanged(client, context, context.primaryTrack, 'primary'))) {
return false;
}
}
const payload = buildManualPayload(context, resolved, deps, {
@@ -1446,6 +1498,7 @@ export async function openSubsyncManualPicker(
guidanceMessage: options.guidanceMessage ?? null,
});
deps.openManualPicker(payload);
return true;
}
async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
@@ -1467,6 +1520,9 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
context.workingDirectory,
);
} catch (extractError) {
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return;
}
const payload = buildManualPayload(context, resolved, deps, {
guidanceMessage: `Automatic sync could not read the active subtitle track (${(extractError as Error).message}). Choose an engine and subtitle tracks below.`,
});
@@ -1478,6 +1534,9 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
const targetInfo = extractSpansFromParsedSubtitle(parsedTarget, { stripSigns: true });
if (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) {
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return;
}
const payload = buildManualPayload(context, resolved, deps, {
guidanceMessage:
'Could not read dialogue cues from the active subtitle track. Choose an engine or reference below.',
@@ -1514,6 +1573,14 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
return;
}
if (isAlreadyInSync(alignment)) {
const delayProperty = targetSlot === 'secondary' ? 'secondary-sub-delay' : 'sub-delay';
const activeDelayRaw = await client.requestProperty(delayProperty).catch(() => null);
const activeDelay = parseOptionalNumber(activeDelayRaw);
if (activeDelay !== null && Math.abs(activeDelay) > 0.005) {
client.send({ command: ['set_property', delayProperty, 0] });
deps.showMpvOsd(`Reset subtitle delay to 0s (already in sync with ${sourceLabel})`);
return;
}
deps.showMpvOsd(`Subtitles are already in sync (${sourceLabel})`);
return;
}
@@ -1722,8 +1789,10 @@ export async function triggerSubsyncFromConfig(deps: TriggerSubsyncFromConfigDep
try {
const resolved = deps.getResolvedConfig();
if (resolved.mode === 'manual') {
await openSubsyncManualPicker(deps, { skipAudioAnalysis: true });
deps.showMpvOsd('Subsync: choose engine and subtitles');
const opened = await openSubsyncManualPicker(deps, { skipAudioAnalysis: true });
if (opened) {
deps.showMpvOsd('Subsync: choose engine and subtitles');
}
return;
}