mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
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:
15 files changed
+306
-84
No files matched your search
@@ -116,21 +116,21 @@ 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.
|
||||
|
||||
| Dependency | Status | What it does |
|
||||
| ------------------------ | ---------------- | -------------------------------------------------------------------- |
|
||||
| mpv | Required | The video player SubMiner draws over |
|
||||
| fuse2 | Required (Linux) | Running the AppImage |
|
||||
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
|
||||
| Dependency | Status | What it does |
|
||||
| ------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||
| mpv | Required | The video player SubMiner draws over |
|
||||
| fuse2 | Required (Linux) | Running the AppImage |
|
||||
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
|
||||
| ffmpeg | Recommended | Card audio/screenshots, embedded subtitle extraction, and built-in audio subtitle sync (first-run setup can download it) |
|
||||
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
|
||||
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
|
||||
| yt-dlp | Optional | YouTube playback |
|
||||
| xz | Optional | TsukiHime subtitle downloads (most Linux distros already have it) |
|
||||
| alass / ffsubsync | Optional | Extra external subtitle sync engines (built-in alass-based sync and audio VAD are included) |
|
||||
| whisper.cpp | Optional | [Subtitle generation](https://docs.subminer.moe/subtitle-generation) |
|
||||
| guessit | Optional | Better title, season, and episode detection for AniSkip and AniList |
|
||||
| fzf / rofi | Optional | Video picker in the `subminer` launcher (rofi is Linux only) |
|
||||
| chafa, ffmpegthumbnailer | Optional | Thumbnail previews in the launcher pickers |
|
||||
| whisper.cpp | Optional | [Subtitle generation](https://docs.subminer.moe/subtitle-generation) |
|
||||
| guessit | Optional | Better title, season, and episode detection for AniSkip and AniList |
|
||||
| fzf / rofi | Optional | Video picker in the `subminer` launcher (rofi is Linux only) |
|
||||
| chafa, ffmpegthumbnailer | Optional | Thumbnail previews in the launcher pickers |
|
||||
|
||||
<details>
|
||||
<summary><b>Platform-specific install commands</b></summary>
|
||||
|
||||
@@ -525,13 +525,13 @@ 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.
|
||||
|
||||
| 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.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffmpeg_path` | `""` | `ffmpeg` path used to extract embedded tracks and audio speech. Empty auto-discovers from `PATH` |
|
||||
| `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `<name>_retimed.<ext>` |
|
||||
| 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.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffmpeg_path` | `""` | `ffmpeg` path used to extract embedded tracks and audio speech. Empty auto-discovers from `PATH` |
|
||||
| `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `<name>_retimed.<ext>` |
|
||||
|
||||
### AniList
|
||||
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
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>
|
||||
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
|
||||
|
||||
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}`)">
|
||||
<source :src="withBase(`/assets/demos/subtitle-sync.webm?v=${v}`)" type="video/webm" />
|
||||
|
||||
@@ -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: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: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 |
|
||||
|
||||
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.
|
||||
|
||||
+11
-11
@@ -14,18 +14,18 @@ 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.
|
||||
|
||||
| Dependency | Needed for | Platforms |
|
||||
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
|
||||
| mpv | Required. The player SubMiner draws over. | All |
|
||||
| fuse2 | Required to run the AppImage. | Linux |
|
||||
| Dependency | Needed for | Platforms |
|
||||
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | ------------ |
|
||||
| mpv | Required. The player SubMiner draws over. | All |
|
||||
| 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 |
|
||||
| MeCab + mecab-ipadic | Recommended. More accurate N+1, JLPT, and frequency highlighting. | All |
|
||||
| yt-dlp | YouTube playback. | All |
|
||||
| xz | [TsukiHime](/tsukihime-integration) subtitle downloads. Most Linux distros already have it. | All |
|
||||
| guessit | Better title, season, and episode detection for [AniSkip](/aniskip-integration) and [AniList](/anilist-integration). | All |
|
||||
| alass or ffsubsync | Optional external subtitle sync engines. SubMiner includes built-in alass-based syncing and speech detection. | All |
|
||||
| fzf, rofi | The file pickers in the `subminer` command (rofi is Linux only). | Linux, macOS |
|
||||
| chafa, ffmpegthumbnailer | Thumbnail previews in the pickers. | Linux, macOS |
|
||||
| MeCab + mecab-ipadic | Recommended. More accurate N+1, JLPT, and frequency highlighting. | All |
|
||||
| yt-dlp | YouTube playback. | All |
|
||||
| xz | [TsukiHime](/tsukihime-integration) subtitle downloads. Most Linux distros already have it. | All |
|
||||
| guessit | Better title, season, and episode detection for [AniSkip](/aniskip-integration) and [AniList](/anilist-integration). | All |
|
||||
| alass or ffsubsync | Optional external subtitle sync engines. SubMiner includes built-in alass-based syncing and speech detection. | All |
|
||||
| fzf, rofi | The file pickers in the `subminer` command (rofi is Linux only). | Linux, macOS |
|
||||
| chafa, ffmpegthumbnailer | Thumbnail previews in the pickers. | Linux, macOS |
|
||||
|
||||
To generate Japanese subtitles from audio, you also need whisper.cpp. See [Subtitle generation](/subtitle-generation).
|
||||
|
||||
|
||||
@@ -67,14 +67,11 @@ With a gamepad and keyboard-only mode on, you can mine without a mouse: move acr
|
||||
|
||||
## 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.
|
||||
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.
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
|
||||
+17
-17
@@ -70,24 +70,24 @@ Built into the overlay, not configurable:
|
||||
|
||||
## Overlay features
|
||||
|
||||
| Shortcut | Action | Config key |
|
||||
| ------------------ | ------------------------------------------------------ | ------------------------------------------ |
|
||||
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle bar: hidden, visible, hover | `shortcuts.toggleSecondarySub` |
|
||||
| `Ctrl/Cmd+Shift+O` | Open runtime options | `shortcuts.openRuntimeOptions` |
|
||||
| `Ctrl/Cmd+/` | Open session help | `shortcuts.openSessionHelp` |
|
||||
| `Ctrl/Cmd+D` | Open character dictionary manager | `shortcuts.openCharacterDictionaryManager` |
|
||||
| `Ctrl/Cmd+N` | Toggle notification history | `shortcuts.toggleNotificationHistory` |
|
||||
| `Ctrl/Cmd+A` | Append the video path on the clipboard to the playlist | `shortcuts.appendClipboardVideoToQueue` |
|
||||
| `Ctrl+Shift+J` | Open Jimaku subtitle search | `shortcuts.openJimaku` |
|
||||
| `Ctrl+Shift+T` | Open TsukiHime subtitle search | `shortcuts.openTsukihime` |
|
||||
| `Ctrl+Shift+G` | Open Japanese subtitle generation | `shortcuts.openSubtitleGeneration` |
|
||||
| Shortcut | Action | Config key |
|
||||
| ------------------ | ------------------------------------------------------------- | ------------------------------------------ |
|
||||
| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle bar: hidden, visible, hover | `shortcuts.toggleSecondarySub` |
|
||||
| `Ctrl/Cmd+Shift+O` | Open runtime options | `shortcuts.openRuntimeOptions` |
|
||||
| `Ctrl/Cmd+/` | Open session help | `shortcuts.openSessionHelp` |
|
||||
| `Ctrl/Cmd+D` | Open character dictionary manager | `shortcuts.openCharacterDictionaryManager` |
|
||||
| `Ctrl/Cmd+N` | Toggle notification history | `shortcuts.toggleNotificationHistory` |
|
||||
| `Ctrl/Cmd+A` | Append the video path on the clipboard to the playlist | `shortcuts.appendClipboardVideoToQueue` |
|
||||
| `Ctrl+Shift+J` | Open Jimaku subtitle search | `shortcuts.openJimaku` |
|
||||
| `Ctrl+Shift+T` | Open TsukiHime subtitle search | `shortcuts.openTsukihime` |
|
||||
| `Ctrl+Shift+G` | Open Japanese subtitle generation | `shortcuts.openSubtitleGeneration` |
|
||||
| `Ctrl+Alt+S` | Sync active subtitle automatically (guided modal on fallback) | `shortcuts.triggerSubsync` |
|
||||
| `g` then `s` | Pick primary and secondary subtitles (when enabled) | `shortcuts.openSubtitleSelection` |
|
||||
| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` |
|
||||
| `` ` `` | Toggle stats overlay | `stats.toggleKey` |
|
||||
| `W` | Mark video watched and play the next one in the queue | `stats.markWatchedKey` |
|
||||
| `Alt+C` | Open controller setup and remapping | `shortcuts.openControllerSelect` |
|
||||
| `Alt+Shift+C` | Open controller debug view | `shortcuts.openControllerDebug` |
|
||||
| `g` then `s` | Pick primary and secondary subtitles (when enabled) | `shortcuts.openSubtitleSelection` |
|
||||
| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` |
|
||||
| `` ` `` | Toggle stats overlay | `stats.toggleKey` |
|
||||
| `W` | Mark video watched and play the next one in the queue | `stats.markWatchedKey` |
|
||||
| `Alt+C` | Open controller setup and remapping | `shortcuts.openControllerSelect` |
|
||||
| `Alt+Shift+C` | Open controller debug view | `shortcuts.openControllerDebug` |
|
||||
|
||||
While a video is playing, session help can also run commands: highlight a row with the arrow keys or the mouse, then press `Enter` or double-click it. Fixed overlay controls, global shortcuts, `y` chords, the multi-line copy and mine actions, Open session help, and the color legend are reference only. Help opened from the tray with no video loaded is read-only.
|
||||
|
||||
|
||||
+1
-1
@@ -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: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: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: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",
|
||||
|
||||
@@ -31,6 +31,11 @@ export const testLanes: Record<string, TestLane> = {
|
||||
include: ['.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: {
|
||||
roots: ['scripts'],
|
||||
include: ['.test.ts'],
|
||||
|
||||
@@ -471,6 +471,64 @@ function fromShellPath(filePath: string): string {
|
||||
.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 () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-ffsubsync-'));
|
||||
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');
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-single-pass-'));
|
||||
const videoPath = path.join(tmpDir, 'ep01.mkv');
|
||||
|
||||
+114
-27
@@ -2,6 +2,7 @@ import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { redactUrlCredentials } from './subtitle-generation-process';
|
||||
import {
|
||||
SubsyncEngine,
|
||||
SubsyncManualPayload,
|
||||
@@ -12,6 +13,7 @@ import {
|
||||
import {
|
||||
buildJellyfinEmbeddedSubtitleUrl,
|
||||
CommandResult,
|
||||
canFfmpegExtractSubtitleExtension,
|
||||
codecToExtension,
|
||||
extensionToFfmpegMuxer,
|
||||
fileExists,
|
||||
@@ -80,12 +82,29 @@ const AUTO_AUDIO_CONFIDENCE_THRESHOLD = 0.65;
|
||||
const AUDIO_SPEECH_LEAD_SEC = 0.1;
|
||||
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 {
|
||||
const parts = [
|
||||
`code=${result.code ?? 'n/a'}`,
|
||||
result.stderr ? `stderr: ${result.stderr}` : '',
|
||||
result.stdout ? `stdout: ${result.stdout}` : '',
|
||||
result.error ? `error: ${result.error}` : '',
|
||||
result.stderr ? `stderr: ${summarizeCommandOutput(result.stderr)}` : '',
|
||||
result.stdout ? `stdout: ${summarizeCommandOutput(result.stdout)}` : '',
|
||||
result.error ? `error: ${summarizeCommandOutput(result.error)}` : '',
|
||||
]
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
@@ -269,14 +288,14 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise<SubsyncConte
|
||||
return typeof filename === 'string' && filename.length > 0;
|
||||
});
|
||||
|
||||
// Resolve active audio stream ff-index if not already cached on mpv client.
|
||||
let audioStreamIndex = client.currentAudioStreamIndex;
|
||||
if (audioStreamIndex === null) {
|
||||
const selectedAudio = tracks.find(
|
||||
(track) =>
|
||||
track.type === 'audio' && track.selected === true && typeof track['ff-index'] === 'number',
|
||||
);
|
||||
if (selectedAudio && typeof selectedAudio['ff-index'] === 'number') {
|
||||
// Resolve the active audio stream's ff-index within the video file. An external audio track
|
||||
// (--audio-file, auto-loaded .mka dub) has an ff-index inside its own file, so mapping it as
|
||||
// `0:N` on the video would pick an unrelated stream; use the video's default audio instead.
|
||||
const selectedAudio = tracks.find((track) => track.type === 'audio' && track.selected === true);
|
||||
let audioStreamIndex: number | null = null;
|
||||
if (!selectedAudio?.external) {
|
||||
audioStreamIndex = client.currentAudioStreamIndex;
|
||||
if (audioStreamIndex === null && typeof selectedAudio?.['ff-index'] === 'number') {
|
||||
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 tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-'));
|
||||
const outputPath = path.join(tempDir, `track_${ffIndex}.${extension}`);
|
||||
@@ -440,6 +464,24 @@ function cleanupTemporaryFile(extraction: FileExtractionResult | null): void {
|
||||
} 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 {
|
||||
if (replace) return subPath;
|
||||
const parsed = path.parse(subPath);
|
||||
@@ -605,10 +647,24 @@ async function findAddedSubtitleTrackId(
|
||||
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(
|
||||
client: MpvClientLike,
|
||||
pathToLoad: string,
|
||||
slot: SubtitleSlot,
|
||||
sourceTrack: MpvTrack,
|
||||
): Promise<void> {
|
||||
if (!client.connected) {
|
||||
throw new Error('MPV disconnected while loading subtitle');
|
||||
@@ -617,7 +673,7 @@ async function loadSyncedSubtitle(
|
||||
if (slot === 'secondary') {
|
||||
// Keep the primary track untouched: load without selecting, then point
|
||||
// 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] });
|
||||
const addedTrackId = await findAddedSubtitleTrackId(client, pathToLoad);
|
||||
if (addedTrackId === null) {
|
||||
@@ -627,7 +683,7 @@ async function loadSyncedSubtitle(
|
||||
return;
|
||||
}
|
||||
|
||||
client.send({ command: ['sub-add', pathToLoad] });
|
||||
client.send({ command: buildSubAddCommand(pathToLoad, 'select', sourceTrack) });
|
||||
client.send({ command: ['set_property', 'sub-delay', 0] });
|
||||
}
|
||||
|
||||
@@ -706,7 +762,13 @@ function collectExtractableEmbeddedRefTracks(
|
||||
if (isSignsOrSongsTrackMeta(track)) continue;
|
||||
const ffIndex = track['ff-index'];
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -840,6 +902,7 @@ async function discoverAndEvaluateSubtitleCandidates(
|
||||
if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') {
|
||||
const preParsed = preExtracted.get(track['ff-index']);
|
||||
if (preParsed && preParsed.events.length > 0) {
|
||||
await yieldToEventLoop();
|
||||
results.push(evaluateParsedCandidate(baseMeta, preParsed));
|
||||
continue;
|
||||
}
|
||||
@@ -852,7 +915,14 @@ async function discoverAndEvaluateSubtitleCandidates(
|
||||
|
||||
let extraction: FileExtractionResult | null = null;
|
||||
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));
|
||||
continue;
|
||||
}
|
||||
@@ -887,6 +957,7 @@ async function discoverAndEvaluateSubtitleCandidates(
|
||||
);
|
||||
}
|
||||
}
|
||||
await yieldToEventLoop();
|
||||
results.push(evaluateParsedCandidate(baseMeta, parsed));
|
||||
} catch {
|
||||
results.push(evaluateParsedCandidate(baseMeta, null));
|
||||
@@ -916,6 +987,7 @@ async function discoverAndEvaluateSubtitleCandidates(
|
||||
};
|
||||
try {
|
||||
const parsed = readAndParseSubtitleFile(sidecar.path);
|
||||
await yieldToEventLoop();
|
||||
results.push(evaluateParsedCandidate(baseMeta, parsed));
|
||||
} catch {
|
||||
// Ignore unreadable sidecars.
|
||||
@@ -1100,9 +1172,9 @@ async function runBuiltinSubsync(
|
||||
leadSec = AUDIO_SPEECH_LEAD_SEC;
|
||||
lengthSec = Math.max(lengthSec, audioSpeech.durationSec);
|
||||
} else if (request.referenceMode === 'file') {
|
||||
const refPath = request.referenceFilePath?.trim() ?? '';
|
||||
if (!refPath || !fileExists(refPath)) {
|
||||
return { ok: false, message: 'Select an existing reference subtitle file.' };
|
||||
const refPath = resolveReferenceFilePath(request.referenceFilePath);
|
||||
if (!refPath) {
|
||||
return { ok: false, message: 'Select an existing reference subtitle file (up to 20 MB).' };
|
||||
}
|
||||
const parsedRef = readAndParseSubtitleFile(refPath);
|
||||
referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans;
|
||||
@@ -1153,7 +1225,7 @@ async function runBuiltinSubsync(
|
||||
if (targetExtraction.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot);
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
||||
return {
|
||||
ok: true,
|
||||
message: formatAlignmentSummary(referenceLabel, alignment),
|
||||
@@ -1204,7 +1276,7 @@ async function runManualOffsetSubsync(
|
||||
if (targetExtraction.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot);
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`,
|
||||
@@ -1275,7 +1347,7 @@ async function subsyncToReference(
|
||||
}
|
||||
|
||||
fs.renameSync(stagedOutputPath, outputPath);
|
||||
await loadSyncedSubtitle(client, outputPath, slot);
|
||||
await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Subtitle synchronized with ${engine}`,
|
||||
@@ -1431,9 +1503,12 @@ export async function runSubsyncManual(
|
||||
}
|
||||
|
||||
if (request.referenceMode === 'file') {
|
||||
const refPath = request.referenceFilePath?.trim() ?? '';
|
||||
if (!refPath || !fileExists(refPath)) {
|
||||
return { ok: false, message: 'Select an existing reference subtitle file for alass' };
|
||||
const refPath = resolveReferenceFilePath(request.referenceFilePath);
|
||||
if (!refPath) {
|
||||
return {
|
||||
ok: false,
|
||||
message: 'Select an existing reference subtitle file (up to 20 MB) for alass',
|
||||
};
|
||||
}
|
||||
const cleaned = maybeWriteCleanedReferenceSrt(refPath, request.stripSigns !== false);
|
||||
try {
|
||||
@@ -1472,7 +1547,7 @@ export async function runSubsyncManual(
|
||||
);
|
||||
cleanedRef = maybeWriteCleanedReferenceSrt(
|
||||
referenceExtraction.path,
|
||||
request.stripSigns === true,
|
||||
request.stripSigns !== false,
|
||||
);
|
||||
return await subsyncToReference(
|
||||
'alass',
|
||||
@@ -1713,6 +1788,8 @@ export async function openSubsyncManualPicker(
|
||||
return true;
|
||||
}
|
||||
|
||||
const STALE_AUTO_RESULT_MESSAGE = 'Subsync: playback changed while syncing; discarded result';
|
||||
|
||||
async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void> {
|
||||
const client = getMpvClientForSubsync(deps);
|
||||
const context = await gatherSubsyncContext(client);
|
||||
@@ -1741,10 +1818,11 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
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.showMpvOsd('Subsync: choose engine and subtitles');
|
||||
@@ -1758,6 +1836,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
const payload = buildManualPayload(context, resolved, deps, {
|
||||
@@ -1805,6 +1884,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
if (alreadyInSync) {
|
||||
@@ -1824,7 +1904,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
if (targetExtraction!.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot);
|
||||
await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack);
|
||||
deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment));
|
||||
};
|
||||
|
||||
@@ -1839,6 +1919,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES,
|
||||
);
|
||||
for (const candidate of fastAligned) {
|
||||
await yieldToEventLoop();
|
||||
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
|
||||
stripSigns: 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!).
|
||||
for (const candidate of alignedCandidates) {
|
||||
await yieldToEventLoop();
|
||||
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
|
||||
stripSigns: 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
|
||||
// reference subtitles are shifted off the audio): sync directly to video audio speech!
|
||||
if (audioSpeech && audioSpeech.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) {
|
||||
await yieldToEventLoop();
|
||||
const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, {
|
||||
stripSigns: 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.
|
||||
if (!audioSpeech) {
|
||||
for (const candidate of unverifiedDialogueCandidates) {
|
||||
await yieldToEventLoop();
|
||||
const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, {
|
||||
stripSigns: true,
|
||||
allowSplits: true,
|
||||
@@ -1985,6 +2069,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
|
||||
const extractedSpans = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
|
||||
if (extractedSpans.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) return false;
|
||||
await yieldToEventLoop();
|
||||
const alignment = alignSubtitleFileToReferenceSpans(
|
||||
parsedTarget,
|
||||
extractedSpans.spans,
|
||||
@@ -2124,6 +2209,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
(item) => item.key === candidate.evaluated.key,
|
||||
);
|
||||
if (matchedItem && triedRemoteEmbedded.has(matchedItem.ffIndex)) continue;
|
||||
await yieldToEventLoop();
|
||||
const alignment = alignSubtitleFileToReferenceSpans(
|
||||
parsedTarget,
|
||||
candidate.dialogueSpans,
|
||||
@@ -2185,6 +2271,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot)) ||
|
||||
!isMediaFileUnchanged()
|
||||
) {
|
||||
deps.showMpvOsd(STALE_AUTO_RESULT_MESSAGE);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { expandSubtitleGenerationPath } from './subtitle-generation-files';
|
||||
const OUTPUT_LIMIT = 64 * 1024;
|
||||
|
||||
// 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>');
|
||||
}
|
||||
|
||||
|
||||
@@ -919,7 +919,7 @@
|
||||
</label>
|
||||
</div>
|
||||
<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" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
@@ -51,6 +51,14 @@ test('unforwarded mpv key reports accept known reasons only', () => {
|
||||
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', () => {
|
||||
const parsed = parseSubsyncManualRunRequest({
|
||||
engine: 'builtin',
|
||||
|
||||
@@ -313,6 +313,9 @@ export function parseControllerConfigUpdate(value: unknown): ControllerConfigUpd
|
||||
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 {
|
||||
if (!isObject(value)) return null;
|
||||
const {
|
||||
@@ -363,7 +366,9 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
|
||||
if (
|
||||
offsetMs !== undefined &&
|
||||
offsetMs !== null &&
|
||||
(typeof offsetMs !== 'number' || !Number.isFinite(offsetMs))
|
||||
(typeof offsetMs !== 'number' ||
|
||||
!Number.isFinite(offsetMs) ||
|
||||
Math.abs(offsetMs) > MAX_SUBSYNC_OFFSET_MS)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user