mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
feat(subsync): integrate built-in automatic subtitle syncing
This commit is contained in:
44 files changed
+6498
-135
No files matched your search
@@ -0,0 +1,210 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
alignNoSplit,
|
||||
alignSubtitleFileToReferenceSpans,
|
||||
evaluateReferenceAlignmentToAudio,
|
||||
evaluateReferenceAlignmentToSampledAudio,
|
||||
joinSpans,
|
||||
type SampledAudioWindow,
|
||||
} from './alass-align';
|
||||
import {
|
||||
formatSrtTimestamp,
|
||||
parseSubtitleFileContent,
|
||||
type SubtitleTimeSpan,
|
||||
} from './subtitle-lines';
|
||||
|
||||
function generateDialogueRhythm(seedInit: bigint, step: bigint): SubtitleTimeSpan[] {
|
||||
const out: SubtitleTimeSpan[] = [];
|
||||
let seed = seedInit;
|
||||
const mask = (1n << 64n) - 1n;
|
||||
let t = 5.0;
|
||||
while (t < 1300.0) {
|
||||
seed = (seed * 6364136223846793005n + step) & mask;
|
||||
const len = 0.8 + (Number(seed >> 33n) / Number(1n << 31n)) * 3.0;
|
||||
const gap = 0.4 + (Number((seed >> 13n) & 0xffffn) / 65536.0) * 4.0;
|
||||
out.push({ start: t, end: t + len });
|
||||
t += len + gap;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function spansToSrtFile(spans: readonly SubtitleTimeSpan[]): string {
|
||||
return spans
|
||||
.map(
|
||||
(s, i) =>
|
||||
`${i + 1}\n${formatSrtTimestamp(Math.max(0, s.start))} --> ${formatSrtTimestamp(Math.max(0.05, s.end))}\nセリフ ${i + 1}\n`,
|
||||
)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
test('joinSpans merges overlapping spans so stacked karaoke lines count once', () => {
|
||||
const merged = joinSpans([
|
||||
{ start: 10, end: 15 },
|
||||
{ start: 10, end: 15 },
|
||||
{ start: 12, end: 18 },
|
||||
{ start: 20, end: 22 },
|
||||
]);
|
||||
assert.deepEqual(merged, [
|
||||
{ start: 10, end: 18 },
|
||||
{ start: 20, end: 22 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('alignNoSplit finds exact large and small offsets', () => {
|
||||
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
const shifted = ref.map((s) => ({ start: s.start + 42.35, end: s.end + 42.35 }));
|
||||
const delta = alignNoSplit(joinSpans(ref), shifted);
|
||||
assert.ok(Math.abs(delta + 42.35) <= 0.05, `expected ~-42.35s, got ${delta}`);
|
||||
});
|
||||
|
||||
test('alignSubtitleFileToReferenceSpans recovers fixed shift and ignores stacked songs in reference', () => {
|
||||
const dialogue = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
const refWithSong: SubtitleTimeSpan[] = [...dialogue];
|
||||
// Simulate 8 simultaneous stacked karaoke lines during an ending song.
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
refWithSong.push({ start: 1310, end: 1400 });
|
||||
}
|
||||
|
||||
const targetSpans = dialogue.map((s) => ({
|
||||
start: s.start + 2.5 - 0.08,
|
||||
end: s.end + 2.5 + 0.15,
|
||||
}));
|
||||
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(targetSpans), 'ep01.ja.srt');
|
||||
|
||||
const result = alignSubtitleFileToReferenceSpans(parsedTarget, refWithSong, {
|
||||
calibration: 'clean',
|
||||
lengthSec: 1420,
|
||||
});
|
||||
|
||||
assert.equal(result.confident, true);
|
||||
assert.ok(result.confidence >= 0.8, `expected high confidence, got ${result.confidence}`);
|
||||
assert.ok(Math.abs(result.offsetMs + 2500) <= 120, `expected ~-2500ms, got ${result.offsetMs}`);
|
||||
assert.equal(result.segments, 1);
|
||||
});
|
||||
|
||||
test('alignSubtitleFileToReferenceSpans corrects PAL 25fps speed-up automatically', () => {
|
||||
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
const palRatio = 23.976 / 25.0;
|
||||
const palSpans = ref.map((s) => ({
|
||||
start: s.start / palRatio + 1.2,
|
||||
end: s.end / palRatio + 1.2,
|
||||
}));
|
||||
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(palSpans), 'pal.ja.srt');
|
||||
|
||||
const result = alignSubtitleFileToReferenceSpans(parsedTarget, ref, {
|
||||
calibration: 'clean',
|
||||
lengthSec: 1320,
|
||||
});
|
||||
|
||||
assert.equal(result.confident, true);
|
||||
assert.ok(
|
||||
Math.abs(result.ratio - palRatio) < 1e-5,
|
||||
`expected ratio ${palRatio}, got ${result.ratio}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('alignSubtitleFileToReferenceSpans handles TV broadcast ad breaks in pieces', () => {
|
||||
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
const broadcastSpans = ref.map((s) => {
|
||||
const adOffset = s.start < 430 ? 30 : s.start < 870 ? 120 : 195;
|
||||
return { start: s.start + adOffset, end: s.end + adOffset };
|
||||
});
|
||||
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(broadcastSpans), 'tv.ja.srt');
|
||||
|
||||
const result = alignSubtitleFileToReferenceSpans(parsedTarget, ref, {
|
||||
calibration: 'clean',
|
||||
lengthSec: 1320,
|
||||
allowSplits: true,
|
||||
});
|
||||
|
||||
assert.equal(result.cut, true);
|
||||
assert.equal(result.segments, 3);
|
||||
assert.equal(result.confident, true);
|
||||
|
||||
const retimed = parseSubtitleFileContent(result.rewrittenContent, 'tv.ja.srt');
|
||||
for (let i = 0; i < ref.length; i += 1) {
|
||||
assert.ok(
|
||||
Math.abs(retimed.events[i]!.start - ref[i]!.start) < 0.25,
|
||||
`line ${i} misaligned: got ${retimed.events[i]!.start}, expected ${ref[i]!.start}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('alignSubtitleFileToReferenceSpans rejects an unrelated episode with low confidence', () => {
|
||||
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
const otherEpisode = generateDialogueRhythm(12345n, 0x9e3779b97f4a7c15n);
|
||||
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(otherEpisode), 'wrong.ja.srt');
|
||||
|
||||
const result = alignSubtitleFileToReferenceSpans(parsedTarget, ref, {
|
||||
calibration: 'clean',
|
||||
lengthSec: 1320,
|
||||
});
|
||||
|
||||
assert.equal(result.confident, false);
|
||||
assert.ok(result.confidence < 0.4, `expected low confidence, got ${result.confidence}`);
|
||||
});
|
||||
|
||||
test('evaluateReferenceAlignmentToAudio distinguishes aligned vs shifted English reference tracks', () => {
|
||||
const audioSpeech = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
// Well-aligned English track (leads audio by ~0.1s).
|
||||
const goodEng = audioSpeech.map((s) => ({ start: Math.max(0, s.start - 0.1), end: s.end + 0.1 }));
|
||||
// Misaligned English track (shifted +2.8s off audio).
|
||||
const badEng = audioSpeech.map((s) => ({ start: s.start + 2.8, end: s.end + 2.8 }));
|
||||
|
||||
const goodEval = evaluateReferenceAlignmentToAudio(goodEng, audioSpeech, {
|
||||
audioCalibration: 'noisy',
|
||||
lengthSec: 1320,
|
||||
});
|
||||
const badEval = evaluateReferenceAlignmentToAudio(badEng, audioSpeech, {
|
||||
audioCalibration: 'noisy',
|
||||
lengthSec: 1320,
|
||||
});
|
||||
|
||||
assert.equal(goodEval.status, 'aligned');
|
||||
assert.ok(
|
||||
Math.abs(goodEval.offsetMs) <= 300,
|
||||
`expected near-0ms offset, got ${goodEval.offsetMs}`,
|
||||
);
|
||||
|
||||
assert.equal(badEval.status, 'misaligned');
|
||||
assert.ok(
|
||||
Math.abs(badEval.offsetMs + 2900) <= 300,
|
||||
`expected ~-2900ms offset, got ${badEval.offsetMs}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('evaluateReferenceAlignmentToSampledAudio verifies aligned vs misaligned refs and marks huge shifts unverified', () => {
|
||||
const fullSpeech = generateDialogueRhythm(7n, 1442695040888963407n);
|
||||
const windowStarts = [160, 460, 780, 1080];
|
||||
const windowDur = 60;
|
||||
const windows: SampledAudioWindow[] = windowStarts.map((startSec) => ({
|
||||
startSec,
|
||||
durationSec: windowDur,
|
||||
speechSpans: fullSpeech
|
||||
.filter((s) => s.end > startSec && s.start < startSec + windowDur)
|
||||
.map((s) => ({
|
||||
start: Math.max(0, s.start - startSec),
|
||||
end: Math.min(windowDur, s.end - startSec),
|
||||
})),
|
||||
}));
|
||||
|
||||
const alignedRef = fullSpeech.map((s) => ({
|
||||
start: Math.max(0, s.start - 0.1),
|
||||
end: s.end + 0.1,
|
||||
}));
|
||||
const shiftedRef = fullSpeech.map((s) => ({ start: s.start + 3.2, end: s.end + 3.2 }));
|
||||
const hugeShiftRef = fullSpeech.map((s) => ({ start: s.start + 45.0, end: s.end + 45.0 }));
|
||||
|
||||
const alignedEval = evaluateReferenceAlignmentToSampledAudio(alignedRef, windows);
|
||||
assert.equal(alignedEval.status, 'aligned');
|
||||
assert.ok(Math.abs(alignedEval.offsetMs) <= 350, `got ${alignedEval.offsetMs}`);
|
||||
|
||||
const shiftedEval = evaluateReferenceAlignmentToSampledAudio(shiftedRef, windows);
|
||||
assert.equal(shiftedEval.status, 'misaligned');
|
||||
assert.ok(Math.abs(shiftedEval.offsetMs + 3300) <= 350, `got ${shiftedEval.offsetMs}`);
|
||||
|
||||
// A 45s shift is outside the ±12s sample window search radius -> returns 'unverified' so caller escalates to full audio.
|
||||
const hugeEval = evaluateReferenceAlignmentToSampledAudio(hugeShiftRef, windows);
|
||||
assert.equal(hugeEval.status, 'unverified');
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,56 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { detectSpeechSpansFromPcm, parseRawSileroVadSegments } from './audio-speech';
|
||||
|
||||
test('detectSpeechSpansFromPcm detects voice-band bursts separated by quiet background', () => {
|
||||
const sampleRate = 8000;
|
||||
const totalSec = 20;
|
||||
const samples = new Int16Array(sampleRate * totalSec);
|
||||
|
||||
const expectedSpans: Array<[number, number]> = [
|
||||
[2.0, 4.0],
|
||||
[7.5, 9.5],
|
||||
[13.0, 15.5],
|
||||
];
|
||||
|
||||
// Fill quiet ambient floor across whole clip.
|
||||
for (let i = 0; i < samples.length; i += 1) {
|
||||
const t = i / sampleRate;
|
||||
samples[i] = Math.round(Math.sin(2 * Math.PI * 500 * t) * 180);
|
||||
}
|
||||
|
||||
// Overlay speech-like multi-frequency formant signal inside expected spans.
|
||||
for (const [start, end] of expectedSpans) {
|
||||
const sIdx = Math.floor(start * sampleRate);
|
||||
const eIdx = Math.floor(end * sampleRate);
|
||||
for (let i = sIdx; i < eIdx; i += 1) {
|
||||
const t = i / sampleRate;
|
||||
const sig =
|
||||
0.5 * Math.sin(2 * Math.PI * 420 * t) +
|
||||
0.3 * Math.sin(2 * Math.PI * 1150 * t) +
|
||||
0.2 * Math.sin(2 * Math.PI * 2100 * t);
|
||||
samples[i] = Math.round(sig * 12000);
|
||||
}
|
||||
}
|
||||
|
||||
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, sampleRate);
|
||||
assert.equal(durationSec, totalSec);
|
||||
assert.equal(spans.length, expectedSpans.length);
|
||||
for (let i = 0; i < expectedSpans.length; i += 1) {
|
||||
assert.ok(Math.abs(spans[i]!.start - expectedSpans[i]![0]) <= 0.15);
|
||||
assert.ok(Math.abs(spans[i]!.end - expectedSpans[i]![1]) <= 0.25);
|
||||
}
|
||||
});
|
||||
|
||||
test('parseRawSileroVadSegments parses fine-grained speech segments from whisper-vad output', () => {
|
||||
const stdout = [
|
||||
'Detected 2 speech segments:',
|
||||
'Speech segment 0: start = 125.00, end = 340.00',
|
||||
'Speech segment 1: start = 510.50, end = 690.00',
|
||||
].join('\n');
|
||||
|
||||
assert.deepEqual(parseRawSileroVadSegments(stdout), [
|
||||
{ start: 1.25, end: 3.4 },
|
||||
{ start: 5.105, end: 6.9 },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,833 @@
|
||||
import * as childProcess from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import type { SampledAudioWindow } from './alass-align';
|
||||
import {
|
||||
decodeSubtitleBytes,
|
||||
parseSubtitleFileContent,
|
||||
type ParsedSubtitleFile,
|
||||
type SubtitleTimeSpan,
|
||||
} from './subtitle-lines';
|
||||
import { fileExists, resolveCommandInvocation, runCommand } from './utils';
|
||||
|
||||
const PCM_VAD_SAMPLE_RATE = 8000;
|
||||
const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400';
|
||||
const AUDIO_EXTRACT_TIMEOUT_MS = 180_000;
|
||||
const SAMPLED_WINDOW_TIMEOUT_MS = 30_000;
|
||||
const SAMPLED_WINDOW_DURATION_SEC = 60;
|
||||
const SAMPLED_MIN_MEDIA_DURATION_SEC = 300;
|
||||
const SAMPLED_WINDOW_FRACTIONS = [0.12, 0.35, 0.6, 0.82] as const;
|
||||
const MAX_CACHED_AUDIO_SPEECH_ENTRIES = 3;
|
||||
|
||||
export type AudioSpeechSource = 'silero-vad' | 'builtin-vad';
|
||||
|
||||
export interface AudioSpeechResult {
|
||||
spans: SubtitleTimeSpan[];
|
||||
durationSec: number;
|
||||
calibration: 'clean' | 'noisy';
|
||||
source: AudioSpeechSource;
|
||||
}
|
||||
|
||||
export interface ExtractAudioSpeechOptions {
|
||||
ffmpegPath: string;
|
||||
videoPath: string;
|
||||
audioStreamIndex: number | null;
|
||||
vadExecutablePath?: string | null;
|
||||
vadModelPath?: string | null;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface EmbeddedTrackSpec {
|
||||
ffIndex: number;
|
||||
extension: string;
|
||||
}
|
||||
|
||||
export interface SinglePassRipMediaOptions extends ExtractAudioSpeechOptions {
|
||||
embeddedTracks: readonly EmbeddedTrackSpec[];
|
||||
includeAudio: boolean;
|
||||
}
|
||||
|
||||
export interface SinglePassRipMediaResult {
|
||||
audioSpeech: AudioSpeechResult | null;
|
||||
embeddedSubtitles: Map<number, ParsedSubtitleFile>;
|
||||
}
|
||||
|
||||
const audioSpeechCache = new Map<string, AudioSpeechResult>();
|
||||
const sampledAudioCache = new Map<string, SampledAudioWindow[]>();
|
||||
const embeddedSubtitlesCache = new Map<string, Map<number, ParsedSubtitleFile>>();
|
||||
|
||||
export function clearAudioSpeechCache(): void {
|
||||
audioSpeechCache.clear();
|
||||
sampledAudioCache.clear();
|
||||
embeddedSubtitlesCache.clear();
|
||||
}
|
||||
|
||||
function buildFileSignatureKey(videoPath: string): string | null {
|
||||
try {
|
||||
const stat = fs.statSync(videoPath);
|
||||
if (!stat.isFile()) return null;
|
||||
return `${videoPath}\0${stat.size}\0${stat.mtimeMs}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildAudioCacheKey(videoPath: string, audioStreamIndex: number | null): string | null {
|
||||
const sig = buildFileSignatureKey(videoPath);
|
||||
if (!sig) return null;
|
||||
return `${sig}\0${audioStreamIndex ?? 'default'}`;
|
||||
}
|
||||
|
||||
export function getCachedAudioSpeechSpans(
|
||||
videoPath: string,
|
||||
audioStreamIndex: number | null,
|
||||
): AudioSpeechResult | null {
|
||||
const key = buildAudioCacheKey(videoPath, audioStreamIndex);
|
||||
return key ? (audioSpeechCache.get(key) ?? null) : null;
|
||||
}
|
||||
|
||||
function rememberLru<T>(cache: Map<string, T>, key: string | null, value: T): void {
|
||||
if (!key) return;
|
||||
if (cache.has(key)) {
|
||||
cache.delete(key);
|
||||
}
|
||||
cache.set(key, value);
|
||||
while (cache.size > MAX_CACHED_AUDIO_SPEECH_ENTRIES) {
|
||||
const oldestKey = cache.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
function rememberAudioSpeech(key: string | null, result: AudioSpeechResult): void {
|
||||
rememberLru(audioSpeechCache, key, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure-TypeScript voice-band speech activity detector operating on 16-bit mono
|
||||
* PCM (expected 8 kHz, voice band-passed 200–3400 Hz). Uses a global dynamic-range
|
||||
* histogram with hysteresis, zero-crossing gating, hangover, and short-gap bridging.
|
||||
*/
|
||||
export function detectSpeechSpansFromPcm(
|
||||
samples: Int16Array,
|
||||
sampleRate = PCM_VAD_SAMPLE_RATE,
|
||||
): { spans: SubtitleTimeSpan[]; durationSec: number } {
|
||||
const durationSec = sampleRate > 0 ? samples.length / sampleRate : 0;
|
||||
const frameSamples = Math.max(1, Math.round(sampleRate * 0.01)); // 10ms frames
|
||||
const frameCount = Math.floor(samples.length / frameSamples);
|
||||
if (frameCount === 0) {
|
||||
return { spans: [], durationSec };
|
||||
}
|
||||
|
||||
const frameDb = new Float32Array(frameCount);
|
||||
const frameZcr = new Float32Array(frameCount);
|
||||
// Histogram from -90 dB to 0 dB in 0.5 dB bins (181 bins) for O(N) percentiles.
|
||||
const HIST_MIN = -90;
|
||||
const HIST_BINS = 181;
|
||||
const hist = new Int32Array(HIST_BINS);
|
||||
let activeFrames = 0;
|
||||
|
||||
for (let f = 0; f < frameCount; f += 1) {
|
||||
const base = f * frameSamples;
|
||||
let sumSq = 0;
|
||||
let crossings = 0;
|
||||
let prevSign = samples[base]! >= 0 ? 1 : -1;
|
||||
for (let i = 0; i < frameSamples; i += 1) {
|
||||
const s = samples[base + i]! / 32768;
|
||||
sumSq += s * s;
|
||||
const sign = samples[base + i]! >= 0 ? 1 : -1;
|
||||
if (i > 0 && sign !== prevSign) crossings += 1;
|
||||
prevSign = sign;
|
||||
}
|
||||
const rms = Math.sqrt(sumSq / frameSamples);
|
||||
const db = rms > 1e-6 ? 20 * Math.log10(rms) : -100;
|
||||
frameDb[f] = db;
|
||||
frameZcr[f] = crossings / frameSamples;
|
||||
|
||||
if (db > -88) {
|
||||
const bin = Math.max(0, Math.min(HIST_BINS - 1, Math.round((db - HIST_MIN) * 2)));
|
||||
hist[bin] = hist[bin]! + 1;
|
||||
activeFrames += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (activeFrames < 10) {
|
||||
return { spans: [], durationSec };
|
||||
}
|
||||
|
||||
const percentileDb = (fraction: number): number => {
|
||||
const target = Math.max(1, Math.floor(activeFrames * fraction));
|
||||
let acc = 0;
|
||||
for (let b = 0; b < HIST_BINS; b += 1) {
|
||||
acc += hist[b]!;
|
||||
if (acc >= target) {
|
||||
return HIST_MIN + b * 0.5;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const p20 = percentileDb(0.2);
|
||||
const p85 = percentileDb(0.85);
|
||||
const dynamicRange = Math.max(0, p85 - p20);
|
||||
|
||||
// Set onset threshold cleanly between background noise floor and speech peak.
|
||||
const onsetDb =
|
||||
dynamicRange >= 8 ? Math.max(p20 + dynamicRange * 0.45, p20 + 5.5) : Math.max(p85 - 5.0, -52);
|
||||
const releaseDb = onsetDb - Math.min(4.0, Math.max(2.0, dynamicRange * 0.15));
|
||||
|
||||
// Hysteresis + 120ms hangover.
|
||||
const HANGOVER_FRAMES = 12;
|
||||
const MIN_SPEECH_FRAMES = 8; // 80ms
|
||||
const BRIDGE_GAP_FRAMES = 12; // 120ms
|
||||
const voiced = new Uint8Array(frameCount);
|
||||
|
||||
let inSpeech = false;
|
||||
let hangover = 0;
|
||||
for (let f = 0; f < frameCount; f += 1) {
|
||||
const db = frameDb[f]!;
|
||||
const zcr = frameZcr[f]!;
|
||||
const speechLikeZcr = zcr >= 0.015 && zcr <= 0.65;
|
||||
if (!inSpeech) {
|
||||
if (db >= onsetDb && speechLikeZcr) {
|
||||
inSpeech = true;
|
||||
hangover = HANGOVER_FRAMES;
|
||||
voiced[f] = 1;
|
||||
}
|
||||
} else if (db >= releaseDb && speechLikeZcr) {
|
||||
hangover = HANGOVER_FRAMES;
|
||||
voiced[f] = 1;
|
||||
} else if (hangover > 0) {
|
||||
hangover -= 1;
|
||||
voiced[f] = 1;
|
||||
} else {
|
||||
inSpeech = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Extract raw spans and bridge tiny gaps.
|
||||
const rawSpans: SubtitleTimeSpan[] = [];
|
||||
let startFrame = -1;
|
||||
for (let f = 0; f < frameCount; f += 1) {
|
||||
if (voiced[f] === 1) {
|
||||
if (startFrame === -1) startFrame = f;
|
||||
} else if (startFrame !== -1) {
|
||||
if (f - startFrame >= MIN_SPEECH_FRAMES) {
|
||||
rawSpans.push({ start: startFrame * 0.01, end: f * 0.01 });
|
||||
}
|
||||
startFrame = -1;
|
||||
}
|
||||
}
|
||||
if (startFrame !== -1 && frameCount - startFrame >= MIN_SPEECH_FRAMES) {
|
||||
rawSpans.push({ start: startFrame * 0.01, end: frameCount * 0.01 });
|
||||
}
|
||||
|
||||
const bridged: SubtitleTimeSpan[] = [];
|
||||
const maxBridgeSec = BRIDGE_GAP_FRAMES * 0.01;
|
||||
for (const span of rawSpans) {
|
||||
const prev = bridged.at(-1);
|
||||
if (prev && span.start - prev.end <= maxBridgeSec) {
|
||||
prev.end = span.end;
|
||||
} else {
|
||||
bridged.push({ ...span });
|
||||
}
|
||||
}
|
||||
|
||||
return { spans: bridged, durationSec };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse raw Silero speech segments emitted by `whisper-vad-speech-segments`
|
||||
* without grouping into 20-second transcription passages.
|
||||
*/
|
||||
export function parseRawSileroVadSegments(output: string): SubtitleTimeSpan[] {
|
||||
const spans: SubtitleTimeSpan[] = [];
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
const match = /^Speech segment \d+: start = (\d+(?:\.\d+)?), end = (\d+(?:\.\d+)?)$/.exec(
|
||||
line.trim(),
|
||||
);
|
||||
if (!match) continue;
|
||||
const start = Number(match[1]) / 100;
|
||||
const end = Number(match[2]) / 100;
|
||||
if (Number.isFinite(start) && Number.isFinite(end) && end > start) {
|
||||
spans.push({ start, end });
|
||||
}
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
function streamFfmpegPcm(
|
||||
ffmpegPath: string,
|
||||
videoPath: string,
|
||||
audioStreamIndex: number | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const args = [
|
||||
'-hide_banner',
|
||||
'-nostdin',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-i',
|
||||
videoPath,
|
||||
'-vn',
|
||||
'-sn',
|
||||
'-dn',
|
||||
];
|
||||
if (audioStreamIndex !== null && Number.isInteger(audioStreamIndex) && audioStreamIndex >= 0) {
|
||||
args.push('-map', `0:${audioStreamIndex}`);
|
||||
} else {
|
||||
args.push('-map', '0:a:0');
|
||||
}
|
||||
args.push(
|
||||
'-ac',
|
||||
'1',
|
||||
'-ar',
|
||||
String(PCM_VAD_SAMPLE_RATE),
|
||||
'-af',
|
||||
PCM_VAD_FILTER,
|
||||
'-f',
|
||||
's16le',
|
||||
'pipe:1',
|
||||
);
|
||||
|
||||
const invocation = resolveCommandInvocation(ffmpegPath, args);
|
||||
const child = childProcess.spawn(invocation.command, invocation.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
let stderr = '';
|
||||
let settled = false;
|
||||
|
||||
const finishError = (err: Error): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
reject(err);
|
||||
};
|
||||
|
||||
const onAbort = (): void => {
|
||||
child.kill('SIGKILL');
|
||||
finishError(new Error('Audio extraction aborted'));
|
||||
};
|
||||
|
||||
if (signal?.aborted) {
|
||||
onAbort();
|
||||
return;
|
||||
}
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
finishError(new Error('Timed out while reading video audio with ffmpeg'));
|
||||
}, AUDIO_EXTRACT_TIMEOUT_MS);
|
||||
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
});
|
||||
child.stderr.on('data', (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
child.on('error', (error: Error) => {
|
||||
finishError(error);
|
||||
});
|
||||
child.on('close', (code: number | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
if (code !== 0) {
|
||||
reject(new Error(`ffmpeg audio read failed (code=${code ?? 'n/a'}): ${stderr.trim()}`));
|
||||
return;
|
||||
}
|
||||
resolve(Buffer.concat(chunks));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function trySileroVadSpeech(
|
||||
options: ExtractAudioSpeechOptions,
|
||||
): Promise<AudioSpeechResult | null> {
|
||||
const vadExec = options.vadExecutablePath?.trim();
|
||||
const vadModel = options.vadModelPath?.trim();
|
||||
if (!vadExec || !vadModel || !fileExists(vadModel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let tempDir: string | null = null;
|
||||
try {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-vad-'));
|
||||
const wavPath = path.join(tempDir, 'audio.wav');
|
||||
const ffmpegArgs = [
|
||||
'-hide_banner',
|
||||
'-nostdin',
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-i',
|
||||
options.videoPath,
|
||||
'-vn',
|
||||
'-sn',
|
||||
'-dn',
|
||||
];
|
||||
if (
|
||||
options.audioStreamIndex !== null &&
|
||||
Number.isInteger(options.audioStreamIndex) &&
|
||||
options.audioStreamIndex >= 0
|
||||
) {
|
||||
ffmpegArgs.push('-map', `0:${options.audioStreamIndex}`);
|
||||
} else {
|
||||
ffmpegArgs.push('-map', '0:a:0');
|
||||
}
|
||||
ffmpegArgs.push('-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', wavPath);
|
||||
|
||||
const wavRes = await runCommand(options.ffmpegPath, ffmpegArgs, AUDIO_EXTRACT_TIMEOUT_MS);
|
||||
if (!wavRes.ok || !fileExists(wavPath)) return null;
|
||||
|
||||
const wavStats = fs.statSync(wavPath);
|
||||
const durationSec = Math.max(0, (wavStats.size - 44) / (16000 * 2));
|
||||
|
||||
const vadRes = await runCommand(
|
||||
vadExec,
|
||||
[
|
||||
'-f',
|
||||
wavPath,
|
||||
'-vm',
|
||||
vadModel,
|
||||
'-vt',
|
||||
'0.35',
|
||||
'--vad-min-speech-duration-ms',
|
||||
'120',
|
||||
'--vad-min-silence-duration-ms',
|
||||
'250',
|
||||
'-vp',
|
||||
'100',
|
||||
'-np',
|
||||
],
|
||||
AUDIO_EXTRACT_TIMEOUT_MS,
|
||||
);
|
||||
if (!vadRes.ok) return null;
|
||||
|
||||
const spans = parseRawSileroVadSegments(`${vadRes.stdout}\n${vadRes.stderr}`);
|
||||
if (spans.length === 0) return null;
|
||||
|
||||
return {
|
||||
spans,
|
||||
durationSec: Math.max(durationSec, spans[spans.length - 1]!.end),
|
||||
calibration: 'clean',
|
||||
source: 'silero-vad',
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
try {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function extractAudioSpeechSpans(
|
||||
options: ExtractAudioSpeechOptions,
|
||||
): Promise<AudioSpeechResult> {
|
||||
const cacheKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex);
|
||||
if (cacheKey) {
|
||||
const cached = audioSpeechCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
}
|
||||
|
||||
// Tier 1: Prefer Silero VAD if whisper-vad-speech-segments + model are available.
|
||||
const silero = await trySileroVadSpeech(options);
|
||||
if (silero) {
|
||||
rememberAudioSpeech(cacheKey, silero);
|
||||
return silero;
|
||||
}
|
||||
|
||||
// Tier 2: Built-in voice-band PCM speech detector via ffmpeg (zero extra dependencies).
|
||||
const pcmBuffer = await streamFfmpegPcm(
|
||||
options.ffmpegPath,
|
||||
options.videoPath,
|
||||
options.audioStreamIndex,
|
||||
options.signal,
|
||||
);
|
||||
const sampleCount = Math.floor(pcmBuffer.byteLength / 2);
|
||||
const samples = new Int16Array(pcmBuffer.buffer, pcmBuffer.byteOffset, sampleCount);
|
||||
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, PCM_VAD_SAMPLE_RATE);
|
||||
|
||||
const result: AudioSpeechResult = {
|
||||
spans,
|
||||
durationSec,
|
||||
calibration: 'noisy',
|
||||
source: 'builtin-vad',
|
||||
};
|
||||
rememberAudioSpeech(cacheKey, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function spawnFfmpegWithStdout(
|
||||
ffmpegPath: string,
|
||||
args: string[],
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const invocation = resolveCommandInvocation(ffmpegPath, args);
|
||||
const child = childProcess.spawn(invocation.command, invocation.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
let stderr = '';
|
||||
let settled = false;
|
||||
|
||||
const finishError = (err: Error): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
reject(err);
|
||||
};
|
||||
|
||||
const onAbort = (): void => {
|
||||
child.kill('SIGKILL');
|
||||
finishError(new Error('ffmpeg operation aborted'));
|
||||
};
|
||||
|
||||
if (signal?.aborted) {
|
||||
onAbort();
|
||||
return;
|
||||
}
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
child.kill('SIGKILL');
|
||||
finishError(new Error('ffmpeg operation timed out'));
|
||||
}, timeoutMs);
|
||||
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
chunks.push(chunk);
|
||||
});
|
||||
child.stderr.on('data', (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
child.on('error', (error: Error) => {
|
||||
finishError(error);
|
||||
});
|
||||
child.on('close', (code: number | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
if (code !== 0) {
|
||||
reject(new Error(`ffmpeg failed (code=${code ?? 'n/a'}): ${stderr.trim()}`));
|
||||
return;
|
||||
}
|
||||
resolve(Buffer.concat(chunks));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function audioMapArg(audioStreamIndex: number | null): string {
|
||||
return audioStreamIndex !== null && Number.isInteger(audioStreamIndex) && audioStreamIndex >= 0
|
||||
? `0:${audioStreamIndex}`
|
||||
: '0:a:0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample 4 seeked 60-second audio windows across a media file in parallel using
|
||||
* fast input-side `-ss` seeks. Used to verify external reference subtitles in
|
||||
* ~0.2-0.5s without decoding the entire episode or movie.
|
||||
*/
|
||||
export async function extractSampledAudioWindows(options: {
|
||||
ffmpegPath: string;
|
||||
videoPath: string;
|
||||
audioStreamIndex: number | null;
|
||||
durationSec: number;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<SampledAudioWindow[] | null> {
|
||||
if (
|
||||
!Number.isFinite(options.durationSec) ||
|
||||
options.durationSec < SAMPLED_MIN_MEDIA_DURATION_SEC
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex);
|
||||
const sampleKey = audioKey ? `${audioKey}\0${Math.round(options.durationSec)}` : null;
|
||||
if (sampleKey) {
|
||||
const cached = sampledAudioCache.get(sampleKey);
|
||||
if (cached) return cached;
|
||||
}
|
||||
|
||||
const maxStart = Math.max(0, options.durationSec - SAMPLED_WINDOW_DURATION_SEC - 5);
|
||||
const starts: number[] = [];
|
||||
for (const frac of SAMPLED_WINDOW_FRACTIONS) {
|
||||
const startSec = Math.round(Math.min(maxStart, Math.max(0, options.durationSec * frac)));
|
||||
if (starts.every((prev) => Math.abs(prev - startSec) >= SAMPLED_WINDOW_DURATION_SEC)) {
|
||||
starts.push(startSec);
|
||||
}
|
||||
}
|
||||
if (starts.length < 2) return null;
|
||||
|
||||
const mapSpec = audioMapArg(options.audioStreamIndex);
|
||||
const maxBytes = SAMPLED_WINDOW_DURATION_SEC * PCM_VAD_SAMPLE_RATE * 2;
|
||||
|
||||
const settled = await Promise.all(
|
||||
starts.map(async (startSec): Promise<SampledAudioWindow | null> => {
|
||||
try {
|
||||
const pcmBuffer = await spawnFfmpegWithStdout(
|
||||
options.ffmpegPath,
|
||||
[
|
||||
'-hide_banner',
|
||||
'-nostdin',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-ss',
|
||||
String(startSec),
|
||||
'-t',
|
||||
String(SAMPLED_WINDOW_DURATION_SEC),
|
||||
'-i',
|
||||
options.videoPath,
|
||||
'-vn',
|
||||
'-sn',
|
||||
'-dn',
|
||||
'-map',
|
||||
mapSpec,
|
||||
'-ac',
|
||||
'1',
|
||||
'-ar',
|
||||
String(PCM_VAD_SAMPLE_RATE),
|
||||
'-af',
|
||||
PCM_VAD_FILTER,
|
||||
'-f',
|
||||
's16le',
|
||||
'pipe:1',
|
||||
],
|
||||
SAMPLED_WINDOW_TIMEOUT_MS,
|
||||
options.signal,
|
||||
);
|
||||
const clampedLen = Math.min(pcmBuffer.byteLength, maxBytes);
|
||||
const sampleCount = Math.floor(clampedLen / 2);
|
||||
if (sampleCount < PCM_VAD_SAMPLE_RATE * 10) return null;
|
||||
const samples = new Int16Array(pcmBuffer.buffer, pcmBuffer.byteOffset, sampleCount);
|
||||
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, PCM_VAD_SAMPLE_RATE);
|
||||
if (spans.length === 0) return null;
|
||||
return {
|
||||
startSec,
|
||||
durationSec: Math.min(SAMPLED_WINDOW_DURATION_SEC, durationSec),
|
||||
speechSpans: spans,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const valid = settled.filter((w): w is SampledAudioWindow => w !== null);
|
||||
if (valid.length < 2) return null;
|
||||
|
||||
rememberLru(sampledAudioCache, sampleKey, valid);
|
||||
return valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract multiple embedded text subtitle tracks AND (optionally) audio speech
|
||||
* in ONE single `ffmpeg` demux pass, avoiding N+1 full-file reads on multi-track
|
||||
* MKVs and caching results for subsequent modal retries.
|
||||
* Returns `null` if the multi-output ffmpeg pass fails so callers can fall back.
|
||||
*/
|
||||
export async function extractSinglePassRipMedia(
|
||||
options: SinglePassRipMediaOptions,
|
||||
): Promise<SinglePassRipMediaResult | null> {
|
||||
const fileKey = buildFileSignatureKey(options.videoPath);
|
||||
const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex);
|
||||
|
||||
const cachedSubs =
|
||||
(fileKey ? embeddedSubtitlesCache.get(fileKey) : undefined) ??
|
||||
new Map<number, ParsedSubtitleFile>();
|
||||
const cachedAudio = audioKey ? (audioSpeechCache.get(audioKey) ?? null) : null;
|
||||
|
||||
const missingTracks = options.embeddedTracks.filter((t) => !cachedSubs.has(t.ffIndex));
|
||||
const needAudio = options.includeAudio && cachedAudio === null;
|
||||
|
||||
if (missingTracks.length === 0 && !needAudio) {
|
||||
return {
|
||||
audioSpeech: options.includeAudio ? cachedAudio : null,
|
||||
embeddedSubtitles: new Map(cachedSubs),
|
||||
};
|
||||
}
|
||||
|
||||
const vadExec = options.vadExecutablePath?.trim() ?? '';
|
||||
const vadModel = options.vadModelPath?.trim() ?? '';
|
||||
const useSilero = needAudio && vadExec.length > 0 && vadModel.length > 0 && fileExists(vadModel);
|
||||
|
||||
let tempDir: string | null = null;
|
||||
|
||||
try {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-rip-'));
|
||||
const wavPath = path.join(tempDir, 'audio.wav');
|
||||
const args: string[] = [
|
||||
'-hide_banner',
|
||||
'-nostdin',
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-i',
|
||||
options.videoPath,
|
||||
];
|
||||
|
||||
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);
|
||||
trackOutputs.push({ ffIndex: track.ffIndex, outPath });
|
||||
}
|
||||
|
||||
if (needAudio) {
|
||||
const mapSpec = audioMapArg(options.audioStreamIndex);
|
||||
if (useSilero) {
|
||||
args.push(
|
||||
'-vn',
|
||||
'-sn',
|
||||
'-dn',
|
||||
'-map',
|
||||
mapSpec,
|
||||
'-ac',
|
||||
'1',
|
||||
'-ar',
|
||||
'16000',
|
||||
'-c:a',
|
||||
'pcm_s16le',
|
||||
wavPath,
|
||||
);
|
||||
} else {
|
||||
args.push(
|
||||
'-vn',
|
||||
'-sn',
|
||||
'-dn',
|
||||
'-map',
|
||||
mapSpec,
|
||||
'-ac',
|
||||
'1',
|
||||
'-ar',
|
||||
String(PCM_VAD_SAMPLE_RATE),
|
||||
'-af',
|
||||
PCM_VAD_FILTER,
|
||||
'-f',
|
||||
's16le',
|
||||
'pipe:1',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const stdoutBuf = await spawnFfmpegWithStdout(
|
||||
options.ffmpegPath,
|
||||
args,
|
||||
AUDIO_EXTRACT_TIMEOUT_MS,
|
||||
options.signal,
|
||||
);
|
||||
|
||||
const updatedSubs = new Map<number, ParsedSubtitleFile>(cachedSubs);
|
||||
for (const { ffIndex, outPath } of trackOutputs) {
|
||||
if (!fileExists(outPath)) continue;
|
||||
try {
|
||||
const bytes = fs.readFileSync(outPath);
|
||||
const parsed = parseSubtitleFileContent(decodeSubtitleBytes(bytes), outPath);
|
||||
updatedSubs.set(ffIndex, parsed);
|
||||
} catch {
|
||||
// Ignore individual unparseable track.
|
||||
}
|
||||
}
|
||||
if (updatedSubs.size > 0) {
|
||||
rememberLru(embeddedSubtitlesCache, fileKey, updatedSubs);
|
||||
}
|
||||
|
||||
let audioSpeech: AudioSpeechResult | null = options.includeAudio ? cachedAudio : null;
|
||||
if (needAudio) {
|
||||
if (useSilero && fileExists(wavPath)) {
|
||||
const wavStats = fs.statSync(wavPath);
|
||||
const durationSec = Math.max(0, (wavStats.size - 44) / (16000 * 2));
|
||||
const vadRes = await runCommand(
|
||||
vadExec,
|
||||
[
|
||||
'-f',
|
||||
wavPath,
|
||||
'-vm',
|
||||
vadModel,
|
||||
'-vt',
|
||||
'0.35',
|
||||
'--vad-min-speech-duration-ms',
|
||||
'120',
|
||||
'--vad-min-silence-duration-ms',
|
||||
'250',
|
||||
'-vp',
|
||||
'100',
|
||||
'-np',
|
||||
],
|
||||
AUDIO_EXTRACT_TIMEOUT_MS,
|
||||
);
|
||||
if (vadRes.ok) {
|
||||
const spans = parseRawSileroVadSegments(`${vadRes.stdout}\n${vadRes.stderr}`);
|
||||
if (spans.length > 0) {
|
||||
audioSpeech = {
|
||||
spans,
|
||||
durationSec: Math.max(durationSec, spans[spans.length - 1]!.end),
|
||||
calibration: 'clean',
|
||||
source: 'silero-vad',
|
||||
};
|
||||
}
|
||||
}
|
||||
// If Silero returned no spans, fall back cleanly to built-in PCM VAD.
|
||||
if (!audioSpeech) {
|
||||
try {
|
||||
audioSpeech = await extractAudioSpeechSpans({
|
||||
ffmpegPath: options.ffmpegPath,
|
||||
videoPath: options.videoPath,
|
||||
audioStreamIndex: options.audioStreamIndex,
|
||||
signal: options.signal,
|
||||
});
|
||||
} catch {
|
||||
audioSpeech = null;
|
||||
}
|
||||
}
|
||||
} else if (!useSilero) {
|
||||
const sampleCount = Math.floor(stdoutBuf.byteLength / 2);
|
||||
if (sampleCount > 0) {
|
||||
const samples = new Int16Array(stdoutBuf.buffer, stdoutBuf.byteOffset, sampleCount);
|
||||
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, PCM_VAD_SAMPLE_RATE);
|
||||
if (spans.length > 0) {
|
||||
audioSpeech = {
|
||||
spans,
|
||||
durationSec,
|
||||
calibration: 'noisy',
|
||||
source: 'builtin-vad',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (audioSpeech) {
|
||||
rememberAudioSpeech(audioKey, audioSpeech);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
audioSpeech,
|
||||
embeddedSubtitles: updatedSubs,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
try {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import test from 'node:test';
|
||||
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 {
|
||||
discoverSidecarReferenceFiles,
|
||||
rankReferenceCandidates,
|
||||
type EvaluatedSubtitleReference,
|
||||
} from './reference-discovery';
|
||||
|
||||
test('discoverSidecarReferenceFiles finds unloaded sidecar subtitle files and skips target/retimed/loaded', () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-sidecars-'));
|
||||
try {
|
||||
const videoPath = path.join(dir, 'Episode 01.mkv');
|
||||
const targetPath = path.join(dir, 'Episode 01.ja.srt');
|
||||
const loadedEngPath = path.join(dir, 'Episode 01.en.srt');
|
||||
const unloadedAssPath = path.join(dir, 'Episode 01.eng.full.ass');
|
||||
const retimedPath = path.join(dir, 'Episode 01.ja_retimed.srt');
|
||||
const otherEpPath = path.join(dir, 'Episode 02.en.srt');
|
||||
|
||||
for (const p of [
|
||||
videoPath,
|
||||
targetPath,
|
||||
loadedEngPath,
|
||||
unloadedAssPath,
|
||||
retimedPath,
|
||||
otherEpPath,
|
||||
]) {
|
||||
fs.writeFileSync(p, 'test');
|
||||
}
|
||||
|
||||
const found = discoverSidecarReferenceFiles(videoPath, [targetPath, loadedEngPath]);
|
||||
assert.deepEqual(
|
||||
found.map((f) => f.filename),
|
||||
['Episode 01.eng.full.ass'],
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('rankReferenceCandidates prefers audio-aligned unloaded track over misaligned secondary track', () => {
|
||||
const misalignedSecondary: EvaluatedSubtitleReference = {
|
||||
key: 'track:2',
|
||||
kind: 'track',
|
||||
trackId: 2,
|
||||
filePath: null,
|
||||
label: 'External #2 - eng (secondary)',
|
||||
isSecondary: true,
|
||||
isEmbedded: false,
|
||||
isEnglish: true,
|
||||
isFullDialogueHint: true,
|
||||
isSignsOnly: false,
|
||||
dialogueCount: 300,
|
||||
signCount: 10,
|
||||
audioStatus: 'misaligned',
|
||||
audioOffsetMs: 2400,
|
||||
audioConfidence: 0.92,
|
||||
};
|
||||
|
||||
const alignedUnloaded: EvaluatedSubtitleReference = {
|
||||
key: 'track:4',
|
||||
kind: 'track',
|
||||
trackId: 4,
|
||||
filePath: null,
|
||||
label: 'Internal #4 - eng - Full Dialogue',
|
||||
isSecondary: false,
|
||||
isEmbedded: true,
|
||||
isEnglish: true,
|
||||
isFullDialogueHint: true,
|
||||
isSignsOnly: false,
|
||||
dialogueCount: 295,
|
||||
signCount: 20,
|
||||
audioStatus: 'aligned',
|
||||
audioOffsetMs: 40,
|
||||
audioConfidence: 0.9,
|
||||
};
|
||||
|
||||
const signsOnly: EvaluatedSubtitleReference = {
|
||||
key: 'track:3',
|
||||
kind: 'track',
|
||||
trackId: 3,
|
||||
filePath: null,
|
||||
label: 'Internal #3 - eng - Signs & Songs',
|
||||
isSecondary: false,
|
||||
isEmbedded: true,
|
||||
isEnglish: true,
|
||||
isFullDialogueHint: false,
|
||||
isSignsOnly: true,
|
||||
dialogueCount: 12,
|
||||
signCount: 180,
|
||||
audioStatus: 'unverified',
|
||||
audioOffsetMs: null,
|
||||
audioConfidence: 0,
|
||||
};
|
||||
|
||||
const ranked = rankReferenceCandidates([misalignedSecondary, signsOnly, alignedUnloaded]);
|
||||
assert.deepEqual(
|
||||
ranked.map((r) => r.key),
|
||||
['track:4', 'track:3', 'track:2'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import type { ReferenceAudioStatus } from './alass-align';
|
||||
import { isSignsOrSongsTrackMeta } from './subtitle-lines';
|
||||
import type { MpvTrack } from './utils';
|
||||
|
||||
const SIDECAR_SUBTITLE_EXTENSIONS = new Set(['.srt', '.ass', '.ssa', '.vtt']);
|
||||
|
||||
export interface SidecarSubtitleFile {
|
||||
path: string;
|
||||
filename: string;
|
||||
languageHint: string;
|
||||
isSignsOnly: boolean;
|
||||
}
|
||||
|
||||
export interface EvaluatedSubtitleReference {
|
||||
key: string;
|
||||
kind: 'track' | 'sidecar';
|
||||
trackId: number | null;
|
||||
filePath: string | null;
|
||||
label: string;
|
||||
isSecondary: boolean;
|
||||
isEmbedded: boolean;
|
||||
isEnglish: boolean;
|
||||
isFullDialogueHint: boolean;
|
||||
isSignsOnly: boolean;
|
||||
dialogueCount: number;
|
||||
signCount: number;
|
||||
audioStatus: ReferenceAudioStatus;
|
||||
audioOffsetMs: number | null;
|
||||
audioConfidence: number;
|
||||
}
|
||||
|
||||
function normalizePathKey(filePath: string): string {
|
||||
const resolved = path.resolve(filePath).replace(/\\/g, '/');
|
||||
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
}
|
||||
|
||||
export function isEnglishReferenceMeta(meta: {
|
||||
lang?: string;
|
||||
title?: string;
|
||||
filename?: string;
|
||||
}): boolean {
|
||||
const lang = (meta.lang ?? '').trim();
|
||||
if (/^(?:en|eng|english)(?:[-_]|$)/i.test(lang)) return true;
|
||||
const combined = `${meta.title ?? ''} ${meta.filename ?? ''}`;
|
||||
return /(?:^|[\s.\[(_-])(?:en|eng|english)(?=$|[\s.\])_-])/i.test(combined);
|
||||
}
|
||||
|
||||
export function isFullDialogueHintMeta(meta: { title?: string; filename?: string }): boolean {
|
||||
const combined = `${meta.title ?? ''} ${meta.filename ?? ''}`;
|
||||
return /\b(?:full|dialogue|dialog|complete|main)\b/i.test(combined);
|
||||
}
|
||||
|
||||
function inferLanguageHintFromFilename(filename: string, videoStem: string): string {
|
||||
const parsed = path.parse(filename);
|
||||
const remainder = parsed.name.startsWith(videoStem)
|
||||
? parsed.name.slice(videoStem.length).replace(/^[.\s_-]+/, '')
|
||||
: parsed.name;
|
||||
return remainder || parsed.ext.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan the video's directory for unloaded sidecar subtitle files matching the
|
||||
* video's stem, excluding the target subtitle, `_retimed` files, and paths
|
||||
* already present in mpv's track list.
|
||||
*/
|
||||
export function discoverSidecarReferenceFiles(
|
||||
videoPath: string,
|
||||
loadedPaths: readonly string[],
|
||||
): SidecarSubtitleFile[] {
|
||||
const parsedVideo = path.parse(videoPath);
|
||||
if (!parsedVideo.dir || !parsedVideo.name) return [];
|
||||
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = fs.readdirSync(parsedVideo.dir);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
const excluded = new Set(loadedPaths.map(normalizePathKey));
|
||||
const stemLower = parsedVideo.name.toLowerCase();
|
||||
const candidates: SidecarSubtitleFile[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
const parsedEntry = path.parse(entry);
|
||||
const ext = parsedEntry.ext.toLowerCase();
|
||||
if (!SIDECAR_SUBTITLE_EXTENSIONS.has(ext)) continue;
|
||||
const nameLower = parsedEntry.name.toLowerCase();
|
||||
if (nameLower.endsWith('_retimed')) continue;
|
||||
if (
|
||||
nameLower !== stemLower &&
|
||||
!nameLower.startsWith(`${stemLower}.`) &&
|
||||
!nameLower.startsWith(`${stemLower}_`) &&
|
||||
!nameLower.startsWith(`${stemLower}-`) &&
|
||||
!nameLower.startsWith(`${stemLower} `)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fullPath = path.join(parsedVideo.dir, entry);
|
||||
if (excluded.has(normalizePathKey(fullPath))) continue;
|
||||
|
||||
try {
|
||||
if (!fs.statSync(fullPath).isFile()) continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
candidates.push({
|
||||
path: fullPath,
|
||||
filename: entry,
|
||||
languageHint: inferLanguageHintFromFilename(entry, parsedVideo.name),
|
||||
isSignsOnly: isSignsOrSongsTrackMeta({ 'external-filename': fullPath }),
|
||||
});
|
||||
}
|
||||
|
||||
return candidates.sort((a, b) => a.filename.localeCompare(b.filename));
|
||||
}
|
||||
|
||||
export function formatReferenceCandidateDetail(candidate: EvaluatedSubtitleReference): string {
|
||||
const parts: string[] = [];
|
||||
if (candidate.audioStatus === 'aligned') {
|
||||
const pct = Math.round(candidate.audioConfidence * 100);
|
||||
parts.push(`aligned with audio${pct > 0 ? ` (${pct}%)` : ''}`);
|
||||
} else if (candidate.audioStatus === 'misaligned' && candidate.audioOffsetMs !== null) {
|
||||
const sec = (candidate.audioOffsetMs / 1000).toFixed(1);
|
||||
const signed = candidate.audioOffsetMs >= 0 ? `+${sec}s` : `${sec}s`;
|
||||
parts.push(`${signed} off audio`);
|
||||
}
|
||||
if (candidate.isSignsOnly) {
|
||||
parts.push('signs/songs');
|
||||
} else if (candidate.signCount > 0 && candidate.dialogueCount > 0) {
|
||||
parts.push(`${candidate.dialogueCount} dialogue, ${candidate.signCount} signs/songs stripped`);
|
||||
} else if (candidate.dialogueCount > 0) {
|
||||
parts.push(`${candidate.dialogueCount} lines`);
|
||||
}
|
||||
if (candidate.kind === 'sidecar') {
|
||||
parts.push('unloaded sidecar');
|
||||
} else if (!candidate.isSecondary && !candidate.isEmbedded) {
|
||||
parts.push('external');
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Score candidate subtitle references so the best audio-verified dialogue track
|
||||
* wins even when it isn't the currently loaded secondary subtitle.
|
||||
*/
|
||||
export function scoreReferenceCandidate(candidate: EvaluatedSubtitleReference): number {
|
||||
let score = 0;
|
||||
|
||||
// Audio verification dominates when available: an aligned track ALWAYS beats a misaligned one.
|
||||
if (candidate.audioStatus === 'aligned') {
|
||||
score += 10_000;
|
||||
score += Math.round(candidate.audioConfidence * 1000);
|
||||
if (candidate.audioOffsetMs !== null) {
|
||||
// Closer to 0ms offset against audio is better.
|
||||
score -= Math.min(500, Math.abs(candidate.audioOffsetMs));
|
||||
}
|
||||
} else if (candidate.audioStatus === 'unverified') {
|
||||
score += 2_000;
|
||||
} else {
|
||||
// Explicitly misaligned with audio: push well below aligned and unverified.
|
||||
score -= 5_000;
|
||||
}
|
||||
|
||||
// Signs/songs-only tracks or tiny dialogue counts are poor references.
|
||||
if (candidate.isSignsOnly) score -= 4_000;
|
||||
if (candidate.dialogueCount < 20) score -= 3_000;
|
||||
|
||||
// Embedded tracks in the container are usually authored for this exact video rip.
|
||||
if (candidate.isEmbedded) score += 250;
|
||||
if (candidate.isFullDialogueHint) score += 150;
|
||||
if (candidate.isEnglish) score += 100;
|
||||
if (candidate.isSecondary) score += 40;
|
||||
|
||||
// Prefer dialogue-rich tracks (capped so huge karaoke tracks don't skew score).
|
||||
score += Math.min(200, Math.floor(candidate.dialogueCount / 5));
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
export function rankReferenceCandidates(
|
||||
candidates: readonly EvaluatedSubtitleReference[],
|
||||
): EvaluatedSubtitleReference[] {
|
||||
return [...candidates].sort((a, b) => scoreReferenceCandidate(b) - scoreReferenceCandidate(a));
|
||||
}
|
||||
|
||||
export function buildTrackReferenceLabel(track: MpvTrack, isSecondary: boolean): string {
|
||||
const id = typeof track.id === 'number' ? track.id : -1;
|
||||
const source = track.external ? 'External' : 'Internal';
|
||||
const parts: string[] = [];
|
||||
if (track.lang) parts.push(track.lang);
|
||||
if (track.title && track.title !== track.lang) parts.push(track.title);
|
||||
if (parts.length === 0 && track.external && track['external-filename']) {
|
||||
parts.push(path.basename(track['external-filename']));
|
||||
}
|
||||
const descriptor = parts.length > 0 ? parts.join(' - ') : 'unknown';
|
||||
const role = isSecondary ? ' (secondary)' : '';
|
||||
return `${source} #${id} - ${descriptor}${role}`;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
applyTimingToSubtitleFile,
|
||||
decodeSubtitleBytes,
|
||||
decodeSubtitleBytesWithStatus,
|
||||
extractSpansFromParsedSubtitle,
|
||||
formatSpansAsSrt,
|
||||
isSignStyleOrEffect,
|
||||
isSignsOrSongsTrackMeta,
|
||||
parseSubtitleFileContent,
|
||||
} from './subtitle-lines';
|
||||
|
||||
test('isSignStyleOrEffect separates signs/songs styles from dialogue styles', () => {
|
||||
for (const dialogueStyle of [
|
||||
'Default',
|
||||
'Subtitle',
|
||||
'Subtitles',
|
||||
'Notebook',
|
||||
'Main Top',
|
||||
'DefaultItalics',
|
||||
'Edward',
|
||||
]) {
|
||||
assert.equal(isSignStyleOrEffect(dialogueStyle), false, `${dialogueStyle} should be dialogue`);
|
||||
}
|
||||
|
||||
for (const signStyle of [
|
||||
'Sign',
|
||||
'Signs',
|
||||
'sign_0423_EpTitle',
|
||||
'Title',
|
||||
'Episode Title',
|
||||
'OP Kara',
|
||||
'ED-Romaji',
|
||||
'OPRomaji',
|
||||
'TLNote',
|
||||
'TL Note',
|
||||
'Insert Song',
|
||||
'Lyrics',
|
||||
'Typeset',
|
||||
]) {
|
||||
assert.equal(isSignStyleOrEffect(signStyle), true, `${signStyle} should be a sign/song`);
|
||||
}
|
||||
});
|
||||
|
||||
test('isSignsOrSongsTrackMeta flags signs, songs, lyrics, and forced tracks', () => {
|
||||
assert.equal(isSignsOrSongsTrackMeta({ forced: true, title: 'English' }), true);
|
||||
assert.equal(isSignsOrSongsTrackMeta({ title: 'English (Signs & Songs)' }), true);
|
||||
assert.equal(isSignsOrSongsTrackMeta({ title: 'S&S' }), true);
|
||||
assert.equal(isSignsOrSongsTrackMeta({ 'external-filename': '/tmp/ep01.forced.ass' }), true);
|
||||
assert.equal(isSignsOrSongsTrackMeta({ title: 'English [Full Dialogue]' }), false);
|
||||
assert.equal(isSignsOrSongsTrackMeta({ title: 'Japanese' }), false);
|
||||
});
|
||||
|
||||
test('parseSubtitleFileContent classifies ASS signs, drawings, karaoke, and preserves format on rewrite', () => {
|
||||
const ass = [
|
||||
'[Script Info]',
|
||||
'Title: Test Episode',
|
||||
'',
|
||||
'[V4+ Styles]',
|
||||
'Format: Name, Fontname',
|
||||
'Style: Default,Arial',
|
||||
'',
|
||||
'[Events]',
|
||||
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
|
||||
'Comment: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,keep this comment',
|
||||
'Dialogue: 0,0:00:10.00,0:00:12.50,Default,,0,0,0,,{\\an8}待って!',
|
||||
'Dialogue: 0,0:00:11.00,0:00:13.00,Sign,,0,0,0,,{\\pos(100,200)}木ノ葉病院',
|
||||
'Dialogue: 0,0:00:13.00,0:00:15.00,Default,,0,0,0,,{\\pos(320,40)}看板',
|
||||
'Dialogue: 0,0:00:16.00,0:00:18.00,OPRomaji,,0,0,0,,{\\k20}ha{\\k30}ru',
|
||||
'Dialogue: 0,0:00:19.00,0:00:21.00,Default,,0,0,0,,{\\p1}m 0 0 l 100 0{\\p0}',
|
||||
'Dialogue: 0,0:00:22.00,0:00:24.00,Default,,0,0,0,,そうか, わかった',
|
||||
].join('\r\n');
|
||||
|
||||
const parsed = parseSubtitleFileContent(ass, 'ep01.ass');
|
||||
assert.equal(parsed.format, 'ass');
|
||||
assert.equal(parsed.eol, '\r\n');
|
||||
assert.equal(parsed.events.length, 6);
|
||||
|
||||
const { spans, dialogueIndices, dialogueCount, signCount } = extractSpansFromParsedSubtitle(
|
||||
parsed,
|
||||
{ stripSigns: true },
|
||||
);
|
||||
assert.equal(dialogueCount, 2);
|
||||
assert.equal(signCount, 4);
|
||||
assert.deepEqual(dialogueIndices, [0, 5]);
|
||||
assert.deepEqual(spans, [
|
||||
{ start: 10, end: 12.5 },
|
||||
{ start: 22, end: 24 },
|
||||
]);
|
||||
|
||||
// Apply different shifts to the two dialogue lines (+2s and +5s) and verify signs follow nearest dialogue.
|
||||
const rewritten = applyTimingToSubtitleFile(parsed, dialogueIndices, [2.0, 5.0], 1.0);
|
||||
assert.ok(
|
||||
rewritten.includes('Comment: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,keep this comment'),
|
||||
);
|
||||
assert.ok(
|
||||
rewritten.includes('Dialogue: 0,0:00:12.00,0:00:14.50,Default,,0,0,0,,{\\an8}待って!'),
|
||||
);
|
||||
// Sign at 11s is nearest to dialogue 0 (10s) -> +2s => 13s..15s
|
||||
assert.ok(
|
||||
rewritten.includes('Dialogue: 0,0:00:13.00,0:00:15.00,Sign,,0,0,0,,{\\pos(100,200)}木ノ葉病院'),
|
||||
);
|
||||
// Drawing at 19s is nearest to dialogue 5 (22s) -> +5s => 24s..26s
|
||||
assert.ok(
|
||||
rewritten.includes(
|
||||
'Dialogue: 0,0:00:24.00,0:00:26.00,Default,,0,0,0,,{\\p1}m 0 0 l 100 0{\\p0}',
|
||||
),
|
||||
);
|
||||
// Commas inside Text field stay intact!
|
||||
assert.ok(
|
||||
rewritten.includes('Dialogue: 0,0:00:27.00,0:00:29.00,Default,,0,0,0,,そうか, わかった'),
|
||||
);
|
||||
assert.ok(rewritten.includes('\r\n'));
|
||||
});
|
||||
|
||||
test('parseSubtitleFileContent keeps positioned ASS lines as dialogue when most lines use \\pos', () => {
|
||||
const ass = [
|
||||
'[Events]',
|
||||
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
|
||||
'Dialogue: 0,0:00:01.00,0:00:03.00,Default,,0,0,0,,{\\pos(640,680)}もしもし',
|
||||
'Dialogue: 0,0:00:04.00,0:00:06.00,Default,,0,0,0,,{\\pos(640,40)}元気?',
|
||||
].join('\n');
|
||||
|
||||
const parsed = parseSubtitleFileContent(ass, 'all-pos.ass');
|
||||
const extracted = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
|
||||
assert.equal(extracted.dialogueCount, 2);
|
||||
assert.equal(extracted.signCount, 0);
|
||||
});
|
||||
|
||||
test('parseSubtitleFileContent preserves SRT/VTT cue settings and strips music-only lines', () => {
|
||||
const vtt = [
|
||||
'WEBVTT',
|
||||
'',
|
||||
'00:01.000 --> 00:02.500 align:center line:90%',
|
||||
'こんにちは',
|
||||
'',
|
||||
'00:03.000 --> 00:05.000',
|
||||
'♪ La la la ♪',
|
||||
'',
|
||||
'00:06.000 --> 00:08.000',
|
||||
'元気ですか?',
|
||||
].join('\n');
|
||||
|
||||
const parsed = parseSubtitleFileContent(vtt, 'ep01.vtt');
|
||||
assert.equal(parsed.format, 'vtt');
|
||||
const extracted = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
|
||||
assert.equal(extracted.dialogueCount, 2);
|
||||
assert.equal(extracted.signCount, 1);
|
||||
|
||||
const rewritten = applyTimingToSubtitleFile(parsed, extracted.dialogueIndices, [1.5, 1.5], 1.0);
|
||||
assert.ok(rewritten.includes('WEBVTT'));
|
||||
assert.ok(rewritten.includes('00:00:02.500 --> 00:00:04.000 align:center line:90%'));
|
||||
assert.ok(rewritten.includes('00:00:04.500 --> 00:00:06.500\n♪ La la la ♪'));
|
||||
});
|
||||
|
||||
test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable bytes accurately', () => {
|
||||
const bomBytes = new Uint8Array([0xef, 0xbb, 0xbf, ...Buffer.from('hello', 'utf8')]);
|
||||
assert.equal(decodeSubtitleBytes(bomBytes), 'hello');
|
||||
assert.deepEqual(decodeSubtitleBytesWithStatus(bomBytes), { text: 'hello', lossless: true });
|
||||
|
||||
// Bytes invalid in UTF-8, Shift_JIS, and EUC-JP trigger lossy fallback.
|
||||
const corrupt = new Uint8Array([0x80, 0xff, 0xfe, 0x80]);
|
||||
const lossy = decodeSubtitleBytesWithStatus(corrupt);
|
||||
assert.equal(lossy.lossless, false);
|
||||
|
||||
const srt = formatSpansAsSrt([
|
||||
{ start: 5.5, end: 7.0 },
|
||||
{ start: 1.25, end: 2.75 },
|
||||
]);
|
||||
assert.ok(srt.includes('00:00:01,250 --> 00:00:02,750'));
|
||||
assert.ok(srt.includes('00:00:05,500 --> 00:00:07,000'));
|
||||
});
|
||||
@@ -0,0 +1,606 @@
|
||||
export type SubtitleFileFormat = 'ass' | 'srt' | 'vtt';
|
||||
|
||||
export interface SubtitleTimeSpan {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export interface ParsedSubtitleLine {
|
||||
/** Line index in the original file's `lines` array (0-based). */
|
||||
lineIndex: number;
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
sign: boolean;
|
||||
/** ASS field positions for format-preserving timestamp rewrite. */
|
||||
assStartFieldIndex?: number;
|
||||
assEndFieldIndex?: number;
|
||||
assFieldCount?: number;
|
||||
/** SRT/VTT suffix after the end timestamp (e.g., VTT cue settings). */
|
||||
timingSuffix?: string;
|
||||
/** SRT/VTT leading indentation before start timestamp. */
|
||||
timingPrefix?: string;
|
||||
}
|
||||
|
||||
export interface ParsedSubtitleFile {
|
||||
format: SubtitleFileFormat;
|
||||
eol: '\r\n' | '\n';
|
||||
rawLines: string[];
|
||||
events: ParsedSubtitleLine[];
|
||||
/** False when byte decoding fell back to lossy replacement (e.g. U+FFFD). */
|
||||
lossless?: boolean;
|
||||
}
|
||||
|
||||
const SIGN_STYLE_WORDS = new Set([
|
||||
'sign',
|
||||
'signs',
|
||||
'signage',
|
||||
'typeset',
|
||||
'ts',
|
||||
'title',
|
||||
'titles',
|
||||
'logo',
|
||||
'screen',
|
||||
'onscreen',
|
||||
'insert',
|
||||
'song',
|
||||
'songs',
|
||||
'lyric',
|
||||
'lyrics',
|
||||
'karaoke',
|
||||
'kara',
|
||||
'kfx',
|
||||
'fx',
|
||||
'op',
|
||||
'ed',
|
||||
'opening',
|
||||
'ending',
|
||||
'note',
|
||||
'notes',
|
||||
'tl',
|
||||
'tn',
|
||||
'credit',
|
||||
'credits',
|
||||
'eyecatch',
|
||||
'next',
|
||||
'preview',
|
||||
'caption',
|
||||
'banner',
|
||||
]);
|
||||
|
||||
const TRACK_SIGNS_OR_SONGS_PATTERN =
|
||||
/(?:^|[^\p{L}\p{N}])(?:signs?(?:\s*(?:&|and|\+|\/|-|_)\s*songs?)?|songs?|lyrics?|karaoke|forced|s[\s&+_-]*s|op|ed|opening|ending)(?=$|[^\p{L}\p{N}])|看板|歌詞/iu;
|
||||
|
||||
const SRT_VTT_TIMING_LINE_PATTERN =
|
||||
/^(\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(\s*-->\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(.*)$/;
|
||||
|
||||
const ASS_DRAWING_PATTERN = /\{[^}]*\\p[1-9][^}]*\}[^{]*/g;
|
||||
const ASS_TAG_PATTERN = /\{[^}]*\}/g;
|
||||
const ASS_KARAOKE_TAG_PATTERN = /\{[^}]*\\(?:k|kf|ko|K)\d+[^}]*\}/;
|
||||
const HTML_TAG_PATTERN = /<\/?[a-zA-Z][^>]*>/g;
|
||||
const MUSIC_ONLY_TEXT_PATTERN =
|
||||
/^(?:[♪♫♩♬\s~~\-–—()()[\]【】]*|(?:[\[((](?:music|song|singing|lyrics?|instrumental|op|ed|opening|ending|bgm|音楽|歌|歌唱)[\]))]\s*)+)$/iu;
|
||||
|
||||
function tryDecode(bytes: Uint8Array, encoding: string, fatal: boolean): string | null {
|
||||
try {
|
||||
return new TextDecoder(encoding, { fatal }).decode(bytes);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface DecodedSubtitleBytes {
|
||||
text: string;
|
||||
lossless: boolean;
|
||||
}
|
||||
|
||||
export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitleBytes {
|
||||
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
|
||||
const rest = bytes.subarray(3);
|
||||
const strict = tryDecode(rest, 'utf-8', true);
|
||||
if (strict !== null) return { text: strict, lossless: true };
|
||||
return { text: new TextDecoder('utf-8').decode(rest), lossless: false };
|
||||
}
|
||||
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
|
||||
const strict = tryDecode(bytes, 'utf-16le', true);
|
||||
if (strict !== null) return { text: strict, lossless: true };
|
||||
return {
|
||||
text: tryDecode(bytes, 'utf-16le', false) ?? new TextDecoder('utf-8').decode(bytes),
|
||||
lossless: false,
|
||||
};
|
||||
}
|
||||
if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
|
||||
const strict = tryDecode(bytes, 'utf-16be', true);
|
||||
if (strict !== null) return { text: strict, lossless: true };
|
||||
return {
|
||||
text: tryDecode(bytes, 'utf-16be', false) ?? new TextDecoder('utf-8').decode(bytes),
|
||||
lossless: false,
|
||||
};
|
||||
}
|
||||
const strictUtf8 = tryDecode(bytes, 'utf-8', true);
|
||||
if (strictUtf8 !== null) {
|
||||
return { text: strictUtf8, lossless: true };
|
||||
}
|
||||
const shiftJis = tryDecode(bytes, 'shift_jis', true);
|
||||
if (shiftJis !== null) {
|
||||
return { text: shiftJis, lossless: true };
|
||||
}
|
||||
const eucJp = tryDecode(bytes, 'euc-jp', true);
|
||||
if (eucJp !== null) {
|
||||
return { text: eucJp, lossless: true };
|
||||
}
|
||||
return { text: new TextDecoder('utf-8').decode(bytes), lossless: false };
|
||||
}
|
||||
|
||||
export function decodeSubtitleBytes(bytes: Uint8Array): string {
|
||||
return decodeSubtitleBytesWithStatus(bytes).text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a style or effect name into lowercase word tokens so camelCase / snake_case /
|
||||
* kebab-case names like "OPRomaji", "TLNote", "sign_0423_EpTitle" match cleanly while
|
||||
* dialogue styles like "Subtitle", "Notebook", or "Edward" do not.
|
||||
*/
|
||||
export function splitStyleWords(name: string): string[] {
|
||||
const words: string[] = [];
|
||||
let word = '';
|
||||
for (let i = 0; i < name.length; i += 1) {
|
||||
const ch = name[i]!;
|
||||
const isAlphaNum = /[A-Za-z0-9]/.test(ch);
|
||||
if (!isAlphaNum) {
|
||||
if (word) {
|
||||
words.push(word);
|
||||
word = '';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (word) {
|
||||
const prev = name[i - 1]!;
|
||||
const next = name[i + 1] ?? '';
|
||||
const prevLower = /[a-z]/.test(prev);
|
||||
const prevUpper = /[A-Z]/.test(prev);
|
||||
const prevDigit = /[0-9]/.test(prev);
|
||||
const currUpper = /[A-Z]/.test(ch);
|
||||
const currDigit = /[0-9]/.test(ch);
|
||||
const nextLower = /[a-z]/.test(next);
|
||||
if (
|
||||
(prevLower && currUpper) ||
|
||||
(prevUpper && currUpper && nextLower) ||
|
||||
prevDigit !== currDigit
|
||||
) {
|
||||
words.push(word);
|
||||
word = '';
|
||||
}
|
||||
}
|
||||
word += ch.toLowerCase();
|
||||
}
|
||||
if (word) {
|
||||
words.push(word);
|
||||
}
|
||||
return words;
|
||||
}
|
||||
|
||||
export function isSignStyleOrEffect(value: string): boolean {
|
||||
if (!value.trim()) return false;
|
||||
return splitStyleWords(value).some((word) => SIGN_STYLE_WORDS.has(word));
|
||||
}
|
||||
|
||||
export function isSignsOrSongsTrackMeta(track: {
|
||||
forced?: boolean;
|
||||
title?: string;
|
||||
'external-filename'?: string;
|
||||
}): boolean {
|
||||
if (track.forced === true) return true;
|
||||
const combined = `${track.title ?? ''} ${track['external-filename'] ? (track['external-filename'].split(/[\\/]/).pop() ?? '') : ''}`;
|
||||
return TRACK_SIGNS_OR_SONGS_PATTERN.test(combined);
|
||||
}
|
||||
|
||||
export function parseSubtitleTimestamp(raw: string): number | null {
|
||||
const normalized = raw.trim().replace(',', '.');
|
||||
const parts = normalized.split(':');
|
||||
if (parts.length === 3) {
|
||||
const h = Number(parts[0]);
|
||||
const m = Number(parts[1]);
|
||||
const s = Number(parts[2]);
|
||||
if (!Number.isFinite(h) || !Number.isFinite(m) || !Number.isFinite(s)) return null;
|
||||
return h * 3600 + m * 60 + s;
|
||||
}
|
||||
if (parts.length === 2) {
|
||||
const m = Number(parts[0]);
|
||||
const s = Number(parts[1]);
|
||||
if (!Number.isFinite(m) || !Number.isFinite(s)) return null;
|
||||
return m * 60 + s;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function cleanCuePlainText(raw: string): string {
|
||||
return raw
|
||||
.replace(ASS_DRAWING_PATTERN, '')
|
||||
.replace(ASS_TAG_PATTERN, '')
|
||||
.replace(HTML_TAG_PATTERN, '')
|
||||
.replace(/\\N|\\n/g, '\n')
|
||||
.replace(/\\h/g, ' ')
|
||||
.replace(/\u200B/g, '')
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function isMusicOrLyricText(plainText: string, rawText: string): boolean {
|
||||
if (!plainText) return true;
|
||||
if (/[♪♫]/u.test(plainText)) return true;
|
||||
if (MUSIC_ONLY_TEXT_PATTERN.test(plainText)) return true;
|
||||
if (ASS_KARAOKE_TAG_PATTERN.test(rawText)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function detectFormat(text: string, filename?: string): SubtitleFileFormat {
|
||||
const lowerName = (filename ?? '').toLowerCase();
|
||||
if (
|
||||
/^\[events\]/im.test(text) ||
|
||||
/^dialogue:/im.test(text) ||
|
||||
lowerName.endsWith('.ass') ||
|
||||
lowerName.endsWith('.ssa')
|
||||
) {
|
||||
return 'ass';
|
||||
}
|
||||
if (/^\s*WEBVTT\b/m.test(text) || lowerName.endsWith('.vtt')) {
|
||||
return 'vtt';
|
||||
}
|
||||
return 'srt';
|
||||
}
|
||||
|
||||
function splitAssDialogueFields(rest: string, fieldCount: number): string[] {
|
||||
const fields: string[] = [];
|
||||
let start = 0;
|
||||
for (let i = 0; i < fieldCount - 1; i += 1) {
|
||||
const comma = rest.indexOf(',', start);
|
||||
if (comma === -1) {
|
||||
fields.push(rest.slice(start));
|
||||
return fields;
|
||||
}
|
||||
fields.push(rest.slice(start, comma));
|
||||
start = comma + 1;
|
||||
}
|
||||
fields.push(rest.slice(start));
|
||||
return fields;
|
||||
}
|
||||
|
||||
function parseAssSubtitle(rawLines: string[], eol: '\r\n' | '\n'): ParsedSubtitleFile {
|
||||
interface RawAssEntry {
|
||||
lineIndex: number;
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
namedSign: boolean;
|
||||
placed: boolean;
|
||||
musicOrEmpty: boolean;
|
||||
startFieldIndex: number;
|
||||
endFieldIndex: number;
|
||||
fieldCount: number;
|
||||
}
|
||||
|
||||
let inEvents = false;
|
||||
let format: string[] = [];
|
||||
const rawEntries: RawAssEntry[] = [];
|
||||
|
||||
for (let i = 0; i < rawLines.length; i += 1) {
|
||||
const trimmed = rawLines[i]!.trim();
|
||||
if (trimmed.startsWith('[')) {
|
||||
inEvents = trimmed.toLowerCase() === '[events]';
|
||||
continue;
|
||||
}
|
||||
if (!inEvents) continue;
|
||||
|
||||
if (/^format:/i.test(trimmed)) {
|
||||
format = trimmed
|
||||
.slice(trimmed.indexOf(':') + 1)
|
||||
.split(',')
|
||||
.map((field) => field.trim().toLowerCase());
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!/^dialogue:/i.test(trimmed)) continue;
|
||||
|
||||
if (format.length === 0) {
|
||||
format = [
|
||||
'layer',
|
||||
'start',
|
||||
'end',
|
||||
'style',
|
||||
'name',
|
||||
'marginl',
|
||||
'marginr',
|
||||
'marginv',
|
||||
'effect',
|
||||
'text',
|
||||
];
|
||||
}
|
||||
|
||||
const colonIndex = rawLines[i]!.indexOf(':');
|
||||
const rest = rawLines[i]!.slice(colonIndex + 1);
|
||||
const fields = splitAssDialogueFields(rest, format.length);
|
||||
|
||||
const startIdx = format.indexOf('start');
|
||||
const endIdx = format.indexOf('end');
|
||||
const styleIdx = format.indexOf('style');
|
||||
const effectIdx = format.indexOf('effect');
|
||||
const textIdx = format.indexOf('text');
|
||||
if (startIdx < 0 || endIdx < 0 || textIdx < 0) continue;
|
||||
|
||||
const start = parseSubtitleTimestamp(fields[startIdx] ?? '');
|
||||
const end = parseSubtitleTimestamp(fields[endIdx] ?? '');
|
||||
if (start === null || end === null || end <= start) continue;
|
||||
|
||||
const style = (fields[styleIdx] ?? '').trim();
|
||||
const effect = (fields[effectIdx] ?? '').trim();
|
||||
const rawBody = fields[textIdx] ?? '';
|
||||
const plainText = cleanCuePlainText(rawBody);
|
||||
const namedSign = isSignStyleOrEffect(style) || isSignStyleOrEffect(effect);
|
||||
const placed = /\\(?:pos|move)\(/.test(rawBody);
|
||||
const musicOrEmpty = isMusicOrLyricText(plainText, rawBody);
|
||||
|
||||
rawEntries.push({
|
||||
lineIndex: i,
|
||||
start,
|
||||
end,
|
||||
text: plainText,
|
||||
namedSign,
|
||||
placed,
|
||||
musicOrEmpty,
|
||||
startFieldIndex: startIdx,
|
||||
endFieldIndex: endIdx,
|
||||
fieldCount: format.length,
|
||||
});
|
||||
}
|
||||
|
||||
// Only treat \pos / \move as sign indicators when fewer than half of the
|
||||
// non-named lines are positioned (some conversion scripts position every line).
|
||||
let unnamedCount = 0;
|
||||
let placedUnnamedCount = 0;
|
||||
for (const entry of rawEntries) {
|
||||
if (!entry.namedSign && !entry.musicOrEmpty) {
|
||||
unnamedCount += 1;
|
||||
if (entry.placed) placedUnnamedCount += 1;
|
||||
}
|
||||
}
|
||||
const placingMarksSigns = placedUnnamedCount * 2 <= unnamedCount;
|
||||
|
||||
const events: ParsedSubtitleLine[] = rawEntries.map((entry) => ({
|
||||
lineIndex: entry.lineIndex,
|
||||
start: entry.start,
|
||||
end: entry.end,
|
||||
text: entry.text,
|
||||
sign: entry.namedSign || entry.musicOrEmpty || (entry.placed && placingMarksSigns),
|
||||
assStartFieldIndex: entry.startFieldIndex,
|
||||
assEndFieldIndex: entry.endFieldIndex,
|
||||
assFieldCount: entry.fieldCount,
|
||||
}));
|
||||
|
||||
return { format: 'ass', eol, rawLines, events };
|
||||
}
|
||||
|
||||
function parseSrtOrVttSubtitle(
|
||||
rawLines: string[],
|
||||
eol: '\r\n' | '\n',
|
||||
format: 'srt' | 'vtt',
|
||||
): ParsedSubtitleFile {
|
||||
const events: ParsedSubtitleLine[] = [];
|
||||
|
||||
for (let i = 0; i < rawLines.length; i += 1) {
|
||||
const match = SRT_VTT_TIMING_LINE_PATTERN.exec(rawLines[i]!);
|
||||
if (!match) continue;
|
||||
|
||||
const start = parseSubtitleTimestamp(match[2]!);
|
||||
const end = parseSubtitleTimestamp(match[4]!);
|
||||
if (start === null || end === null || end <= start) continue;
|
||||
|
||||
const bodyLines: string[] = [];
|
||||
let j = i + 1;
|
||||
while (j < rawLines.length && rawLines[j]!.trim() !== '') {
|
||||
if (SRT_VTT_TIMING_LINE_PATTERN.test(rawLines[j]!)) break;
|
||||
bodyLines.push(rawLines[j]!);
|
||||
j += 1;
|
||||
}
|
||||
|
||||
const rawBody = bodyLines.join('\n');
|
||||
const plainText = cleanCuePlainText(rawBody);
|
||||
events.push({
|
||||
lineIndex: i,
|
||||
start,
|
||||
end,
|
||||
text: plainText,
|
||||
sign: isMusicOrLyricText(plainText, rawBody),
|
||||
timingPrefix: match[1] ?? '',
|
||||
timingSuffix: match[5] ?? '',
|
||||
});
|
||||
|
||||
i = j - 1;
|
||||
}
|
||||
|
||||
return { format, eol, rawLines, events };
|
||||
}
|
||||
|
||||
export function parseSubtitleFileContent(content: string, filename?: string): ParsedSubtitleFile {
|
||||
const cleanContent = content.startsWith('\uFEFF') ? content.slice(1) : content;
|
||||
const eol: '\r\n' | '\n' = cleanContent.includes('\r\n') ? '\r\n' : '\n';
|
||||
const rawLines = cleanContent.split(/\r?\n/);
|
||||
const format = detectFormat(cleanContent, filename);
|
||||
if (format === 'ass') {
|
||||
return parseAssSubtitle(rawLines, eol);
|
||||
}
|
||||
return parseSrtOrVttSubtitle(rawLines, eol, format);
|
||||
}
|
||||
|
||||
export function extractSpansFromParsedSubtitle(
|
||||
parsed: ParsedSubtitleFile,
|
||||
options: { stripSigns?: boolean } = {},
|
||||
): {
|
||||
spans: SubtitleTimeSpan[];
|
||||
dialogueIndices: number[];
|
||||
dialogueCount: number;
|
||||
signCount: number;
|
||||
} {
|
||||
const stripSigns = options.stripSigns !== false;
|
||||
const dialogueIndices: number[] = [];
|
||||
let signCount = 0;
|
||||
|
||||
for (let i = 0; i < parsed.events.length; i += 1) {
|
||||
const event = parsed.events[i]!;
|
||||
if (event.sign) {
|
||||
signCount += 1;
|
||||
if (stripSigns) continue;
|
||||
}
|
||||
dialogueIndices.push(i);
|
||||
}
|
||||
|
||||
// Fallback: if stripping signs left zero lines in an unusual file, keep all lines.
|
||||
const activeIndices =
|
||||
dialogueIndices.length > 0 ? dialogueIndices : parsed.events.map((_, idx) => idx);
|
||||
|
||||
const spans = activeIndices.map((idx) => {
|
||||
const ev = parsed.events[idx]!;
|
||||
return { start: ev.start, end: ev.end };
|
||||
});
|
||||
|
||||
return {
|
||||
spans,
|
||||
dialogueIndices: activeIndices,
|
||||
dialogueCount: parsed.events.length - signCount,
|
||||
signCount,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatAssTimestamp(seconds: number): string {
|
||||
const clamped = Math.max(0, seconds);
|
||||
const totalCentiseconds = Math.round(clamped * 100);
|
||||
const cs = totalCentiseconds % 100;
|
||||
const totalSeconds = Math.floor(totalCentiseconds / 100);
|
||||
const sec = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const min = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
return `${hours}:${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')}.${String(cs).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function formatSrtTimestamp(seconds: number): string {
|
||||
const clamped = Math.max(0, seconds);
|
||||
const totalMs = Math.round(clamped * 1000);
|
||||
const ms = totalMs % 1000;
|
||||
const totalSeconds = Math.floor(totalMs / 1000);
|
||||
const sec = totalSeconds % 60;
|
||||
const totalMinutes = Math.floor(totalSeconds / 60);
|
||||
const min = totalMinutes % 60;
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
return `${String(hours).padStart(2, '0')}:${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')},${String(ms).padStart(3, '0')}`;
|
||||
}
|
||||
|
||||
export function formatVttTimestamp(seconds: number): string {
|
||||
return formatSrtTimestamp(seconds).replace(',', '.');
|
||||
}
|
||||
|
||||
function findNearestDialogueMoveIndex(
|
||||
eventIndex: number,
|
||||
dialogueIndices: readonly number[],
|
||||
events: readonly ParsedSubtitleLine[],
|
||||
): number {
|
||||
if (dialogueIndices.length === 0) return 0;
|
||||
let lo = 0;
|
||||
let hi = dialogueIndices.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if (dialogueIndices[mid]! < eventIndex) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
if (lo === 0) return 0;
|
||||
if (lo >= dialogueIndices.length) return dialogueIndices.length - 1;
|
||||
const eventStart = events[eventIndex]!.start;
|
||||
const prevStart = events[dialogueIndices[lo - 1]!]!.start;
|
||||
const nextStart = events[dialogueIndices[lo]!]!.start;
|
||||
return Math.abs(eventStart - prevStart) <= Math.abs(nextStart - eventStart) ? lo - 1 : lo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite only the timestamps of the original subtitle file, preserving all ASS
|
||||
* styles/headers/tags/comments, SRT cue numbers, and VTT settings. Non-dialogue
|
||||
* signs/songs follow the shift of the dialogue line nearest them in time.
|
||||
*/
|
||||
export function applyTimingToSubtitleFile(
|
||||
parsed: ParsedSubtitleFile,
|
||||
dialogueIndices: readonly number[],
|
||||
movesSec: readonly number[],
|
||||
ratio: number,
|
||||
): string {
|
||||
if (parsed.events.length === 0 || dialogueIndices.length === 0 || movesSec.length === 0) {
|
||||
return parsed.rawLines.join(parsed.eol);
|
||||
}
|
||||
|
||||
const outLines = [...parsed.rawLines];
|
||||
const dialogueMoveByEventIndex = new Map<number, number>();
|
||||
for (let k = 0; k < dialogueIndices.length; k += 1) {
|
||||
dialogueMoveByEventIndex.set(dialogueIndices[k]!, movesSec[k] ?? 0);
|
||||
}
|
||||
|
||||
for (let i = 0; i < parsed.events.length; i += 1) {
|
||||
const ev = parsed.events[i]!;
|
||||
const directMove = dialogueMoveByEventIndex.get(i);
|
||||
const shift =
|
||||
directMove !== undefined
|
||||
? directMove
|
||||
: (movesSec[findNearestDialogueMoveIndex(i, dialogueIndices, parsed.events)] ?? 0);
|
||||
|
||||
const newStart = Math.max(0, ev.start * ratio + shift);
|
||||
const newEnd = Math.max(newStart + 0.05, ev.end * ratio + shift);
|
||||
|
||||
if (parsed.format === 'ass') {
|
||||
const rawLine = outLines[ev.lineIndex]!;
|
||||
const colonIndex = rawLine.indexOf(':');
|
||||
const prefix = rawLine.slice(0, colonIndex + 1);
|
||||
const rest = rawLine.slice(colonIndex + 1);
|
||||
const fieldCount = ev.assFieldCount ?? 10;
|
||||
const fields = splitAssDialogueFields(rest, fieldCount);
|
||||
if (
|
||||
ev.assStartFieldIndex !== undefined &&
|
||||
ev.assEndFieldIndex !== undefined &&
|
||||
ev.assStartFieldIndex < fields.length &&
|
||||
ev.assEndFieldIndex < fields.length
|
||||
) {
|
||||
fields[ev.assStartFieldIndex] = formatAssTimestamp(newStart);
|
||||
fields[ev.assEndFieldIndex] = formatAssTimestamp(newEnd);
|
||||
outLines[ev.lineIndex] = `${prefix}${fields.join(',')}`;
|
||||
}
|
||||
} else if (parsed.format === 'vtt') {
|
||||
outLines[ev.lineIndex] =
|
||||
`${ev.timingPrefix ?? ''}${formatVttTimestamp(newStart)} --> ${formatVttTimestamp(newEnd)}${ev.timingSuffix ?? ''}`;
|
||||
} else {
|
||||
outLines[ev.lineIndex] =
|
||||
`${ev.timingPrefix ?? ''}${formatSrtTimestamp(newStart)} --> ${formatSrtTimestamp(newEnd)}${ev.timingSuffix ?? ''}`;
|
||||
}
|
||||
}
|
||||
|
||||
return outLines.join(parsed.eol);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a clean dialogue-only SRT file from spans, useful when feeding a cleaned
|
||||
* reference subtitle into external `alass`.
|
||||
*/
|
||||
export function formatSpansAsSrt(spans: readonly SubtitleTimeSpan[]): string {
|
||||
const valid = spans
|
||||
.filter(
|
||||
(span) => Number.isFinite(span.start) && Number.isFinite(span.end) && span.end > span.start,
|
||||
)
|
||||
.sort((a, b) => a.start - b.start || a.end - b.end);
|
||||
|
||||
return valid
|
||||
.map(
|
||||
(span, index) =>
|
||||
`${index + 1}\n${formatSrtTimestamp(span.start)} --> ${formatSrtTimestamp(span.end)}\nDialogue ${index + 1}\n`,
|
||||
)
|
||||
.join('\n');
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { codecToExtension, getSubsyncConfig } from './utils';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { codecToExtension, findSubsyncExecutable, getSubsyncConfig } from './utils';
|
||||
|
||||
test('codecToExtension maps stream/web formats to ffmpeg extractable extensions', () => {
|
||||
assert.equal(codecToExtension('subrip'), 'srt');
|
||||
@@ -22,3 +25,36 @@ test('getSubsyncConfig respects explicit replace value', () => {
|
||||
assert.equal(getSubsyncConfig({ replace: false }).replace, false);
|
||||
assert.equal(getSubsyncConfig({ replace: true }).replace, true);
|
||||
});
|
||||
|
||||
test('getSubsyncConfig defaults mode to auto and respects manual mode', () => {
|
||||
assert.equal(getSubsyncConfig(undefined).mode, 'auto');
|
||||
assert.equal(getSubsyncConfig({}).mode, 'auto');
|
||||
assert.equal(getSubsyncConfig({ mode: 'manual' }).mode, 'manual');
|
||||
});
|
||||
|
||||
test('findSubsyncExecutable skips non-executable files on POSIX and resolves bare overrides', () => {
|
||||
if (process.platform === 'win32') return;
|
||||
const dirA = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-path-a-'));
|
||||
const dirB = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-path-b-'));
|
||||
const prevPath = process.env.PATH;
|
||||
try {
|
||||
const nonExec = path.join(dirA, 'my-custom-tool');
|
||||
const execFile = path.join(dirB, 'my-custom-tool');
|
||||
fs.writeFileSync(nonExec, '#!/bin/sh\nexit 0\n', { mode: 0o644 });
|
||||
fs.chmodSync(nonExec, 0o644);
|
||||
fs.writeFileSync(execFile, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
|
||||
fs.chmodSync(execFile, 0o755);
|
||||
|
||||
process.env.PATH = `${dirA}${path.delimiter}${dirB}`;
|
||||
assert.equal(findSubsyncExecutable('my-custom-tool', ['my-custom-tool']), execFile);
|
||||
assert.equal(getSubsyncConfig({ ffmpeg_path: 'my-custom-tool' }).ffmpegPath, execFile);
|
||||
assert.equal(
|
||||
getSubsyncConfig({ ffmpeg_path: 'missing-custom-tool' }).ffmpegPath,
|
||||
'missing-custom-tool',
|
||||
);
|
||||
} finally {
|
||||
process.env.PATH = prevPath;
|
||||
fs.rmSync(dirA, { recursive: true, force: true });
|
||||
fs.rmSync(dirB, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
+102
-7
@@ -2,13 +2,15 @@ import * as fs from 'fs';
|
||||
import * as childProcess from 'child_process';
|
||||
import * as path from 'path';
|
||||
import { DEFAULT_CONFIG } from '../config';
|
||||
import { SubsyncConfig } from '../types';
|
||||
import { SubsyncConfig, SubsyncMode } from '../types';
|
||||
|
||||
export interface MpvTrack {
|
||||
id?: number;
|
||||
type?: string;
|
||||
selected?: boolean;
|
||||
external?: boolean;
|
||||
forced?: boolean;
|
||||
default?: boolean;
|
||||
lang?: string;
|
||||
title?: string;
|
||||
codec?: string;
|
||||
@@ -17,6 +19,7 @@ export interface MpvTrack {
|
||||
}
|
||||
|
||||
export interface SubsyncResolvedConfig {
|
||||
mode?: SubsyncMode;
|
||||
alassPath: string;
|
||||
ffsubsyncPath: string;
|
||||
ffmpegPath: string;
|
||||
@@ -29,8 +32,73 @@ const DEFAULT_SUBSYNC_EXECUTABLE_PATHS = {
|
||||
ffmpeg: '/usr/bin/ffmpeg',
|
||||
} as const;
|
||||
|
||||
const COMMON_BIN_DIRS = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'];
|
||||
const WINDOWS_RUNNABLE_EXTENSIONS = new Set(['.exe', '.com', '.cmd', '.bat', '.ps1', '.sh']);
|
||||
|
||||
function isExecutablePath(filePath: string): boolean {
|
||||
try {
|
||||
if (!fs.statSync(filePath).isFile()) return false;
|
||||
if (process.platform !== 'win32') {
|
||||
fs.accessSync(filePath, fs.constants.X_OK);
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function candidateExecutableNames(name: string): string[] {
|
||||
if (process.platform !== 'win32' || path.extname(name)) return [name];
|
||||
const extensions = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT')
|
||||
.split(';')
|
||||
.map((ext) => ext.trim())
|
||||
.filter((ext) => ext.length > 0 && WINDOWS_RUNNABLE_EXTENSIONS.has(ext.toLowerCase()));
|
||||
return [name, ...extensions.map((ext) => `${name}${ext}`)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an executable on PATH (or common install dirs), honoring an explicit
|
||||
* configured override first. Returns null if not found.
|
||||
*/
|
||||
export function findSubsyncExecutable(
|
||||
configuredPath: string | undefined,
|
||||
names: readonly string[],
|
||||
): string | null {
|
||||
const trimmed = configuredPath?.trim() ?? '';
|
||||
if (trimmed) {
|
||||
if (hasPathSeparators(trimmed)) {
|
||||
return isExecutablePath(trimmed) ? trimmed : null;
|
||||
}
|
||||
const foundConfigured = findSubsyncExecutable(undefined, [trimmed]);
|
||||
return foundConfigured;
|
||||
}
|
||||
|
||||
const dirs = [
|
||||
...(process.env.PATH ?? '')
|
||||
.split(path.delimiter)
|
||||
.map((entry) => entry.trim())
|
||||
.filter(Boolean),
|
||||
...(process.platform === 'win32' ? [] : COMMON_BIN_DIRS),
|
||||
];
|
||||
|
||||
const seen = new Set<string>();
|
||||
for (const dir of dirs) {
|
||||
if (seen.has(dir)) continue;
|
||||
seen.add(dir);
|
||||
for (const name of names) {
|
||||
for (const candidateName of candidateExecutableNames(name)) {
|
||||
const candidate = path.join(dir, candidateName);
|
||||
if (isExecutablePath(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface SubsyncContext {
|
||||
videoPath: string;
|
||||
workingDirectory?: string | null;
|
||||
durationSec?: number | null;
|
||||
primaryTrack: MpvTrack;
|
||||
secondaryTrack: MpvTrack | null;
|
||||
/** Every usable subtitle track, including the primary one. */
|
||||
@@ -46,7 +114,7 @@ export interface CommandResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function resolveCommandInvocation(
|
||||
export function resolveCommandInvocation(
|
||||
executable: string,
|
||||
args: string[],
|
||||
): { command: string; args: string[] } {
|
||||
@@ -65,6 +133,12 @@ function resolveCommandInvocation(
|
||||
return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`;
|
||||
};
|
||||
const extension = path.extname(executable).toLowerCase();
|
||||
if (extension === '.cmd' || extension === '.bat') {
|
||||
return {
|
||||
command: process.env.ComSpec || 'cmd.exe',
|
||||
args: ['/d', '/c', executable, ...args],
|
||||
};
|
||||
}
|
||||
if (extension === '.ps1') {
|
||||
return {
|
||||
command: 'powershell.exe',
|
||||
@@ -83,15 +157,36 @@ function resolveCommandInvocation(
|
||||
}
|
||||
|
||||
export function getSubsyncConfig(config: SubsyncConfig | undefined): SubsyncResolvedConfig {
|
||||
const resolvePath = (value: string | undefined, fallback: string): string => {
|
||||
const resolvePath = (
|
||||
value: string | undefined,
|
||||
names: readonly string[],
|
||||
fallback: string,
|
||||
): string => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : fallback;
|
||||
if (trimmed && trimmed.length > 0) {
|
||||
if (hasPathSeparators(trimmed)) return trimmed;
|
||||
return findSubsyncExecutable(trimmed, [trimmed]) ?? trimmed;
|
||||
}
|
||||
return findSubsyncExecutable(undefined, names) ?? fallback;
|
||||
};
|
||||
|
||||
return {
|
||||
alassPath: resolvePath(config?.alass_path, DEFAULT_SUBSYNC_EXECUTABLE_PATHS.alass),
|
||||
ffsubsyncPath: resolvePath(config?.ffsubsync_path, DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffsubsync),
|
||||
ffmpegPath: resolvePath(config?.ffmpeg_path, DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffmpeg),
|
||||
mode: config?.mode ?? DEFAULT_CONFIG.subsync.mode,
|
||||
alassPath: resolvePath(
|
||||
config?.alass_path,
|
||||
['alass', 'alass-cli'],
|
||||
DEFAULT_SUBSYNC_EXECUTABLE_PATHS.alass,
|
||||
),
|
||||
ffsubsyncPath: resolvePath(
|
||||
config?.ffsubsync_path,
|
||||
['ffsubsync'],
|
||||
DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffsubsync,
|
||||
),
|
||||
ffmpegPath: resolvePath(
|
||||
config?.ffmpeg_path,
|
||||
['ffmpeg'],
|
||||
DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffmpeg,
|
||||
),
|
||||
replace: config?.replace ?? DEFAULT_CONFIG.subsync.replace,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user