feat(subsync): integrate built-in automatic subtitle syncing

This commit is contained in:
sudacode committed 2026-11-25 19:47:56 -08:00
1 parent 926e6b047e
commit 05bdb64880
44 files changed
+6498 -135

No files matched your search

+1
View File
@@ -137,6 +137,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
},
},
subsync: {
mode: 'auto',
alass_path: '',
ffsubsync_path: '',
ffmpeg_path: '',
+8
View File
@@ -611,6 +611,14 @@ export function buildCoreConfigOptionRegistry(
defaultValue: defaultConfig.annotationWebsocket.port,
description: 'Annotated subtitle websocket server port.',
},
{
path: 'subsync.mode',
kind: 'enum',
enumValues: ['auto', 'manual'],
defaultValue: defaultConfig.subsync.mode,
description:
'Automatic subtitle sync mode ("auto" syncs immediately and opens the guided modal only when needed; "manual" always opens the modal).',
},
{
path: 'subsync.replace',
kind: 'boolean',
+5
View File
@@ -397,6 +397,11 @@ export function applyCoreDomainConfig(context: ResolveContext): void {
}
if (isObject(src.subsync)) {
if (src.subsync.mode === 'auto' || src.subsync.mode === 'manual') {
resolved.subsync.mode = src.subsync.mode;
} else if (src.subsync.mode !== undefined) {
warn('subsync.mode', src.subsync.mode, resolved.subsync.mode, "Expected 'auto' or 'manual'.");
}
const alass = asString(src.subsync.alass_path);
if (alass !== undefined) resolved.subsync.alass_path = alass;
const ffsubsync = asString(src.subsync.ffsubsync_path);
+5 -1
View File
@@ -121,7 +121,11 @@ export { handleMpvCommandFromIpc } from './ipc-command';
export { createFieldGroupingOverlayRuntime } from './field-grouping-overlay';
export { createNumericShortcutRuntime } from './numeric-shortcut';
export { runStartupBootstrapRuntime } from './startup';
export { runSubsyncManualFromIpcRuntime, triggerSubsyncFromConfigRuntime } from './subsync-runner';
export {
openSubsyncManualPickerRuntime,
runSubsyncManualFromIpcRuntime,
triggerSubsyncFromConfigRuntime,
} from './subsync-runner';
export { registerAnkiJimakuIpcRuntime } from './anki-jimaku';
export { ImmersionTrackerService } from './immersion-tracker-service';
export {
+14
View File
@@ -102,6 +102,8 @@ export interface IpcServiceDeps {
focusMainWindow: () => void;
activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise<boolean>;
runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
openSubsyncManual?: () => Promise<void>;
pickSubsyncReferenceFile?: () => Promise<string | null>;
onYoutubePickerResolve: (
request: YoutubePickerResolveRequest,
) => Promise<YoutubePickerResolveResult>;
@@ -373,6 +375,8 @@ export interface IpcDepsRuntimeOptions {
focusMainWindow: () => void;
activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise<boolean>;
runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
openSubsyncManual?: () => Promise<void>;
pickSubsyncReferenceFile?: () => Promise<string | null>;
onYoutubePickerResolve: (
request: YoutubePickerResolveRequest,
) => Promise<YoutubePickerResolveResult>;
@@ -457,6 +461,8 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
activatePlaybackWindowForOverlayInteraction:
options.activatePlaybackWindowForOverlayInteraction ?? (() => false),
runSubsyncManual: options.runSubsyncManual,
openSubsyncManual: options.openSubsyncManual,
pickSubsyncReferenceFile: options.pickSubsyncReferenceFile,
onYoutubePickerResolve: options.onYoutubePickerResolve,
previewMediaTimingReview: options.previewMediaTimingReview,
getMediaTimingReviewFrame: options.getMediaTimingReviewFrame,
@@ -819,6 +825,14 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
return await deps.runSubsyncManual(parsedRequest);
});
ipc.handle(IPC_CHANNELS.request.openSubsyncManual, async () => {
await deps.openSubsyncManual?.();
});
ipc.handle(IPC_CHANNELS.request.pickSubsyncReferenceFile, async () => {
return (await deps.pickSubsyncReferenceFile?.()) ?? null;
});
ipc.handle(IPC_CHANNELS.request.getRuntimeOptions, () => {
return deps.getRuntimeOptions();
});
+27
View File
@@ -2,7 +2,9 @@ import { SubsyncManualPayload, SubsyncManualRunRequest, SubsyncResult } from '..
import { SubsyncResolvedConfig } from '../../subsync/utils';
import { runSubsyncManualFromIpc } from './ipc-command';
import {
SubsyncVadPaths,
TriggerSubsyncFromConfigDeps,
openSubsyncManualPicker,
runSubsyncManual,
triggerSubsyncFromConfig,
} from './subsync';
@@ -19,6 +21,8 @@ interface MpvClientLike {
export interface SubsyncRuntimeDeps {
getMpvClient: () => MpvClientLike | null;
getResolvedSubsyncConfig: () => SubsyncResolvedConfig;
getVadPaths?: () => SubsyncVadPaths;
canPickReferenceFile?: () => boolean;
isSubsyncInProgress: () => boolean;
setSubsyncInProgress: (inProgress: boolean) => void;
showMpvOsd: (text: string) => void;
@@ -47,6 +51,8 @@ function buildTriggerSubsyncDeps(deps: SubsyncRuntimeDeps): TriggerSubsyncFromCo
return {
getMpvClient: deps.getMpvClient,
getResolvedConfig: deps.getResolvedSubsyncConfig,
getVadPaths: deps.getVadPaths,
canPickReferenceFile: deps.canPickReferenceFile,
isSubsyncInProgress: deps.isSubsyncInProgress,
setSubsyncInProgress: deps.setSubsyncInProgress,
showMpvOsd: deps.showMpvOsd,
@@ -60,6 +66,27 @@ export async function triggerSubsyncFromConfigRuntime(deps: SubsyncRuntimeDeps):
await triggerSubsyncFromConfig(buildTriggerSubsyncDeps(deps));
}
export async function openSubsyncManualPickerRuntime(deps: SubsyncRuntimeDeps): Promise<void> {
const triggerDeps = buildTriggerSubsyncDeps(deps);
if (triggerDeps.isSubsyncInProgress()) {
triggerDeps.showMpvOsd('Subsync already running');
return;
}
triggerDeps.setSubsyncInProgress(true);
try {
await triggerDeps.runWithSubsyncSpinner(() =>
openSubsyncManualPicker(triggerDeps, {
guidanceMessage: null,
}),
);
triggerDeps.showMpvOsd('Subsync: choose engine and subtitles');
} catch (error) {
triggerDeps.showMpvOsd(`Subsync failed: ${(error as Error).message}`);
} finally {
triggerDeps.setSubsyncInProgress(false);
}
}
export async function runSubsyncManualFromIpcRuntime(
request: SubsyncManualRunRequest,
deps: SubsyncRuntimeDeps,
+823 -1
View File
@@ -427,7 +427,7 @@ test('triggerSubsyncFromConfig does not validate sync tool paths before manual s
}),
);
assert.deepEqual(inProgress, [false]);
assert.deepEqual(inProgress, [true, false]);
assert.equal(payloadTrackCount, 2);
assert.deepEqual(osd, ['Subsync: choose engine and subtitles']);
});
@@ -1007,3 +1007,825 @@ test('runSubsyncManual resolves string sid values from mpv stream properties', a
assert.ok(outputPath!.length > 0);
assert.equal(fs.readFileSync(fromShellPath(outputPath!), 'utf8'), '');
});
function generateSyntheticSpans(
seedInit: bigint,
step: bigint,
limitSec = 900,
): Array<{ start: number; end: number }> {
const out: Array<{ start: number; end: number }> = [];
let seed = seedInit;
const mask = (1n << 64n) - 1n;
let t = 5.0;
while (t < limitSec) {
seed = (seed * 6364136223846793005n + step) & mask;
const len = 0.8 + (Number(seed >> 33n) / Number(1n << 31n)) * 2.5;
const gap = 0.5 + (Number((seed >> 13n) & 0xffffn) / 65536.0) * 3.5;
out.push({ start: t, end: t + len });
t += len + gap;
}
return out;
}
function fmtSrtTime(sec: number): string {
const totalMs = Math.max(0, Math.round(sec * 1000));
const ms = totalMs % 1000;
const totalSec = Math.floor(totalMs / 1000);
const s = totalSec % 60;
const totalMin = Math.floor(totalSec / 60);
const m = totalMin % 60;
const h = Math.floor(totalMin / 60);
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},${String(ms).padStart(3, '0')}`;
}
function fmtAssTime(sec: number): string {
const totalCs = Math.max(0, Math.round(sec * 100));
const cs = totalCs % 100;
const totalSec = Math.floor(totalCs / 100);
const s = totalSec % 60;
const totalMin = Math.floor(totalSec / 60);
const m = totalMin % 60;
const h = Math.floor(totalMin / 60);
return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}.${String(cs).padStart(2, '0')}`;
}
function writeSrtFromSpans(
filePath: string,
spans: ReadonlyArray<{ start: number; end: number }>,
shiftSec = 0,
): void {
const content = spans
.map(
(span, idx) =>
`${idx + 1}\n${fmtSrtTime(span.start + shiftSec)} --> ${fmtSrtTime(span.end + shiftSec)}\nセリフ ${idx + 1}\n`,
)
.join('\n');
fs.writeFileSync(filePath, content, 'utf8');
}
function writeAssWithSignsFromSpans(
filePath: string,
spans: ReadonlyArray<{ start: number; end: number }>,
shiftSec = 0,
): void {
const lines = [
'[Script Info]',
'Title: Test',
'',
'[Events]',
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
];
for (let i = 0; i < spans.length; i += 1) {
const s = spans[i]!;
lines.push(
`Dialogue: 0,${fmtAssTime(s.start + shiftSec)},${fmtAssTime(s.end + shiftSec)},Default,,0,0,0,,Line ${i + 1}`,
);
}
// Add heavy stacked karaoke/song & sign noise that would confuse naive syncers.
for (let k = 0; k < 10; k += 1) {
lines.push(
`Dialogue: 0,${fmtAssTime(910)},${fmtAssTime(990)},OPRomaji,,0,0,0,,{\\k20}song ${k}`,
);
lines.push(
`Dialogue: 0,${fmtAssTime(20 + k * 5)},${fmtAssTime(24 + k * 5)},Sign,,0,0,0,,{\\pos(100,200)}Sign ${k}`,
);
}
fs.writeFileSync(filePath, lines.join('\n'), 'utf8');
}
function writeSpeechPcmFile(
pcmPath: string,
spans: ReadonlyArray<{ start: number; end: number }>,
durationSec = 920,
): void {
const sampleRate = 8000;
const samples = new Int16Array(sampleRate * durationSec);
for (let i = 0; i < samples.length; i += 1) {
const t = i / sampleRate;
samples[i] = Math.round(Math.sin(2 * Math.PI * 500 * t) * 120);
}
for (const span of spans) {
const sIdx = Math.max(0, Math.floor(span.start * sampleRate));
const eIdx = Math.min(samples.length, Math.floor(span.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);
}
}
fs.writeFileSync(pcmPath, Buffer.from(samples.buffer));
}
test('triggerSubsyncFromConfig automatically syncs with built-in alass and strips reference signs/songs', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-auto-builtin-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const refPath = path.join(tmpDir, 'ep01.en.ass');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spans, 3.2);
writeAssWithSignsFromSpans(refPath, spans, 0);
let modalOpened = false;
const osd: string[] = [];
const sentCommands: Array<Array<string | number>> = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: (payload) => {
sentCommands.push(payload.command);
},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 1000;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': refPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: false,
}),
openManualPicker: () => {
modalOpened = true;
},
showMpvOsd: (text) => {
osd.push(text);
},
}),
);
assert.equal(modalOpened, false);
const retimedPath = path.join(tmpDir, 'ep01.ja_retimed.srt');
assert.equal(fs.existsSync(retimedPath), true);
assert.equal(sentCommands[0]?.[0], 'sub-add');
assert.equal(sentCommands[0]?.[1], retimedPath);
assert.deepEqual(sentCommands[1], ['set_property', 'sub-delay', 0]);
assert.ok(osd.some((line) => line.startsWith('Synced via') && line.includes('-3.20s')));
});
test('triggerSubsyncFromConfig prefers an audio-aligned unloaded sidecar over a misaligned secondary track', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-auto-audio-verify-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const badSecondaryPath = path.join(tmpDir, 'ep01.bad.en.srt');
const goodSidecarPath = path.join(tmpDir, 'ep01.good.en.srt');
const pcmPath = path.join(tmpDir, 'speech.pcm');
const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 400);
fs.writeFileSync(videoPath, 'video');
// Target is +2.5s off audio; loaded secondary is +5.0s off audio (misaligned!); unloaded sidecar matches audio!
writeSrtFromSpans(targetPath, spans, 2.5);
writeSrtFromSpans(badSecondaryPath, spans, 5.0);
writeSrtFromSpans(goodSidecarPath, spans, 0);
writeSpeechPcmFile(pcmPath, spans, 420);
writeExecutableScript(fakeFfmpeg, `#!/bin/sh\ncat "${toShellPath(pcmPath)}"\nexit 0\n`);
let modalOpened = false;
const osd: string[] = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: 0,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 420;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': badSecondaryPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: fakeFfmpeg,
replace: false,
}),
openManualPicker: () => {
modalOpened = true;
},
showMpvOsd: (text) => {
osd.push(text);
},
}),
);
assert.equal(modalOpened, false);
assert.ok(
osd.some((line) => line.includes('ep01.good.en.srt') && line.includes('-2.5')),
`expected sync via aligned sidecar around -2.5s, got: ${osd.join(' | ')}`,
);
});
test('triggerSubsyncFromConfig falls back to built-in audio speech sync when no reference subtitle exists', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-auto-audio-only-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const pcmPath = path.join(tmpDir, 'speech.pcm');
const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 400);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spans, 3.0);
writeSpeechPcmFile(pcmPath, spans, 420);
writeExecutableScript(fakeFfmpeg, `#!/bin/sh\ncat "${toShellPath(pcmPath)}"\nexit 0\n`);
let modalOpened = false;
const osd: string[] = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: 0,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'duration') return 420;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: fakeFfmpeg,
replace: false,
}),
openManualPicker: () => {
modalOpened = true;
},
showMpvOsd: (text) => {
osd.push(text);
},
}),
);
assert.equal(modalOpened, false);
assert.ok(
osd.some((line) => line.includes('video audio') && line.includes('-3.')),
`expected audio-only sync around -3s, got: ${osd.join(' | ')}`,
);
});
test('triggerSubsyncFromConfig opens guided modal with explanation when auto-sync confidence is low', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-auto-low-conf-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'wrong-ep.ja.srt');
const refPath = path.join(tmpDir, 'ep01.en.srt');
const spansA = generateSyntheticSpans(7n, 1442695040888963407n, 600);
const spansB = generateSyntheticSpans(99999n, 0x9e3779b97f4a7c15n, 600);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spansB, 0);
writeSrtFromSpans(refPath, spansA, 0);
let modalPayload: SubsyncManualPayload | null = null;
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 620;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': refPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: false,
}),
openManualPicker: (payload) => {
modalPayload = payload;
},
}),
);
assert.ok(modalPayload);
const resolved = modalPayload as SubsyncManualPayload;
assert.match(resolved.guidanceMessage ?? '', /low confidence/i);
assert.equal(resolved.defaultEngine, 'builtin');
});
test('runSubsyncManual supports built-in file reference and manual offset engine', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-manual-builtin-offset-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const externalRefPath = path.join(tmpDir, 'custom-ref.srt');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 500);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spans, 2.0);
writeSrtFromSpans(externalRefPath, spans, 0);
const deps = makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: false,
}),
});
const builtinResult = await runSubsyncManual(
{
engine: 'builtin',
referenceMode: 'file',
referenceFilePath: externalRefPath,
stripSigns: true,
allowSplits: true,
},
deps,
);
assert.equal(builtinResult.ok, true);
assert.match(builtinResult.message, /Synced via custom-ref\.srt/);
const offsetResult = await runSubsyncManual({ engine: 'offset', offsetMs: -1250 }, deps);
assert.equal(offsetResult.ok, true);
assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s');
});
test('triggerSubsyncFromConfig extracts multiple embedded tracks and audio in a single ffmpeg pass and skips signs tracks', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-single-pass-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const badEmbeddedPath = path.join(tmpDir, 'bad-embedded.srt');
const goodEmbeddedPath = path.join(tmpDir, 'good-embedded.srt');
const pcmPath = path.join(tmpDir, 'speech.pcm');
const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log');
const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 400);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spans, 2.2);
writeSrtFromSpans(badEmbeddedPath, spans, 4.5);
writeSrtFromSpans(goodEmbeddedPath, spans, 0);
writeSpeechPcmFile(pcmPath, spans, 420);
// Mock ffmpeg that records each invocation, writes mapped embedded tracks 0:2 and 0:4, and streams audio PCM to stdout.
writeExecutableScript(
fakeFfmpeg,
`#!/bin/sh
echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}"
prev=""
cur_map=""
for arg in "$@"; do
if [ "$prev" = "-map" ]; then cur_map="$arg"; fi
case "$arg" in
*.srt)
if [ "$cur_map" = "0:2" ]; then cp "${toShellPath(badEmbeddedPath)}" "$arg"; fi
if [ "$cur_map" = "0:4" ]; then cp "${toShellPath(goodEmbeddedPath)}" "$arg"; fi
;;
pipe:1)
cat "${toShellPath(pcmPath)}"
;;
esac
prev="$arg"
done
exit 0
`,
);
let modalOpened = false;
const osd: string[] = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: 1,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 420;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: false,
lang: 'eng',
title: 'English (Bad)',
codec: 'subrip',
'ff-index': 2,
},
{
id: 3,
type: 'sub',
selected: false,
external: false,
lang: 'eng',
title: 'Signs & Songs',
codec: 'ass',
'ff-index': 3,
},
{
id: 4,
type: 'sub',
selected: false,
external: false,
lang: 'eng',
title: 'English (Full)',
codec: 'subrip',
'ff-index': 4,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: fakeFfmpeg,
replace: false,
}),
openManualPicker: () => {
modalOpened = true;
},
showMpvOsd: (text) => {
osd.push(text);
},
}),
);
assert.equal(modalOpened, false);
const calls = fs.readFileSync(ffmpegCallsLog, 'utf8').trim().split('\n');
assert.equal(
calls.length,
1,
`expected single ffmpeg pass, got ${calls.length}: ${calls.join(' | ')}`,
);
assert.equal(
calls[0]!.includes('0:3'),
false,
'signs/songs embedded track 0:3 should not be demuxed',
);
assert.ok(calls[0]!.includes('0:2') && calls[0]!.includes('0:4') && calls[0]!.includes('0:1'));
assert.ok(
osd.some((line) => line.includes('English (Full)') && line.includes('-2.2')),
`expected sync via aligned embedded track #4 around -2.2s, got: ${osd.join(' | ')}`,
);
});
test('triggerSubsyncFromConfig verifies external references via fast sampled audio without reading full video', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-sampled-fastpath-'));
const videoPath = path.join(tmpDir, 'movie.mkv');
const targetPath = path.join(tmpDir, 'movie.ja.srt');
const refPath = path.join(tmpDir, 'movie.en.srt');
const pcmPath = path.join(tmpDir, 'speech.pcm');
const ffmpegCallsLog = path.join(tmpDir, 'ffmpeg-calls.log');
const fakeFfmpeg = path.join(tmpDir, 'ffmpeg.sh');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 900);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spans, 2.6);
writeSrtFromSpans(refPath, spans, 0);
writeSpeechPcmFile(pcmPath, spans, 920);
// Seek-aware mock ffmpeg: honors -ss and -t by slicing the 8kHz s16le PCM file (16000 bytes/sec).
writeExecutableScript(
fakeFfmpeg,
`#!/bin/sh
echo "CALL:$*" >> "${toShellPath(ffmpegCallsLog)}"
ss=0
dur=0
prev=""
for arg in "$@"; do
if [ "$prev" = "-ss" ]; then ss="$arg"; fi
if [ "$prev" = "-t" ]; then dur="$arg"; fi
prev="$arg"
done
if [ "$dur" -gt 0 ] 2>/dev/null; then
dd if="${toShellPath(pcmPath)}" bs=16000 skip="$ss" count="$dur" 2>/dev/null
else
cat "${toShellPath(pcmPath)}"
fi
exit 0
`,
);
let modalOpened = false;
const osd: string[] = [];
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: 0,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 920;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': refPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: fakeFfmpeg,
replace: false,
}),
openManualPicker: () => {
modalOpened = true;
},
showMpvOsd: (text) => {
osd.push(text);
},
}),
);
assert.equal(modalOpened, false);
const calls = fs.readFileSync(ffmpegCallsLog, 'utf8').trim().split('\n');
assert.ok(
calls.length >= 2 && calls.every((line) => line.includes('-ss ') && line.includes('-t 60')),
`expected only sampled -ss/-t 60 calls without full decode, got: ${calls.join(' | ')}`,
);
assert.ok(
osd.some((line) => line.startsWith('Synced via') && line.includes('-2.6')),
`expected fast-path sync around -2.6s, got: ${osd.join(' | ')}`,
);
});
test('triggerSubsyncFromConfig discards stale result when playback switches to another video mid-sync', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-stale-session-'));
const videoA = path.join(tmpDir, 'ep01.mkv');
const videoB = path.join(tmpDir, 'ep02.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const refPath = path.join(tmpDir, 'ep01.en.srt');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 500);
fs.writeFileSync(videoA, 'videoA');
fs.writeFileSync(videoB, 'videoB');
writeSrtFromSpans(targetPath, spans, 2.5);
writeSrtFromSpans(refPath, spans, 0);
const originalContent = fs.readFileSync(targetPath, 'utf8');
let pathCalls = 0;
const sentCommands: Array<Array<string | number>> = [];
let modalOpened = false;
await triggerSubsyncFromConfig(
makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: (payload) => {
sentCommands.push(payload.command);
},
requestProperty: async (name: string) => {
if (name === 'path') {
pathCalls += 1;
// First call sees ep01, subsequent staleness check sees ep02.
return pathCalls === 1 ? videoA : videoB;
}
if (name === 'sid') return 1;
if (name === 'secondary-sid') return 2;
if (name === 'duration') return 520;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
{
id: 2,
type: 'sub',
selected: true,
external: true,
lang: 'eng',
'external-filename': refPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
mode: 'auto',
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: true,
}),
openManualPicker: () => {
modalOpened = true;
},
}),
);
assert.equal(modalOpened, false);
assert.deepEqual(sentCommands, []);
assert.equal(fs.readFileSync(targetPath, 'utf8'), originalContent);
});
test('runSubsyncManual refuses destructive replace when target subtitle encoding is lossy', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-lossy-replace-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'lossy.srt');
fs.writeFileSync(videoPath, 'video');
// Valid SRT header + corrupt non-UTF8/non-SJIS/non-EUCJP bytes in dialogue text.
const corruptBytes = Buffer.concat([
Buffer.from('1\n00:00:01,000 --> 00:00:02,500\n', 'utf8'),
Buffer.from([0x80, 0xff, 0xfe, 0x80]),
Buffer.from('\n', 'utf8'),
]);
fs.writeFileSync(targetPath, corruptBytes);
const deps = makeDeps({
getMpvClient: () => ({
connected: true,
currentAudioStreamIndex: null,
send: () => {},
requestProperty: async (name: string) => {
if (name === 'path') return videoPath;
if (name === 'sid') return 1;
if (name === 'secondary-sid') return null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
'external-filename': targetPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: true,
}),
});
const result = await runSubsyncManual({ engine: 'offset', offsetMs: 500 }, deps);
assert.equal(result.ok, false);
assert.match(result.message, /losslessly/i);
assert.deepEqual(fs.readFileSync(targetPath), corruptBytes);
});
File diff suppressed because it is too large. Load diff
+25
View File
@@ -744,6 +744,8 @@ const configDerivedRuntime = createConfigDerivedRuntime({
const subsyncRuntime = createMainSubsyncRuntime({
getMpvClient: () => appState.mpvClient,
getResolvedConfig: () => configService.getConfig(),
getSubtitleGenerationModelDirectory,
canPickReferenceFile: () => true,
getSubsyncInProgress: () => appState.subsyncInProgress,
setSubsyncInProgress: (inProgress) => {
appState.subsyncInProgress = inProgress;
@@ -1516,6 +1518,29 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
...stats.ipc,
...playlistBrowserMainDeps,
// App-level handlers with no owning assembly.
openSubsyncManual: () => subsyncRuntime.openManualPicker(),
pickSubsyncReferenceFile: async () => {
const owner =
BrowserWindow.getFocusedWindow() ?? overlayManager.getMainWindow() ?? undefined;
const result = owner
? await dialog.showOpenDialog(owner, {
title: 'Select reference subtitle file',
properties: ['openFile'],
filters: [
{ name: 'Subtitle files', extensions: ['srt', 'ass', 'ssa', 'vtt'] },
{ name: 'All files', extensions: ['*'] },
],
})
: await dialog.showOpenDialog({
title: 'Select reference subtitle file',
properties: ['openFile'],
filters: [
{ name: 'Subtitle files', extensions: ['srt', 'ass', 'ssa', 'vtt'] },
{ name: 'All files', extensions: ['*'] },
],
});
return result.canceled || result.filePaths.length === 0 ? null : result.filePaths[0]!;
},
onYoutubePickerResolve: (request) => youtube.flow.resolveActivePicker(request),
handleOverlayNotificationAction: (notificationId, actionId, noteId) => {
if (
+8
View File
@@ -16,6 +16,8 @@ export interface RuntimeOptionsIpcDepsParams {
export interface SubsyncRuntimeDepsParams {
getMpvClient: () => ReturnType<SubsyncRuntimeDeps['getMpvClient']>;
getResolvedSubsyncConfig: () => SubsyncResolvedConfig;
getVadPaths?: SubsyncRuntimeDeps['getVadPaths'];
canPickReferenceFile?: SubsyncRuntimeDeps['canPickReferenceFile'];
isSubsyncInProgress: () => boolean;
setSubsyncInProgress: (inProgress: boolean) => void;
showMpvOsd: (text: string) => void;
@@ -37,6 +39,8 @@ export function createSubsyncRuntimeDeps(params: SubsyncRuntimeDepsParams): Subs
return {
getMpvClient: params.getMpvClient,
getResolvedSubsyncConfig: params.getResolvedSubsyncConfig,
getVadPaths: params.getVadPaths,
canPickReferenceFile: params.canPickReferenceFile,
isSubsyncInProgress: params.isSubsyncInProgress,
setSubsyncInProgress: params.setSubsyncInProgress,
showMpvOsd: params.showMpvOsd,
@@ -84,6 +88,8 @@ export interface MainIpcRuntimeServiceDepsParams {
getSecondarySubMode: IpcDepsRuntimeOptions['getSecondarySubMode'];
getMpvClient: IpcDepsRuntimeOptions['getMpvClient'];
runSubsyncManual: IpcDepsRuntimeOptions['runSubsyncManual'];
openSubsyncManual?: IpcDepsRuntimeOptions['openSubsyncManual'];
pickSubsyncReferenceFile?: IpcDepsRuntimeOptions['pickSubsyncReferenceFile'];
getRuntimeOptions: IpcDepsRuntimeOptions['getRuntimeOptions'];
setRuntimeOption: IpcDepsRuntimeOptions['setRuntimeOption'];
reportOverlayContentBounds: IpcDepsRuntimeOptions['reportOverlayContentBounds'];
@@ -267,6 +273,8 @@ export function createMainIpcRuntimeServiceDeps(
getSecondarySubMode: params.getSecondarySubMode,
getMpvClient: params.getMpvClient,
runSubsyncManual: params.runSubsyncManual,
openSubsyncManual: params.openSubsyncManual,
pickSubsyncReferenceFile: params.pickSubsyncReferenceFile,
getRuntimeOptions: params.getRuntimeOptions,
setRuntimeOption: params.setRuntimeOption,
reportOverlayContentBounds: params.reportOverlayContentBounds,
+35 -1
View File
@@ -1,20 +1,26 @@
import * as path from 'node:path';
import type { MpvIpcClient } from '../../core/services/mpv';
import {
openSubsyncManualPickerRuntime,
runSubsyncManualFromIpcRuntime,
triggerSubsyncFromConfigRuntime,
} from '../../core/services/subsync-runner';
import { expandSubtitleGenerationPath } from '../../core/services/subtitle-generation-files';
import { SUBTITLE_GENERATION_VAD_MODEL } from '../../shared/subtitle-generation-vad-model';
import type {
SubsyncResult,
SubsyncManualPayload,
SubsyncManualRunRequest,
ResolvedConfig,
} from '../../types';
import { getSubsyncConfig } from '../../subsync/utils';
import { fileExists, findSubsyncExecutable, getSubsyncConfig } from '../../subsync/utils';
import { createSubsyncRuntimeServiceInputFromState } from '../subsync-runtime';
export type MainSubsyncRuntimeDeps = {
getMpvClient: () => MpvIpcClient | null;
getResolvedConfig: () => ResolvedConfig;
getSubtitleGenerationModelDirectory?: () => string;
canPickReferenceFile?: () => boolean;
getSubsyncInProgress: () => boolean;
setSubsyncInProgress: (inProgress: boolean) => void;
showMpvOsd: (text: string) => void;
@@ -23,12 +29,37 @@ export type MainSubsyncRuntimeDeps = {
export function createMainSubsyncRuntime(deps: MainSubsyncRuntimeDeps): {
triggerFromConfig: () => Promise<void>;
openManualPicker: () => Promise<void>;
runManualFromIpc: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
} {
const resolveVadPaths = () => {
const config = deps.getResolvedConfig();
const gen = config.subtitleGeneration;
const vadExecutablePath = findSubsyncExecutable(gen?.vadPath, [
'whisper-vad-speech-segments',
'vad-speech-segments',
]);
let vadModelPath: string | null = null;
const configuredModel = gen?.vadModelPath?.trim() ?? '';
if (configuredModel) {
const expanded = path.resolve(expandSubtitleGenerationPath(configuredModel));
if (fileExists(expanded)) vadModelPath = expanded;
} else if (deps.getSubtitleGenerationModelDirectory) {
const managedModel = path.join(
deps.getSubtitleGenerationModelDirectory(),
SUBTITLE_GENERATION_VAD_MODEL.filename,
);
if (fileExists(managedModel)) vadModelPath = managedModel;
}
return { vadExecutablePath, vadModelPath };
};
const getRuntimeServiceParams = () =>
createSubsyncRuntimeServiceInputFromState({
getMpvClient: () => deps.getMpvClient(),
getResolvedSubsyncConfig: () => getSubsyncConfig(deps.getResolvedConfig().subsync),
getVadPaths: resolveVadPaths,
canPickReferenceFile: deps.canPickReferenceFile,
getSubsyncInProgress: () => deps.getSubsyncInProgress(),
setSubsyncInProgress: (inProgress: boolean) => deps.setSubsyncInProgress(inProgress),
showMpvOsd: (text: string) => deps.showMpvOsd(text),
@@ -39,6 +70,9 @@ export function createMainSubsyncRuntime(deps: MainSubsyncRuntimeDeps): {
triggerFromConfig: async (): Promise<void> => {
await triggerSubsyncFromConfigRuntime(getRuntimeServiceParams());
},
openManualPicker: async (): Promise<void> => {
await openSubsyncManualPickerRuntime(getRuntimeServiceParams());
},
runManualFromIpc: async (request: SubsyncManualRunRequest): Promise<SubsyncResult> =>
runSubsyncManualFromIpcRuntime(request, getRuntimeServiceParams()),
};
+13
View File
@@ -3,6 +3,7 @@ import type { SubsyncManualPayload, SubsyncManualRunRequest, SubsyncResult } fro
import type { SubsyncRuntimeDeps } from '../core/services/subsync-runner';
import { createSubsyncRuntimeDeps } from './dependencies';
import {
openSubsyncManualPickerRuntime as openSubsyncManualPickerRuntimeCore,
runSubsyncManualFromIpcRuntime as runSubsyncManualFromIpcRuntimeCore,
triggerSubsyncFromConfigRuntime as triggerSubsyncFromConfigRuntimeCore,
} from '../core/services';
@@ -10,6 +11,8 @@ import {
export interface SubsyncRuntimeServiceInput {
getMpvClient: SubsyncRuntimeDeps['getMpvClient'];
getResolvedSubsyncConfig: () => SubsyncResolvedConfig;
getVadPaths?: SubsyncRuntimeDeps['getVadPaths'];
canPickReferenceFile?: SubsyncRuntimeDeps['canPickReferenceFile'];
isSubsyncInProgress: SubsyncRuntimeDeps['isSubsyncInProgress'];
setSubsyncInProgress: SubsyncRuntimeDeps['setSubsyncInProgress'];
showMpvOsd: SubsyncRuntimeDeps['showMpvOsd'];
@@ -19,6 +22,8 @@ export interface SubsyncRuntimeServiceInput {
export interface SubsyncRuntimeServiceStateInput {
getMpvClient: SubsyncRuntimeServiceInput['getMpvClient'];
getResolvedSubsyncConfig: SubsyncRuntimeServiceInput['getResolvedSubsyncConfig'];
getVadPaths?: SubsyncRuntimeServiceInput['getVadPaths'];
canPickReferenceFile?: SubsyncRuntimeServiceInput['canPickReferenceFile'];
getSubsyncInProgress: () => boolean;
setSubsyncInProgress: SubsyncRuntimeServiceInput['setSubsyncInProgress'];
showMpvOsd: SubsyncRuntimeServiceInput['showMpvOsd'];
@@ -31,6 +36,8 @@ export function createSubsyncRuntimeServiceInputFromState(
return {
getMpvClient: input.getMpvClient,
getResolvedSubsyncConfig: input.getResolvedSubsyncConfig,
getVadPaths: input.getVadPaths,
canPickReferenceFile: input.canPickReferenceFile,
isSubsyncInProgress: input.getSubsyncInProgress,
setSubsyncInProgress: input.setSubsyncInProgress,
showMpvOsd: input.showMpvOsd,
@@ -44,6 +51,8 @@ export function createSubsyncRuntimeServiceDeps(
return createSubsyncRuntimeDeps({
getMpvClient: params.getMpvClient,
getResolvedSubsyncConfig: params.getResolvedSubsyncConfig,
getVadPaths: params.getVadPaths,
canPickReferenceFile: params.canPickReferenceFile,
isSubsyncInProgress: params.isSubsyncInProgress,
setSubsyncInProgress: params.setSubsyncInProgress,
showMpvOsd: params.showMpvOsd,
@@ -55,6 +64,10 @@ export function triggerSubsyncFromConfigRuntime(params: SubsyncRuntimeServiceInp
return triggerSubsyncFromConfigRuntimeCore(createSubsyncRuntimeServiceDeps(params));
}
export function openSubsyncManualPickerRuntime(params: SubsyncRuntimeServiceInput): Promise<void> {
return openSubsyncManualPickerRuntimeCore(createSubsyncRuntimeServiceDeps(params));
}
export async function runSubsyncManualFromIpcRuntime(
request: SubsyncManualRunRequest,
params: SubsyncRuntimeServiceInput,
+4
View File
@@ -428,6 +428,10 @@ const electronAPI: ElectronAPI = {
onSubsyncManualOpen: onSubsyncManualOpenEvent,
runSubsyncManual: (request: SubsyncManualRunRequest): Promise<SubsyncResult> =>
ipcRenderer.invoke(IPC_CHANNELS.request.runSubsyncManual, request),
openSubsyncManual: (): Promise<void> =>
ipcRenderer.invoke(IPC_CHANNELS.request.openSubsyncManual),
pickSubsyncReferenceFile: (): Promise<string | null> =>
ipcRenderer.invoke(IPC_CHANNELS.request.pickSubsyncReferenceFile),
onKikuFieldGroupingRequest: onKikuFieldGroupingRequestEvent,
onKikuFieldGroupingCancel: onKikuFieldGroupingCancelEvent,
+52 -10
View File
@@ -868,26 +868,60 @@
<button id="subsyncClose" class="modal-close" type="button">Close</button>
</div>
<div class="modal-body">
<div id="subsyncGuidance" class="subsync-guidance hidden" role="status"></div>
<div class="subsync-form">
<div class="subsync-field">
<span>Engine</span>
<label class="subsync-radio">
<input id="subsyncEngineAlass" type="radio" name="subsyncEngine" checked />
alass
</label>
<label class="subsync-radio">
<input id="subsyncEngineFfsubsync" type="radio" name="subsyncEngine" />
ffsubsync
</label>
<div class="subsync-radio-group">
<label class="subsync-radio">
<input id="subsyncEngineBuiltin" type="radio" name="subsyncEngine" checked />
Built-in (alass)
</label>
<label class="subsync-radio">
<input id="subsyncEngineAlass" type="radio" name="subsyncEngine" />
External alass
</label>
<label class="subsync-radio">
<input id="subsyncEngineFfsubsync" type="radio" name="subsyncEngine" />
ffsubsync
</label>
<label class="subsync-radio">
<input id="subsyncEngineOffset" type="radio" name="subsyncEngine" />
Manual offset
</label>
</div>
</div>
<label id="subsyncReferenceLabel" class="subsync-field">
<span>Reference (correct timing, for alass)</span>
<select id="subsyncReferenceSelect"></select>
<span>Reference (correct timing)</span>
<div class="subsync-reference-row">
<select id="subsyncReferenceSelect"></select>
<button
id="subsyncBrowseReference"
class="kiku-cancel-button subsync-browse-button hidden"
type="button"
>
Browse…
</button>
</div>
</label>
<label id="subsyncTargetLabel" class="subsync-field">
<span>Out-of-sync Subtitle (gets retimed)</span>
<select id="subsyncTargetSelect"></select>
</label>
<div id="subsyncOptionsGroup" class="subsync-options">
<label class="subsync-checkbox">
<input id="subsyncStripSigns" type="checkbox" checked />
Ignore signs &amp; songs
</label>
<label id="subsyncAllowSplitsLabel" class="subsync-checkbox">
<input id="subsyncAllowSplits" type="checkbox" checked />
Allow scene cuts &amp; ad-break splits
</label>
</div>
<label id="subsyncOffsetLabel" class="subsync-field hidden">
<span>Shift offset (milliseconds, e.g. -1200 or +850)</span>
<input id="subsyncOffsetInput" type="number" step="50" value="0" />
</label>
</div>
<div id="subsyncStatus" class="runtime-options-status"></div>
<div class="subsync-footer">
@@ -962,6 +996,14 @@
<div id="subtitleSidebarContent" class="modal-content subtitle-sidebar-content">
<div class="modal-header">
<div class="modal-title">Subtitle Sidebar</div>
<button
id="subtitleSidebarSync"
class="modal-close"
type="button"
title="Sync subtitles automatically (Shift+click for options)"
>
Sync
</button>
<button id="subtitleSidebarCopy" class="modal-close" type="button" hidden>Copy</button>
<button id="subtitleSidebarClose" class="modal-close" type="button">Close</button>
</div>
+120
View File
@@ -421,3 +421,123 @@ test('subsync modal hides the reference picker for ffsubsync but keeps the targe
harness.restoreGlobals();
}
});
test('guided subsync modal shows guidance banner, ranked candidates, browse file, and built-in options', async () => {
let request: SubsyncManualRunRequest | null = null;
const harness = createTestHarness(async (nextRequest) => {
request = nextRequest;
return { ok: true, message: 'ok' };
});
const guidanceClassList = createClassList();
guidanceClassList.add('hidden');
const optionsClassList = createClassList();
const allowSplitsClassList = createClassList();
const offsetLabelClassList = createClassList();
offsetLabelClassList.add('hidden');
const browseClassList = createClassList();
browseClassList.add('hidden');
const engineBuiltinEvents = createEventTarget();
const engineOffsetEvents = createEventTarget();
const browseEvents = createEventTarget();
const subsyncEngineBuiltin = {
checked: true,
disabled: false,
addEventListener: engineBuiltinEvents.addEventListener,
dispatch: engineBuiltinEvents.dispatch,
};
const subsyncEngineOffset = {
checked: false,
disabled: false,
addEventListener: engineOffsetEvents.addEventListener,
dispatch: engineOffsetEvents.dispatch,
};
const subsyncBrowseReferenceButton = {
classList: browseClassList,
addEventListener: browseEvents.addEventListener,
dispatch: browseEvents.dispatch,
};
const subsyncGuidance = {
textContent: '',
classList: guidanceClassList,
};
const subsyncStripSignsCheckbox = { checked: true };
const subsyncAllowSplitsCheckbox = { checked: true };
const subsyncOffsetInput = { value: '0' };
Object.assign(harness.ctx.dom, {
subsyncGuidance,
subsyncEngineBuiltin,
subsyncEngineOffset,
subsyncBrowseReferenceButton,
subsyncOptionsGroup: { classList: optionsClassList },
subsyncStripSignsCheckbox,
subsyncAllowSplitsLabel: { classList: allowSplitsClassList },
subsyncAllowSplitsCheckbox,
subsyncOffsetLabel: { classList: offsetLabelClassList },
subsyncOffsetInput,
});
(
globalThis as unknown as { window: { electronAPI: Record<string, unknown> } }
).window.electronAPI.pickSubsyncReferenceFile = async () => '/tmp/browsed-ref.srt';
try {
harness.modal.wireDomEvents();
harness.modal.openSubsyncModal(
payloadWith({
guidanceMessage: 'Loaded English track appears +2.4s off audio.',
defaultEngine: 'builtin',
builtinAvailable: true,
alassAvailable: false,
canPickReferenceFile: true,
referenceCandidates: [
{
key: 'track:2',
kind: 'track',
label: 'External #2 - eng (secondary)',
detail: '+2.4s off audio',
trackId: 2,
},
{
key: 'video',
kind: 'video',
label: 'Video audio (built-in speech detection)',
recommended: true,
},
],
defaultReferenceKey: 'video',
}),
);
assert.equal(guidanceClassList.contains('hidden'), false);
assert.equal(subsyncGuidance.textContent, 'Loaded English track appears +2.4s off audio.');
assert.equal(subsyncEngineBuiltin.checked, true);
assert.equal(harness.ctx.dom.subsyncEngineAlass.disabled, true);
assert.equal(browseClassList.contains('hidden'), false);
assert.equal(harness.referenceSelect.value, 'video');
// Browse a custom file from disk and submit built-in sync with it.
subsyncBrowseReferenceButton.dispatch('click');
await flushMicrotasks();
assert.equal(harness.referenceSelect.value, 'file:/tmp/browsed-ref.srt');
subsyncAllowSplitsCheckbox.checked = false;
harness.runButton.dispatch('click');
await flushMicrotasks();
assert.deepEqual(request, {
engine: 'builtin',
targetTrackId: 1,
referenceMode: 'file',
referenceTrackId: null,
referenceFilePath: '/tmp/browsed-ref.srt',
stripSigns: true,
allowSplits: false,
});
} finally {
harness.restoreGlobals();
}
});
+308 -33
View File
@@ -1,12 +1,22 @@
import type { SubsyncManualPayload, SubsyncManualRunRequest } from '../../types';
import type {
SubsyncEngine,
SubsyncManualPayload,
SubsyncManualRunRequest,
SubsyncReferenceCandidate,
} from '../../types';
import type { ModalStateReader, RendererContext } from '../context';
const VIDEO_REFERENCE_VALUE = 'video';
const TRACK_PREFIX = 'track:';
const FILE_PREFIX = 'file:';
interface SubsyncSelection {
engine: 'alass' | 'ffsubsync';
engine: SubsyncEngine;
referenceValue: string;
targetTrackId: number | null;
stripSigns: boolean;
allowSplits: boolean;
offsetMs: number;
}
export function createSubsyncModal(
@@ -17,24 +27,81 @@ export function createSubsyncModal(
},
) {
let currentPayload: SubsyncManualPayload | null = null;
let customFileCandidates: SubsyncReferenceCandidate[] = [];
function setSubsyncStatus(message: string, isError = false): void {
ctx.dom.subsyncStatus.textContent = message;
ctx.dom.subsyncStatus.classList.toggle('error', isError);
}
function hasBuiltinEngineUi(): boolean {
return Boolean(ctx.dom.subsyncEngineBuiltin);
}
function hasBuiltinReference(): boolean {
if (!currentPayload) return false;
if (currentPayload.builtinAvailable === false) return false;
return (
currentPayload.audioReferenceAvailable === true ||
currentPayload.videoReferenceAvailable ||
currentPayload.subtitleTracks.length > 1 ||
(currentPayload.referenceCandidates?.length ?? 0) > 0 ||
customFileCandidates.length > 0 ||
currentPayload.canPickReferenceFile === true
);
}
function hasAlassReference(): boolean {
if (!currentPayload) return false;
return currentPayload.videoReferenceAvailable || currentPayload.subtitleTracks.length > 1;
if (currentPayload.alassAvailable === false) return false;
return (
currentPayload.videoReferenceAvailable ||
currentPayload.subtitleTracks.length > 1 ||
(currentPayload.referenceCandidates?.some((c) => c.kind !== 'video') ?? false) ||
customFileCandidates.length > 0
);
}
function hasOffsetEngine(): boolean {
return Boolean(ctx.dom.subsyncEngineOffset) && ctx.state.subsyncSubtitleTracks.length > 0;
}
function getSelectedEngine(): SubsyncEngine | null {
if (ctx.dom.subsyncEngineBuiltin?.checked) return 'builtin';
if (ctx.dom.subsyncEngineAlass.checked) return 'alass';
if (ctx.dom.subsyncEngineFfsubsync.checked) return 'ffsubsync';
if (ctx.dom.subsyncEngineOffset?.checked) return 'offset';
return null;
}
function setSelectedEngine(engine: SubsyncEngine | null): void {
if (ctx.dom.subsyncEngineBuiltin) {
ctx.dom.subsyncEngineBuiltin.checked = engine === 'builtin';
}
ctx.dom.subsyncEngineAlass.checked = engine === 'alass';
ctx.dom.subsyncEngineFfsubsync.checked = engine === 'ffsubsync';
if (ctx.dom.subsyncEngineOffset) {
ctx.dom.subsyncEngineOffset.checked = engine === 'offset';
}
}
function updateSubsyncFieldVisibility(): void {
const useAlass = ctx.dom.subsyncEngineAlass.checked;
ctx.dom.subsyncReferenceLabel.classList.toggle('hidden', !useAlass);
const engine = getSelectedEngine();
const usesReference = engine === 'builtin' || engine === 'alass';
const isOffset = engine === 'offset';
ctx.dom.subsyncReferenceLabel.classList.toggle('hidden', !usesReference);
ctx.dom.subsyncTargetLabel.classList.toggle(
'hidden',
ctx.state.subsyncSubtitleTracks.length === 0,
);
ctx.dom.subsyncOptionsGroup?.classList.toggle('hidden', !usesReference);
ctx.dom.subsyncAllowSplitsLabel?.classList.toggle('hidden', engine !== 'builtin');
ctx.dom.subsyncOffsetLabel?.classList.toggle('hidden', !isOffset);
ctx.dom.subsyncBrowseReferenceButton?.classList.toggle(
'hidden',
!usesReference || !currentPayload?.canPickReferenceFile,
);
}
function appendOption(select: HTMLSelectElement, value: string, label: string): void {
@@ -68,32 +135,88 @@ export function createSubsyncModal(
}
}
function formatCandidateOptionLabel(candidate: SubsyncReferenceCandidate): string {
const prefix = candidate.recommended ? '★ ' : '';
const detail = candidate.detail ? ` — ${candidate.detail}` : '';
return `${prefix}${candidate.label}${detail}`;
}
function buildReferenceOptions(): Array<{ value: string; label: string }> {
const targetTrackId = getSelectedTargetTrackId();
const options: Array<{ value: string; label: string }> = [];
const seen = new Set<string>();
// When rich candidates are supplied, preserve their diagnostic ranking while
// ensuring any non-target track in subtitleTracks is also reachable.
if (currentPayload?.referenceCandidates && currentPayload.referenceCandidates.length > 0) {
for (const candidate of [...customFileCandidates, ...currentPayload.referenceCandidates]) {
if (candidate.kind === 'track' && candidate.trackId === targetTrackId) continue;
if (seen.has(candidate.key)) continue;
seen.add(candidate.key);
options.push({
value: candidate.key,
label: formatCandidateOptionLabel(candidate),
});
}
for (const track of ctx.state.subsyncSubtitleTracks) {
if (track.id === targetTrackId) continue;
const key = `${TRACK_PREFIX}${track.id}`;
if (seen.has(key)) continue;
seen.add(key);
options.push({ value: key, label: track.label });
}
return options;
}
// Legacy / simplified payload format (used by minimal payloads & existing tests).
for (const candidate of customFileCandidates) {
if (seen.has(candidate.key)) continue;
seen.add(candidate.key);
options.push({
value: candidate.key,
label: formatCandidateOptionLabel(candidate),
});
}
for (const track of ctx.state.subsyncSubtitleTracks) {
if (track.id === targetTrackId) continue;
const value = String(track.id);
if (seen.has(value)) continue;
seen.add(value);
options.push({ value, label: track.label });
}
if (currentPayload?.videoReferenceAvailable) {
options.push({ value: VIDEO_REFERENCE_VALUE, label: 'Video file (audio reference)' });
}
return options;
}
function renderReferenceTracks(preferredValue: string | null): void {
const select = ctx.dom.subsyncReferenceSelect;
const targetTrackId = getSelectedTargetTrackId();
const values: string[] = [];
const items = buildReferenceOptions();
const values = items.map((item) => item.value);
select.innerHTML = '';
select.value = '';
for (const track of ctx.state.subsyncSubtitleTracks) {
if (track.id === targetTrackId) continue;
appendOption(select, String(track.id), track.label);
values.push(String(track.id));
}
if (currentPayload?.videoReferenceAvailable) {
appendOption(select, VIDEO_REFERENCE_VALUE, 'Video file (audio reference)');
values.push(VIDEO_REFERENCE_VALUE);
for (const item of items) {
appendOption(select, item.value, item.label);
}
select.disabled = values.length === 0;
const preferred = preferredValue && values.includes(preferredValue) ? preferredValue : null;
const defaultKey =
currentPayload?.defaultReferenceKey && values.includes(currentPayload.defaultReferenceKey)
? currentPayload.defaultReferenceKey
: null;
const defaultTrackValue =
currentPayload?.defaultReferenceTrackId !== null &&
currentPayload?.defaultReferenceTrackId !== undefined
? String(currentPayload.defaultReferenceTrackId)
? values.includes(`${TRACK_PREFIX}${currentPayload.defaultReferenceTrackId}`)
? `${TRACK_PREFIX}${currentPayload.defaultReferenceTrackId}`
: values.includes(String(currentPayload.defaultReferenceTrackId))
? String(currentPayload.defaultReferenceTrackId)
: null
: null;
const fallback =
defaultTrackValue && values.includes(defaultTrackValue) ? defaultTrackValue : values[0];
const fallback = defaultKey ?? defaultTrackValue ?? values[0];
const selected = preferred ?? fallback;
if (selected) {
select.value = selected;
@@ -102,7 +225,11 @@ export function createSubsyncModal(
function describeSubsyncState(): string {
if (!currentPayload) return '';
const builtinReady = hasBuiltinEngineUi() && hasBuiltinReference();
const alassReady = hasAlassReference();
if (builtinReady) {
return 'Choose reference and options, or switch engines, then run.';
}
if (alassReady && currentPayload.ffsubsyncAvailable) {
return 'Choose engine, reference and out-of-sync subtitle, then run.';
}
@@ -112,6 +239,9 @@ export function createSubsyncModal(
if (currentPayload.ffsubsyncAvailable) {
return 'No reference available for alass. Use ffsubsync.';
}
if (hasOffsetEngine()) {
return 'Apply a manual offset or browse for a reference subtitle file.';
}
return 'No sync engine available for current media.';
}
@@ -130,18 +260,75 @@ export function createSubsyncModal(
}
}
function chooseInitialEngine(
payload: SubsyncManualPayload,
selection?: SubsyncSelection,
): SubsyncEngine | null {
const builtinReady = hasBuiltinEngineUi() && hasBuiltinReference();
const alassReady = hasAlassReference();
const ffsubsyncReady = payload.ffsubsyncAvailable;
const offsetReady = hasOffsetEngine();
const isEngineAvailable = (engine: SubsyncEngine): boolean => {
if (engine === 'builtin') return builtinReady;
if (engine === 'alass') return alassReady;
if (engine === 'ffsubsync') return ffsubsyncReady;
if (engine === 'offset') return offsetReady;
return false;
};
if (selection && isEngineAvailable(selection.engine)) {
return selection.engine;
}
if (payload.defaultEngine && isEngineAvailable(payload.defaultEngine)) {
return payload.defaultEngine;
}
if (builtinReady) return 'builtin';
if (alassReady) return 'alass';
if (ffsubsyncReady) return 'ffsubsync';
if (offsetReady) return 'offset';
return null;
}
function openSubsyncModal(payload: SubsyncManualPayload, selection?: SubsyncSelection): void {
ctx.state.subsyncSubmitting = false;
ctx.state.subsyncSubtitleTracks = payload.subtitleTracks;
currentPayload = payload;
if (!selection) {
customFileCandidates = [];
}
const builtinReady = hasBuiltinEngineUi() && hasBuiltinReference();
const alassReady = hasAlassReference();
const useAlass = selection ? selection.engine === 'alass' && alassReady : alassReady;
ctx.dom.subsyncEngineAlass.checked = useAlass;
ctx.dom.subsyncEngineFfsubsync.checked = !useAlass && payload.ffsubsyncAvailable;
const offsetReady = hasOffsetEngine();
const chosenEngine = chooseInitialEngine(payload, selection);
setSelectedEngine(chosenEngine);
if (ctx.dom.subsyncEngineBuiltin) {
ctx.dom.subsyncEngineBuiltin.disabled = !builtinReady;
}
ctx.dom.subsyncEngineAlass.disabled = !alassReady;
ctx.dom.subsyncEngineFfsubsync.disabled = !payload.ffsubsyncAvailable;
ctx.dom.subsyncRunButton.disabled = !alassReady && !payload.ffsubsyncAvailable;
if (ctx.dom.subsyncEngineOffset) {
ctx.dom.subsyncEngineOffset.disabled = !offsetReady;
}
ctx.dom.subsyncRunButton.disabled = chosenEngine === null;
if (ctx.dom.subsyncGuidance) {
const guidance = payload.guidanceMessage?.trim() ?? '';
ctx.dom.subsyncGuidance.textContent = guidance;
ctx.dom.subsyncGuidance.classList.toggle('hidden', guidance.length === 0);
}
if (ctx.dom.subsyncStripSignsCheckbox) {
ctx.dom.subsyncStripSignsCheckbox.checked = selection ? selection.stripSigns : true;
}
if (ctx.dom.subsyncAllowSplitsCheckbox) {
ctx.dom.subsyncAllowSplitsCheckbox.checked = selection ? selection.allowSplits : true;
}
if (ctx.dom.subsyncOffsetInput) {
ctx.dom.subsyncOffsetInput.value = String(selection ? selection.offsetMs : 0);
}
renderTargetTracks(
selection
@@ -170,46 +357,125 @@ export function createSubsyncModal(
window.electronAPI.notifyOverlayModalOpened('subsync');
}
async function browseReferenceFile(): Promise<void> {
if (!window.electronAPI.pickSubsyncReferenceFile) return;
const picked = await window.electronAPI.pickSubsyncReferenceFile();
if (!picked) return;
const key = `${FILE_PREFIX}${picked}`;
const filename = picked.split(/[\\/]/).pop() ?? picked;
customFileCandidates = [
{
key,
kind: 'file',
label: `File - ${filename}`,
detail: 'selected from disk',
filePath: picked,
},
...customFileCandidates.filter((c) => c.key !== key),
];
if (ctx.dom.subsyncEngineBuiltin && ctx.dom.subsyncEngineBuiltin.disabled) {
ctx.dom.subsyncEngineBuiltin.disabled = false;
setSelectedEngine('builtin');
ctx.dom.subsyncRunButton.disabled = false;
}
renderReferenceTracks(key);
updateSubsyncFieldVisibility();
}
function parseReferenceValue(referenceValue: string): {
referenceMode: 'track' | 'video' | 'file';
referenceTrackId: number | null;
referenceFilePath: string | null;
} {
if (referenceValue === VIDEO_REFERENCE_VALUE) {
return { referenceMode: 'video', referenceTrackId: null, referenceFilePath: null };
}
if (referenceValue.startsWith(FILE_PREFIX)) {
return {
referenceMode: 'file',
referenceTrackId: null,
referenceFilePath: referenceValue.slice(FILE_PREFIX.length),
};
}
const rawId = referenceValue.startsWith(TRACK_PREFIX)
? referenceValue.slice(TRACK_PREFIX.length)
: referenceValue;
return {
referenceMode: 'track',
referenceTrackId: Number.parseInt(rawId, 10),
referenceFilePath: null,
};
}
async function runSubsyncManualFromModal(): Promise<void> {
if (ctx.state.subsyncSubmitting) return;
if (ctx.dom.subsyncRunButton.disabled) return;
if (!currentPayload) return;
const useAlass = ctx.dom.subsyncEngineAlass.checked;
const useFfsubsync = ctx.dom.subsyncEngineFfsubsync.checked;
if (!useAlass && !useFfsubsync) {
const engine = getSelectedEngine();
if (!engine) {
setSubsyncStatus('No sync engine available for current media.', true);
return;
}
const engine = useAlass ? 'alass' : 'ffsubsync';
const referenceValue = ctx.dom.subsyncReferenceSelect.value;
const targetTrackId = getSelectedTargetTrackId();
const stripSigns = ctx.dom.subsyncStripSignsCheckbox?.checked ?? true;
const allowSplits = ctx.dom.subsyncAllowSplitsCheckbox?.checked ?? true;
const offsetMs = Number.parseInt(ctx.dom.subsyncOffsetInput?.value ?? '0', 10) || 0;
if (targetTrackId === null) {
setSubsyncStatus('Select the out-of-sync subtitle track to retime.', true);
return;
}
if (engine === 'alass' && !referenceValue) {
setSubsyncStatus('Select a reference for alass.', true);
if ((engine === 'builtin' || engine === 'alass') && !referenceValue) {
setSubsyncStatus(
engine === 'builtin' ? 'Select a reference source.' : 'Select a reference for alass.',
true,
);
return;
}
if (engine === 'offset' && offsetMs === 0) {
setSubsyncStatus('Enter a non-zero offset in milliseconds.', true);
return;
}
const useVideoReference = referenceValue === VIDEO_REFERENCE_VALUE;
const request: SubsyncManualRunRequest = {
engine,
targetTrackId,
};
if (engine === 'alass') {
request.referenceMode = useVideoReference ? 'video' : 'track';
request.referenceTrackId = useVideoReference ? null : Number.parseInt(referenceValue, 10);
if (engine === 'builtin' || engine === 'alass') {
const parsed = parseReferenceValue(referenceValue);
request.referenceMode = parsed.referenceMode;
request.referenceTrackId = parsed.referenceTrackId;
if (parsed.referenceFilePath !== null) {
request.referenceFilePath = parsed.referenceFilePath;
}
if (ctx.dom.subsyncStripSignsCheckbox) {
request.stripSigns = stripSigns;
}
if (engine === 'builtin' && ctx.dom.subsyncAllowSplitsCheckbox) {
request.allowSplits = allowSplits;
}
} else if (engine === 'offset') {
request.offsetMs = offsetMs;
}
const payloadSnapshot: SubsyncManualPayload = {
...currentPayload,
subtitleTracks: currentPayload.subtitleTracks.map((track) => ({ ...track })),
referenceCandidates: currentPayload.referenceCandidates?.map((candidate) => ({
...candidate,
})),
};
const selection: SubsyncSelection = {
engine,
referenceValue,
targetTrackId,
stripSigns,
allowSplits,
offsetMs,
};
const selection: SubsyncSelection = { engine, referenceValue, targetTrackId };
ctx.state.subsyncSubmitting = true;
ctx.dom.subsyncRunButton.disabled = true;
@@ -251,12 +517,21 @@ export function createSubsyncModal(
ctx.dom.subsyncCloseButton.addEventListener('click', () => {
closeSubsyncModal();
});
ctx.dom.subsyncEngineBuiltin?.addEventListener('change', () => {
updateSubsyncFieldVisibility();
});
ctx.dom.subsyncEngineAlass.addEventListener('change', () => {
updateSubsyncFieldVisibility();
});
ctx.dom.subsyncEngineFfsubsync.addEventListener('change', () => {
updateSubsyncFieldVisibility();
});
ctx.dom.subsyncEngineOffset?.addEventListener('change', () => {
updateSubsyncFieldVisibility();
});
ctx.dom.subsyncBrowseReferenceButton?.addEventListener('click', () => {
void browseReferenceFile();
});
ctx.dom.subsyncTargetSelect.addEventListener('change', () => {
renderReferenceTracks(ctx.dom.subsyncReferenceSelect.value || null);
});
+7
View File
@@ -759,6 +759,13 @@ export function createSubtitleSidebarModal(
ctx.dom.subtitleSidebarClose.addEventListener('click', () => {
closeSubtitleSidebarModal();
});
ctx.dom.subtitleSidebarSync?.addEventListener('click', (event) => {
if (event.shiftKey && window.electronAPI.openSubsyncManual) {
void window.electronAPI.openSubsyncManual();
return;
}
void window.electronAPI.dispatchSessionAction('triggerSubsync');
});
ctx.dom.subtitleSidebarList.addEventListener('click', (event) => {
if (hasSubtitleSidebarSelection(ctx.dom.subtitleSidebarList)) return;
const target = event.target;
+54 -4
View File
@@ -3197,6 +3197,17 @@ iframe[id^='yomitan-popup'],
display: none;
}
.subsync-guidance {
margin-bottom: 12px;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid rgba(249, 226, 175, 0.35);
background: rgba(249, 226, 175, 0.08);
color: var(--ctp-yellow);
font-size: 12.5px;
line-height: 1.45;
}
.subsync-form {
display: flex;
flex-direction: column;
@@ -3211,16 +3222,54 @@ iframe[id^='yomitan-popup'],
color: var(--ctp-subtext1);
}
.subsync-radio-group {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
}
.subsync-radio {
display: inline-flex;
align-items: center;
gap: 8px;
margin-right: 14px;
gap: 6px;
font-size: 13px;
color: var(--ctp-subtext1);
}
.subsync-field select {
.subsync-reference-row {
display: flex;
gap: 8px;
align-items: stretch;
}
.subsync-reference-row select {
flex: 1 1 auto;
min-width: 0;
}
.subsync-browse-button {
flex: 0 0 auto;
padding: 6px 12px;
font-size: 12.5px;
}
.subsync-options {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
padding-top: 2px;
}
.subsync-checkbox {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
color: var(--ctp-subtext1);
}
.subsync-field select,
.subsync-field input[type='number'] {
background: rgba(24, 25, 38, 0.9);
border: 1px solid rgba(110, 115, 141, 0.2);
border-radius: 6px;
@@ -3228,7 +3277,8 @@ iframe[id^='yomitan-popup'],
padding: 8px 10px;
}
.subsync-field select:focus-visible {
.subsync-field select:focus-visible,
.subsync-field input[type='number']:focus-visible {
outline: 2px solid var(--ctp-blue);
outline-offset: 2px;
}
+22
View File
@@ -142,12 +142,22 @@ export type RendererDom = {
subsyncModal: HTMLDivElement;
subsyncCloseButton: HTMLButtonElement;
subsyncGuidance: HTMLDivElement;
subsyncEngineBuiltin: HTMLInputElement;
subsyncEngineAlass: HTMLInputElement;
subsyncEngineFfsubsync: HTMLInputElement;
subsyncEngineOffset: HTMLInputElement;
subsyncReferenceLabel: HTMLLabelElement;
subsyncReferenceSelect: HTMLSelectElement;
subsyncBrowseReferenceButton: HTMLButtonElement;
subsyncTargetLabel: HTMLLabelElement;
subsyncTargetSelect: HTMLSelectElement;
subsyncOptionsGroup: HTMLDivElement;
subsyncStripSignsCheckbox: HTMLInputElement;
subsyncAllowSplitsLabel: HTMLLabelElement;
subsyncAllowSplitsCheckbox: HTMLInputElement;
subsyncOffsetLabel: HTMLLabelElement;
subsyncOffsetInput: HTMLInputElement;
subsyncRunButton: HTMLButtonElement;
subsyncStatus: HTMLDivElement;
@@ -172,6 +182,7 @@ export type RendererDom = {
subtitleSidebarModal: HTMLDivElement;
subtitleSidebarContent: HTMLDivElement;
subtitleSidebarClose: HTMLButtonElement;
subtitleSidebarSync: HTMLButtonElement;
subtitleSidebarCopy: HTMLButtonElement;
subtitleSidebarStatus: HTMLDivElement;
subtitleSidebarList: HTMLUListElement;
@@ -419,12 +430,22 @@ export function resolveRendererDom(): RendererDom {
subsyncModal: getRequiredElement<HTMLDivElement>('subsyncModal'),
subsyncCloseButton: getRequiredElement<HTMLButtonElement>('subsyncClose'),
subsyncGuidance: getRequiredElement<HTMLDivElement>('subsyncGuidance'),
subsyncEngineBuiltin: getRequiredElement<HTMLInputElement>('subsyncEngineBuiltin'),
subsyncEngineAlass: getRequiredElement<HTMLInputElement>('subsyncEngineAlass'),
subsyncEngineFfsubsync: getRequiredElement<HTMLInputElement>('subsyncEngineFfsubsync'),
subsyncEngineOffset: getRequiredElement<HTMLInputElement>('subsyncEngineOffset'),
subsyncReferenceLabel: getRequiredElement<HTMLLabelElement>('subsyncReferenceLabel'),
subsyncReferenceSelect: getRequiredElement<HTMLSelectElement>('subsyncReferenceSelect'),
subsyncBrowseReferenceButton: getRequiredElement<HTMLButtonElement>('subsyncBrowseReference'),
subsyncTargetLabel: getRequiredElement<HTMLLabelElement>('subsyncTargetLabel'),
subsyncTargetSelect: getRequiredElement<HTMLSelectElement>('subsyncTargetSelect'),
subsyncOptionsGroup: getRequiredElement<HTMLDivElement>('subsyncOptionsGroup'),
subsyncStripSignsCheckbox: getRequiredElement<HTMLInputElement>('subsyncStripSigns'),
subsyncAllowSplitsLabel: getRequiredElement<HTMLLabelElement>('subsyncAllowSplitsLabel'),
subsyncAllowSplitsCheckbox: getRequiredElement<HTMLInputElement>('subsyncAllowSplits'),
subsyncOffsetLabel: getRequiredElement<HTMLLabelElement>('subsyncOffsetLabel'),
subsyncOffsetInput: getRequiredElement<HTMLInputElement>('subsyncOffsetInput'),
subsyncRunButton: getRequiredElement<HTMLButtonElement>('subsyncRun'),
subsyncStatus: getRequiredElement<HTMLDivElement>('subsyncStatus'),
@@ -453,6 +474,7 @@ export function resolveRendererDom(): RendererDom {
subtitleSidebarModal: getRequiredElement<HTMLDivElement>('subtitleSidebarModal'),
subtitleSidebarContent: getRequiredElement<HTMLDivElement>('subtitleSidebarContent'),
subtitleSidebarClose: getRequiredElement<HTMLButtonElement>('subtitleSidebarClose'),
subtitleSidebarSync: getRequiredElement<HTMLButtonElement>('subtitleSidebarSync'),
subtitleSidebarCopy: getRequiredElement<HTMLButtonElement>('subtitleSidebarCopy'),
subtitleSidebarStatus: getRequiredElement<HTMLDivElement>('subtitleSidebarStatus'),
subtitleSidebarList: getRequiredElement<HTMLUListElement>('subtitleSidebarList'),
+2
View File
@@ -82,6 +82,8 @@ export const IPC_CHANNELS = {
focusMainWindow: 'focus-main-window',
activatePlaybackWindowForOverlayInteraction: 'overlay:activate-playback-window',
runSubsyncManual: 'subsync:run-manual',
openSubsyncManual: 'subsync:open-manual-request',
pickSubsyncReferenceFile: 'subsync:pick-reference-file',
getRuntimeOptions: 'runtime-options:get',
setRuntimeOption: 'runtime-options:set',
getAnilistStatus: 'anilist:get-status',
+40 -3
View File
@@ -315,9 +315,25 @@ export function parseControllerConfigUpdate(value: unknown): ControllerConfigUpd
export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRequest | null {
if (!isObject(value)) return null;
const { engine, referenceMode, referenceTrackId, targetTrackId } = value;
if (engine !== 'alass' && engine !== 'ffsubsync') return null;
if (referenceMode !== undefined && referenceMode !== 'track' && referenceMode !== 'video') {
const {
engine,
referenceMode,
referenceTrackId,
referenceFilePath,
targetTrackId,
stripSigns,
allowSplits,
offsetMs,
} = value;
if (engine !== 'builtin' && engine !== 'alass' && engine !== 'ffsubsync' && engine !== 'offset') {
return null;
}
if (
referenceMode !== undefined &&
referenceMode !== 'track' &&
referenceMode !== 'video' &&
referenceMode !== 'file'
) {
return null;
}
@@ -331,11 +347,32 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
const parsedTargetTrackId = parseOptionalTrackId(targetTrackId);
if (parsedReferenceTrackId === false || parsedTargetTrackId === false) return null;
if (
referenceFilePath !== undefined &&
referenceFilePath !== null &&
typeof referenceFilePath !== 'string'
) {
return null;
}
if (stripSigns !== undefined && typeof stripSigns !== 'boolean') return null;
if (allowSplits !== undefined && typeof allowSplits !== 'boolean') return null;
if (
offsetMs !== undefined &&
offsetMs !== null &&
(typeof offsetMs !== 'number' || !Number.isFinite(offsetMs))
) {
return null;
}
return {
engine,
referenceMode,
referenceTrackId: parsedReferenceTrackId,
referenceFilePath: typeof referenceFilePath === 'string' ? referenceFilePath : null,
targetTrackId: parsedTargetTrackId,
stripSigns,
allowSplits,
offsetMs: typeof offsetMs === 'number' ? Math.round(offsetMs) : null,
};
}
+210
View File
@@ -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
+56
View File
@@ -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 },
]);
});
+833
View File
@@ -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.
}
}
}
}
+103
View File
@@ -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'],
);
});
+203
View File
@@ -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}`;
}
+173
View File
@@ -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'));
});
+606
View File
@@ -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');
}
+37 -1
View File
@@ -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
View File
@@ -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,
};
}
+3
View File
@@ -77,7 +77,10 @@ export interface MpvConfig {
aniskipButtonKey?: string;
}
export type SubsyncMode = 'auto' | 'manual';
export interface SubsyncConfig {
mode?: SubsyncMode;
alass_path?: string;
ffsubsync_path?: string;
ffmpeg_path?: string;
+40 -3
View File
@@ -97,28 +97,63 @@ export interface MpvClient {
send(command: { command: unknown[]; request_id?: number }): boolean;
}
export type SubsyncEngine = 'builtin' | 'alass' | 'ffsubsync' | 'offset';
export interface SubsyncSubtitleTrack {
id: number;
label: string;
}
export interface SubsyncReferenceCandidate {
/** Unique option value used in the modal picker (`track:<id>`, `file:<path>`, or `video`). */
key: string;
kind: 'track' | 'file' | 'video';
label: string;
detail?: string;
trackId?: number | null;
filePath?: string | null;
audioStatus?: 'aligned' | 'misaligned' | 'unverified';
audioOffsetMs?: number | null;
isSignsOnly?: boolean;
recommended?: boolean;
}
export interface SubsyncManualPayload {
subtitleTracks: SubsyncSubtitleTrack[];
defaultReferenceTrackId: number | null;
defaultTargetTrackId: number | null;
videoReferenceAvailable: boolean;
ffsubsyncAvailable: boolean;
/** Optional guidance shown when automatic sync hands off to the modal. */
guidanceMessage?: string | null;
/** Ranked candidate references (loaded tracks, unloaded tracks, sidecar files, audio). */
referenceCandidates?: SubsyncReferenceCandidate[];
/** Key of the recommended reference candidate in `referenceCandidates`. */
defaultReferenceKey?: string | null;
/** Default engine to select when the modal opens. */
defaultEngine?: SubsyncEngine;
builtinAvailable?: boolean;
alassAvailable?: boolean;
audioReferenceAvailable?: boolean;
canPickReferenceFile?: boolean;
}
export type SubsyncReferenceMode = 'track' | 'video';
export type SubsyncReferenceMode = 'track' | 'video' | 'file';
export interface SubsyncManualRunRequest {
engine: 'alass' | 'ffsubsync';
/** alass reference source: another subtitle track, or the loaded media file itself. */
engine: SubsyncEngine;
/** Reference source: another subtitle track, the loaded video/audio, or a local file on disk. */
referenceMode?: SubsyncReferenceMode;
referenceTrackId?: number | null;
referenceFilePath?: string | null;
/** Subtitle track to retime. Defaults to the active primary track. */
targetTrackId?: number | null;
/** Ignore signs, songs, karaoke, and typesets while computing alignment (default true). */
stripSigns?: boolean;
/** Allow scene-cut / broadcast ad-break split alignment (default true). */
allowSplits?: boolean;
/** Direct offset in milliseconds when `engine === 'offset'`. */
offsetMs?: number | null;
}
export interface SubsyncResult {
@@ -654,6 +689,8 @@ export interface ElectronAPI {
) => Promise<void>;
onSubsyncManualOpen: (callback: (payload: SubsyncManualPayload) => void) => void;
runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
openSubsyncManual?: () => Promise<void>;
pickSubsyncReferenceFile?: () => Promise<string | null>;
onKikuFieldGroupingRequest: (callback: (data: KikuFieldGroupingRequestData) => void) => void;
onKikuFieldGroupingCancel: (callback: () => void) => void;
kikuBuildMergePreview: (request: KikuMergePreviewRequest) => Promise<KikuMergePreviewResponse>;