fix(subsync): harden manual requests, error output, and track reload

- validate reference files (absolute regular file, size cap) before reading
- redact stream tokens and truncate tool output in failure messages
- keep title and lang when re-adding the synced track
- ignore an external audio track's ff-index when mapping the video's audio
- report discarded stale auto results, bound manual offsets, yield between alignments
- update stale subsync docs, fix markdown formatting, discover subtitle tests by lane
This commit is contained in:
sudacode committed 2026-11-28 03:15:35 -08:00
1 parent a303d6be27
commit 24b25287bd
15 files changed
+266 -44

No files matched your search

+1 -1
View File
@@ -117,7 +117,7 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi
SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to run it (plus `fuse2` for the Linux AppImage). Mining cards also needs Anki with the [AnkiConnect](https://ankiweb.net/shared/info/2055492159) add-on. Everything else is optional. SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to run it (plus `fuse2` for the Linux AppImage). Mining cards also needs Anki with the [AnkiConnect](https://ankiweb.net/shared/info/2055492159) add-on. Everything else is optional.
| Dependency | Status | What it does | | Dependency | Status | What it does |
| ------------------------ | ---------------- | -------------------------------------------------------------------- | | ------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------ |
| mpv | Required | The video player SubMiner draws over | | mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage | | fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup | | Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
+1 -1
View File
@@ -526,7 +526,7 @@ Built-in alass-based subtitle alignment works out of the box with no extra sync
Optional external [`alass`](https://github.com/kaegi/alass) and [`ffsubsync`](https://github.com/smacke/ffsubsync) binaries are also supported in the guided modal when installed. Optional external [`alass`](https://github.com/kaegi/alass) and [`ffsubsync`](https://github.com/smacke/ffsubsync) binaries are also supported in the guided modal when installed.
| Key | Default | What it does | | Key | Default | What it does |
| ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------- | | ------------------------ | -------- | --------------------------------------------------------------------------------------------------------- |
| `subsync.mode` | `"auto"` | `"auto"` syncs immediately and opens the guided modal only when needed; `"manual"` always opens the modal | | `subsync.mode` | `"auto"` | `"auto"` syncs immediately and opens the guided modal only when needed; `"manual"` always opens the modal |
| `subsync.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` | | `subsync.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` |
| `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` | | `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` |
+2 -2
View File
@@ -2,7 +2,7 @@
Short recordings from real playback sessions. Short recordings from real playback sessions.
_Yomitan_ is the pop-up dictionary. _Jimaku_ is a community subtitle database. _alass_ and _ffsubsync_ retime subtitles against the audio. _Jellyfin_ is a self-hosted media server. A _texthooker_ is a web page that mirrors the current subtitle as selectable text. _Yomitan_ is the pop-up dictionary. _Jimaku_ is a community subtitle database. _alass_ is the subtitle aligner SubMiner's built-in sync is based on. _Jellyfin_ is a self-hosted media server. A _texthooker_ is a web page that mirrors the current subtitle as selectable text.
<script setup> <script setup>
import { withBase } from 'vitepress'; import { withBase } from 'vitepress';
@@ -24,7 +24,7 @@ Mine a card from Yomitan or straight from a subtitle line. SubMiner attaches the
## Subtitle download and sync ## Subtitle download and sync
Search Jimaku, download a track, then retime it with alass or ffsubsync without leaving SubMiner. Search Jimaku, download a track, then sync it in one click without leaving SubMiner.
<!-- <video controls playsinline preload="metadata" :poster="withBase(`/assets/demos/subtitle-sync-poster.jpg?v=${v}`)"> <!-- <video controls playsinline preload="metadata" :poster="withBase(`/assets/demos/subtitle-sync-poster.jpg?v=${v}`)">
<source :src="withBase(`/assets/demos/subtitle-sync.webm?v=${v}`)" type="video/webm" /> <source :src="withBase(`/assets/demos/subtitle-sync.webm?v=${v}`)" type="video/webm" />
+1 -1
View File
@@ -85,7 +85,7 @@ For smaller changes, start with the cheapest lane that covers what you touched:
| `bun run test:stats` | Stats dashboard UI under `stats/src/**` | | `bun run test:stats` | Stats dashboard UI under `stats/src/**` |
| `bun run test:runtime:compat` | Compiled-runtime smoke against `dist/` (run `bun run build` first) | | `bun run test:runtime:compat` | Compiled-runtime smoke against `dist/` (run `bun run build` first) |
| `bun run test:immersion:sqlite` | Compiles, then runs the SQLite-backed immersion tracker tests | | `bun run test:immersion:sqlite` | Compiles, then runs the SQLite-backed immersion tracker tests |
| `bun run test:subtitle` | alass/ffsubsync subtitle sync | | `bun run test:subtitle` | Subtitle sync (`src/subsync/**` and the subsync service) |
| `bun run test:docs:kb` | Internal docs, `AGENTS.md`, and repo skills | | `bun run test:docs:kb` | Internal docs, `AGENTS.md`, and repo skills |
Lane membership is defined in `scripts/test-lanes.ts` and discovered by directory, so a new test file joins its lane automatically. Do not hand-list test files in `package.json`. `scripts/run-test-lane.mjs` runs each file in its own `bun test` process, so a hanging test cannot take down the rest of the lane. Pass `--jobs N` to parallelize or `--single-process` to share one process while debugging. Lane membership is defined in `scripts/test-lanes.ts` and discovered by directory, so a new test file joins its lane automatically. Do not hand-list test files in `package.json`. `scripts/run-test-lane.mjs` runs each file in its own `bun test` process, so a hanging test cannot take down the rest of the lane. Pass `--jobs N` to parallelize or `--single-process` to share one process while debugging.
+1 -1
View File
@@ -15,7 +15,7 @@ Getting started takes three steps:
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner. Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner.
| Dependency | Needed for | Platforms | | Dependency | Needed for | Platforms |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | ------------ |
| mpv | Required. The player SubMiner draws over. | All | | mpv | Required. The player SubMiner draws over. | All |
| fuse2 | Required to run the AppImage. | Linux | | fuse2 | Required to run the AppImage. | Linux |
| ffmpeg | Recommended. Audio clips and screenshots on cards, plus embedded subtitle extraction and built-in audio subtitle sync/verification. | All | | ffmpeg | Recommended. Audio clips and screenshots on cards, plus embedded subtitle extraction and built-in audio subtitle sync/verification. | All |
+3 -6
View File
@@ -67,14 +67,11 @@ With a gamepad and keyboard-only mode on, you can mine without a mouse: move acr
## Fix subtitle timing (subsync) ## Fix subtitle timing (subsync)
If the subtitles are out of sync, press `Ctrl+Alt+S` to open the subsync dialog. It uses [alass](https://github.com/kaegi/alass) or [ffsubsync](https://github.com/smacke/ffsubsync), which you install separately. If the subtitles are out of sync, press `Ctrl+Alt+S` or click **Sync** in the [subtitle sidebar](/subtitle-sidebar). SubMiner picks the best-aligned reference (another subtitle track, a sidecar file, or speech in the video's audio), retimes the active subtitle with its built-in aligner, and loads the result back into the same slot. No external tool is needed.
1. Pick the engine. When it cannot sync confidently, it opens the guided sync modal instead (`Shift+click` **Sync** opens it directly, and `subsync.mode: "manual"` always opens it). There you can pick another reference, browse for a subtitle file, try external [alass](https://github.com/kaegi/alass) or [ffsubsync](https://github.com/smacke/ffsubsync) if installed, or apply a manual offset.
2. For alass, pick a reference: a subtitle track with correct timing (the secondary track by default) or the video file.
3. Pick the track to retime (the active primary track by default).
4. Run it. SubMiner loads the retimed subtitle back into the same slot.
For remote streams such as Jellyfin, only alass with a subtitle reference is available, because ffsubsync and the video reference need the local file. If the tools are not found, see [Troubleshooting](/troubleshooting#subtitle-sync-subsync). Audio-based sync and ffsubsync need a local video file, so remote streams such as Jellyfin can only sync against a subtitle reference. See [Troubleshooting](/troubleshooting#subtitle-sync-subsync) if a sync keeps falling back to the modal.
## Texthooker ## Texthooker
+1 -1
View File
@@ -71,7 +71,7 @@ Built into the overlay, not configurable:
## Overlay features ## Overlay features
| Shortcut | Action | Config key | | Shortcut | Action | Config key |
| ------------------ | ------------------------------------------------------ | ------------------------------------------ | | ------------------ | ------------------------------------------------------------- | ------------------------------------------ |
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle bar: hidden, visible, hover | `shortcuts.toggleSecondarySub` | | `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle bar: hidden, visible, hover | `shortcuts.toggleSecondarySub` |
| `Ctrl/Cmd+Shift+O` | Open runtime options | `shortcuts.openRuntimeOptions` | | `Ctrl/Cmd+Shift+O` | Open runtime options | `shortcuts.openRuntimeOptions` |
| `Ctrl/Cmd+/` | Open session help | `shortcuts.openSessionHelp` | | `Ctrl/Cmd+/` | Open session help | `shortcuts.openSessionHelp` |
+1 -1
View File
@@ -53,7 +53,7 @@
"test:plugin:src": "lua scripts/test-plugin-lua-compat.lua && lua scripts/test-plugin-start-gate.lua && lua scripts/test-plugin-process-start-retries.lua && lua scripts/test-plugin-restart-feedback.lua && lua scripts/test-plugin-session-bindings.lua && lua scripts/test-plugin-binary-windows.lua", "test:plugin:src": "lua scripts/test-plugin-lua-compat.lua && lua scripts/test-plugin-start-gate.lua && lua scripts/test-plugin-process-start-retries.lua && lua scripts/test-plugin-restart-feedback.lua && lua scripts/test-plugin-session-bindings.lua && lua scripts/test-plugin-binary-windows.lua",
"test:launcher:smoke:src": "bun test launcher/smoke.e2e.test.ts", "test:launcher:smoke:src": "bun test launcher/smoke.e2e.test.ts",
"test:smoke:dist": "env ELECTRON_RUN_AS_NODE=1 electron scripts/compiled-runtime-smoke.mjs", "test:smoke:dist": "env ELECTRON_RUN_AS_NODE=1 electron scripts/compiled-runtime-smoke.mjs",
"test:subtitle:src": "bun test src/core/services/subsync.test.ts src/subsync/utils.test.ts", "test:subtitle:src": "bun scripts/run-test-lane.mjs subtitle",
"test:immersion:sqlite:src": "bun test src/core/services/immersion-tracker-service.test.ts src/core/services/immersion-tracker/storage-session.test.ts", "test:immersion:sqlite:src": "bun test src/core/services/immersion-tracker-service.test.ts src/core/services/immersion-tracker/storage-session.test.ts",
"test:immersion:sqlite:dist": "bun test dist/core/services/immersion-tracker-service.test.js dist/core/services/immersion-tracker/storage-session.test.js", "test:immersion:sqlite:dist": "bun test dist/core/services/immersion-tracker-service.test.js dist/core/services/immersion-tracker/storage-session.test.js",
"test:immersion:sqlite": "bun run tsc && bun run test:immersion:sqlite:dist", "test:immersion:sqlite": "bun run tsc && bun run test:immersion:sqlite:dist",
+5
View File
@@ -31,6 +31,11 @@ export const testLanes: Record<string, TestLane> = {
include: ['.test.ts'], include: ['.test.ts'],
exclude: ['launcher/smoke.e2e.test.ts'], exclude: ['launcher/smoke.e2e.test.ts'],
}, },
subtitle: {
roots: ['src/subsync'],
include: ['.test.ts'],
extraFiles: ['src/core/services/subsync.test.ts', 'src/renderer/modals/subsync.test.ts'],
},
scripts: { scripts: {
roots: ['scripts'], roots: ['scripts'],
include: ['.test.ts'], include: ['.test.ts'],
+120
View File
@@ -471,6 +471,64 @@ function fromShellPath(filePath: string): string {
.replace(/\//g, '\\'); .replace(/\//g, '\\');
} }
test('runSubsyncManual ignores the ff-index of an external audio track', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-external-audio-'));
const ffsubsyncLogPath = path.join(tmpDir, 'ffsubsync-args.log');
const ffsubsyncPath = path.join(tmpDir, 'ffsubsync.sh');
const videoPath = path.join(tmpDir, 'video.mkv');
const primaryPath = path.join(tmpDir, 'primary.srt');
fs.writeFileSync(videoPath, 'video');
fs.writeFileSync(primaryPath, 'sub');
writeExecutableScript(
ffsubsyncPath,
`#!/bin/sh\n: > "${toShellPath(ffsubsyncLogPath)}"\nfor arg in "$@"; do printf '%s\\n' "$arg" >> "${toShellPath(ffsubsyncLogPath)}"; done\nout=""\nprev=""\nfor arg in "$@"; do\n if [ "$prev" = "-o" ]; then out="$arg"; fi\n prev="$arg"\ndone\nif [ -n "$out" ]; then : > "$out"; fi\nexit 0\n`,
);
const deps = makeDeps({
getMpvClient: () => ({
connected: true,
// ff-index 1 inside the dub file, not inside video.mkv
currentAudioStreamIndex: 1,
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,
'external-filename': primaryPath,
},
{
id: 3,
type: 'audio',
selected: true,
external: true,
'ff-index': 1,
'external-filename': path.join(tmpDir, 'dub.mka'),
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath: '/missing/alass',
ffsubsyncPath,
ffmpegPath: '/missing/ffmpeg',
}),
});
const result = await runSubsyncManual({ engine: 'ffsubsync' }, deps);
assert.equal(result.ok, true);
const ffArgs = fs.readFileSync(ffsubsyncLogPath, 'utf8').trim().split('\n');
assert.equal(ffArgs.includes('--reference-stream'), false);
});
test('runSubsyncManual constructs ffsubsync command and returns success', async () => { test('runSubsyncManual constructs ffsubsync command and returns success', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-ffsubsync-')); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-ffsubsync-'));
const ffsubsyncLogPath = path.join(tmpDir, 'ffsubsync-args.log'); const ffsubsyncLogPath = path.join(tmpDir, 'ffsubsync-args.log');
@@ -1487,6 +1545,68 @@ test('runSubsyncManual supports built-in file reference and manual offset engine
assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s'); assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s');
}); });
test('runSubsyncManual rejects non-file references and keeps the track title and lang on reload', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-manual-ref-validation-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const targetPath = path.join(tmpDir, 'ep01.ja.srt');
const refPath = path.join(tmpDir, 'ref.srt');
const spans = generateSyntheticSpans(7n, 1442695040888963407n, 500);
fs.writeFileSync(videoPath, 'video');
writeSrtFromSpans(targetPath, spans, 2.0);
writeSrtFromSpans(refPath, spans, 0);
const sentCommands: Array<Array<string | number>> = [];
const deps = 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 null;
if (name === 'track-list') {
return [
{
id: 1,
type: 'sub',
selected: true,
external: true,
lang: 'jpn',
title: 'Japanese (CC)',
'external-filename': targetPath,
},
];
}
return null;
},
}),
getResolvedConfig: () => ({
alassPath: '/missing/alass',
ffsubsyncPath: '/missing/ffsubsync',
ffmpegPath: '/missing/ffmpeg',
replace: false,
}),
});
const runWithReference = (referenceFilePath: string) =>
runSubsyncManual({ engine: 'builtin', referenceMode: 'file', referenceFilePath }, deps);
assert.equal((await runWithReference(tmpDir)).ok, false);
assert.equal((await runWithReference('ref.srt')).ok, false);
assert.equal(sentCommands.length, 0);
assert.equal((await runWithReference(refPath)).ok, true);
assert.deepEqual(sentCommands[0], [
'sub-add',
path.join(tmpDir, 'ep01.ja_retimed.srt'),
'select',
'Japanese (CC)',
'jpn',
]);
});
test('triggerSubsyncFromConfig extracts multiple embedded tracks and audio in a single ffmpeg pass and skips signs tracks', async () => { 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 tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-single-pass-'));
const videoPath = path.join(tmpDir, 'ep01.mkv'); const videoPath = path.join(tmpDir, 'ep01.mkv');
+114 -27
View File
@@ -2,6 +2,7 @@ import * as fs from 'fs';
import * as os from 'os'; import * as os from 'os';
import * as path from 'path'; import * as path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import { redactUrlCredentials } from './subtitle-generation-process';
import { import {
SubsyncEngine, SubsyncEngine,
SubsyncManualPayload, SubsyncManualPayload,
@@ -12,6 +13,7 @@ import {
import { import {
buildJellyfinEmbeddedSubtitleUrl, buildJellyfinEmbeddedSubtitleUrl,
CommandResult, CommandResult,
canFfmpegExtractSubtitleExtension,
codecToExtension, codecToExtension,
extensionToFfmpegMuxer, extensionToFfmpegMuxer,
fileExists, fileExists,
@@ -80,12 +82,29 @@ const AUTO_AUDIO_CONFIDENCE_THRESHOLD = 0.65;
const AUDIO_SPEECH_LEAD_SEC = 0.1; const AUDIO_SPEECH_LEAD_SEC = 0.1;
const JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS = 15_000; const JELLYFIN_SUBTITLE_FETCH_TIMEOUT_MS = 15_000;
const COMMAND_OUTPUT_SUMMARY_CHARS = 300;
// Alignment and candidate scoring are synchronous CPU work (100ms to 1s each on long media).
// Yield between them so mpv IPC, the overlay, and other main-process work keep flowing.
function yieldToEventLoop(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
// Keep the tail of tool output (errors come last; alass prints progress first) and strip
// stream tokens: ffmpeg echoes input URLs, and Jellyfin URLs carry ApiKey.
function summarizeCommandOutput(text: string): string {
const trimmed = redactUrlCredentials(text.trim());
return trimmed.length > COMMAND_OUTPUT_SUMMARY_CHARS
? `…${trimmed.slice(-COMMAND_OUTPUT_SUMMARY_CHARS)}`
: trimmed;
}
function summarizeCommandFailure(command: string, result: CommandResult): string { function summarizeCommandFailure(command: string, result: CommandResult): string {
const parts = [ const parts = [
`code=${result.code ?? 'n/a'}`, `code=${result.code ?? 'n/a'}`,
result.stderr ? `stderr: ${result.stderr}` : '', result.stderr ? `stderr: ${summarizeCommandOutput(result.stderr)}` : '',
result.stdout ? `stdout: ${result.stdout}` : '', result.stdout ? `stdout: ${summarizeCommandOutput(result.stdout)}` : '',
result.error ? `error: ${result.error}` : '', result.error ? `error: ${summarizeCommandOutput(result.error)}` : '',
] ]
.map((value) => value.trim()) .map((value) => value.trim())
.filter(Boolean); .filter(Boolean);
@@ -269,14 +288,14 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncConte
return typeof filename === 'string' && filename.length > 0; return typeof filename === 'string' && filename.length > 0;
}); });
// Resolve active audio stream ff-index if not already cached on mpv client. // Resolve the active audio stream's ff-index within the video file. An external audio track
let audioStreamIndex = client.currentAudioStreamIndex; // (--audio-file, auto-loaded .mka dub) has an ff-index inside its own file, so mapping it as
if (audioStreamIndex === null) { // `0:N` on the video would pick an unrelated stream; use the video's default audio instead.
const selectedAudio = tracks.find( const selectedAudio = tracks.find((track) => track.type === 'audio' && track.selected === true);
(track) => let audioStreamIndex: number | null = null;
track.type === 'audio' && track.selected === true && typeof track['ff-index'] === 'number', if (!selectedAudio?.external) {
); audioStreamIndex = client.currentAudioStreamIndex;
if (selectedAudio && typeof selectedAudio['ff-index'] === 'number') { if (audioStreamIndex === null && typeof selectedAudio?.['ff-index'] === 'number') {
audioStreamIndex = selectedAudio['ff-index']; audioStreamIndex = selectedAudio['ff-index'];
} }
} }
@@ -388,6 +407,11 @@ async function extractSubtitleTrackToFile(
} }
} }
if (!canFfmpegExtractSubtitleExtension(extension)) {
throw new Error(
`${extension.toUpperCase()} subtitle tracks cannot be extracted locally (ffmpeg has no decoder for them)`,
);
}
const resolvedFfmpegPath = ensureExecutablePath(ffmpegPath, 'ffmpeg'); const resolvedFfmpegPath = ensureExecutablePath(ffmpegPath, 'ffmpeg');
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-')); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-'));
const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`); const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`);
@@ -440,6 +464,24 @@ function cleanupTemporaryFile(extraction: FileExtractionResult | null): void {
} catch {} } catch {}
} }
const MAX_REFERENCE_FILE_BYTES = 20 * 1024 * 1024;
/**
* Validate a renderer-supplied reference subtitle path before main reads it synchronously:
* absolute regular file under a subtitle-sized cap (rejects directories, FIFOs, and videos
* picked by mistake through the "All files" filter). Returns the path or null.
*/
function resolveReferenceFilePath(rawPath: string | null | undefined): string | null {
const refPath = rawPath?.trim() ?? '';
if (!refPath || !path.isAbsolute(refPath)) return null;
try {
const stat = fs.statSync(refPath);
return stat.isFile() && stat.size <= MAX_REFERENCE_FILE_BYTES ? refPath : null;
} catch {
return null;
}
}
function buildRetimedPath(subPath: string, replace: boolean): string { function buildRetimedPath(subPath: string, replace: boolean): string {
if (replace) return subPath; if (replace) return subPath;
const parsed = path.parse(subPath); const parsed = path.parse(subPath);
@@ -605,10 +647,24 @@ async function findAddedSubtitleTrackId(
return null; return null;
} }
/** `sub-add` args that keep the retimed track's original title/lang (used for ranking and labels). */
function buildSubAddCommand(
pathToLoad: string,
flag: 'select' | 'auto',
track: MpvTrack,
): string[] {
const title = track.title?.trim() ?? '';
const lang = track.lang?.trim() ?? '';
if (!title && !lang)
return flag === 'select' ? ['sub-add', pathToLoad] : ['sub-add', pathToLoad, flag];
return ['sub-add', pathToLoad, flag, title || path.basename(pathToLoad), lang];
}
async function loadSyncedSubtitle( async function loadSyncedSubtitle(
client: MpvClientLike, client: MpvClientLike,
pathToLoad: string, pathToLoad: string,
slot: SubtitleSlot, slot: SubtitleSlot,
sourceTrack: MpvTrack,
): Promise<void> { ): Promise<void> {
if (!client.connected) { if (!client.connected) {
throw new Error('MPV disconnected while loading subtitle'); throw new Error('MPV disconnected while loading subtitle');
@@ -617,7 +673,7 @@ async function loadSyncedSubtitle(
if (slot === 'secondary') { if (slot === 'secondary') {
// Keep the primary track untouched: load without selecting, then point // Keep the primary track untouched: load without selecting, then point
// secondary-sid at the freshly added track. // secondary-sid at the freshly added track.
client.send({ command: ['sub-add', pathToLoad, 'auto'] }); client.send({ command: buildSubAddCommand(pathToLoad, 'auto', sourceTrack) });
client.send({ command: ['set_property', 'secondary-sub-delay', 0] }); client.send({ command: ['set_property', 'secondary-sub-delay', 0] });
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad); const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad);
if (addedTrackId === null) { if (addedTrackId === null) {
@@ -627,7 +683,7 @@ async function loadSyncedSubtitle(
return; return;
} }
client.send({ command: ['sub-add', pathToLoad] }); client.send({ command: buildSubAddCommand(pathToLoad, 'select', sourceTrack) });
client.send({ command: ['set_property', 'sub-delay', 0] }); client.send({ command: ['set_property', 'sub-delay', 0] });
} }
@@ -706,7 +762,13 @@ function collectExtractableEmbeddedRefTracks(
if (isSignsOrSongsTrackMeta(track)) continue; if (isSignsOrSongsTrackMeta(track)) continue;
const ffIndex = track['ff-index']; const ffIndex = track['ff-index'];
const extension = codecToExtension(track.codec); const extension = codecToExtension(track.codec);
if (typeof ffIndex === 'number' && Number.isInteger(ffIndex) && ffIndex >= 0 && extension) { if (
typeof ffIndex === 'number' &&
Number.isInteger(ffIndex) &&
ffIndex >= 0 &&
extension &&
canFfmpegExtractSubtitleExtension(extension)
) {
specs.push({ ffIndex, extension }); specs.push({ ffIndex, extension });
} }
} }
@@ -840,6 +902,7 @@ async function discoverAndEvaluateSubtitleCandidates(
if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') { if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') {
const preParsed = preExtracted.get(track['ff-index']); const preParsed = preExtracted.get(track['ff-index']);
if (preParsed && preParsed.events.length > 0) { if (preParsed && preParsed.events.length > 0) {
await yieldToEventLoop();
results.push(evaluateParsedCandidate(baseMeta, preParsed)); results.push(evaluateParsedCandidate(baseMeta, preParsed));
continue; continue;
} }
@@ -852,7 +915,14 @@ async function discoverAndEvaluateSubtitleCandidates(
let extraction: FileExtractionResult | null = null; let extraction: FileExtractionResult | null = null;
try { try {
if (isEmbedded && (!ffmpegAvailable || !codecToExtension(track.codec))) { const embeddedExtension = isEmbedded ? codecToExtension(track.codec) : null;
if (
isEmbedded &&
(!ffmpegAvailable ||
!embeddedExtension ||
(!isRemoteMediaPath(context.videoPath) &&
!canFfmpegExtractSubtitleExtension(embeddedExtension)))
) {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(evaluateParsedCandidate(baseMeta, null));
continue; continue;
} }
@@ -887,6 +957,7 @@ async function discoverAndEvaluateSubtitleCandidates(
); );
} }
} }
await yieldToEventLoop();
results.push(evaluateParsedCandidate(baseMeta, parsed)); results.push(evaluateParsedCandidate(baseMeta, parsed));
} catch { } catch {
results.push(evaluateParsedCandidate(baseMeta, null)); results.push(evaluateParsedCandidate(baseMeta, null));
@@ -916,6 +987,7 @@ async function discoverAndEvaluateSubtitleCandidates(
}; };
try { try {
const parsed = readAndParseSubtitleFile(sidecar.path); const parsed = readAndParseSubtitleFile(sidecar.path);
await yieldToEventLoop();
results.push(evaluateParsedCandidate(baseMeta, parsed)); results.push(evaluateParsedCandidate(baseMeta, parsed));
} catch { } catch {
// Ignore unreadable sidecars. // Ignore unreadable sidecars.
@@ -1100,9 +1172,9 @@ async function runBuiltinSubsync(
leadSec = AUDIO_SPEECH_LEAD_SEC; leadSec = AUDIO_SPEECH_LEAD_SEC;
lengthSec = Math.max(lengthSec, audioSpeech.durationSec); lengthSec = Math.max(lengthSec, audioSpeech.durationSec);
} else if (request.referenceMode === 'file') { } else if (request.referenceMode === 'file') {
const refPath = request.referenceFilePath?.trim() ?? ''; const refPath = resolveReferenceFilePath(request.referenceFilePath);
if (!refPath || !fileExists(refPath)) { if (!refPath) {
return { ok: false, message: 'Select an existing reference subtitle file.' }; return { ok: false, message: 'Select an existing reference subtitle file (up to 20 MB).' };
} }
const parsedRef = readAndParseSubtitleFile(refPath); const parsedRef = readAndParseSubtitleFile(refPath);
referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans; referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans;
@@ -1153,7 +1225,7 @@ async function runBuiltinSubsync(
if (targetExtraction.temporary) { if (targetExtraction.temporary) {
keepTempTarget = true; keepTempTarget = true;
} }
await loadSyncedSubtitle(client, outputPath, targetSlot); await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
return { return {
ok: true, ok: true,
message: formatAlignmentSummary(referenceLabel, alignment), message: formatAlignmentSummary(referenceLabel, alignment),
@@ -1204,7 +1276,7 @@ async function runManualOffsetSubsync(
if (targetExtraction.temporary) { if (targetExtraction.temporary) {
keepTempTarget = true; keepTempTarget = true;
} }
await loadSyncedSubtitle(client, outputPath, targetSlot); await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
return { return {
ok: true, ok: true,
message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`, message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`,
@@ -1275,7 +1347,7 @@ async function subsyncToReference(
} }
fs.renameSync(stagedOutputPath, outputPath); fs.renameSync(stagedOutputPath, outputPath);
await loadSyncedSubtitle(client, outputPath, slot); await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
return { return {
ok: true, ok: true,
message: `Subtitle synchronized with ${engine}`, message: `Subtitle synchronized with ${engine}`,
@@ -1431,9 +1503,12 @@ export async function runSubsyncManual(
} }
if (request.referenceMode === 'file') { if (request.referenceMode === 'file') {
const refPath = request.referenceFilePath?.trim() ?? ''; const refPath = resolveReferenceFilePath(request.referenceFilePath);
if (!refPath || !fileExists(refPath)) { if (!refPath) {
return { ok: false, message: 'Select an existing reference subtitle file for alass' }; return {
ok: false,
message: 'Select an existing reference subtitle file (up to 20 MB) for alass',
};
} }
const cleaned = maybeWriteCleanedReferenceSrt(refPath, request.stripSigns !== false); const cleaned = maybeWriteCleanedReferenceSrt(refPath, request.stripSigns !== false);
try { try {
@@ -1472,7 +1547,7 @@ export async function runSubsyncManual(
); );
cleanedRef = maybeWriteCleanedReferenceSrt( cleanedRef = maybeWriteCleanedReferenceSrt(
referenceExtraction.path, referenceExtraction.path,
request.stripSigns === true, request.stripSigns !== false,
); );
return await subsyncToReference( return await subsyncToReference(
'alass', 'alass',
@@ -1713,6 +1788,8 @@ export async function openSubsyncManualPicker(
return true; return true;
} }
const STALE_AUTO_RESULT_MESSAGE = 'Subsync: playback changed while syncing; discarded result';
async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> { async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
const client = getMpvClientForSubsync(deps); const client = getMpvClientForSubsync(deps);
const context = await gatherSubsyncContext(client); const context = await gatherSubsyncContext(client);
@@ -1741,10 +1818,11 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) || !(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
!isMediaFileUnchanged() !isMediaFileUnchanged()
) { ) {
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
return; return;
} }
const payload = buildManualPayload(context, resolved, deps, { const payload = buildManualPayload(context, resolved, deps, {
guidanceMessage: `Automatic sync could not read the active subtitle track (${(extractError as Error).message}). Choose an engine and subtitle tracks below.`, guidanceMessage: `Automatic sync could not read the active subtitle track (${redactUrlCredentials((extractError as Error).message)}). Choose an engine and subtitle tracks below.`,
}); });
deps.openManualPicker(payload); deps.openManualPicker(payload);
deps.showMpvOsd('Subsync: choose engine and subtitles'); deps.showMpvOsd('Subsync: choose engine and subtitles');
@@ -1758,6 +1836,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) || !(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
!isMediaFileUnchanged() !isMediaFileUnchanged()
) { ) {
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
return; return;
} }
const payload = buildManualPayload(context, resolved, deps, { const payload = buildManualPayload(context, resolved, deps, {
@@ -1805,6 +1884,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) || !(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
!isMediaFileUnchanged() !isMediaFileUnchanged()
) { ) {
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
return; return;
} }
if (alreadyInSync) { if (alreadyInSync) {
@@ -1824,7 +1904,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
if (targetExtraction!.temporary) { if (targetExtraction!.temporary) {
keepTempTarget = true; keepTempTarget = true;
} }
await loadSyncedSubtitle(client, outputPath, targetSlot); await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment)); deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment));
}; };
@@ -1839,6 +1919,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES,
); );
for (const candidate of fastAligned) { for (const candidate of fastAligned) {
await yieldToEventLoop();
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -1898,6 +1979,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// 1. Best path: an audio-verified aligned dialogue subtitle reference (loaded or unloaded!). // 1. Best path: an audio-verified aligned dialogue subtitle reference (loaded or unloaded!).
for (const candidate of alignedCandidates) { for (const candidate of alignedCandidates) {
await yieldToEventLoop();
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -1921,6 +2003,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// 2. Fallback when no subtitle track is audio-aligned (none exist, only signs/songs, or all // 2. Fallback when no subtitle track is audio-aligned (none exist, only signs/songs, or all
// reference subtitles are shifted off the audio): sync directly to video audio speech! // reference subtitles are shifted off the audio): sync directly to video audio speech!
if (audioSpeech && audioSpeech.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) { if (audioSpeech && audioSpeech.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) {
await yieldToEventLoop();
const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, { const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -1947,6 +2030,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
// try already-loaded external dialogue tracks first with a stricter confidence bar. // try already-loaded external dialogue tracks first with a stricter confidence bar.
if (!audioSpeech) { if (!audioSpeech) {
for (const candidate of unverifiedDialogueCandidates) { for (const candidate of unverifiedDialogueCandidates) {
await yieldToEventLoop();
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
stripSigns: true, stripSigns: true,
allowSplits: true, allowSplits: true,
@@ -1985,6 +2069,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true }); const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) return false; if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) return false;
await yieldToEventLoop();
const alignment = alignSubtitleFileToReferenceSpans( const alignment = alignSubtitleFileToReferenceSpans(
parsedTarget, parsedTarget,
extractedSpans.spans, extractedSpans.spans,
@@ -2124,6 +2209,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
(item) => item.key === candidate.evaluated.key, (item) => item.key === candidate.evaluated.key,
); );
if (matchedItem && triedRemoteEmbedded.has(matchedItem.ffIndex)) continue; if (matchedItem && triedRemoteEmbedded.has(matchedItem.ffIndex)) continue;
await yieldToEventLoop();
const alignment = alignSubtitleFileToReferenceSpans( const alignment = alignSubtitleFileToReferenceSpans(
parsedTarget, parsedTarget,
candidate.dialogueSpans, candidate.dialogueSpans,
@@ -2185,6 +2271,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) || !(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
!isMediaFileUnchanged() !isMediaFileUnchanged()
) { ) {
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
return; return;
} }
@@ -4,7 +4,7 @@ import { expandSubtitleGenerationPath } from './subtitle-generation-files';
const OUTPUT_LIMIT = 64 * 1024; const OUTPUT_LIMIT = 64 * 1024;
// ffmpeg echoes input URLs in its errors; streamed media carries access tokens in the query. // ffmpeg echoes input URLs in its errors; streamed media carries access tokens in the query.
function redactUrlCredentials(text: string): string { export function redactUrlCredentials(text: string): string {
return text.replace(/([?&](?:api_?key|token|access_token)=)[^&#\s'"]+/gi, '$1<redacted>'); return text.replace(/([?&](?:api_?key|token|access_token)=)[^&#\s'"]+/gi, '$1<redacted>');
} }
+1 -1
View File
@@ -919,7 +919,7 @@
</label> </label>
</div> </div>
<label id="subsyncOffsetLabel" class="subsync-field hidden"> <label id="subsyncOffsetLabel" class="subsync-field hidden">
<span>Shift offset (milliseconds, e.g. -1200 or +850)</span> <span>Shift offset in milliseconds (positive = later, e.g. 850 or -1200)</span>
<input id="subsyncOffsetInput" type="number" step="50" value="0" /> <input id="subsyncOffsetInput" type="number" step="50" value="0" />
</label> </label>
</div> </div>
+8
View File
@@ -51,6 +51,14 @@ test('unforwarded mpv key reports accept known reasons only', () => {
assert.equal(parseUnforwardedMpvKeyReport(null), null); assert.equal(parseUnforwardedMpvKeyReport(null), null);
}); });
test('parseSubsyncManualRunRequest bounds manual offsets to one hour', () => {
assert.equal(
parseSubsyncManualRunRequest({ engine: 'offset', offsetMs: -3_600_000 })?.offsetMs,
-3_600_000,
);
assert.equal(parseSubsyncManualRunRequest({ engine: 'offset', offsetMs: 3_600_001 }), null);
});
test('parseSubsyncManualRunRequest validates optional mediaPath', () => { test('parseSubsyncManualRunRequest validates optional mediaPath', () => {
const parsed = parseSubsyncManualRunRequest({ const parsed = parseSubsyncManualRunRequest({
engine: 'builtin', engine: 'builtin',
+6 -1
View File
@@ -313,6 +313,9 @@ export function parseControllerConfigUpdate(value: unknown): ControllerConfigUpd
return update; return update;
} }
// A manual subtitle shift beyond an hour is a typo, not a timing fix.
const MAX_SUBSYNC_OFFSET_MS = 60 * 60 * 1000;
export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRequest | null { export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRequest | null {
if (!isObject(value)) return null; if (!isObject(value)) return null;
const { const {
@@ -363,7 +366,9 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
if ( if (
offsetMs !== undefined && offsetMs !== undefined &&
offsetMs !== null && offsetMs !== null &&
(typeof offsetMs !== 'number' || !Number.isFinite(offsetMs)) (typeof offsetMs !== 'number' ||
!Number.isFinite(offsetMs) ||
Math.abs(offsetMs) > MAX_SUBSYNC_OFFSET_MS)
) { ) {
return null; return null;
} }