mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
fix(subsync): address PR review findings and deterministic CI check
This commit is contained in:
16 files changed
+852
-82
No files matched your search
@@ -6,6 +6,7 @@ import {
|
||||
evaluateReferenceAlignmentToAudio,
|
||||
evaluateReferenceAlignmentToSampledAudio,
|
||||
joinSpans,
|
||||
wrappedCoverage,
|
||||
type SampledAudioWindow,
|
||||
} from './alass-align';
|
||||
import {
|
||||
@@ -208,3 +209,48 @@ test('evaluateReferenceAlignmentToSampledAudio verifies aligned vs misaligned re
|
||||
const hugeEval = evaluateReferenceAlignmentToSampledAudio(hugeShiftRef, windows);
|
||||
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
@@ -421,28 +421,78 @@ function startsStanding(
|
||||
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[],
|
||||
total: number,
|
||||
joinedRef: readonly SubtitleTimeSpan[],
|
||||
shift: number,
|
||||
lengthSec: number,
|
||||
): number {
|
||||
let covered = 0;
|
||||
if (shift >= 0) {
|
||||
let cut = 0;
|
||||
while (cut < sortedLines.length && sortedLines[cut]!.start + shift < lengthSec) cut += 1;
|
||||
covered =
|
||||
coveredAt(sortedLines.slice(0, cut), joinedRef, shift) +
|
||||
coveredAt(sortedLines.slice(cut), joinedRef, shift - lengthSec);
|
||||
} else {
|
||||
let cut = 0;
|
||||
while (cut < sortedLines.length && sortedLines[cut]!.start + shift < 0) cut += 1;
|
||||
covered =
|
||||
coveredAt(sortedLines.slice(0, cut), joinedRef, shift + lengthSec) +
|
||||
coveredAt(sortedLines.slice(cut), joinedRef, shift);
|
||||
if (sortedLines.length === 0 || total <= 0 || lengthSec <= 0) return 0;
|
||||
const modShift = ((shift % lengthSec) + lengthSec) % lengthSec;
|
||||
const firstStart = sortedLines[0]!.start;
|
||||
const lastStart = sortedLines[sortedLines.length - 1]!.start;
|
||||
if (firstStart >= 0 && lastStart < lengthSec) {
|
||||
const inRange: SubtitleTimeSpan[] = [];
|
||||
const wrapped: SubtitleTimeSpan[] = [];
|
||||
const crossingHeads: SubtitleTimeSpan[] = [];
|
||||
for (let i = 0; i < sortedLines.length; i += 1) {
|
||||
const line = sortedLines[i]!;
|
||||
const dur = Math.min(lengthSec, line.end - line.start);
|
||||
if (dur <= 0) continue;
|
||||
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(
|
||||
@@ -725,6 +775,29 @@ function alignBroadcastPieces(
|
||||
|
||||
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 totalLines = 0;
|
||||
let weakest = Infinity;
|
||||
@@ -851,29 +924,35 @@ export function alignSubtitleFileToReferenceSpans(
|
||||
};
|
||||
|
||||
const plain = evaluateRatio(1.0);
|
||||
const plainScore = scoreStanding(plain.standing, cal);
|
||||
let chosen = plain;
|
||||
|
||||
// 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);
|
||||
const bestAltByAbove = altFits.reduce(
|
||||
(best, cur) => (cur.standing.above > best.standing.above ? cur : best),
|
||||
altFits[0]!,
|
||||
);
|
||||
const bestAltByStarts = altFits.reduce(
|
||||
(best, cur) => (cur.standing.starts > best.standing.starts ? cur : best),
|
||||
altFits[0]!,
|
||||
);
|
||||
// Never replace the plain fit with an alternate that lowers final confidence.
|
||||
const altFits = FRAMERATE_RATIOS.slice(1)
|
||||
.map(evaluateRatio)
|
||||
.filter((alt) => scoreStanding(alt.standing, cal) >= plainScore);
|
||||
if (altFits.length > 0) {
|
||||
const bestAltByAbove = altFits.reduce(
|
||||
(best, cur) => (cur.standing.above > best.standing.above ? cur : best),
|
||||
altFits[0]!,
|
||||
);
|
||||
const bestAltByStarts = altFits.reduce(
|
||||
(best, cur) => (cur.standing.starts > best.standing.starts ? cur : best),
|
||||
altFits[0]!,
|
||||
);
|
||||
|
||||
if (
|
||||
bestAltByAbove.standing.above > plain.standing.above + 2.0 &&
|
||||
bestAltByAbove.standing.above >= Math.max(4.0, cal.cutsFrom)
|
||||
) {
|
||||
chosen = bestAltByAbove;
|
||||
} else if (
|
||||
bestAltByStarts.standing.starts >= STARTS_Z_MIN &&
|
||||
bestAltByStarts.standing.starts > plain.standing.starts + 2.0
|
||||
) {
|
||||
chosen = bestAltByStarts;
|
||||
if (
|
||||
bestAltByAbove.standing.above > plain.standing.above + 2.0 &&
|
||||
bestAltByAbove.standing.above >= Math.max(4.0, cal.cutsFrom)
|
||||
) {
|
||||
chosen = bestAltByAbove;
|
||||
} else if (
|
||||
bestAltByStarts.standing.starts >= STARTS_Z_MIN &&
|
||||
bestAltByStarts.standing.starts > plain.standing.starts + 2.0
|
||||
) {
|
||||
chosen = bestAltByStarts;
|
||||
}
|
||||
}
|
||||
|
||||
const ratio = chosen.ratio;
|
||||
@@ -1221,14 +1300,7 @@ export function evaluateReferenceAlignmentToSampledAudio(
|
||||
const shiftedWindows = localWindows.map((w) => ({
|
||||
durationSec: w.durationSec,
|
||||
speechSpans: w.speechSpans,
|
||||
refSpans: w.refSpans
|
||||
.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),
|
||||
refSpans: wrapSpansInPeriod(w.refSpans, targetShift, w.durationSec),
|
||||
}));
|
||||
|
||||
let hereCovered = 0;
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import test from 'node:test';
|
||||
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', () => {
|
||||
const sampleRate = 8000;
|
||||
@@ -54,3 +63,80 @@ test('parseRawSileroVadSegments parses fine-grained speech segments from whisper
|
||||
{ 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 });
|
||||
}
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type ParsedSubtitleFile,
|
||||
type SubtitleTimeSpan,
|
||||
} 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_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);
|
||||
if (!sig) return null;
|
||||
return `${sig}\0${audioStreamIndex ?? 'default'}`;
|
||||
return `${sig}\0${audioStreamIndex ?? 'default'}\0${vadConfigKey}`;
|
||||
}
|
||||
|
||||
export function getCachedAudioSpeechSpans(
|
||||
videoPath: string,
|
||||
audioStreamIndex: number | null,
|
||||
vadConfig?: { vadExecutablePath?: string | null; vadModelPath?: string | null } | 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;
|
||||
}
|
||||
|
||||
@@ -295,6 +313,7 @@ function streamFfmpegPcm(
|
||||
const invocation = resolveCommandInvocation(ffmpegPath, args);
|
||||
const child = childProcess.spawn(invocation.command, invocation.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
let stderr = '';
|
||||
@@ -435,7 +454,8 @@ async function trySileroVadSpeech(
|
||||
export async function extractAudioSpeechSpans(
|
||||
options: ExtractAudioSpeechOptions,
|
||||
): 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) {
|
||||
const cached = audioSpeechCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
@@ -479,6 +499,7 @@ function spawnFfmpegWithStdout(
|
||||
const invocation = resolveCommandInvocation(ffmpegPath, args);
|
||||
const child = childProcess.spawn(invocation.command, invocation.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
let stderr = '';
|
||||
@@ -644,7 +665,8 @@ export async function extractSinglePassRipMedia(
|
||||
options: SinglePassRipMediaOptions,
|
||||
): Promise<SinglePassRipMediaResult | null> {
|
||||
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 =
|
||||
(fileKey ? embeddedSubtitlesCache.get(fileKey) : undefined) ??
|
||||
@@ -683,7 +705,15 @@ export async function extractSinglePassRipMedia(
|
||||
const trackOutputs: Array<{ ffIndex: number; outPath: string }> = [];
|
||||
for (const track of missingTracks) {
|
||||
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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -164,6 +164,15 @@ test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable b
|
||||
const lossy = decodeSubtitleBytesWithStatus(corrupt);
|
||||
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([
|
||||
{ start: 5.5, end: 7.0 },
|
||||
{ start: 1.25, end: 2.75 },
|
||||
|
||||
@@ -122,13 +122,19 @@ export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitl
|
||||
return { text: strictUtf8, lossless: 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 };
|
||||
}
|
||||
const eucJp = tryDecode(bytes, 'euc-jp', true);
|
||||
if (eucJp !== null) {
|
||||
if (eucJp !== null && shiftJis === null) {
|
||||
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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -3,13 +3,23 @@ import assert from 'node:assert/strict';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
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', () => {
|
||||
assert.equal(codecToExtension('subrip'), 'srt');
|
||||
assert.equal(codecToExtension('webvtt'), 'vtt');
|
||||
assert.equal(codecToExtension('vtt'), 'vtt');
|
||||
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', () => {
|
||||
@@ -58,3 +68,29 @@ test('findSubsyncExecutable skips non-executable files on POSIX and resolves bar
|
||||
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
@@ -2,6 +2,10 @@ import * as fs from 'fs';
|
||||
import * as childProcess from 'child_process';
|
||||
import * as path from 'path';
|
||||
import { DEFAULT_CONFIG } from '../config';
|
||||
import {
|
||||
buildWindowsShimInvocation,
|
||||
isWindowsCommandShim,
|
||||
} from '../core/utils/windows-command-shim';
|
||||
import { SubsyncConfig, SubsyncMode } from '../types';
|
||||
|
||||
export interface MpvTrack {
|
||||
@@ -47,13 +51,18 @@ function isExecutablePath(filePath: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function candidateExecutableNames(name: string): string[] {
|
||||
if (process.platform !== 'win32' || path.extname(name)) return [name];
|
||||
const extensions = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT')
|
||||
export function candidateExecutableNames(
|
||||
name: string,
|
||||
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(';')
|
||||
.map((ext) => ext.trim())
|
||||
.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(
|
||||
executable: string,
|
||||
args: string[],
|
||||
): { command: string; args: string[] } {
|
||||
if (process.platform !== 'win32') {
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): { command: string; args: string[]; windowsVerbatimArguments?: boolean } {
|
||||
if (platform !== 'win32') {
|
||||
return { command: executable, args };
|
||||
}
|
||||
|
||||
@@ -133,10 +143,12 @@ export function resolveCommandInvocation(
|
||||
return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`;
|
||||
};
|
||||
const extension = path.extname(executable).toLowerCase();
|
||||
if (extension === '.cmd' || extension === '.bat') {
|
||||
if (isWindowsCommandShim(executable)) {
|
||||
const shim = buildWindowsShimInvocation(executable, args, process.env);
|
||||
return {
|
||||
command: process.env.ComSpec || 'cmd.exe',
|
||||
args: ['/d', '/c', executable, ...args],
|
||||
command: shim.file,
|
||||
args: shim.args,
|
||||
windowsVerbatimArguments: true,
|
||||
};
|
||||
}
|
||||
if (extension === '.ps1') {
|
||||
@@ -233,6 +245,11 @@ export function codecToExtension(codec: string | undefined): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extensionToFfmpegMuxer(extension: string): string {
|
||||
if (extension === 'vtt') return 'webvtt';
|
||||
return extension;
|
||||
}
|
||||
|
||||
export function runCommand(
|
||||
executable: string,
|
||||
args: string[],
|
||||
@@ -242,6 +259,7 @@ export function runCommand(
|
||||
const invocation = resolveCommandInvocation(executable, args);
|
||||
const child = childProcess.spawn(invocation.command, invocation.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||
});
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
Reference in new issue
Block a user