diff --git a/README.md b/README.md index 1016773b..a760ce8a 100644 --- a/README.md +++ b/README.md @@ -95,8 +95,8 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi Automatic intro detection with chapter markers and a one-key skip (TAB by default) - alass / ffsubsync - Retime a subtitle against the audio or another subtitle track (Ctrl+Alt+S). Requires alass or ffsubsync; set subsync.alass_path or subsync.ffsubsync_path if they are not in /usr/bin + Subtitle sync + One-click built-in alass-based syncing (Ctrl+Alt+S or the subtitle sidebar Sync button) with sign/song stripping, audio alignment checks across loaded/embedded/sidecar tracks, built-in speech-activity fallback, and a guided modal when manual input is needed. Works out of the box with no external sync binary; ffmpeg enables embedded-track extraction and audio sync/verification, and external alass or ffsubsync are optional WebSocket @@ -121,12 +121,12 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to | 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 and screenshots (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 | Subtitle sync | +| 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) | diff --git a/changes/builtin-subtitle-sync.md b/changes/builtin-subtitle-sync.md new file mode 100644 index 00000000..31dc6506 --- /dev/null +++ b/changes/builtin-subtitle-sync.md @@ -0,0 +1,5 @@ +type: added +area: subsync + +- Integrated built-in alass-based subtitle syncing with sign/song stripping, framerate and scene-cut/ad-break handling, audio alignment verification across all loaded/embedded/sidecar tracks, and built-in speech-activity audio fallback. +- Added one-click automatic syncing via the subtitle sidebar Sync button and `Ctrl+Alt+S` (`subsync.mode: "auto"`), automatically opening the guided Subtitle Sync modal with diagnostics, file browsing, external engine fallbacks, and manual offset only when guidance is needed. diff --git a/config.example.jsonc b/config.example.jsonc index 581ec69f..f90f491c 100644 --- a/config.example.jsonc +++ b/config.example.jsonc @@ -730,6 +730,7 @@ // Hot-reload: subsync changes apply to the next subtitle sync run. // ========================================== "subsync": { + "mode": "auto", // Automatic subtitle sync mode ("auto" syncs immediately and opens the guided modal only when needed; "manual" always opens the modal). Values: auto | manual "alass_path": "", // Optional absolute path to the alass binary used by subsync. Leave empty to auto-discover from PATH. "ffsubsync_path": "", // Optional absolute path to the ffsubsync binary used by subsync. Leave empty to auto-discover from PATH. "ffmpeg_path": "", // Optional absolute path to the ffmpeg binary used by subsync. Leave empty to auto-discover from PATH. diff --git a/docs-site/configuration.md b/docs-site/configuration.md index 4c4d7d89..64fe87bc 100644 --- a/docs-site/configuration.md +++ b/docs-site/configuration.md @@ -521,16 +521,17 @@ Transcribes Japanese subtitles locally with whisper.cpp. Open it with `Ctrl+Shif ### Subtitle sync -Retimes a subtitle track with [`alass`](https://github.com/kaegi/alass) (against another subtitle or the video) or [`ffsubsync`](https://github.com/smacke/ffsubsync) (against the video's audio). Install them yourself. Open the picker with `Ctrl+Alt+S` (`shortcuts.triggerSubsync`). +Built-in alass-based subtitle alignment works out of the box with no extra sync binary required. Press `Ctrl+Alt+S` (`shortcuts.triggerSubsync`) or click **Sync** in the [subtitle sidebar](/subtitle-sidebar) to sync automatically: SubMiner inspects loaded, embedded, and sidecar subtitle tracks, strips signs and songs, checks reference alignment against the video's audio (falling back to built-in speech detection when no aligned reference subtitle is available), and opens the guided modal whenever it cannot finish cleanly on its own. -| Key | Default | What it does | -| ------------------------ | ------- | ------------------------------------------------------------------- | -| `subsync.alass_path` | `""` | `alass` path. Empty uses `/usr/bin/alass` | -| `subsync.ffsubsync_path` | `""` | `ffsubsync` path. Empty uses `/usr/bin/ffsubsync` | -| `subsync.ffmpeg_path` | `""` | `ffmpeg` path. Empty uses `/usr/bin/ffmpeg` | -| `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `_retimed.` | +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. -If a tool lives somewhere else, such as on macOS or Windows, set its path. +| 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 `_retimed.` | ### AniList diff --git a/docs-site/index.md b/docs-site/index.md index 8279e3dc..103e3819 100644 --- a/docs-site/index.md +++ b/docs-site/index.md @@ -66,7 +66,7 @@ features: src: /assets/subtitle-download.svg alt: Subtitle download icon title: Subtitle download and sync - details: Search Jimaku or TsukiHime and download a track, then retime it with alass or ffsubsync. Both run from the overlay. + details: Search Jimaku or TsukiHime and download a track, then sync it automatically with SubMiner's built-in alass-based aligner and speech fallback (or optional external alass/ffsubsync). Both run from the overlay. link: /jimaku-integration linkText: Jimaku integration - icon: diff --git a/docs-site/installation.md b/docs-site/installation.md index d26e42f9..cd1334dc 100644 --- a/docs-site/installation.md +++ b/docs-site/installation.md @@ -18,12 +18,12 @@ Only mpv is required. Install ffmpeg too unless you are fine with cards that hav | ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ | | mpv | Required. The player SubMiner draws over. | All | | fuse2 | Required to run the AppImage. | Linux | -| ffmpeg | Recommended. Audio clips and screenshots on cards. Without it those fields stay empty. | All | +| 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 | Subtitle syncing. You need at least one to use it. | 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 | diff --git a/docs-site/public/config.example.jsonc b/docs-site/public/config.example.jsonc index 581ec69f..f90f491c 100644 --- a/docs-site/public/config.example.jsonc +++ b/docs-site/public/config.example.jsonc @@ -730,6 +730,7 @@ // Hot-reload: subsync changes apply to the next subtitle sync run. // ========================================== "subsync": { + "mode": "auto", // Automatic subtitle sync mode ("auto" syncs immediately and opens the guided modal only when needed; "manual" always opens the modal). Values: auto | manual "alass_path": "", // Optional absolute path to the alass binary used by subsync. Leave empty to auto-discover from PATH. "ffsubsync_path": "", // Optional absolute path to the ffsubsync binary used by subsync. Leave empty to auto-discover from PATH. "ffmpeg_path": "", // Optional absolute path to the ffmpeg binary used by subsync. Leave empty to auto-discover from PATH. diff --git a/docs-site/shortcuts.md b/docs-site/shortcuts.md index 207aae13..e809f2d4 100644 --- a/docs-site/shortcuts.md +++ b/docs-site/shortcuts.md @@ -81,7 +81,7 @@ Built into the overlay, not configurable: | `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` | Open subtitle sync (subsync) | `shortcuts.triggerSubsync` | +| `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` | diff --git a/docs-site/subtitle-sidebar.md b/docs-site/subtitle-sidebar.md index 647b9962..9fc033b7 100644 --- a/docs-site/subtitle-sidebar.md +++ b/docs-site/subtitle-sidebar.md @@ -7,6 +7,7 @@ The subtitle sidebar lists every line of the current subtitle file in a scrollab Press `\` to open or close it. The sidebar is on by default. Set `subtitleSidebar.enabled` to `false` to turn it off, or `subtitleSidebar.autoOpen` to `true` to open it at startup. - Click a line to seek to it. With a line focused from the keyboard, `Enter` seeks to it. +- Click **Sync** in the sidebar header to automatically sync the active subtitle track (`Shift+click` opens the guided sync modal directly). - The current line is highlighted and kept in view as playback moves (`autoScroll`). - Hovering the list pauses playback (`pauseVideoOnHover`). - Switching media or subtitle track updates the list. diff --git a/docs-site/troubleshooting.md b/docs-site/troubleshooting.md index e203e999..d797b05a 100644 --- a/docs-site/troubleshooting.md +++ b/docs-site/troubleshooting.md @@ -144,18 +144,20 @@ Audio clips and screenshots need FFmpeg. Without it, cards are still created wit ## Subtitle sync (subsync) -Subtitle sync needs at least one of alass or ffsubsync. Neither ships with SubMiner. +SubMiner includes a built-in alass-based aligner and speech-activity fallback (using `ffmpeg`, or Silero VAD if configured for [subtitle generation](/subtitle-generation)), so external `alass` and `ffsubsync` are optional. -**"Configured alass executable not found"**: install it (`paru -S alass` or `cargo install alass-cli`), or set `subsync.alass_path`. +**Automatic sync opens the guided modal instead of applying immediately**: -**"Configured ffsubsync executable not found"**: install it (`paru -S python-ffsubsync` or `pip install ffsubsync`), or set `subsync.ffsubsync_path`. +- SubMiner pauses for guidance when confidence is low (for example, a mismatched episode), when a reference subtitle track is itself misaligned with the audio and audio-only alignment is uncertain, or when a remote stream has no usable reference track. +- In the guided modal you can switch to another embedded/sidecar track, browse for a local reference subtitle file, switch to built-in video audio speech detection, toggle **Ignore signs & songs** or **Allow scene cuts & ad-break splits**, try external `alass`/`ffsubsync`, or apply a **Manual offset**. + +**"Configured alass executable not found"** / **"Configured ffsubsync executable not found"**: only applies when selecting the optional external engines. Install them (`paru -S alass`, `cargo install alass-cli`, or `pip install ffsubsync`), set `subsync.alass_path` / `subsync.ffsubsync_path`, or use the **Built-in (alass)** engine. **"alass synchronization failed" / "ffsubsync synchronization failed"**: -- alass needs a reference: a second subtitle track or the local video file. It cannot use the track being retimed. -- `ffmpeg` must be installed to extract internal subtitle tracks. -- ffsubsync only works on local files, not streams. -- Run the tool by hand to see its full error output. +- `ffmpeg` must be installed to extract internal subtitle tracks or run audio-based sync/verification. +- Audio-based sync and `ffsubsync` require a local video file, not a remote stream URL. +- Run the external tool by hand to see its full error output if you are using an external engine. ## "xz binary not found" diff --git a/docs/architecture/README.md b/docs/architecture/README.md index c5015892..b3f8d16f 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -35,6 +35,7 @@ Update checks and startup launcher migration share a serialized update-state sto - `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative. - Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments. - `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps. +- `src/subsync/` and `src/core/services/subsync*.ts` own built-in subtitle synchronization: format-preserving SRT/VTT/ASS parsing and sign/song/karaoke stripping (`subtitle-lines.ts`), pure-TypeScript alass-based single-shift, framerate-ratio, Viterbi piecewise, and broadcast multi-piece alignment with statistical standing/start-agreement scoring (`alass-align.ts`), cached local audio speech detection preferring Silero VAD when available with a built-in ffmpeg voice-band PCM VAD fallback, single-pass multi-track `ffmpeg` demuxing for embedded tracks, and fast parallel seeked-window audio verification for external-only references (`audio-speech.ts`), plus sidecar/track candidate discovery and audio-alignment verification (`reference-discovery.ts`). Triggering subsync in default `auto` mode evaluates all available tracks and sidecars (skipping signs/songs-tagged embedded tracks), verifies references against audio on local media so misaligned secondary tracks are skipped in favor of better-aligned tracks or audio speech, applies confident syncs automatically, and opens the guided modal (supporting built-in, external `alass`/`ffsubsync`, file browse, sign/split toggles, and manual offset) whenever automatic sync cannot finish cleanly. - `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry. - `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes. - `src/core/services/plugins/` owns user plugins: discovery from `/plugins//plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `src/main/assemblies/plugins.ts` builds the host. The playback assembly attaches each new mpv client so plugin listeners survive client replacement, the startup assembly starts plugins from the app-ready path after logging is configured, and the `will-quit` cleanup unloads them first, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:/`, CLI `--plugin-action /`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `/plugin-data//` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open. diff --git a/src/config/definitions/defaults-core.ts b/src/config/definitions/defaults-core.ts index 4c1ccd43..09a4f285 100644 --- a/src/config/definitions/defaults-core.ts +++ b/src/config/definitions/defaults-core.ts @@ -137,6 +137,7 @@ export const CORE_DEFAULT_CONFIG: Pick< }, }, subsync: { + mode: 'auto', alass_path: '', ffsubsync_path: '', ffmpeg_path: '', diff --git a/src/config/definitions/options-core.ts b/src/config/definitions/options-core.ts index 9a7abf20..ac9ef8ea 100644 --- a/src/config/definitions/options-core.ts +++ b/src/config/definitions/options-core.ts @@ -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', diff --git a/src/config/resolve/core-domains.ts b/src/config/resolve/core-domains.ts index b0553031..278ae1c8 100644 --- a/src/config/resolve/core-domains.ts +++ b/src/config/resolve/core-domains.ts @@ -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); diff --git a/src/core/services/index.ts b/src/core/services/index.ts index 59443233..3842ce4e 100644 --- a/src/core/services/index.ts +++ b/src/core/services/index.ts @@ -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 { diff --git a/src/core/services/ipc.ts b/src/core/services/ipc.ts index a746f4f9..b5b33645 100644 --- a/src/core/services/ipc.ts +++ b/src/core/services/ipc.ts @@ -102,6 +102,8 @@ export interface IpcServiceDeps { focusMainWindow: () => void; activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise; runSubsyncManual: (request: SubsyncManualRunRequest) => Promise; + openSubsyncManual?: () => Promise; + pickSubsyncReferenceFile?: () => Promise; onYoutubePickerResolve: ( request: YoutubePickerResolveRequest, ) => Promise; @@ -373,6 +375,8 @@ export interface IpcDepsRuntimeOptions { focusMainWindow: () => void; activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise; runSubsyncManual: (request: SubsyncManualRunRequest) => Promise; + openSubsyncManual?: () => Promise; + pickSubsyncReferenceFile?: () => Promise; onYoutubePickerResolve: ( request: YoutubePickerResolveRequest, ) => Promise; @@ -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(); }); diff --git a/src/core/services/subsync-runner.ts b/src/core/services/subsync-runner.ts index 20927294..4a8777a1 100644 --- a/src/core/services/subsync-runner.ts +++ b/src/core/services/subsync-runner.ts @@ -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 { + 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, diff --git a/src/core/services/subsync.test.ts b/src/core/services/subsync.test.ts index 1fc86be0..4081511a 100644 --- a/src/core/services/subsync.test.ts +++ b/src/core/services/subsync.test.ts @@ -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> = []; + + 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> = []; + 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); +}); diff --git a/src/core/services/subsync.ts b/src/core/services/subsync.ts index c7c54d5f..840e1a99 100644 --- a/src/core/services/subsync.ts +++ b/src/core/services/subsync.ts @@ -1,11 +1,19 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { SubsyncManualPayload, SubsyncManualRunRequest, SubsyncResult } from '../../types'; +import { fileURLToPath } from 'url'; +import { + SubsyncEngine, + SubsyncManualPayload, + SubsyncManualRunRequest, + SubsyncReferenceCandidate, + SubsyncResult, +} from '../../types'; import { CommandResult, codecToExtension, fileExists, + findSubsyncExecutable, formatTrackLabel, getTrackById, hasPathSeparators, @@ -14,6 +22,40 @@ import { SubsyncContext, SubsyncResolvedConfig, } from '../../subsync/utils'; +import { + alignSubtitleFileToReferenceSpans, + evaluateReferenceAlignmentToAudio, + evaluateReferenceAlignmentToSampledAudio, + type AlignmentResult, + type SampledAudioWindow, +} from '../../subsync/alass-align'; +import { + extractAudioSpeechSpans, + extractSampledAudioWindows, + extractSinglePassRipMedia, + getCachedAudioSpeechSpans, + type AudioSpeechResult, + type EmbeddedTrackSpec, +} from '../../subsync/audio-speech'; +import { + buildTrackReferenceLabel, + discoverSidecarReferenceFiles, + formatReferenceCandidateDetail, + isEnglishReferenceMeta, + isFullDialogueHintMeta, + rankReferenceCandidates, + type EvaluatedSubtitleReference, +} from '../../subsync/reference-discovery'; +import { + applyTimingToSubtitleFile, + decodeSubtitleBytesWithStatus, + extractSpansFromParsedSubtitle, + formatSpansAsSrt, + isSignsOrSongsTrackMeta, + parseSubtitleFileContent, + type ParsedSubtitleFile, + type SubtitleTimeSpan, +} from '../../subsync/subtitle-lines'; import { isRemoteMediaPath } from '../../jimaku/utils'; interface FileExtractionResult { @@ -25,6 +67,12 @@ type SubtitleSlot = 'primary' | 'secondary'; const SYNCED_TRACK_LOOKUP_ATTEMPTS = 5; const SYNCED_TRACK_LOOKUP_RETRY_MS = 100; +const ALREADY_IN_SYNC_MS = 80; +const MIN_REFERENCE_DIALOGUE_LINES = 15; +const AUTO_SUBTITLE_CONFIDENCE_THRESHOLD = 0.65; +const AUTO_REMOTE_CONFIDENCE_THRESHOLD = 0.7; +const AUTO_AUDIO_CONFIDENCE_THRESHOLD = 0.65; +const AUDIO_SPEECH_LEAD_SEC = 0.1; function summarizeCommandFailure(command: string, result: CommandResult): string { const parts = [ @@ -47,9 +95,16 @@ interface MpvClientLike { requestProperty: (name: string) => Promise; } +export interface SubsyncVadPaths { + vadExecutablePath: string | null; + vadModelPath: string | null; +} + interface SubsyncCoreDeps { getMpvClient: () => MpvClientLike | null; getResolvedConfig: () => SubsyncResolvedConfig; + getVadPaths?: () => SubsyncVadPaths; + canPickReferenceFile?: () => boolean; } function parseTrackId(value: unknown): number | null { @@ -65,6 +120,15 @@ function parseTrackId(value: unknown): number | null { return null; } +function parseOptionalNumber(value: unknown): number | null { + if (typeof value === 'number' && Number.isFinite(value)) return value; + if (typeof value === 'string') { + const parsed = Number(value.trim()); + if (Number.isFinite(parsed)) return parsed; + } + return null; +} + function normalizeTrackIds(tracks: unknown[]): MpvTrack[] { return tracks.map((track) => { if (!track || typeof track !== 'object') return track as MpvTrack; @@ -135,19 +199,49 @@ function getMpvClientForSubsync(deps: SubsyncCoreDeps): MpvClientLike { return client; } +function resolveLocalSubtitlePath( + rawPath: string, + workingDirectory?: string | null, +): string | null { + if (!rawPath) return null; + let local = rawPath; + if (local.startsWith('file://')) { + try { + local = fileURLToPath(local); + } catch { + return null; + } + } else if (/^[a-z][a-z\d+.-]*:\/\//i.test(local)) { + return null; + } + if (!path.isAbsolute(local) && workingDirectory) { + local = path.resolve(workingDirectory, local); + } + return local; +} + async function gatherSubsyncContext(client: MpvClientLike): Promise { - const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw] = await Promise.all([ - client.requestProperty('path'), - client.requestProperty('sid'), - client.requestProperty('secondary-sid'), - client.requestProperty('track-list'), - ]); + const [videoPathRaw, sidRaw, secondarySidRaw, trackListRaw, workingDirRaw, durationRaw] = + await Promise.all([ + client.requestProperty('path'), + client.requestProperty('sid'), + client.requestProperty('secondary-sid'), + client.requestProperty('track-list'), + client.requestProperty('working-directory').catch(() => null), + client.requestProperty('duration').catch(() => null), + ]); const videoPath = typeof videoPathRaw === 'string' ? videoPathRaw : ''; if (!videoPath) { throw new Error('No video is currently loaded'); } + const workingDirectory = + typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null; + const resolvedVideoPath = isRemoteMediaPath(videoPath) + ? videoPath + : (resolveLocalSubtitlePath(videoPath, workingDirectory) ?? videoPath); + const tracks = Array.isArray(trackListRaw) ? normalizeTrackIds(trackListRaw as MpvTrack[]) : []; const subtitleTracks = tracks.filter((track) => track.type === 'sub'); const sid = parseTrackId(sidRaw); @@ -166,15 +260,29 @@ async function gatherSubsyncContext(client: MpvClientLike): Promise 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') { + audioStreamIndex = selectedAudio['ff-index']; + } + } + return { - videoPath, + videoPath: resolvedVideoPath, + workingDirectory, + durationSec: parseOptionalNumber(durationRaw), primaryTrack, secondaryTrack, subtitleTracks: dedupeSubtitleTracks( usableTracks, new Set([sid, secondarySid].filter((id): id is number => typeof id === 'number')), ), - audioStreamIndex: client.currentAudioStreamIndex, + audioStreamIndex, }; } @@ -189,20 +297,28 @@ function ensureExecutablePath(pathOrName: string, name: string): string { return pathOrName; } +function isExecutableAvailable(configuredPath: string, names: readonly string[]): boolean { + if (!configuredPath) return findSubsyncExecutable(undefined, names) !== null; + if (hasPathSeparators(configuredPath)) return fileExists(configuredPath); + return findSubsyncExecutable(configuredPath, names) !== null; +} + async function extractSubtitleTrackToFile( ffmpegPath: string, videoPath: string, track: MpvTrack, + workingDirectory?: string | null, ): Promise { if (track.external) { const externalPath = track['external-filename']; if (typeof externalPath !== 'string' || externalPath.length === 0) { throw new Error('External subtitle track has no file path'); } - if (!fileExists(externalPath)) { - throw new Error(`Subtitle file not found: ${externalPath}`); + const localPath = resolveLocalSubtitlePath(externalPath, workingDirectory) ?? externalPath; + if (!fileExists(localPath)) { + throw new Error(`Subtitle file not found: ${localPath}`); } - return { path: externalPath, temporary: false }; + return { path: localPath, temporary: false }; } const ffIndex = track['ff-index']; @@ -245,8 +361,8 @@ async function extractSubtitleTrackToFile( return { path: outputPath, temporary: true }; } -function cleanupTemporaryFile(extraction: FileExtractionResult): void { - if (!extraction.temporary) return; +function cleanupTemporaryFile(extraction: FileExtractionResult | null): void { + if (!extraction || !extraction.temporary) return; try { if (fileExists(extraction.path)) { fs.unlinkSync(extraction.path); @@ -266,6 +382,78 @@ function buildRetimedPath(subPath: string, replace: boolean): string { return path.join(parsed.dir, `${parsed.name}_retimed${parsed.ext || '.srt'}`); } +const LOSSY_REPLACE_ERROR_MESSAGE = + 'Cannot safely replace subtitle file in place because its text encoding could not be decoded losslessly. Set subsync.replace to false or convert the file to UTF-8.'; + +function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile { + const bytes = fs.readFileSync(filePath); + const decoded = decodeSubtitleBytesWithStatus(bytes); + return { + ...parseSubtitleFileContent(decoded.text, filePath), + lossless: decoded.lossless, + }; +} + +function writeRetimedContent(outputPath: string, content: string): void { + const dir = path.dirname(outputPath); + const tmpPath = path.join( + dir, + `.subminer-subsync-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`, + ); + try { + fs.writeFileSync(tmpPath, content, 'utf8'); + fs.renameSync(tmpPath, outputPath); + } catch (error) { + try { + if (fs.existsSync(tmpPath)) { + fs.unlinkSync(tmpPath); + } + } catch { + // Best-effort cleanup of temp write artifact. + } + throw error; + } +} + +async function isPlaybackSessionUnchanged( + client: MpvClientLike, + context: SubsyncContext, + targetTrack: MpvTrack, + slot: SubtitleSlot, +): Promise { + if (!client.connected) return false; + try { + const slotProperty = slot === 'secondary' ? 'secondary-sid' : 'sid'; + const [videoPathRaw, workingDirRaw, slotTrackRaw] = await Promise.all([ + client.requestProperty('path'), + client.requestProperty('working-directory').catch(() => null), + client.requestProperty(slotProperty), + ]); + const currentRawPath = typeof videoPathRaw === 'string' ? videoPathRaw : ''; + if (!currentRawPath) return false; + const currentWorkingDir = + typeof workingDirRaw === 'string' && workingDirRaw.trim().length > 0 ? workingDirRaw : null; + const currentVideoPath = isRemoteMediaPath(currentRawPath) + ? currentRawPath + : (resolveLocalSubtitlePath(currentRawPath, currentWorkingDir) ?? currentRawPath); + if ( + normalizeSubtitlePathForCompare(currentVideoPath) !== + normalizeSubtitlePathForCompare(context.videoPath) + ) { + return false; + } + if (typeof targetTrack.id === 'number') { + const currentSlotId = parseTrackId(slotTrackRaw); + if (currentSlotId !== null && currentSlotId !== targetTrack.id) { + return false; + } + } + return true; + } catch { + return false; + } +} + async function runAlassSync( alassPath: string, referenceFile: string, @@ -358,6 +546,557 @@ async function loadSyncedSubtitle( client.send({ command: ['set_property', 'sub-delay', 0] }); } +function formatOffsetSummary(offsetMs: number): string { + const sec = offsetMs / 1000; + const formatted = Math.abs(sec) >= 10 ? sec.toFixed(1) : sec.toFixed(2); + return offsetMs >= 0 ? `+${formatted}s` : `${formatted}s`; +} + +function formatAlignmentSummary(sourceLabel: string, alignment: AlignmentResult): string { + const parts = [`Synced via ${sourceLabel}`, formatOffsetSummary(alignment.offsetMs)]; + if (Math.abs(alignment.ratio - 1.0) > 1e-4) { + parts.push(`speed ${alignment.ratio.toFixed(4)}x`); + } + if (alignment.segments > 1) { + parts.push(`${alignment.segments} segments`); + } + const pct = Math.round(alignment.confidence * 100); + if (pct > 0) { + parts.push(`${pct}%`); + } + return parts.join(' · '); +} + +function isAlreadyInSync(alignment: AlignmentResult): boolean { + return ( + alignment.confident && + !alignment.cut && + alignment.segments === 1 && + Math.abs(alignment.ratio - 1.0) < 1e-4 && + Math.abs(alignment.offsetMs) <= ALREADY_IN_SYNC_MS + ); +} + +async function resolveAudioSpeechForContext( + context: SubsyncContext, + resolved: SubsyncResolvedConfig, + deps: SubsyncCoreDeps, +): Promise { + if (isRemoteMediaPath(context.videoPath) || !fileExists(context.videoPath)) { + return null; + } + if (!isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg'])) { + return null; + } + const vadPaths = deps.getVadPaths?.(); + try { + const speech = await extractAudioSpeechSpans({ + ffmpegPath: resolved.ffmpegPath, + videoPath: context.videoPath, + audioStreamIndex: context.audioStreamIndex, + vadExecutablePath: vadPaths?.vadExecutablePath ?? null, + vadModelPath: vadPaths?.vadModelPath ?? null, + }); + return speech.spans.length > 0 ? speech : null; + } catch { + return null; + } +} + +interface CandidateWithSpans { + evaluated: EvaluatedSubtitleReference; + dialogueSpans: SubtitleTimeSpan[]; + allSpans: SubtitleTimeSpan[]; +} + +function collectExtractableEmbeddedRefTracks( + context: SubsyncContext, + targetTrack: MpvTrack, +): EmbeddedTrackSpec[] { + const specs: EmbeddedTrackSpec[] = []; + for (const track of context.subtitleTracks) { + if (typeof track.id !== 'number' || track.id === targetTrack.id) continue; + if (track.external) continue; + // Skip embedded tracks already tagged as signs/songs or forced so we don't waste demux I/O. + if (isSignsOrSongsTrackMeta(track)) continue; + const ffIndex = track['ff-index']; + const extension = codecToExtension(track.codec); + if (typeof ffIndex === 'number' && Number.isInteger(ffIndex) && ffIndex >= 0 && extension) { + specs.push({ ffIndex, extension }); + } + } + return specs; +} + +async function discoverAndEvaluateSubtitleCandidates( + context: SubsyncContext, + targetTrack: MpvTrack, + resolved: SubsyncResolvedConfig, + audioSpeech: AudioSpeechResult | null, + options: { + sampledAudioWindows?: SampledAudioWindow[] | null; + preExtractedEmbedded?: ReadonlyMap | null; + skipSignsEmbeddedExtraction?: boolean; + } = {}, +): Promise { + const results: CandidateWithSpans[] = []; + const loadedPaths: string[] = []; + const ffmpegAvailable = isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg']); + const sampledWindows = options.sampledAudioWindows ?? null; + const preExtracted = options.preExtractedEmbedded ?? null; + const skipSignsEmbedded = options.skipSignsEmbeddedExtraction !== false; + + for (const track of context.subtitleTracks) { + if (track.external && track['external-filename']) { + const resolvedPath = resolveLocalSubtitlePath( + track['external-filename'], + context.workingDirectory, + ); + if (resolvedPath) loadedPaths.push(resolvedPath); + } + } + + const evaluateParsedCandidate = ( + meta: Omit< + EvaluatedSubtitleReference, + 'dialogueCount' | 'signCount' | 'audioStatus' | 'audioOffsetMs' | 'audioConfidence' + >, + parsed: ParsedSubtitleFile | null, + ): CandidateWithSpans => { + const stripped = parsed + ? extractSpansFromParsedSubtitle(parsed, { stripSigns: true }) + : { spans: [], dialogueCount: 0, signCount: 0 }; + const all = parsed + ? extractSpansFromParsedSubtitle(parsed, { stripSigns: false }) + : { spans: [] }; + + const effectiveSignsOnly = + meta.isSignsOnly || + (parsed !== null && stripped.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES); + + let audioStatus: EvaluatedSubtitleReference['audioStatus'] = 'unverified'; + let audioOffsetMs: number | null = null; + let audioConfidence = 0; + + if (!effectiveSignsOnly && stripped.spans.length >= MIN_REFERENCE_DIALOGUE_LINES) { + if (audioSpeech && audioSpeech.spans.length > 0) { + const audioEval = evaluateReferenceAlignmentToAudio(stripped.spans, audioSpeech.spans, { + lengthSec: context.durationSec ?? audioSpeech.durationSec, + audioCalibration: audioSpeech.calibration, + audioLeadSec: AUDIO_SPEECH_LEAD_SEC, + }); + audioStatus = audioEval.status; + audioOffsetMs = audioEval.offsetMs; + audioConfidence = audioEval.confidence; + } else if (sampledWindows && sampledWindows.length >= 2) { + const sampleEval = evaluateReferenceAlignmentToSampledAudio( + stripped.spans, + sampledWindows, + { audioLeadSec: AUDIO_SPEECH_LEAD_SEC }, + ); + audioStatus = sampleEval.status; + audioOffsetMs = sampleEval.offsetMs; + audioConfidence = sampleEval.confidence; + } + } + + return { + evaluated: { + ...meta, + isSignsOnly: effectiveSignsOnly, + dialogueCount: stripped.dialogueCount, + signCount: stripped.signCount, + audioStatus, + audioOffsetMs, + audioConfidence, + }, + dialogueSpans: stripped.spans, + allSpans: all.spans, + }; + }; + + // 1. Evaluate all mpv subtitle tracks other than target. + for (const track of context.subtitleTracks) { + if (typeof track.id !== 'number' || track.id === targetTrack.id) continue; + const isSecondary = context.secondaryTrack !== null && track.id === context.secondaryTrack.id; + const isEmbedded = !track.external; + const isSignsTrack = isSignsOrSongsTrackMeta(track); + const externalFilename = track['external-filename']; + const baseMeta = { + key: `track:${track.id}`, + kind: 'track' as const, + trackId: track.id, + filePath: track.external + ? (resolveLocalSubtitlePath(externalFilename ?? '', context.workingDirectory) ?? null) + : null, + label: buildTrackReferenceLabel(track, isSecondary), + isSecondary, + isEmbedded, + isEnglish: isEnglishReferenceMeta({ + lang: track.lang, + title: track.title, + filename: externalFilename, + }), + isFullDialogueHint: isFullDialogueHintMeta({ + title: track.title, + filename: externalFilename, + }), + isSignsOnly: isSignsTrack, + }; + + if (isEmbedded && skipSignsEmbedded && isSignsTrack) { + results.push(evaluateParsedCandidate(baseMeta, null)); + continue; + } + + if (isEmbedded && preExtracted && typeof track['ff-index'] === 'number') { + const preParsed = preExtracted.get(track['ff-index']); + if (preParsed) { + results.push(evaluateParsedCandidate(baseMeta, preParsed)); + continue; + } + } + + let extraction: FileExtractionResult | null = null; + try { + if (isEmbedded && (!ffmpegAvailable || !codecToExtension(track.codec))) { + results.push(evaluateParsedCandidate(baseMeta, null)); + continue; + } + extraction = await extractSubtitleTrackToFile( + resolved.ffmpegPath, + context.videoPath, + track, + context.workingDirectory, + ); + const parsed = readAndParseSubtitleFile(extraction.path); + results.push(evaluateParsedCandidate(baseMeta, parsed)); + } catch { + results.push(evaluateParsedCandidate(baseMeta, null)); + } finally { + cleanupTemporaryFile(extraction); + } + } + + // 2. Discover unloaded sidecar subtitle files beside the local video. + if (!isRemoteMediaPath(context.videoPath) && fileExists(context.videoPath)) { + const sidecars = discoverSidecarReferenceFiles(context.videoPath, loadedPaths); + for (const sidecar of sidecars) { + const baseMeta = { + key: `file:${sidecar.path}`, + kind: 'sidecar' as const, + trackId: null, + filePath: sidecar.path, + label: `Sidecar - ${sidecar.filename}`, + isSecondary: false, + isEmbedded: false, + isEnglish: isEnglishReferenceMeta({ + lang: sidecar.languageHint, + filename: sidecar.filename, + }), + isFullDialogueHint: isFullDialogueHintMeta({ filename: sidecar.filename }), + isSignsOnly: sidecar.isSignsOnly, + }; + try { + const parsed = readAndParseSubtitleFile(sidecar.path); + results.push(evaluateParsedCandidate(baseMeta, parsed)); + } catch { + // Ignore unreadable sidecars. + } + } + } + + const rankedEvaluated = rankReferenceCandidates(results.map((r) => r.evaluated)); + const byKey = new Map(results.map((r) => [r.evaluated.key, r])); + return rankedEvaluated.map((ev) => byKey.get(ev.key)!); +} + +function buildManualPayload( + context: SubsyncContext, + resolved: SubsyncResolvedConfig, + deps: SubsyncCoreDeps, + options: { + evaluatedCandidates?: CandidateWithSpans[]; + audioSpeechAvailable?: boolean; + guidanceMessage?: string | null; + defaultEngine?: SubsyncEngine; + defaultReferenceKey?: string | null; + } = {}, +): SubsyncManualPayload { + const subtitleTracks = context.subtitleTracks + .filter((track) => typeof track.id === 'number') + .map((track) => ({ + id: track.id as number, + label: formatTrackLabel(track), + })); + const primaryTrackId = + typeof context.primaryTrack.id === 'number' ? context.primaryTrack.id : null; + const secondaryTrackId = + typeof context.secondaryTrack?.id === 'number' ? context.secondaryTrack.id : null; + + const isLocalMedia = !isRemoteMediaPath(context.videoPath); + const ffmpegAvailable = isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg']); + const alassAvailable = isExecutableAvailable(resolved.alassPath, ['alass', 'alass-cli']); + const ffsubsyncAvailable = + isLocalMedia && isExecutableAvailable(resolved.ffsubsyncPath, ['ffsubsync']); + const audioReferenceAvailable = options.audioSpeechAvailable ?? (isLocalMedia && ffmpegAvailable); + + const referenceCandidates: SubsyncReferenceCandidate[] = []; + if (options.evaluatedCandidates && options.evaluatedCandidates.length > 0) { + for (const [idx, item] of options.evaluatedCandidates.entries()) { + const ev = item.evaluated; + referenceCandidates.push({ + key: ev.key, + kind: ev.kind === 'sidecar' ? 'file' : 'track', + label: ev.label, + detail: formatReferenceCandidateDetail(ev) || undefined, + trackId: ev.trackId, + filePath: ev.filePath, + audioStatus: ev.audioStatus, + audioOffsetMs: ev.audioOffsetMs, + isSignsOnly: ev.isSignsOnly, + recommended: idx === 0 && ev.audioStatus === 'aligned' && !ev.isSignsOnly, + }); + } + } else { + for (const track of context.subtitleTracks) { + if (typeof track.id !== 'number' || track.id === primaryTrackId) continue; + const isSecondary = secondaryTrackId !== null && track.id === secondaryTrackId; + referenceCandidates.push({ + key: `track:${track.id}`, + kind: 'track', + label: buildTrackReferenceLabel(track, isSecondary), + trackId: track.id, + filePath: null, + isSignsOnly: isSignsOrSongsTrackMeta(track), + }); + } + } + + if (isLocalMedia) { + const audioRecommended = + !referenceCandidates.some((c) => c.recommended) && audioReferenceAvailable; + referenceCandidates.push({ + key: 'video', + kind: 'video', + label: 'Video audio (built-in speech detection)', + detail: audioReferenceAvailable ? 'no reference subtitle needed' : 'requires ffmpeg', + recommended: audioRecommended, + }); + } + + const defaultReferenceTrackId = + subtitleTracks.find((track) => track.id === secondaryTrackId)?.id ?? + subtitleTracks.find((track) => track.id !== primaryTrackId)?.id ?? + null; + + const recommendedKey = + options.defaultReferenceKey ?? + referenceCandidates.find((c) => c.recommended)?.key ?? + (defaultReferenceTrackId !== null ? `track:${defaultReferenceTrackId}` : null) ?? + referenceCandidates[0]?.key ?? + null; + + return { + subtitleTracks, + defaultReferenceTrackId, + defaultTargetTrackId: primaryTrackId, + videoReferenceAvailable: isLocalMedia, + ffsubsyncAvailable, + guidanceMessage: options.guidanceMessage ?? null, + referenceCandidates, + defaultReferenceKey: recommendedKey, + defaultEngine: options.defaultEngine ?? 'builtin', + builtinAvailable: true, + alassAvailable, + audioReferenceAvailable, + canPickReferenceFile: deps.canPickReferenceFile?.() ?? false, + }; +} + +async function runBuiltinSubsync( + request: SubsyncManualRunRequest, + targetTrack: MpvTrack, + targetSlot: SubtitleSlot, + context: SubsyncContext, + resolved: SubsyncResolvedConfig, + client: MpvClientLike, + deps: SubsyncCoreDeps, +): Promise { + const stripSigns = request.stripSigns !== false; + const allowSplits = request.allowSplits !== false; + + const targetExtraction = await extractSubtitleTrackToFile( + resolved.ffmpegPath, + context.videoPath, + targetTrack, + context.workingDirectory, + ); + const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; + const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); + + let refExtraction: FileExtractionResult | null = null; + let keepTempTarget = false; + try { + const parsedTarget = readAndParseSubtitleFile(targetExtraction.path); + if (parsedTarget.events.length === 0) { + return { ok: false, message: 'Target subtitle file has no readable dialogue cues.' }; + } + if (replaceTarget && parsedTarget.lossless === false) { + return { ok: false, message: LOSSY_REPLACE_ERROR_MESSAGE }; + } + + let referenceSpans: SubtitleTimeSpan[] = []; + let referenceLabel = 'reference'; + let calibration: 'clean' | 'noisy' = 'clean'; + let leadSec = 0; + let lengthSec = context.durationSec ?? 0; + + if (request.referenceMode === 'video') { + if (isRemoteMediaPath(context.videoPath)) { + return { + ok: false, + message: + 'Built-in audio sync cannot read remote stream URLs directly. Pick a reference subtitle track or browse a local subtitle file.', + }; + } + const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); + const vadPaths = deps.getVadPaths?.(); + const audioSpeech = await extractAudioSpeechSpans({ + ffmpegPath, + videoPath: context.videoPath, + audioStreamIndex: context.audioStreamIndex, + vadExecutablePath: vadPaths?.vadExecutablePath ?? null, + vadModelPath: vadPaths?.vadModelPath ?? null, + }); + if (audioSpeech.spans.length === 0) { + return { + ok: false, + message: 'No spoken dialogue was detected in the video audio.', + }; + } + referenceSpans = audioSpeech.spans; + referenceLabel = audioSpeech.source === 'silero-vad' ? 'audio (Silero VAD)' : 'video audio'; + calibration = audioSpeech.calibration; + 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 parsedRef = readAndParseSubtitleFile(refPath); + referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans; + referenceLabel = path.basename(refPath); + } else { + const referenceTrack = getTrackById(context.subtitleTracks, request.referenceTrackId ?? null); + if (!referenceTrack) { + return { ok: false, message: 'Select a reference subtitle track.' }; + } + if (referenceTrack.id === targetTrack.id) { + return { + ok: false, + message: 'Reference and out-of-sync subtitles must be different tracks', + }; + } + const ffmpegPath = referenceTrack.external + ? resolved.ffmpegPath + : ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); + refExtraction = await extractSubtitleTrackToFile( + ffmpegPath, + context.videoPath, + referenceTrack, + context.workingDirectory, + ); + const parsedRef = readAndParseSubtitleFile(refExtraction.path); + referenceSpans = extractSpansFromParsedSubtitle(parsedRef, { stripSigns }).spans; + referenceLabel = buildTrackReferenceLabel( + referenceTrack, + context.secondaryTrack?.id === referenceTrack.id, + ); + } + + if (referenceSpans.length === 0) { + return { ok: false, message: 'Selected reference has no usable dialogue timestamps.' }; + } + + const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, referenceSpans, { + stripSigns, + allowSplits, + calibration, + leadSec, + lengthSec, + }); + + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { + return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; + } + + writeRetimedContent(outputPath, alignment.rewrittenContent); + if (targetExtraction.temporary) { + keepTempTarget = true; + } + await loadSyncedSubtitle(client, outputPath, targetSlot); + return { + ok: true, + message: formatAlignmentSummary(referenceLabel, alignment), + }; + } finally { + cleanupTemporaryFile(refExtraction); + if (!keepTempTarget) { + cleanupTemporaryFile(targetExtraction); + } + } +} + +async function runManualOffsetSubsync( + offsetMs: number, + targetTrack: MpvTrack, + targetSlot: SubtitleSlot, + context: SubsyncContext, + resolved: SubsyncResolvedConfig, + client: MpvClientLike, +): Promise { + const targetExtraction = await extractSubtitleTrackToFile( + resolved.ffmpegPath, + context.videoPath, + targetTrack, + context.workingDirectory, + ); + const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; + const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); + + let keepTempTarget = false; + try { + const parsedTarget = readAndParseSubtitleFile(targetExtraction.path); + if (parsedTarget.events.length === 0) { + return { ok: false, message: 'Target subtitle file has no readable cues to shift.' }; + } + if (replaceTarget && parsedTarget.lossless === false) { + return { ok: false, message: LOSSY_REPLACE_ERROR_MESSAGE }; + } + const allIndices = parsedTarget.events.map((_, idx) => idx); + const moves = new Array(allIndices.length).fill(offsetMs / 1000); + const rewritten = applyTimingToSubtitleFile(parsedTarget, allIndices, moves, 1.0); + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { + return { ok: false, message: 'Playback changed while syncing; discarded stale result.' }; + } + writeRetimedContent(outputPath, rewritten); + if (targetExtraction.temporary) { + keepTempTarget = true; + } + await loadSyncedSubtitle(client, outputPath, targetSlot); + return { + ok: true, + message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`, + }; + } finally { + if (!keepTempTarget) { + cleanupTemporaryFile(targetExtraction); + } + } +} + async function subsyncToReference( engine: 'alass' | 'ffsubsync', referenceFilePath: string, @@ -372,6 +1111,7 @@ async function subsyncToReference( ffmpegPath, context.videoPath, targetTrack, + context.workingDirectory, ); const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); @@ -413,7 +1153,7 @@ async function subsyncToReference( function validateFfsubsyncReference(videoPath: string): void { if (isRemoteMediaPath(videoPath)) { throw new Error( - 'FFsubsync cannot reliably sync stream URLs because it needs direct reference media access. Use Alass with a secondary subtitle source or play a local file.', + 'FFsubsync cannot reliably sync stream URLs because it needs direct reference media access. Use built-in or alass sync with a subtitle track, or play a local file.', ); } } @@ -437,6 +1177,26 @@ function resolveTargetSlot(targetTrack: MpvTrack, context: SubsyncContext): Subt return 'primary'; } +function maybeWriteCleanedReferenceSrt( + sourcePath: string, + stripSigns: boolean, +): FileExtractionResult | null { + if (!stripSigns) return null; + try { + const parsed = readAndParseSubtitleFile(sourcePath); + const extracted = extractSpansFromParsedSubtitle(parsed, { stripSigns: true }); + if (extracted.signCount === 0 || extracted.dialogueCount < MIN_REFERENCE_DIALOGUE_LINES) { + return null; + } + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-cleanref-')); + const cleanPath = path.join(tempDir, 'clean_ref.srt'); + fs.writeFileSync(cleanPath, formatSpansAsSrt(extracted.spans), 'utf8'); + return { path: cleanPath, temporary: true }; + } catch { + return null; + } +} + export async function runSubsyncManual( request: SubsyncManualRunRequest, deps: SubsyncCoreDeps, @@ -451,6 +1211,18 @@ export async function runSubsyncManual( } const targetSlot = resolveTargetSlot(targetTrack, context); + if (request.engine === 'offset') { + const offsetMs = request.offsetMs ?? 0; + if (!Number.isFinite(offsetMs) || offsetMs === 0) { + return { ok: false, message: 'Enter a non-zero offset in milliseconds' }; + } + return runManualOffsetSubsync(offsetMs, targetTrack, targetSlot, context, resolved, client); + } + + if (request.engine === 'builtin') { + return runBuiltinSubsync(request, targetTrack, targetSlot, context, resolved, client, deps); + } + if (request.engine === 'ffsubsync') { try { validateFfsubsyncReference(context.videoPath); @@ -490,6 +1262,27 @@ 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 cleaned = maybeWriteCleanedReferenceSrt(refPath, request.stripSigns !== false); + try { + return await subsyncToReference( + 'alass', + cleaned ? cleaned.path : refPath, + targetTrack, + context, + resolved, + client, + targetSlot, + ); + } finally { + cleanupTemporaryFile(cleaned); + } + } + const referenceTrack = getTrackById(context.subtitleTracks, request.referenceTrackId ?? null); if (!referenceTrack) { return { ok: false, message: 'Select a reference subtitle track for alass' }; @@ -500,15 +1293,21 @@ export async function runSubsyncManual( const ffmpegPath = ensureExecutablePath(resolved.ffmpegPath, 'ffmpeg'); let referenceExtraction: FileExtractionResult | null = null; + let cleanedRef: FileExtractionResult | null = null; try { referenceExtraction = await extractSubtitleTrackToFile( ffmpegPath, context.videoPath, referenceTrack, + context.workingDirectory, + ); + cleanedRef = maybeWriteCleanedReferenceSrt( + referenceExtraction.path, + request.stripSigns === true, ); return await subsyncToReference( 'alass', - referenceExtraction.path, + cleanedRef ? cleanedRef.path : referenceExtraction.path, targetTrack, context, resolved, @@ -516,49 +1315,419 @@ export async function runSubsyncManual( targetSlot, ); } finally { - if (referenceExtraction) { - cleanupTemporaryFile(referenceExtraction); - } + cleanupTemporaryFile(cleanedRef); + cleanupTemporaryFile(referenceExtraction); } } -export async function openSubsyncManualPicker(deps: TriggerSubsyncFromConfigDeps): Promise { +async function prepareRipCandidatesAndAudio( + context: SubsyncContext, + targetTrack: MpvTrack, + resolved: SubsyncResolvedConfig, + deps: SubsyncCoreDeps, + options: { allowSampledAudioFastPath: boolean }, +): Promise<{ + audioSpeech: AudioSpeechResult | null; + sampledAudioWindows: SampledAudioWindow[] | null; + preExtractedEmbedded: Map | null; +}> { + const isLocal = !isRemoteMediaPath(context.videoPath) && fileExists(context.videoPath); + const ffmpegAvailable = isLocal && isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg']); + if (!ffmpegAvailable) { + return { audioSpeech: null, sampledAudioWindows: null, preExtractedEmbedded: null }; + } + + const embeddedSpecs = collectExtractableEmbeddedRefTracks(context, targetTrack); + const vadPaths = deps.getVadPaths?.(); + + // Single-pass demux when 1+ non-signs embedded tracks exist: reads the MKV ONCE + // for all embedded subtitle tracks + full audio simultaneously. + if (embeddedSpecs.length > 0) { + const rip = await extractSinglePassRipMedia({ + ffmpegPath: resolved.ffmpegPath, + videoPath: context.videoPath, + audioStreamIndex: context.audioStreamIndex, + vadExecutablePath: vadPaths?.vadExecutablePath ?? null, + vadModelPath: vadPaths?.vadModelPath ?? null, + embeddedTracks: embeddedSpecs, + includeAudio: true, + }); + if (rip) { + return { + audioSpeech: rip.audioSpeech, + sampledAudioWindows: null, + preExtractedEmbedded: rip.embeddedSubtitles, + }; + } + // Single-pass failed (e.g. a broken track in container): fall back cleanly. + const audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps); + return { audioSpeech, sampledAudioWindows: null, preExtractedEmbedded: null }; + } + + // External-only reference fast path: reuse cached full audio if already available, + // otherwise sample 4 seeked 60s windows (~0.2-0.5s) to verify external subtitle + // references before ever decoding the full video audio. + const cachedFull = getCachedAudioSpeechSpans(context.videoPath, context.audioStreamIndex); + if (cachedFull) { + return { audioSpeech: cachedFull, sampledAudioWindows: null, preExtractedEmbedded: null }; + } + + const hasExternalOrSidecarHint = + context.subtitleTracks.some( + (t) => typeof t.id === 'number' && t.id !== targetTrack.id && t.external, + ) || discoverSidecarReferenceFiles(context.videoPath, []).length > 0; + + if ( + options.allowSampledAudioFastPath && + hasExternalOrSidecarHint && + context.durationSec !== null && + context.durationSec !== undefined && + context.durationSec >= 300 + ) { + const sampled = await extractSampledAudioWindows({ + ffmpegPath: resolved.ffmpegPath, + videoPath: context.videoPath, + audioStreamIndex: context.audioStreamIndex, + durationSec: context.durationSec, + }); + if (sampled && sampled.length >= 2) { + return { audioSpeech: null, sampledAudioWindows: sampled, preExtractedEmbedded: null }; + } + } + + const audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps); + return { audioSpeech, sampledAudioWindows: null, preExtractedEmbedded: null }; +} + +export async function openSubsyncManualPicker( + deps: TriggerSubsyncFromConfigDeps, + options: { + guidanceMessage?: string | null; + skipAudioAnalysis?: boolean; + } = {}, +): Promise { const client = getMpvClientForSubsync(deps); const context = await gatherSubsyncContext(client); - const subtitleTracks = context.subtitleTracks - .filter((track) => typeof track.id === 'number') - .map((track) => ({ - id: track.id as number, - label: formatTrackLabel(track), - })); - const primaryTrackId = - typeof context.primaryTrack.id === 'number' ? context.primaryTrack.id : null; - const secondaryTrackId = - typeof context.secondaryTrack?.id === 'number' ? context.secondaryTrack.id : null; - const payload: SubsyncManualPayload = { - subtitleTracks, - // The secondary track can be filtered or deduped out of the emitted list, - // so only default to it when the picker actually offers it. - defaultReferenceTrackId: - subtitleTracks.find((track) => track.id === secondaryTrackId)?.id ?? - subtitleTracks.find((track) => track.id !== primaryTrackId)?.id ?? - null, - defaultTargetTrackId: primaryTrackId, - videoReferenceAvailable: !isRemoteMediaPath(context.videoPath), - ffsubsyncAvailable: !isRemoteMediaPath(context.videoPath), - }; + const resolved = deps.getResolvedConfig(); + + let evaluatedCandidates: CandidateWithSpans[] | undefined; + let audioSpeechAvailable: boolean | undefined; + + if (!options.skipAudioAnalysis) { + const prepared = await prepareRipCandidatesAndAudio( + context, + context.primaryTrack, + resolved, + deps, + { + allowSampledAudioFastPath: true, + }, + ); + audioSpeechAvailable = + prepared.audioSpeech !== null || + prepared.sampledAudioWindows !== null || + (!isRemoteMediaPath(context.videoPath) && + isExecutableAvailable(resolved.ffmpegPath, ['ffmpeg'])); + evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( + context, + context.primaryTrack, + resolved, + prepared.audioSpeech, + { + sampledAudioWindows: prepared.sampledAudioWindows, + preExtractedEmbedded: prepared.preExtractedEmbedded, + }, + ); + } + + const payload = buildManualPayload(context, resolved, deps, { + evaluatedCandidates, + audioSpeechAvailable, + guidanceMessage: options.guidanceMessage ?? null, + }); deps.openManualPicker(payload); } +async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise { + const client = getMpvClientForSubsync(deps); + const context = await gatherSubsyncContext(client); + const resolved = deps.getResolvedConfig(); + + const targetTrack = context.primaryTrack; + const targetSlot = resolveTargetSlot(targetTrack, context); + + let targetExtraction: FileExtractionResult | null = null; + let keepTempTarget = false; + try { + try { + targetExtraction = await extractSubtitleTrackToFile( + resolved.ffmpegPath, + context.videoPath, + targetTrack, + context.workingDirectory, + ); + } catch (extractError) { + 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.`, + }); + deps.openManualPicker(payload); + deps.showMpvOsd('Subsync: choose engine and subtitles'); + return; + } + const parsedTarget = readAndParseSubtitleFile(targetExtraction.path); + const targetInfo = extractSpansFromParsedSubtitle(parsedTarget, { stripSigns: true }); + + if (parsedTarget.events.length === 0 || targetInfo.spans.length === 0) { + const payload = buildManualPayload(context, resolved, deps, { + guidanceMessage: + 'Could not read dialogue cues from the active subtitle track. Choose an engine or reference below.', + }); + deps.openManualPicker(payload); + deps.showMpvOsd('Subsync: choose engine and subtitles'); + return; + } + + const prepared = await prepareRipCandidatesAndAudio(context, targetTrack, resolved, deps, { + allowSampledAudioFastPath: true, + }); + let audioSpeech = prepared.audioSpeech; + let evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( + context, + targetTrack, + resolved, + audioSpeech, + { + sampledAudioWindows: prepared.sampledAudioWindows, + preExtractedEmbedded: prepared.preExtractedEmbedded, + }, + ); + + const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; + const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); + let lengthSec = context.durationSec ?? audioSpeech?.durationSec ?? 0; + + const applyAlignment = async ( + alignment: AlignmentResult, + sourceLabel: string, + ): Promise => { + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { + return; + } + if (isAlreadyInSync(alignment)) { + deps.showMpvOsd(`Subtitles are already in sync (${sourceLabel})`); + return; + } + if (replaceTarget && parsedTarget.lossless === false) { + deps.showMpvOsd(`Subsync failed: ${LOSSY_REPLACE_ERROR_MESSAGE}`); + return; + } + writeRetimedContent(outputPath, alignment.rewrittenContent); + if (targetExtraction!.temporary) { + keepTempTarget = true; + } + await loadSyncedSubtitle(client, outputPath, targetSlot); + deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment)); + }; + + // Fast path: if sampled audio already verified a clean aligned subtitle reference + // and target alignment succeeds with high confidence, finish immediately without + // reading the full video audio! + if (!audioSpeech && prepared.sampledAudioWindows) { + const fastAligned = evaluatedCandidates.filter( + (c) => + c.evaluated.audioStatus === 'aligned' && + !c.evaluated.isSignsOnly && + c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, + ); + for (const candidate of fastAligned) { + const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { + stripSigns: true, + allowSplits: true, + calibration: 'clean', + lengthSec, + confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD, + }); + if (alignment.confident) { + await applyAlignment(alignment, candidate.evaluated.label); + return; + } + } + + // Sampled verification didn't yield a confident aligned subtitle sync (e.g. all + // references were misaligned or sampled windows were inconclusive) — escalate + // to full-episode audio extraction for complete verification + audio VAD sync! + audioSpeech = await resolveAudioSpeechForContext(context, resolved, deps); + if (audioSpeech) { + lengthSec = context.durationSec ?? audioSpeech.durationSec; + evaluatedCandidates = await discoverAndEvaluateSubtitleCandidates( + context, + targetTrack, + resolved, + audioSpeech, + { preExtractedEmbedded: prepared.preExtractedEmbedded }, + ); + } + } + + const misalignedCandidates = evaluatedCandidates.filter( + (c) => c.evaluated.audioStatus === 'misaligned' && !c.evaluated.isSignsOnly, + ); + const alignedCandidates = evaluatedCandidates.filter( + (c) => + c.evaluated.audioStatus === 'aligned' && + !c.evaluated.isSignsOnly && + c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, + ); + const unverifiedDialogueCandidates = evaluatedCandidates.filter( + (c) => + c.evaluated.audioStatus === 'unverified' && + !c.evaluated.isSignsOnly && + c.dialogueSpans.length >= MIN_REFERENCE_DIALOGUE_LINES, + ); + + let bestAttempt: { + alignment: AlignmentResult; + sourceLabel: string; + referenceKey: string; + } | null = null; + + // 1. Best path: an audio-verified aligned dialogue subtitle reference (loaded or unloaded!). + for (const candidate of alignedCandidates) { + const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { + stripSigns: true, + allowSplits: true, + calibration: 'clean', + lengthSec, + confidenceThreshold: AUTO_SUBTITLE_CONFIDENCE_THRESHOLD, + }); + if (alignment.confident) { + await applyAlignment(alignment, candidate.evaluated.label); + return; + } + if (!bestAttempt || alignment.confidence > bestAttempt.alignment.confidence) { + bestAttempt = { + alignment, + sourceLabel: candidate.evaluated.label, + referenceKey: candidate.evaluated.key, + }; + } + } + + // 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) { + const audioAlignment = alignSubtitleFileToReferenceSpans(parsedTarget, audioSpeech.spans, { + stripSigns: true, + allowSplits: true, + calibration: audioSpeech.calibration, + leadSec: AUDIO_SPEECH_LEAD_SEC, + lengthSec, + confidenceThreshold: AUTO_AUDIO_CONFIDENCE_THRESHOLD, + }); + const audioLabel = audioSpeech.source === 'silero-vad' ? 'audio (Silero VAD)' : 'video audio'; + if (audioAlignment.confident) { + await applyAlignment(audioAlignment, audioLabel); + return; + } + if (!bestAttempt || audioAlignment.confidence > bestAttempt.alignment.confidence) { + bestAttempt = { + alignment: audioAlignment, + sourceLabel: audioLabel, + referenceKey: 'video', + }; + } + } + + // 3. When audio verification wasn't available (e.g. remote stream or no ffmpeg): + // try the highest-ranked clean dialogue subtitle track with a stricter confidence bar. + if (!audioSpeech) { + for (const candidate of unverifiedDialogueCandidates) { + const alignment = alignSubtitleFileToReferenceSpans(parsedTarget, candidate.dialogueSpans, { + stripSigns: true, + allowSplits: true, + calibration: 'clean', + lengthSec, + confidenceThreshold: AUTO_REMOTE_CONFIDENCE_THRESHOLD, + }); + if (alignment.confident) { + await applyAlignment(alignment, candidate.evaluated.label); + return; + } + if (!bestAttempt || alignment.confidence > bestAttempt.alignment.confidence) { + bestAttempt = { + alignment, + sourceLabel: candidate.evaluated.label, + referenceKey: candidate.evaluated.key, + }; + } + } + } + + // 4. Automatic sync could not finish with high confidence -> open guided modal with explanation! + const reasons: string[] = []; + if (misalignedCandidates.length > 0 && alignedCandidates.length === 0) { + const sample = misalignedCandidates[0]!.evaluated; + const shiftStr = + sample.audioOffsetMs !== null ? formatOffsetSummary(sample.audioOffsetMs) : ''; + reasons.push( + `Reference subtitle "${sample.label}" appears misaligned with the audio${shiftStr ? ` (${shiftStr})` : ''}.`, + ); + } else if ( + evaluatedCandidates.length > 0 && + alignedCandidates.length === 0 && + unverifiedDialogueCandidates.length === 0 + ) { + reasons.push( + 'Available subtitle tracks look like signs/songs or have too few dialogue lines.', + ); + } else if (evaluatedCandidates.length === 0 && !audioSpeech) { + reasons.push('No reference subtitle track or local audio source was available.'); + } + + if (bestAttempt) { + const pct = Math.round(bestAttempt.alignment.confidence * 100); + reasons.push( + `Best automatic match (${bestAttempt.sourceLabel}) had low confidence (${pct}%).`, + ); + } + reasons.push('Pick a reference, browse a subtitle file, or adjust sync options below.'); + + if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) { + return; + } + + const payload = buildManualPayload(context, resolved, deps, { + evaluatedCandidates, + audioSpeechAvailable: audioSpeech !== null, + guidanceMessage: reasons.join(' '), + defaultEngine: 'builtin', + defaultReferenceKey: bestAttempt?.referenceKey ?? null, + }); + deps.openManualPicker(payload); + deps.showMpvOsd('Subsync needs guidance — opened options'); + } finally { + if (!keepTempTarget) { + cleanupTemporaryFile(targetExtraction); + } + } +} + export async function triggerSubsyncFromConfig(deps: TriggerSubsyncFromConfigDeps): Promise { if (deps.isSubsyncInProgress()) { deps.showMpvOsd('Subsync already running'); return; } + deps.setSubsyncInProgress(true); try { - await openSubsyncManualPicker(deps); - deps.showMpvOsd('Subsync: choose engine and subtitles'); + const resolved = deps.getResolvedConfig(); + if (resolved.mode === 'manual') { + await openSubsyncManualPicker(deps, { skipAudioAnalysis: true }); + deps.showMpvOsd('Subsync: choose engine and subtitles'); + return; + } + + await deps.runWithSubsyncSpinner(() => runAutoSubsync(deps)); } catch (error) { deps.showMpvOsd(`Subsync failed: ${(error as Error).message}`); } finally { diff --git a/src/main.ts b/src/main.ts index a629af0f..b70ef950 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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 ( diff --git a/src/main/dependencies.ts b/src/main/dependencies.ts index 29117915..1081d233 100644 --- a/src/main/dependencies.ts +++ b/src/main/dependencies.ts @@ -16,6 +16,8 @@ export interface RuntimeOptionsIpcDepsParams { export interface SubsyncRuntimeDepsParams { getMpvClient: () => ReturnType; 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, diff --git a/src/main/runtime/subsync-runtime.ts b/src/main/runtime/subsync-runtime.ts index 88573038..6ac03bdb 100644 --- a/src/main/runtime/subsync-runtime.ts +++ b/src/main/runtime/subsync-runtime.ts @@ -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; + openManualPicker: () => Promise; runManualFromIpc: (request: SubsyncManualRunRequest) => Promise; } { + 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 => { await triggerSubsyncFromConfigRuntime(getRuntimeServiceParams()); }, + openManualPicker: async (): Promise => { + await openSubsyncManualPickerRuntime(getRuntimeServiceParams()); + }, runManualFromIpc: async (request: SubsyncManualRunRequest): Promise => runSubsyncManualFromIpcRuntime(request, getRuntimeServiceParams()), }; diff --git a/src/main/subsync-runtime.ts b/src/main/subsync-runtime.ts index eb274fb5..97e3d497 100644 --- a/src/main/subsync-runtime.ts +++ b/src/main/subsync-runtime.ts @@ -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 { + return openSubsyncManualPickerRuntimeCore(createSubsyncRuntimeServiceDeps(params)); +} + export async function runSubsyncManualFromIpcRuntime( request: SubsyncManualRunRequest, params: SubsyncRuntimeServiceInput, diff --git a/src/preload.ts b/src/preload.ts index 9ddde2af..351ace05 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -428,6 +428,10 @@ const electronAPI: ElectronAPI = { onSubsyncManualOpen: onSubsyncManualOpenEvent, runSubsyncManual: (request: SubsyncManualRunRequest): Promise => ipcRenderer.invoke(IPC_CHANNELS.request.runSubsyncManual, request), + openSubsyncManual: (): Promise => + ipcRenderer.invoke(IPC_CHANNELS.request.openSubsyncManual), + pickSubsyncReferenceFile: (): Promise => + ipcRenderer.invoke(IPC_CHANNELS.request.pickSubsyncReferenceFile), onKikuFieldGroupingRequest: onKikuFieldGroupingRequestEvent, onKikuFieldGroupingCancel: onKikuFieldGroupingCancelEvent, diff --git a/src/renderer/index.html b/src/renderer/index.html index bff9553e..ad74b4bc 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -868,26 +868,60 @@