fix(subsync): stage external output and harden path and encoding guards

This commit is contained in:
sudacode committed 2026-11-25 21:00:32 -08:00
1 parent fc113cfbca
commit 58c0dfaed2
2 files changed
+253 -25

No files matched your search

+215 -7
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import * as fs from 'fs'; import * as fs from 'fs';
import * as os from 'os'; import * as os from 'os';
import * as path from 'path'; import * as path from 'path';
import { pathToFileURL } from 'url';
import { import {
TriggerSubsyncFromConfigDeps, TriggerSubsyncFromConfigDeps,
runSubsyncManual, runSubsyncManual,
@@ -78,6 +79,7 @@ test('triggerSubsyncFromConfig opens manual picker', async () => {
await triggerSubsyncFromConfig( await triggerSubsyncFromConfig(
makeDeps({ makeDeps({
getResolvedConfig: () => ({ getResolvedConfig: () => ({
mode: 'manual',
alassPath: process.execPath, alassPath: process.execPath,
ffsubsyncPath: process.execPath, ffsubsyncPath: process.execPath,
ffmpegPath: process.execPath, ffmpegPath: process.execPath,
@@ -530,8 +532,13 @@ test('runSubsyncManual constructs ffsubsync command and returns success', async
assert.ok(ffArgs.includes('0:2')); assert.ok(ffArgs.includes('0:2'));
const ffOutputFlagIndex = ffArgs.indexOf('-o'); const ffOutputFlagIndex = ffArgs.indexOf('-o');
assert.equal(ffOutputFlagIndex >= 0, true); assert.equal(ffOutputFlagIndex >= 0, true);
assert.equal(ffArgs[ffOutputFlagIndex + 1], toShellPath(primaryPath)); const stagedArg = ffArgs[ffOutputFlagIndex + 1]!;
assert.equal(sentCommands[0]?.[0], 'sub-add'); assert.equal(path.dirname(fromShellPath(stagedArg)), tmpDir);
assert.equal(path.extname(stagedArg), '.srt');
assert.notEqual(stagedArg, toShellPath(primaryPath));
assert.equal(fs.existsSync(fromShellPath(stagedArg)), false);
assert.equal(fs.existsSync(primaryPath), true);
assert.deepEqual(sentCommands[0], ['sub-add', primaryPath]);
assert.deepEqual(sentCommands[1], ['set_property', 'sub-delay', 0]); assert.deepEqual(sentCommands[1], ['set_property', 'sub-delay', 0]);
}); });
@@ -590,8 +597,12 @@ test('runSubsyncManual writes deterministic _retimed filename when replace is fa
const ffArgs = fs.readFileSync(ffsubsyncLogPath, 'utf8').trim().split('\n'); const ffArgs = fs.readFileSync(ffsubsyncLogPath, 'utf8').trim().split('\n');
const ffOutputFlagIndex = ffArgs.indexOf('-o'); const ffOutputFlagIndex = ffArgs.indexOf('-o');
assert.equal(ffOutputFlagIndex >= 0, true); assert.equal(ffOutputFlagIndex >= 0, true);
const outputPath = ffArgs[ffOutputFlagIndex + 1]; const stagedOutputArg = ffArgs[ffOutputFlagIndex + 1]!;
assert.equal(outputPath, toShellPath(path.join(tmpDir, 'episode.ja_retimed.srt'))); const expectedRetimedPath = path.join(tmpDir, 'episode.ja_retimed.srt');
assert.equal(path.dirname(fromShellPath(stagedOutputArg)), tmpDir);
assert.equal(path.extname(stagedOutputArg), '.srt');
assert.equal(fs.existsSync(fromShellPath(stagedOutputArg)), false);
assert.equal(fs.existsSync(expectedRetimedPath), true);
}); });
test('runSubsyncManual reports ffsubsync command failures with details', async () => { test('runSubsyncManual reports ffsubsync command failures with details', async () => {
@@ -1013,7 +1024,8 @@ test('runSubsyncManual resolves string sid values from mpv stream properties', a
const outputPath = ffArgs[syncOutputIndex + 1]; const outputPath = ffArgs[syncOutputIndex + 1];
assert.equal(typeof outputPath, 'string'); assert.equal(typeof outputPath, 'string');
assert.ok(outputPath!.length > 0); assert.ok(outputPath!.length > 0);
assert.equal(fs.readFileSync(fromShellPath(outputPath!), 'utf8'), ''); assert.equal(fs.existsSync(fromShellPath(outputPath!)), false);
assert.equal(fs.readFileSync(primaryPath, 'utf8'), '');
}); });
function generateSyntheticSpans( function generateSyntheticSpans(
@@ -1889,9 +1901,9 @@ test('runSubsyncManual rejects stale submissions when active video changed since
test('triggerSubsyncFromConfig normalizes file:// video URLs as local media', async () => { test('triggerSubsyncFromConfig normalizes file:// video URLs as local media', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-file-url-')); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-file-url-'));
const videoPath = path.join(tmpDir, 'ep01.mkv'); const videoPath = path.join(tmpDir, 'ep#01.mkv');
fs.writeFileSync(videoPath, 'video'); fs.writeFileSync(videoPath, 'video');
const fileUrl = `file://${videoPath}`; const fileUrl = pathToFileURL(videoPath).href;
let capturedPayload: SubsyncManualPayload | null = null; let capturedPayload: SubsyncManualPayload | null = null;
await triggerSubsyncFromConfig( await triggerSubsyncFromConfig(
@@ -2190,3 +2202,199 @@ test('triggerSubsyncFromConfig resets non-zero sub-delay when already in sync wi
assert.equal(fs.statSync(targetPath).mtimeMs, mtimeBefore); assert.equal(fs.statSync(targetPath).mtimeMs, mtimeBefore);
assert.ok(osd.some((line) => line.includes('Reset subtitle delay to 0s'))); assert.ok(osd.some((line) => line.includes('Reset subtitle delay to 0s')));
}); });
test('runSubsyncManual stages external engine output and preserves original when playback switches mid-run', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-external-stage-'));
const ffsubsyncPath = path.join(tmpDir, 'ffsubsync.sh');
const ffmpegPath = path.join(tmpDir, 'ffmpeg.sh');
const alassPath = path.join(tmpDir, 'alass.sh');
const videoA = path.join(tmpDir, 'ep01.mkv');
const videoB = path.join(tmpDir, 'ep02.mkv');
const primaryPath = path.join(tmpDir, 'primary.srt');
const originalContent = '1\n00:00:01,000 --> 00:00:02,000\noriginal\n';
fs.writeFileSync(videoA, 'a');
fs.writeFileSync(videoB, 'b');
fs.writeFileSync(primaryPath, originalContent, 'utf8');
writeExecutableScript(ffmpegPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript(alassPath, '#!/bin/sh\nexit 0\n');
writeExecutableScript(
ffsubsyncPath,
'#!/bin/sh\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then printf "overwritten" > "$out"; fi\nexit 0\n',
);
let pathCalls = 0;
const sentCommands: Array<Array<string | number>> = [];
const result = await runSubsyncManual(
{ engine: 'ffsubsync', mediaPath: videoA },
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: (payload) => {
sentCommands.push(payload.command);
},
requestProperty: async (name: string) => {
if (name === 'path') {
pathCalls += 1;
return pathCalls === 1 ? videoA : 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,
'external-filename': primaryPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath,
ffsubsyncPath,
ffmpegPath,
replace: true,
}),
}),
);
assert.equal(result.ok, false);
assert.match(result.message, /Playback changed/i);
assert.equal(fs.readFileSync(primaryPath, 'utf8'), originalContent);
assert.deepEqual(sentCommands, []);
const leftoverStaged = fs
.readdirSync(tmpDir)
.filter((name) => name.startsWith('.subminer-subsync-'));
assert.deepEqual(leftoverStaged, []);
});
test('runSubsyncManual preserves POSIX trailing whitespace and backslash distinctions in mediaPath', async () => {
if (process.platform === 'win32') return;
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-posix-paths-'));
const trailingSpaceVideo = path.join(tmpDir, 'episode.mkv ');
const subPath = path.join(tmpDir, 'episode.srt');
fs.writeFileSync(trailingSpaceVideo, 'video');
fs.writeFileSync(subPath, '1\n00:00:01,000 --> 00:00:02,000\nhello\n', 'utf8');
const okResult = await runSubsyncManual(
{ engine: 'offset', mediaPath: trailingSpaceVideo, targetTrackId: 1, offsetMs: 500 },
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return trailingSpaceVideo;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
'external-filename': subPath,
},
];
}
return null;
},
}),
}),
);
assert.equal(okResult.ok, true);
const slashVideo = path.join(tmpDir, 'show', 'episode.mkv');
const backslashVideo = path.join(tmpDir, 'show\\episode.mkv');
const mismatchResult = await runSubsyncManual(
{ engine: 'offset', mediaPath: backslashVideo, targetTrackId: 1, offsetMs: 500 },
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return slashVideo;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
'external-filename': subPath,
},
];
}
return null;
},
}),
}),
);
assert.equal(mismatchResult.ok, false);
assert.match(mismatchResult.message, /Active video changed/i);
});
test('runSubsyncManual refuses to write ambiguous Shift_JIS/EUC-JP output even when replace is false', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-ambiguous-noreplace-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ambiguous.srt');
const retimedPath = path.join(tmpDir, 'ambiguous_retimed.srt');
fs.writeFileSync(videoPath, 'video');
const ambiguousBytes = Buffer.concat([
Buffer.from('1\n00:00:01,000 --> 00:00:02,500\n', 'utf8'),
Buffer.from([0xa4, 0xa2]),
Buffer.from('\n', 'utf8'),
]);
fs.writeFileSync(targetPath, ambiguousBytes);
const result = await runSubsyncManual(
{ engine: 'offset', offsetMs: 500 },
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
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': targetPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: false,
}),
}),
);
assert.equal(result.ok, false);
assert.match(result.message, /losslessly/i);
assert.deepEqual(fs.readFileSync(targetPath), ambiguousBytes);
assert.equal(fs.existsSync(retimedPath), false);
});
+38 -18
View File
@@ -385,8 +385,8 @@ function buildRetimedPath(subPath: string, replace: boolean): string {
return path.join(parsed.dir, `${parsed.name}_retimed${parsed.ext || '.srt'}`); return path.join(parsed.dir, `${parsed.name}_retimed${parsed.ext || '.srt'}`);
} }
const LOSSY_REPLACE_ERROR_MESSAGE = const LOSSY_REWRITE_ERROR_MESSAGE =
'Cannot safely replace subtitle file in place because its text encoding could not be decoded losslessly. Set subsync.replace to false or convert the file to UTF-8.'; 'Cannot safely rewrite subtitle file because its text encoding could not be decoded unambiguously and losslessly. Convert the file to UTF-8 and retry.';
function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile { function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile {
const bytes = fs.readFileSync(filePath); const bytes = fs.readFileSync(filePath);
@@ -503,11 +503,13 @@ function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }
// mpv may echo the path back with different separators, and Windows paths are // Windows local paths are case-insensitive and mpv may echo them with different
// case-insensitive, so compare normalized forms instead of raw strings. // separators; on POSIX, backslashes are valid filename characters and must stay distinct.
function normalizeSubtitlePathForCompare(value: string): string { function normalizeSubtitlePathForCompare(value: string): string {
const normalized = value.replace(/\\/g, '/'); if (process.platform === 'win32' && !isRemoteMediaPath(value)) {
return process.platform === 'win32' ? normalized.toLowerCase() : normalized; return value.replace(/\\/g, '/').toLowerCase();
}
return value;
} }
async function findAddedSubtitleTrackId( async function findAddedSubtitleTrackId(
@@ -965,8 +967,8 @@ async function runBuiltinSubsync(
if (parsedTarget.events.length === 0) { if (parsedTarget.events.length === 0) {
return { ok: false, message: 'Target subtitle file has no readable dialogue cues.' }; return { ok: false, message: 'Target subtitle file has no readable dialogue cues.' };
} }
if (replaceTarget && parsedTarget.lossless === false) { if (parsedTarget.lossless === false) {
return { ok: false, message: LOSSY_REPLACE_ERROR_MESSAGE }; return { ok: false, message: LOSSY_REWRITE_ERROR_MESSAGE };
} }
let referenceSpans: SubtitleTimeSpan[] = []; let referenceSpans: SubtitleTimeSpan[] = [];
@@ -1095,8 +1097,8 @@ async function runManualOffsetSubsync(
if (parsedTarget.events.length === 0) { if (parsedTarget.events.length === 0) {
return { ok: false, message: 'Target subtitle file has no readable cues to shift.' }; return { ok: false, message: 'Target subtitle file has no readable cues to shift.' };
} }
if (replaceTarget && parsedTarget.lossless === false) { if (parsedTarget.lossless === false) {
return { ok: false, message: LOSSY_REPLACE_ERROR_MESSAGE }; return { ok: false, message: LOSSY_REWRITE_ERROR_MESSAGE };
} }
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);
@@ -1138,24 +1140,34 @@ async function subsyncToReference(
); );
const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const replaceTarget = resolved.replace !== false && !targetExtraction.temporary;
const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget);
const parsedOutput = path.parse(outputPath);
const stagedOutputPath = path.join(
parsedOutput.dir,
`.subminer-subsync-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}${parsedOutput.ext || '.srt'}`,
);
try { try {
let result: CommandResult; let result: CommandResult;
if (engine === 'alass') { if (engine === 'alass') {
const alassPath = ensureExecutablePath(resolved.alassPath, 'alass'); const alassPath = ensureExecutablePath(resolved.alassPath, 'alass');
result = await runAlassSync(alassPath, referenceFilePath, targetExtraction.path, outputPath); result = await runAlassSync(
alassPath,
referenceFilePath,
targetExtraction.path,
stagedOutputPath,
);
} else { } else {
const ffsubsyncPath = ensureExecutablePath(resolved.ffsubsyncPath, 'ffsubsync'); const ffsubsyncPath = ensureExecutablePath(resolved.ffsubsyncPath, 'ffsubsync');
result = await runFfsubsyncSync( result = await runFfsubsyncSync(
ffsubsyncPath, ffsubsyncPath,
context.videoPath, context.videoPath,
targetExtraction.path, targetExtraction.path,
outputPath, stagedOutputPath,
context.audioStreamIndex, context.audioStreamIndex,
); );
} }
if (!result.ok || !fileExists(outputPath)) { if (!result.ok || !fileExists(stagedOutputPath)) {
const details = summarizeCommandFailure(engine, result); const details = summarizeCommandFailure(engine, result);
return { return {
ok: false, ok: false,
@@ -1167,12 +1179,20 @@ async function subsyncToReference(
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
} }
fs.renameSync(stagedOutputPath, outputPath);
await loadSyncedSubtitle(client, outputPath, slot); await loadSyncedSubtitle(client, outputPath, slot);
return { return {
ok: true, ok: true,
message: `Subtitle synchronized with ${engine}`, message: `Subtitle synchronized with ${engine}`,
}; };
} finally { } finally {
try {
if (fs.existsSync(stagedOutputPath)) {
fs.unlinkSync(stagedOutputPath);
}
} catch {
// Best-effort cleanup of staged external-engine output.
}
cleanupTemporaryFile(targetExtraction); cleanupTemporaryFile(targetExtraction);
} }
} }
@@ -1233,9 +1253,9 @@ export async function runSubsyncManual(
const resolved = deps.getResolvedConfig(); const resolved = deps.getResolvedConfig();
if (request.mediaPath !== undefined && request.mediaPath !== null) { if (request.mediaPath !== undefined && request.mediaPath !== null) {
const trimmedMediaPath = request.mediaPath.trim(); const expectedVideoPath =
const expectedVideoPath = trimmedMediaPath request.mediaPath.trim().length > 0
? normalizeMediaVideoPath(trimmedMediaPath, context.workingDirectory) ? normalizeMediaVideoPath(request.mediaPath, context.workingDirectory)
: ''; : '';
if ( if (
!expectedVideoPath || !expectedVideoPath ||
@@ -1584,8 +1604,8 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
deps.showMpvOsd(`Subtitles are already in sync (${sourceLabel})`); deps.showMpvOsd(`Subtitles are already in sync (${sourceLabel})`);
return; return;
} }
if (replaceTarget && parsedTarget.lossless === false) { if (parsedTarget.lossless === false) {
deps.showMpvOsd(`Subsync failed: ${LOSSY_REPLACE_ERROR_MESSAGE}`); deps.showMpvOsd(`Subsync failed: ${LOSSY_REWRITE_ERROR_MESSAGE}`);
return; return;
} }
writeRetimedContent(outputPath, alignment.rewrittenContent); writeRetimedContent(outputPath, alignment.rewrittenContent);