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); triggerDeps.setSubsyncInProgress(true);
try { try {
await triggerDeps.runWithSubsyncSpinner(() => const opened = await triggerDeps.runWithSubsyncSpinner(() =>
openSubsyncManualPicker(triggerDeps, { openSubsyncManualPicker(triggerDeps, {
guidanceMessage: null, guidanceMessage: null,
}), }),
); );
triggerDeps.showMpvOsd('Subsync: choose engine and subtitles'); if (opened) {
triggerDeps.showMpvOsd('Subsync: choose engine and subtitles');
}
} catch (error) { } catch (error) {
triggerDeps.showMpvOsd(`Subsync failed: ${(error as Error).message}`); triggerDeps.showMpvOsd(`Subsync failed: ${(error as Error).message}`);
} finally { } finally {
+361
View File
@@ -72,13 +72,20 @@ test('triggerSubsyncFromConfig opens manual picker', async () => {
const osd: string[] = []; const osd: string[] = [];
let payloadTrackCount = 0; let payloadTrackCount = 0;
let ffsubsyncAvailable: boolean | null = null; let ffsubsyncAvailable: boolean | null = null;
let payloadMediaPath: string | null | undefined = undefined;
let inProgressState: boolean | null = null; let inProgressState: boolean | null = null;
await triggerSubsyncFromConfig( await triggerSubsyncFromConfig(
makeDeps({ makeDeps({
getResolvedConfig: () => ({
alassPath: process.execPath,
ffsubsyncPath: process.execPath,
ffmpegPath: process.execPath,
}),
openManualPicker: (payload) => { openManualPicker: (payload) => {
payloadTrackCount = payload.subtitleTracks.length; payloadTrackCount = payload.subtitleTracks.length;
ffsubsyncAvailable = payload.ffsubsyncAvailable; ffsubsyncAvailable = payload.ffsubsyncAvailable;
payloadMediaPath = payload.mediaPath;
}, },
showMpvOsd: (text) => { showMpvOsd: (text) => {
osd.push(text); osd.push(text);
@@ -91,6 +98,7 @@ test('triggerSubsyncFromConfig opens manual picker', async () => {
assert.equal(payloadTrackCount, 2); assert.equal(payloadTrackCount, 2);
assert.equal(ffsubsyncAvailable, true); assert.equal(ffsubsyncAvailable, true);
assert.equal(payloadMediaPath, '/tmp/video.mkv');
assert.ok(osd.includes('Subsync: choose engine and subtitles')); assert.ok(osd.includes('Subsync: choose engine and subtitles'));
assert.equal(inProgressState, false); assert.equal(inProgressState, false);
}); });
@@ -1829,3 +1837,356 @@ test('runSubsyncManual refuses destructive replace when target subtitle encoding
assert.match(result.message, /losslessly/i); assert.match(result.message, /losslessly/i);
assert.deepEqual(fs.readFileSync(targetPath), corruptBytes); 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 { import {
CommandResult, CommandResult,
codecToExtension, codecToExtension,
extensionToFfmpegMuxer,
fileExists, fileExists,
findSubsyncExecutable, findSubsyncExecutable,
formatTrackLabel, formatTrackLabel,
@@ -205,7 +206,7 @@ function resolveLocalSubtitlePath(
): string | null { ): string | null {
if (!rawPath) return null; if (!rawPath) return null;
let local = rawPath; let local = rawPath;
if (local.startsWith('file://')) { if (/^file:\/\//i.test(local)) {
try { try {
local = fileURLToPath(local); local = fileURLToPath(local);
} catch { } catch {
@@ -220,6 +221,10 @@ function resolveLocalSubtitlePath(
return local; return local;
} }
function normalizeMediaVideoPath(rawPath: string, workingDirectory?: string | null): string {
return resolveLocalSubtitlePath(rawPath, workingDirectory) ?? rawPath;
}
async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncContext> { async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncContext> {
const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw, workingDirRaw, durationRaw] = const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw, workingDirRaw, durationRaw] =
await Promise.all([ await Promise.all([
@@ -238,9 +243,7 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncConte
const workingDirectory = const workingDirectory =
typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null; typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null;
const resolvedVideoPath = isRemoteMediaPath(videoPath) const resolvedVideoPath = normalizeMediaVideoPath(videoPath, workingDirectory);
? videoPath
: (resolveLocalSubtitlePath(videoPath, workingDirectory) ?? videoPath);
const tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : []; const tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : [];
const subtitleTracks = tracks.filter((track) => track.type === 'sub'); const subtitleTracks = tracks.filter((track) => track.type === 'sub');
@@ -345,7 +348,7 @@ async function extractSubtitleTrackToFile(
'-map', '-map',
`0:${ffIndex}`, `0:${ffIndex}`,
'-f', '-f',
extension, extensionToFfmpegMuxer(extension),
outputPath, outputPath,
]); ]);
@@ -424,27 +427,46 @@ async function isPlaybackSessionUnchanged(
if (!client.connected) return false; if (!client.connected) return false;
try { try {
const slotProperty = slot === 'secondary' ? 'secondary-sid' : 'sid'; 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('path'),
client.requestProperty('working-directory').catch(() => null), client.requestProperty('working-directory').catch(() => null),
client.requestProperty(slotProperty), client.requestProperty(slotProperty),
needsTrackIdentityCheck
? client.requestProperty('track-list').catch(() => null)
: Promise.resolve(null),
]); ]);
const currentRawPath = typeof videoPathRaw === 'string' ? videoPathRaw : ''; const currentRawPath = typeof videoPathRaw === 'string' ? videoPathRaw : '';
if (!currentRawPath) return false; if (!currentRawPath) return false;
const currentWorkingDir = const currentWorkingDir =
typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null; typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null;
const currentVideoPath = isRemoteMediaPath(currentRawPath) const currentVideoPath = normalizeMediaVideoPath(currentRawPath, currentWorkingDir);
? currentRawPath
: (resolveLocalSubtitlePath(currentRawPath, currentWorkingDir) ?? currentRawPath);
if ( if (
normalizeSubtitlePathForCompare(currentVideoPath) !== normalizeSubtitlePathForCompare(currentVideoPath) !==
normalizeSubtitlePathForCompare(context.videoPath) normalizeSubtitlePathForCompare(context.videoPath)
) { ) {
return false; return false;
} }
if (typeof targetTrack.id === 'number') { const currentSlotId = parseTrackId(slotTrackRaw);
const currentSlotId = parseTrackId(slotTrackRaw); if (currentSlotId !== initialSlotTrackId) {
if (currentSlotId !== null && currentSlotId !== targetTrack.id) { 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; return false;
} }
} }
@@ -903,6 +925,7 @@ function buildManualPayload(
defaultTargetTrackId: primaryTrackId, defaultTargetTrackId: primaryTrackId,
videoReferenceAvailable: isLocalMedia, videoReferenceAvailable: isLocalMedia,
ffsubsyncAvailable, ffsubsyncAvailable,
mediaPath: context.videoPath,
guidanceMessage: options.guidanceMessage ?? null, guidanceMessage: options.guidanceMessage ?? null,
referenceCandidates, referenceCandidates,
defaultReferenceKey: recommendedKey, 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); await loadSyncedSubtitle(client, outputPath, slot);
return { return {
ok: true, ok: true,
@@ -1205,6 +1232,24 @@ export async function runSubsyncManual(
const context = await gatherSubsyncContext(client); const context = await gatherSubsyncContext(client);
const resolved = deps.getResolvedConfig(); 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); const targetTrack = resolveTargetTrack(request, context);
if (!targetTrack) { if (!targetTrack) {
return { ok: false, message: 'Select the out-of-sync subtitle track to retime' }; 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, // 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 // otherwise sample 4 seeked 60s windows (~0.2-0.5s) to verify external subtitle
// references before ever decoding the full video audio. // 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) { if (cachedFull) {
return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null }; return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null };
} }
@@ -1405,7 +1454,7 @@ export async function openSubsyncManualPicker(
guidanceMessage?: string | null; guidanceMessage?: string | null;
skipAudioAnalysis?: boolean; skipAudioAnalysis?: boolean;
} = {}, } = {},
): Promise<void> { ): Promise<boolean> {
const client = getMpvClientForSubsync(deps); const client = getMpvClientForSubsync(deps);
const context = await gatherSubsyncContext(client); const context = await gatherSubsyncContext(client);
const resolved = deps.getResolvedConfig(); const resolved = deps.getResolvedConfig();
@@ -1438,6 +1487,9 @@ export async function openSubsyncManualPicker(
preExtractedEmbedded: prepared.preExtractedEmbedded, preExtractedEmbedded: prepared.preExtractedEmbedded,
}, },
); );
if (!(await isPlaybackSessionUnchanged(client, context, context.primaryTrack, 'primary'))) {
return false;
}
} }
const payload = buildManualPayload(context, resolved, deps, { const payload = buildManualPayload(context, resolved, deps, {
@@ -1446,6 +1498,7 @@ export async function openSubsyncManualPicker(
guidanceMessage: options.guidanceMessage ?? null, guidanceMessage: options.guidanceMessage ?? null,
}); });
deps.openManualPicker(payload); deps.openManualPicker(payload);
return true;
} }
async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> { async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
@@ -1467,6 +1520,9 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
context.workingDirectory, context.workingDirectory,
); );
} catch (extractError) { } catch (extractError) {
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return;
}
const payload = buildManualPayload(context, resolved, deps, { 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.`, 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 }); const targetInfo = extractSpansFromParsedSubtitle(parsedTarget, { stripSigns: true });
if (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) { if (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) {
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
return;
}
const payload = buildManualPayload(context, resolved, deps, { const payload = buildManualPayload(context, resolved, deps, {
guidanceMessage: guidanceMessage:
'Could not read dialogue cues from the active subtitle track. Choose an engine or reference below.', '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; return;
} }
if (isAlreadyInSync(alignment)) { 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})`); deps.showMpvOsd(`Subtitles are already in sync (${sourceLabel})`);
return; return;
} }
@@ -1722,8 +1789,10 @@ export async function triggerSubsyncFromConfig(deps: TriggerSubsyncFromConfigDep
try { try {
const resolved = deps.getResolvedConfig(); const resolved = deps.getResolvedConfig();
if (resolved.mode === 'manual') { if (resolved.mode === 'manual') {
await openSubsyncManualPicker(deps, { skipAudioAnalysis: true }); const opened = await openSubsyncManualPicker(deps, { skipAudioAnalysis: true });
deps.showMpvOsd('Subsync: choose engine and subtitles'); if (opened) {
deps.showMpvOsd('Subsync: choose engine and subtitles');
}
return; return;
} }
+2
View File
@@ -488,6 +488,7 @@ test('guided subsync modal shows guidance banner, ranked candidates, browse file
harness.modal.wireDomEvents(); harness.modal.wireDomEvents();
harness.modal.openSubsyncModal( harness.modal.openSubsyncModal(
payloadWith({ payloadWith({
mediaPath: '/tmp/ep01.mkv',
guidanceMessage: 'Loaded English track appears +2.4s off audio.', guidanceMessage: 'Loaded English track appears +2.4s off audio.',
defaultEngine: 'builtin', defaultEngine: 'builtin',
builtinAvailable: true, builtinAvailable: true,
@@ -530,6 +531,7 @@ test('guided subsync modal shows guidance banner, ranked candidates, browse file
assert.deepEqual(request, { assert.deepEqual(request, {
engine: 'builtin', engine: 'builtin',
mediaPath: '/tmp/ep01.mkv',
targetTrackId: 1, targetTrackId: 1,
referenceMode: 'file', referenceMode: 'file',
referenceTrackId: null, referenceTrackId: null,
+1
View File
@@ -443,6 +443,7 @@ export function createSubsyncModal(
const request: SubsyncManualRunRequest = { const request: SubsyncManualRunRequest = {
engine, engine,
targetTrackId, targetTrackId,
...(currentPayload.mediaPath ? { mediaPath: currentPayload.mediaPath } : {}),
}; };
if (engine === 'builtin' || engine === 'alass') { if (engine === 'builtin' || engine === 'alass') {
const parsed = parseReferenceValue(referenceValue); const parsed = parseReferenceValue(referenceValue);
+24 -1
View File
@@ -4,7 +4,11 @@ import test from 'node:test';
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions'; import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions';
import { compileSessionBindings } from '../../core/services/session-bindings'; import { compileSessionBindings } from '../../core/services/session-bindings';
import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config'; import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config';
import { parseSessionActionDispatchRequest, parseUnforwardedMpvKeyReport } from './validators'; import {
parseSessionActionDispatchRequest,
parseSubsyncManualRunRequest,
parseUnforwardedMpvKeyReport,
} from './validators';
// Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the // Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the
// SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to // SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to
@@ -46,3 +50,22 @@ test('unforwarded mpv key reports accept known reasons only', () => {
assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null); assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null);
assert.equal(parseUnforwardedMpvKeyReport(null), null); assert.equal(parseUnforwardedMpvKeyReport(null), null);
}); });
test('parseSubsyncManualRunRequest validates optional mediaPath', () => {
const parsed = parseSubsyncManualRunRequest({
engine: 'builtin',
mediaPath: '/tmp/ep01.mkv',
referenceMode: 'track',
referenceTrackId: 2,
targetTrackId: 1,
});
assert.equal(parsed?.mediaPath, '/tmp/ep01.mkv');
assert.equal(
parseSubsyncManualRunRequest({
engine: 'builtin',
mediaPath: 123,
targetTrackId: 1,
}),
null,
);
});
+5
View File
@@ -317,6 +317,7 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
if (!isObject(value)) return null; if (!isObject(value)) return null;
const { const {
engine, engine,
mediaPath,
referenceMode, referenceMode,
referenceTrackId, referenceTrackId,
referenceFilePath, referenceFilePath,
@@ -328,6 +329,9 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
if (engine !== 'builtin' && engine !== 'alass' && engine !== 'ffsubsync' && engine !== 'offset') { if (engine !== 'builtin' && engine !== 'alass' && engine !== 'ffsubsync' && engine !== 'offset') {
return null; return null;
} }
if (mediaPath !== undefined && mediaPath !== null && typeof mediaPath !== 'string') {
return null;
}
if ( if (
referenceMode !== undefined && referenceMode !== undefined &&
referenceMode !== 'track' && referenceMode !== 'track' &&
@@ -366,6 +370,7 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
return { return {
engine, engine,
...(mediaPath !== undefined ? { mediaPath } : {}),
referenceMode, referenceMode,
referenceTrackId: parsedReferenceTrackId, referenceTrackId: parsedReferenceTrackId,
referenceFilePath: typeof referenceFilePath === 'string' ? referenceFilePath : null, referenceFilePath: typeof referenceFilePath === 'string' ? referenceFilePath : null,
+46
View File
@@ -6,6 +6,7 @@ import {
evaluateReferenceAlignmentToAudio, evaluateReferenceAlignmentToAudio,
evaluateReferenceAlignmentToSampledAudio, evaluateReferenceAlignmentToSampledAudio,
joinSpans, joinSpans,
wrappedCoverage,
type SampledAudioWindow, type SampledAudioWindow,
} from './alass-align'; } from './alass-align';
import { import {
@@ -208,3 +209,48 @@ test('evaluateReferenceAlignmentToSampledAudio verifies aligned vs misaligned re
const hugeEval = evaluateReferenceAlignmentToSampledAudio(hugeShiftRef, windows); const hugeEval = evaluateReferenceAlignmentToSampledAudio(hugeShiftRef, windows);
assert.equal(hugeEval.status, 'unverified'); assert.equal(hugeEval.status, 'unverified');
}); });
test('wrappedCoverage counts both fragments of a cue crossing the wrap boundary', () => {
const line = [{ start: 54, end: 58 }];
const ref = [
{ start: 0, end: 3 },
{ start: 59, end: 60 },
];
// Shifting [54, 58] by +5s in a 60s window wraps to [59, 60] (1s) + [0, 3] (3s) = 4s / 4s = 1.0.
assert.equal(wrappedCoverage(line, 4, ref, 5, 60), 1);
// Also works for shifts larger than the window length and negative shifts.
assert.equal(wrappedCoverage(line, 4, ref, 65, 60), 1);
assert.equal(
wrappedCoverage(
[{ start: 1, end: 5 }],
4,
[
{ start: 0, end: 2 },
{ start: 58, end: 60 },
],
-3,
60,
),
1,
);
});
test('alignSubtitleFileToReferenceSpans rejects broadcast pieces that collapse onto the same reference section', () => {
const actPattern = generateDialogueRhythm(7n, 1442695040888963407n).filter((s) => s.end < 120);
// Two identical target acts separated by a long pause within the standing shift range,
// while the reference only contains one matching section.
const repeatedTarget = [
...actPattern,
...actPattern.map((s) => ({ start: s.start + 150, end: s.end + 150 })),
];
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(repeatedTarget), 'dup-acts.ja.srt');
const result = alignSubtitleFileToReferenceSpans(parsedTarget, actPattern, {
calibration: 'clean',
lengthSec: 320,
allowSplits: true,
});
assert.equal(result.cut, false);
assert.equal(result.confident, false);
});
+114 -42
View File
@@ -421,28 +421,78 @@ function startsStanding(
return weakest >= PIECE_Z_MIN ? whole : Math.min(weakest, whole); return weakest >= PIECE_Z_MIN ? whole : Math.min(weakest, whole);
} }
function wrappedCoverage( function wrapSpansInPeriod(
spans: readonly SubtitleTimeSpan[],
shift: number,
period: number,
): SubtitleTimeSpan[] {
if (period <= 0 || spans.length === 0) return [];
const modShift = ((shift % period) + period) % period;
const out: SubtitleTimeSpan[] = [];
for (let i = 0; i < spans.length; i += 1) {
const line = spans[i]!;
const dur = Math.min(period, line.end - line.start);
if (dur <= 0) continue;
const wStart = (((line.start + modShift) % period) + period) % period;
const wEnd = wStart + dur;
if (wEnd <= period) {
out.push({ start: wStart, end: wEnd });
} else {
out.push({ start: wStart, end: period });
out.push({ start: 0, end: wEnd - period });
}
}
out.sort((a, b) => a.start - b.start);
return out;
}
export function wrappedCoverage(
sortedLines: readonly SubtitleTimeSpan[], sortedLines: readonly SubtitleTimeSpan[],
total: number, total: number,
joinedRef: readonly SubtitleTimeSpan[], joinedRef: readonly SubtitleTimeSpan[],
shift: number, shift: number,
lengthSec: number, lengthSec: number,
): number { ): number {
let covered = 0; if (sortedLines.length === 0 || total <= 0 || lengthSec <= 0) return 0;
if (shift >= 0) { const modShift = ((shift % lengthSec) + lengthSec) % lengthSec;
let cut = 0; const firstStart = sortedLines[0]!.start;
while (cut < sortedLines.length && sortedLines[cut]!.start + shift < lengthSec) cut += 1; const lastStart = sortedLines[sortedLines.length - 1]!.start;
covered = if (firstStart >= 0 && lastStart < lengthSec) {
coveredAt(sortedLines.slice(0, cut), joinedRef, shift) + const inRange: SubtitleTimeSpan[] = [];
coveredAt(sortedLines.slice(cut), joinedRef, shift - lengthSec); const wrapped: SubtitleTimeSpan[] = [];
} else { const crossingHeads: SubtitleTimeSpan[] = [];
let cut = 0; for (let i = 0; i < sortedLines.length; i += 1) {
while (cut < sortedLines.length && sortedLines[cut]!.start + shift < 0) cut += 1; const line = sortedLines[i]!;
covered = const dur = Math.min(lengthSec, line.end - line.start);
coveredAt(sortedLines.slice(0, cut), joinedRef, shift + lengthSec) + if (dur <= 0) continue;
coveredAt(sortedLines.slice(cut), joinedRef, shift); const shiftedStart = line.start + modShift;
if (shiftedStart < lengthSec) {
const shiftedEnd = shiftedStart + dur;
if (shiftedEnd <= lengthSec) {
inRange.push({ start: shiftedStart, end: shiftedEnd });
} else {
inRange.push({ start: shiftedStart, end: lengthSec });
crossingHeads.push({ start: 0, end: shiftedEnd - lengthSec });
}
} else {
const wStart = shiftedStart - lengthSec;
const wEnd = wStart + dur;
if (wEnd <= lengthSec) {
wrapped.push({ start: wStart, end: wEnd });
} else {
wrapped.push({ start: wStart, end: lengthSec });
crossingHeads.push({ start: 0, end: wEnd - lengthSec });
}
}
}
let covered = 0;
if (inRange.length > 0) covered += coveredAt(inRange, joinedRef, 0);
if (wrapped.length > 0) covered += coveredAt(wrapped, joinedRef, 0);
if (crossingHeads.length > 0) covered += coveredAt(crossingHeads, joinedRef, 0);
return covered / total;
} }
return covered / total; const wrapped = wrapSpansInPeriod(sortedLines, modShift, lengthSec);
return coveredAt(wrapped, joinedRef, 0) / total;
} }
export function evaluateStanding( export function evaluateStanding(
@@ -725,6 +775,29 @@ function alignBroadcastPieces(
if (pieces.length < 2 || pieces.length > MAX_PIECES) return null; if (pieces.length < 2 || pieces.length > MAX_PIECES) return null;
// Placed acts must stay in chronological reference order and must not overlap
// onto the same reference interval.
const MAX_PIECE_OVERLAP_SEC = 2.0;
let prevPlacedStart = -Infinity;
let prevPlacedEnd = -Infinity;
for (const p of pieces) {
const placedStart = scaledSorted[p.first]!.start + p.shift;
let maxRawEnd = scaledSorted[p.first]!.end;
for (let i = p.first + 1; i < p.end; i += 1) {
if (scaledSorted[i]!.end > maxRawEnd) maxRawEnd = scaledSorted[i]!.end;
}
const placedEnd = maxRawEnd + p.shift;
if (
placedStart < prevPlacedStart ||
placedEnd <= prevPlacedEnd ||
placedStart < prevPlacedEnd - MAX_PIECE_OVERLAP_SEC
) {
return null;
}
prevPlacedStart = placedStart;
prevPlacedEnd = placedEnd;
}
let weightedZSum = 0; let weightedZSum = 0;
let totalLines = 0; let totalLines = 0;
let weakest = Infinity; let weakest = Infinity;
@@ -851,29 +924,35 @@ export function alignSubtitleFileToReferenceSpans(
}; };
const plain = evaluateRatio(1.0); const plain = evaluateRatio(1.0);
const plainScore = scoreStanding(plain.standing, cal);
let chosen = plain; let chosen = plain;
// Only test framerate conversions if plain fit isn't already near-perfect or to catch PAL speedup. // Only test framerate conversions if plain fit isn't already near-perfect or to catch PAL speedup.
const altFits = FRAMERATE_RATIOS.slice(1).map(evaluateRatio); // Never replace the plain fit with an alternate that lowers final confidence.
const bestAltByAbove = altFits.reduce( const altFits = FRAMERATE_RATIOS.slice(1)
(best, cur) => (cur.standing.above > best.standing.above ? cur : best), .map(evaluateRatio)
altFits[0]!, .filter((alt) => scoreStanding(alt.standing, cal) >= plainScore);
); if (altFits.length > 0) {
const bestAltByStarts = altFits.reduce( const bestAltByAbove = altFits.reduce(
(best, cur) => (cur.standing.starts > best.standing.starts ? cur : best), (best, cur) => (cur.standing.above > best.standing.above ? cur : best),
altFits[0]!, altFits[0]!,
); );
const bestAltByStarts = altFits.reduce(
(best, cur) => (cur.standing.starts > best.standing.starts ? cur : best),
altFits[0]!,
);
if ( if (
bestAltByAbove.standing.above > plain.standing.above + 2.0 && bestAltByAbove.standing.above > plain.standing.above + 2.0 &&
bestAltByAbove.standing.above >= Math.max(4.0, cal.cutsFrom) bestAltByAbove.standing.above >= Math.max(4.0, cal.cutsFrom)
) { ) {
chosen = bestAltByAbove; chosen = bestAltByAbove;
} else if ( } else if (
bestAltByStarts.standing.starts >= STARTS_Z_MIN && bestAltByStarts.standing.starts >= STARTS_Z_MIN &&
bestAltByStarts.standing.starts > plain.standing.starts + 2.0 bestAltByStarts.standing.starts > plain.standing.starts + 2.0
) { ) {
chosen = bestAltByStarts; chosen = bestAltByStarts;
}
} }
const ratio = chosen.ratio; const ratio = chosen.ratio;
@@ -1221,14 +1300,7 @@ export function evaluateReferenceAlignmentToSampledAudio(
const shiftedWindows = localWindows.map((w) => ({ const shiftedWindows = localWindows.map((w) => ({
durationSec: w.durationSec, durationSec: w.durationSec,
speechSpans: w.speechSpans, speechSpans: w.speechSpans,
refSpans: w.refSpans refSpans: wrapSpansInPeriod(w.refSpans, targetShift, w.durationSec),
.map((s) => ({
start: (((s.start + targetShift) % w.durationSec) + w.durationSec) % w.durationSec,
end:
((((s.start + targetShift) % w.durationSec) + w.durationSec) % w.durationSec) +
(s.end - s.start),
}))
.sort((a, b) => a.start - b.start),
})); }));
let hereCovered = 0; let hereCovered = 0;
+87 -1
View File
@@ -1,6 +1,15 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { detectSpeechSpansFromPcm, parseRawSileroVadSegments } from './audio-speech'; import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
clearAudioSpeechCache,
detectSpeechSpansFromPcm,
extractAudioSpeechSpans,
getCachedAudioSpeechSpans,
parseRawSileroVadSegments,
} from './audio-speech';
test('detectSpeechSpansFromPcm detects voice-band bursts separated by quiet background', () => { test('detectSpeechSpansFromPcm detects voice-band bursts separated by quiet background', () => {
const sampleRate = 8000; const sampleRate = 8000;
@@ -54,3 +63,80 @@ test('parseRawSileroVadSegments parses fine-grained speech segments from whisper
{ start: 5.105, end: 6.9 }, { start: 5.105, end: 6.9 },
]); ]);
}); });
test('audio speech cache keys distinguish built-in VAD from Silero VAD config', async () => {
if (process.platform === 'win32') return;
clearAudioSpeechCache();
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-vad-cache-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const modelPath = path.join(tmpDir, 'silero.bin');
const ffmpegScript = path.join(tmpDir, 'ffmpeg.sh');
const vadScript = path.join(tmpDir, 'whisper-vad.sh');
fs.writeFileSync(videoPath, 'video');
fs.writeFileSync(modelPath, 'model');
// Fake ffmpeg outputs silence for pipe:1 (built-in VAD) and a tiny WAV when given an output file (Silero).
fs.writeFileSync(
ffmpegScript,
`#!/bin/sh
last=""
for arg in "$@"; do last="$arg"; done
if [ "$last" = "pipe:1" ]; then
dd if=/dev/zero bs=1600 count=1 2>/dev/null
else
printf 'RIFF....WAVEdata................................................' > "$last"
fi
exit 0
`,
{ mode: 0o755 },
);
fs.chmodSync(ffmpegScript, 0o755);
fs.writeFileSync(
vadScript,
`#!/bin/sh
echo "Speech segment 0: start = 100.00, end = 300.00"
exit 0
`,
{ mode: 0o755 },
);
fs.chmodSync(vadScript, 0o755);
try {
const builtin = await extractAudioSpeechSpans({
ffmpegPath: ffmpegScript,
videoPath,
audioStreamIndex: 1,
});
assert.equal(builtin.source, 'builtin-vad');
assert.equal(builtin.spans.length, 0);
assert.ok(getCachedAudioSpeechSpans(videoPath, 1) !== null);
assert.equal(
getCachedAudioSpeechSpans(videoPath, 1, {
vadExecutablePath: vadScript,
vadModelPath: modelPath,
}),
null,
);
const silero = await extractAudioSpeechSpans({
ffmpegPath: ffmpegScript,
videoPath,
audioStreamIndex: 1,
vadExecutablePath: vadScript,
vadModelPath: modelPath,
});
assert.equal(silero.source, 'silero-vad');
assert.deepEqual(silero.spans, [{ start: 1.0, end: 3.0 }]);
assert.equal(
getCachedAudioSpeechSpans(videoPath, 1, {
vadExecutablePath: vadScript,
vadModelPath: modelPath,
})?.source,
'silero-vad',
);
} finally {
clearAudioSpeechCache();
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
+37 -7
View File
@@ -9,7 +9,7 @@ import {
type ParsedSubtitleFile, type ParsedSubtitleFile,
type SubtitleTimeSpan, type SubtitleTimeSpan,
} from './subtitle-lines'; } from './subtitle-lines';
import { fileExists, resolveCommandInvocation, runCommand } from './utils'; import { extensionToFfmpegMuxer, fileExists, resolveCommandInvocation, runCommand } from './utils';
const PCM_VAD_SAMPLE_RATE = 8000; const PCM_VAD_SAMPLE_RATE = 8000;
const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400'; const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400';
@@ -73,17 +73,35 @@ function buildFileSignatureKey(videoPath: string): string | null {
} }
} }
function buildAudioCacheKey(videoPath: string, audioStreamIndex: number | null): string | null { function buildVadConfigKey(
vadExecutablePath?: string | null,
vadModelPath?: string | null,
): string {
const exec = vadExecutablePath?.trim() ?? '';
const model = vadModelPath?.trim() ?? '';
if (exec.length > 0 && model.length > 0 && fileExists(model)) {
return `silero:${exec}\0${model}`;
}
return 'builtin';
}
function buildAudioCacheKey(
videoPath: string,
audioStreamIndex: number | null,
vadConfigKey = 'builtin',
): string | null {
const sig = buildFileSignatureKey(videoPath); const sig = buildFileSignatureKey(videoPath);
if (!sig) return null; if (!sig) return null;
return `${sig}\0${audioStreamIndex ?? 'default'}`; return `${sig}\0${audioStreamIndex ?? 'default'}\0${vadConfigKey}`;
} }
export function getCachedAudioSpeechSpans( export function getCachedAudioSpeechSpans(
videoPath: string, videoPath: string,
audioStreamIndex: number | null, audioStreamIndex: number | null,
vadConfig?: { vadExecutablePath?: string | null; vadModelPath?: string | null } | null,
): AudioSpeechResult | null { ): AudioSpeechResult | null {
const key = buildAudioCacheKey(videoPath, audioStreamIndex); const vadKey = buildVadConfigKey(vadConfig?.vadExecutablePath, vadConfig?.vadModelPath);
const key = buildAudioCacheKey(videoPath, audioStreamIndex, vadKey);
return key ? (audioSpeechCache.get(key) ?? null) : null; return key ? (audioSpeechCache.get(key) ?? null) : null;
} }
@@ -295,6 +313,7 @@ function streamFfmpegPcm(
const invocation = resolveCommandInvocation(ffmpegPath, args); const invocation = resolveCommandInvocation(ffmpegPath, args);
const child = childProcess.spawn(invocation.command, invocation.args, { const child = childProcess.spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
}); });
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let stderr = ''; let stderr = '';
@@ -435,7 +454,8 @@ async function trySileroVadSpeech(
export async function extractAudioSpeechSpans( export async function extractAudioSpeechSpans(
options: ExtractAudioSpeechOptions, options: ExtractAudioSpeechOptions,
): Promise<AudioSpeechResult> { ): Promise<AudioSpeechResult> {
const cacheKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex); const vadKey = buildVadConfigKey(options.vadExecutablePath, options.vadModelPath);
const cacheKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex, vadKey);
if (cacheKey) { if (cacheKey) {
const cached = audioSpeechCache.get(cacheKey); const cached = audioSpeechCache.get(cacheKey);
if (cached) return cached; if (cached) return cached;
@@ -479,6 +499,7 @@ function spawnFfmpegWithStdout(
const invocation = resolveCommandInvocation(ffmpegPath, args); const invocation = resolveCommandInvocation(ffmpegPath, args);
const child = childProcess.spawn(invocation.command, invocation.args, { const child = childProcess.spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
}); });
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let stderr = ''; let stderr = '';
@@ -644,7 +665,8 @@ export async function extractSinglePassRipMedia(
options: SinglePassRipMediaOptions, options: SinglePassRipMediaOptions,
): Promise<SinglePassRipMediaResult | null> { ): Promise<SinglePassRipMediaResult | null> {
const fileKey = buildFileSignatureKey(options.videoPath); const fileKey = buildFileSignatureKey(options.videoPath);
const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex); const vadKey = buildVadConfigKey(options.vadExecutablePath, options.vadModelPath);
const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex, vadKey);
const cachedSubs = const cachedSubs =
(fileKey ? embeddedSubtitlesCache.get(fileKey) : undefined) ?? (fileKey ? embeddedSubtitlesCache.get(fileKey) : undefined) ??
@@ -683,7 +705,15 @@ export async function extractSinglePassRipMedia(
const trackOutputs: Array<{ ffIndex: number; outPath: string }> = []; const trackOutputs: Array<{ ffIndex: number; outPath: string }> = [];
for (const track of missingTracks) { for (const track of missingTracks) {
const outPath = path.join(tempDir, `track_${track.ffIndex}.${track.extension}`); const outPath = path.join(tempDir, `track_${track.ffIndex}.${track.extension}`);
args.push('-vn', '-an', '-map', `0:${track.ffIndex}`, '-f', track.extension, outPath); args.push(
'-vn',
'-an',
'-map',
`0:${track.ffIndex}`,
'-f',
extensionToFfmpegMuxer(track.extension),
outPath,
);
trackOutputs.push({ ffIndex: track.ffIndex, outPath }); trackOutputs.push({ ffIndex: track.ffIndex, outPath });
} }
+9
View File
@@ -164,6 +164,15 @@ test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable b
const lossy = decodeSubtitleBytesWithStatus(corrupt); const lossy = decodeSubtitleBytesWithStatus(corrupt);
assert.equal(lossy.lossless, false); assert.equal(lossy.lossless, false);
// Ambiguous bytes valid in both Shift_JIS and EUC-JP (e.g. EUC-JP 'あ' = A4 A2) must not be marked lossless.
const ambiguousEucJp = new Uint8Array([0xa4, 0xa2]);
const ambiguousResult = decodeSubtitleBytesWithStatus(ambiguousEucJp);
assert.equal(ambiguousResult.lossless, false);
// Unambiguous Shift_JIS bytes (0x82 0xA0 = 'あ', invalid in UTF-8 and EUC-JP) remain lossless.
const unambiguousSjis = new Uint8Array([0x82, 0xa0]);
assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), { text: 'あ', lossless: true });
const srt = formatSpansAsSrt([ const srt = formatSpansAsSrt([
{ start: 5.5, end: 7.0 }, { start: 5.5, end: 7.0 },
{ start: 1.25, end: 2.75 }, { start: 1.25, end: 2.75 },
+9 -3
View File
@@ -122,13 +122,19 @@ export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitl
return { text: strictUtf8, lossless: true }; return { text: strictUtf8, lossless: true };
} }
const shiftJis = tryDecode(bytes, 'shift_jis', true); const shiftJis = tryDecode(bytes, 'shift_jis', true);
if (shiftJis !== null) { const eucJp = tryDecode(bytes, 'euc-jp', true);
if (shiftJis !== null && eucJp === null) {
return { text: shiftJis, lossless: true }; return { text: shiftJis, lossless: true };
} }
const eucJp = tryDecode(bytes, 'euc-jp', true); if (eucJp !== null && shiftJis === null) {
if (eucJp !== null) {
return { text: eucJp, lossless: true }; return { text: eucJp, lossless: true };
} }
if (shiftJis !== null && eucJp !== null) {
if (shiftJis === eucJp) {
return { text: shiftJis, lossless: true };
}
return { text: eucJp, lossless: false };
}
return { text: new TextDecoder('utf-8').decode(bytes), lossless: false }; return { text: new TextDecoder('utf-8').decode(bytes), lossless: false };
} }
+37 -1
View File
@@ -3,13 +3,23 @@ import assert from 'node:assert/strict';
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import * as os from 'node:os'; import * as os from 'node:os';
import * as path from 'node:path'; import * as path from 'node:path';
import { codecToExtension, findSubsyncExecutable, getSubsyncConfig } from './utils'; import {
candidateExecutableNames,
codecToExtension,
extensionToFfmpegMuxer,
findSubsyncExecutable,
getSubsyncConfig,
resolveCommandInvocation,
} from './utils';
test('codecToExtension maps stream/web formats to ffmpeg extractable extensions', () => { test('codecToExtension maps stream/web formats to ffmpeg extractable extensions', () => {
assert.equal(codecToExtension('subrip'), 'srt'); assert.equal(codecToExtension('subrip'), 'srt');
assert.equal(codecToExtension('webvtt'), 'vtt'); assert.equal(codecToExtension('webvtt'), 'vtt');
assert.equal(codecToExtension('vtt'), 'vtt'); assert.equal(codecToExtension('vtt'), 'vtt');
assert.equal(codecToExtension('ttml'), 'ttml'); assert.equal(codecToExtension('ttml'), 'ttml');
assert.equal(extensionToFfmpegMuxer('vtt'), 'webvtt');
assert.equal(extensionToFfmpegMuxer('srt'), 'srt');
assert.equal(extensionToFfmpegMuxer('ass'), 'ass');
}); });
test('codecToExtension returns null for unsupported codecs', () => { test('codecToExtension returns null for unsupported codecs', () => {
@@ -58,3 +68,29 @@ test('findSubsyncExecutable skips non-executable files on POSIX and resolves bar
fs.rmSync(dirB, { recursive: true, force: true }); fs.rmSync(dirB, { recursive: true, force: true });
} }
}); });
test('Windows candidate discovery excludes extensionless shims and escapes cmd.exe batch arguments', () => {
assert.deepEqual(candidateExecutableNames('ffsubsync', 'win32', '.COM;.EXE;.BAT;.CMD'), [
'ffsubsync.COM',
'ffsubsync.EXE',
'ffsubsync.BAT',
'ffsubsync.CMD',
]);
assert.deepEqual(candidateExecutableNames('ffsubsync.exe', 'win32', '.EXE;.CMD'), [
'ffsubsync.exe',
]);
const invocation = resolveCommandInvocation(
'C:\\Tools\\ffsubsync.cmd',
['C:\\Videos\\Show & (Remix) [1080p].mkv', '-i', 'C:\\Subs\\ep1.srt'],
'win32',
);
assert.equal(invocation.windowsVerbatimArguments, true);
assert.equal(invocation.args[0], '/d');
assert.equal(invocation.args[1], '/s');
assert.equal(invocation.args[2], '/v:off');
assert.equal(invocation.args[3], '/c');
assert.ok(invocation.args[4]!.includes('^&'));
assert.ok(invocation.args[4]!.includes('^('));
assert.ok(invocation.args[4]!.includes('^)'));
});
+27 -9
View File
@@ -2,6 +2,10 @@ import * as fs from 'fs';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import * as path from 'path'; import * as path from 'path';
import { DEFAULT_CONFIG } from '../config'; import { DEFAULT_CONFIG } from '../config';
import {
buildWindowsShimInvocation,
isWindowsCommandShim,
} from '../core/utils/windows-command-shim';
import { SubsyncConfig, SubsyncMode } from '../types'; import { SubsyncConfig, SubsyncMode } from '../types';
export interface MpvTrack { export interface MpvTrack {
@@ -47,13 +51,18 @@ function isExecutablePath(filePath: string): boolean {
} }
} }
function candidateExecutableNames(name: string): string[] { export function candidateExecutableNames(
if (process.platform !== 'win32' || path.extname(name)) return [name]; name: string,
const extensions = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT') platform: NodeJS.Platform = process.platform,
pathExt: string | undefined = process.env.PATHEXT,
): string[] {
if (platform !== 'win32' || path.extname(name)) return [name];
const extensions = (pathExt ?? '.COM;.EXE;.BAT;.CMD')
.split(';') .split(';')
.map((ext) => ext.trim()) .map((ext) => ext.trim())
.filter((ext) => ext.length > 0 && WINDOWS_RUNNABLE_EXTENSIONS.has(ext.toLowerCase())); .filter((ext) => ext.length > 0 && WINDOWS_RUNNABLE_EXTENSIONS.has(ext.toLowerCase()));
return [name, ...extensions.map((ext) => `${name}${ext}`)]; const effective = extensions.length > 0 ? extensions : ['.exe', '.com', '.cmd', '.bat'];
return effective.map((ext) => `${name}${ext}`);
} }
/** /**
@@ -117,8 +126,9 @@ export interface CommandResult {
export function resolveCommandInvocation( export function resolveCommandInvocation(
executable: string, executable: string,
args: string[], args: string[],
): { command: string; args: string[] } { platform: NodeJS.Platform = process.platform,
if (process.platform !== 'win32') { ): { command: string; args: string[]; windowsVerbatimArguments?: boolean } {
if (platform !== 'win32') {
return { command: executable, args }; return { command: executable, args };
} }
@@ -133,10 +143,12 @@ export function resolveCommandInvocation(
return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`; return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`;
}; };
const extension = path.extname(executable).toLowerCase(); const extension = path.extname(executable).toLowerCase();
if (extension === '.cmd' || extension === '.bat') { if (isWindowsCommandShim(executable)) {
const shim = buildWindowsShimInvocation(executable, args, process.env);
return { return {
command: process.env.ComSpec || 'cmd.exe', command: shim.file,
args: ['/d', '/c', executable, ...args], args: shim.args,
windowsVerbatimArguments: true,
}; };
} }
if (extension === '.ps1') { if (extension === '.ps1') {
@@ -233,6 +245,11 @@ export function codecToExtension(codec: string | undefined): string | null {
return null; return null;
} }
export function extensionToFfmpegMuxer(extension: string): string {
if (extension === 'vtt') return 'webvtt';
return extension;
}
export function runCommand( export function runCommand(
executable: string, executable: string,
args: string[], args: string[],
@@ -242,6 +259,7 @@ export function runCommand(
const invocation = resolveCommandInvocation(executable, args); const invocation = resolveCommandInvocation(executable, args);
const child = childProcess.spawn(invocation.command, invocation.args, { const child = childProcess.spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
}); });
let stdout = ''; let stdout = '';
let stderr = ''; let stderr = '';
+4
View File
@@ -124,6 +124,8 @@ export interface SubsyncManualPayload {
defaultTargetTrackId: number | null; defaultTargetTrackId: number | null;
videoReferenceAvailable: boolean; videoReferenceAvailable: boolean;
ffsubsyncAvailable: boolean; ffsubsyncAvailable: boolean;
/** Normalized media path this picker payload was built for. */
mediaPath?: string | null;
/** Optional guidance shown when automatic sync hands off to the modal. */ /** Optional guidance shown when automatic sync hands off to the modal. */
guidanceMessage?: string | null; guidanceMessage?: string | null;
/** Ranked candidate references (loaded tracks, unloaded tracks, sidecar files, audio). */ /** Ranked candidate references (loaded tracks, unloaded tracks, sidecar files, audio). */
@@ -142,6 +144,8 @@ export type SubsyncReferenceMode = 'track' | 'video' | 'file';
export interface SubsyncManualRunRequest { export interface SubsyncManualRunRequest {
engine: SubsyncEngine; engine: SubsyncEngine;
/** Media path captured when the picker opened, verified against the active video before running. */
mediaPath?: string | null;
/** Reference source: another subtitle track, the loaded video/audio, or a local file on disk. */ /** Reference source: another subtitle track, the loaded video/audio, or a local file on disk. */
referenceMode?: SubsyncReferenceMode; referenceMode?: SubsyncReferenceMode;
referenceTrackId?: number | null; referenceTrackId?: number | null;