Compare commits

..
89 changed files with 9954 additions and 297 deletions

No files matched your search

+7 -1
View File
@@ -66,7 +66,13 @@ jobs:
- name: Install mpv and ffmpeg (Windows) - name: Install mpv and ffmpeg (Windows)
if: runner.os == 'Windows' if: runner.os == 'Windows'
run: | run: |
choco install mpv ffmpeg -y --no-progress # community.chocolatey.org has short 503/504 outages, so retry before failing the job.
for attempt in 1 2 3 4; do
choco install mpv ffmpeg -y --no-progress && break
if [ "$attempt" -eq 4 ]; then exit 1; fi
echo "choco install failed (attempt $attempt), retrying in $((attempt * 30))s"
sleep $((attempt * 30))
done
# The mpv package adds no shim, so put its directory on PATH for later steps. # The mpv package adds no shim, so put its directory on PATH for later steps.
mpv_exe="$(find /c/ProgramData/chocolatey/lib /c/ProgramData/chocolatey/bin "/c/Program Files" /c/tools -maxdepth 6 -iname mpv.exe 2>/dev/null | head -n 1)" mpv_exe="$(find /c/ProgramData/chocolatey/lib /c/ProgramData/chocolatey/bin "/c/Program Files" /c/tools -maxdepth 6 -iname mpv.exe 2>/dev/null | head -n 1)"
test -n "$mpv_exe" test -n "$mpv_exe"
+4 -4
View File
@@ -95,8 +95,8 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi
<td>Automatic intro detection with chapter markers and a one-key skip (<code>TAB</code> by default)</td> <td>Automatic intro detection with chapter markers and a one-key skip (<code>TAB</code> by default)</td>
</tr> </tr>
<tr> <tr>
<td><b>alass / ffsubsync</b></td> <td><b>Subtitle sync</b></td>
<td>Retime a subtitle against the audio or another subtitle track (<code>Ctrl+Alt+S</code>). Requires <code>alass</code> or <code>ffsubsync</code>; set <code>subsync.alass_path</code> or <code>subsync.ffsubsync_path</code> if they are not in <code>/usr/bin</code></td> <td>One-click built-in alass-based syncing (<code>Ctrl+Alt+S</code> or the subtitle sidebar <b>Sync</b> 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; <code>ffmpeg</code> enables embedded-track extraction and audio sync/verification, and external <code>alass</code> or <code>ffsubsync</code> are optional</td>
</tr> </tr>
<tr> <tr>
<td><b>WebSocket</b></td> <td><b>WebSocket</b></td>
@@ -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 | | mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage | | fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup | | Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
| ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) | | 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 | | 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 | | xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
| yt-dlp | Optional | YouTube playback | | yt-dlp | Optional | YouTube playback |
| xz | Optional | TsukiHime subtitle downloads (most Linux distros already have it) | | xz | Optional | TsukiHime subtitle downloads (most Linux distros already have it) |
| alass / ffsubsync | Optional | Subtitle sync | | 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) | | whisper.cpp | Optional | [Subtitle generation](https://docs.subminer.moe/subtitle-generation) |
| guessit | Optional | Better title, season, and episode detection for AniSkip and AniList | | 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) | | fzf / rofi | Optional | Video picker in the `subminer` launcher (rofi is Linux only) |
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: anki
- Fixed mined cards occasionally being dropped with an "Anki update already in progress" notification. The background AnkiConnect check for new cards no longer blocks mining while it waits on Anki.
+5
View File
@@ -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.
+6
View File
@@ -0,0 +1,6 @@
type: added
area: jellyfin
- Jellyfin playback now adds the episodes around the playing one to mpv's playlist, so mpv's playlist keys and end-of-file advance move through the series (across seasons) in the same session, with resume, progress reporting, stats, and subtitles handled per episode.
- New `jellyfin.episodePlaylist.enabled` (on by default) and `jellyfin.episodePlaylist.maxEpisodes` settings, under Settings > Integrations > Jellyfin > Episode Playlist.
- mpv's playlist lists the queued episodes by title instead of stream URLs that carry the API key. Before mpv 0.42 this needs the SubMiner mpv plugin.
@@ -0,0 +1,4 @@
type: fixed
area: jellyfin
- Starting Jellyfin playback while another file was playing could drop the new item's playback tracking, so Jellyfin never received its progress or stop reports. mpv's unload of the previous file no longer cancels the new playback.
+6 -1
View File
@@ -730,6 +730,7 @@
// Hot-reload: subsync changes apply to the next subtitle sync run. // Hot-reload: subsync changes apply to the next subtitle sync run.
// ========================================== // ==========================================
"subsync": { "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. "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. "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. "ffmpeg_path": "", // Optional absolute path to the ffmpeg binary used by subsync. Leave empty to auto-discover from PATH.
@@ -1111,7 +1112,11 @@
"mp3", "mp3",
"aac" "aac"
], // Container allowlist for direct play decisions. ], // Container allowlist for direct play decisions.
"transcodeVideoCodec": "h264" // Preferred transcode video codec when direct play is unavailable. "transcodeVideoCodec": "h264", // Preferred transcode video codec when direct play is unavailable.
"episodePlaylist": {
"enabled": true, // Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes. Values: true | false
"maxEpisodes": 5 // Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).
} // Episode playlist setting.
}, // Optional Jellyfin integration for auth, browsing, and playback launch. }, // Optional Jellyfin integration for auth, browsing, and playback launch.
// ========================================== // ==========================================
+11 -8
View File
@@ -521,17 +521,18 @@ Transcribes Japanese subtitles locally with whisper.cpp. Open it with `Ctrl+Shif
### Subtitle sync ### 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.
Optional external [`alass`](https://github.com/kaegi/alass) and [`ffsubsync`](https://github.com/smacke/ffsubsync) binaries are also supported in the guided modal when installed.
| Key | Default | What it does | | Key | Default | What it does |
| ------------------------ | ------- | ------------------------------------------------------------------- | | ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `subsync.alass_path` | `""` | `alass` path. Empty uses `/usr/bin/alass` | | `subsync.mode` | `"auto"` | `"auto"` syncs immediately and opens the guided modal only when needed; `"manual"` always opens the modal |
| `subsync.ffsubsync_path` | `""` | `ffsubsync` path. Empty uses `/usr/bin/ffsubsync` | | `subsync.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` |
| `subsync.ffmpeg_path` | `""` | `ffmpeg` path. Empty uses `/usr/bin/ffmpeg` | | `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` |
| `subsync.ffmpeg_path` | `""` | `ffmpeg` path used to extract embedded tracks and audio speech. Empty auto-discovers from `PATH` |
| `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `<name>_retimed.<ext>` | | `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `<name>_retimed.<ext>` |
If a tool lives somewhere else, such as on macOS or Windows, set its path.
### AniList ### AniList
Updates your AniList watch progress after an episode, and controls the character dictionary. With `enabled` on and no token, SubMiner opens a login window. See [AniList integration](/anilist-integration) and [Character dictionary](/character-dictionary). Updates your AniList watch progress after an episode, and controls the character dictionary. With `enabled` on and no token, SubMiner opens a login window. See [AniList integration](/anilist-integration) and [Character dictionary](/character-dictionary).
@@ -560,7 +561,7 @@ In external-profile mode, SubMiner only reads the profile. It does not open its
Log in to a Jellyfin server, browse libraries, and play or cast to SubMiner. Login tokens are stored encrypted, not in this file. See [Jellyfin integration](/jellyfin-integration). Log in to a Jellyfin server, browse libraries, and play or cast to SubMiner. Login tokens are stored encrypted, not in this file. See [Jellyfin integration](/jellyfin-integration).
| Key | Default | What it does | | Key | Default | What it does |
| ----------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------- | | -------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `jellyfin.enabled` | `false` | Enable Jellyfin | | `jellyfin.enabled` | `false` | Enable Jellyfin |
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` | | `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` | | `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
@@ -571,6 +572,8 @@ Log in to a Jellyfin server, browse libraries, and play or cast to SubMiner. Log
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder | | `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding | | `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding |
| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding | | `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding |
| `jellyfin.episodePlaylist.enabled` | `true` | Queue the episodes around the playing one in mpv's playlist ([episode playlist](/jellyfin-integration#episode-playlist)) |
| `jellyfin.episodePlaylist.maxEpisodes` | `5` | Most episodes in that playlist, the playing one included (3-25) |
### Discord rich presence ### Discord rich presence
+1 -1
View File
@@ -66,7 +66,7 @@ features:
src: /assets/subtitle-download.svg src: /assets/subtitle-download.svg
alt: Subtitle download icon alt: Subtitle download icon
title: Subtitle download and sync 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 link: /jimaku-integration
linkText: Jimaku integration linkText: Jimaku integration
- icon: - icon:
+2 -2
View File
@@ -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 | | mpv | Required. The player SubMiner draws over. | All |
| fuse2 | Required to run the AppImage. | Linux | | fuse2 | Required to run the AppImage. | Linux |
| ffmpeg | Recommended. Audio clips and screenshots on cards. 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 | | MeCab + mecab-ipadic | Recommended. More accurate N+1, JLPT, and frequency highlighting. | All |
| yt-dlp | YouTube playback. | All | | yt-dlp | YouTube playback. | All |
| xz | [TsukiHime](/tsukihime-integration) subtitle downloads. Most Linux distros already have it. | 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 | | 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 | | fzf, rofi | The file pickers in the `subminer` command (rofi is Linux only). | Linux, macOS |
| chafa, ffmpegthumbnailer | Thumbnail previews in the pickers. | Linux, macOS | | chafa, ffmpegthumbnailer | Thumbnail previews in the pickers. | Linux, macOS |
+11 -1
View File
@@ -27,6 +27,14 @@ If an episode has no Japanese subtitles, you can [generate them with Whisper](/s
Casting finds mpv through `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then `PATH`. On macOS it then checks `/opt/homebrew/bin/mpv`, `/usr/local/bin/mpv`, and `/Applications/mpv.app`, because an app opened from Finder, the Dock, or Spotlight does not get your shell's `PATH`. If mpv lives somewhere else, set `mpv.executablePath` to its full path (`command -v mpv` prints it). An invalid `mpv.executablePath` stops mpv from starting. Casting finds mpv through `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then `PATH`. On macOS it then checks `/opt/homebrew/bin/mpv`, `/usr/local/bin/mpv`, and `/Applications/mpv.app`, because an app opened from Finder, the Dock, or Spotlight does not get your shell's `PATH`. If mpv lives somewhere else, set `mpv.executablePath` to its full path (`command -v mpv` prints it). An invalid `mpv.executablePath` stops mpv from starting.
## Episode playlist
When you play an episode, by casting or from the terminal, SubMiner adds the episodes around it from the same series to mpv's playlist. Move between them with mpv's playlist keys (`<` and `>` by default) or your playlist UI, and mpv moves on to the next episode when one ends. The series order runs across seasons. Each switch happens in the running mpv and overlay; nothing restarts.
SubMiner waits until the first episode is playing before it looks up the others, so startup is no slower. Every episode you switch to reports progress like one you picked yourself, and resumes from the position Jellyfin had saved when it was added to the playlist. Its subtitles load the same way. The playlist lists the episodes by title. Before mpv 0.42 that needs the SubMiner mpv plugin; without it, older mpv versions show their stream URLs.
`episodePlaylist.maxEpisodes` caps how many episodes the playlist holds, centered on the playing one. Turn `episodePlaylist.enabled` off to play one episode at a time. Changes apply from the next episode switch.
## Playing from the terminal ## Playing from the terminal
The launcher can browse your libraries and play an item without a Jellyfin client: The launcher can browse your libraries and play an item without a Jellyfin client:
@@ -43,13 +51,15 @@ Sign in first. Playback resumes from Jellyfin's saved position, and watch progre
All options are under **Settings > Integrations > Jellyfin**, or `jellyfin` in `config.jsonc`. See [Configuration](/configuration#jellyfin) for the full list and defaults. All options are under **Settings > Integrations > Jellyfin**, or `jellyfin` in `config.jsonc`. See [Configuration](/configuration#jellyfin) for the full list and defaults.
| Key | What it does | | Key | What it does |
| -------------------------- | ---------------------------------------------------------------------- | | ----------------------------- | ---------------------------------------------------------------------- |
| `enabled` | Turns the integration on. Set for you when you sign in. | | `enabled` | Turns the integration on. Set for you when you sign in. |
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. | | `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
| `remoteControlEnabled` | Lets SubMiner act as a cast target. | | `remoteControlEnabled` | Lets SubMiner act as a cast target. |
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. | | `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. | | `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. | | `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. |
| `episodePlaylist.enabled` | Adds the surrounding episodes to mpv's playlist. |
| `episodePlaylist.maxEpisodes` | Most episodes in that playlist, the playing one included. |
For headless setups, `SUBMINER_JELLYFIN_ACCESS_TOKEN` and `SUBMINER_JELLYFIN_USER_ID` supply a session without the sign-in window. Treat the token store and `config.jsonc` as secrets. For headless setups, `SUBMINER_JELLYFIN_ACCESS_TOKEN` and `SUBMINER_JELLYFIN_USER_ID` supply a session without the sign-in window. Treat the token store and `config.jsonc` as secrets.
+1 -1
View File
@@ -124,7 +124,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
`log-level` sets SubMiner's log verbosity. Do not use `--debug` for this; it turns on the app's dev mode. `log-level` sets SubMiner's log verbosity. Do not use `--debug` for this; it turns on the app's dev mode.
The plugin also handles messages the SubMiner app sends it (`subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv). The plugin also handles messages the SubMiner app sends it (`subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-managed-playlist-entries`, `subminer-playlist-entry-options`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv).
## Auto-start behavior ## Auto-start behavior
+6 -1
View File
@@ -730,6 +730,7 @@
// Hot-reload: subsync changes apply to the next subtitle sync run. // Hot-reload: subsync changes apply to the next subtitle sync run.
// ========================================== // ==========================================
"subsync": { "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. "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. "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. "ffmpeg_path": "", // Optional absolute path to the ffmpeg binary used by subsync. Leave empty to auto-discover from PATH.
@@ -1111,7 +1112,11 @@
"mp3", "mp3",
"aac" "aac"
], // Container allowlist for direct play decisions. ], // Container allowlist for direct play decisions.
"transcodeVideoCodec": "h264" // Preferred transcode video codec when direct play is unavailable. "transcodeVideoCodec": "h264", // Preferred transcode video codec when direct play is unavailable.
"episodePlaylist": {
"enabled": true, // Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes. Values: true | false
"maxEpisodes": 5 // Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).
} // Episode playlist setting.
}, // Optional Jellyfin integration for auth, browsing, and playback launch. }, // Optional Jellyfin integration for auth, browsing, and playback launch.
// ========================================== // ==========================================
+1 -1
View File
@@ -81,7 +81,7 @@ Built into the overlay, not configurable:
| `Ctrl+Shift+J` | Open Jimaku subtitle search | `shortcuts.openJimaku` | | `Ctrl+Shift+J` | Open Jimaku subtitle search | `shortcuts.openJimaku` |
| `Ctrl+Shift+T` | Open TsukiHime subtitle search | `shortcuts.openTsukihime` | | `Ctrl+Shift+T` | Open TsukiHime subtitle search | `shortcuts.openTsukihime` |
| `Ctrl+Shift+G` | Open Japanese subtitle generation | `shortcuts.openSubtitleGeneration` | | `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` | | `g` then `s` | Pick primary and secondary subtitles (when enabled) | `shortcuts.openSubtitleSelection` |
| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` | | `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` |
| `` ` `` | Toggle stats overlay | `stats.toggleKey` | | `` ` `` | Toggle stats overlay | `stats.toggleKey` |
+1
View File
@@ -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. 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 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`). - The current line is highlighted and kept in view as playback moves (`autoScroll`).
- Hovering the list pauses playback (`pauseVideoOnHover`). - Hovering the list pauses playback (`pauseVideoOnHover`).
- Switching media or subtitle track updates the list. - Switching media or subtitle track updates the list.
+9 -7
View File
@@ -144,18 +144,20 @@ Audio clips and screenshots need FFmpeg. Without it, cards are still created wit
## Subtitle sync (subsync) ## 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 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 or run audio-based sync/verification.
- `ffmpeg` must be installed to extract internal subtitle tracks. - Audio-based sync and `ffsubsync` require a local video file, not a remote stream URL.
- ffsubsync only works on local files, not streams. - Run the external tool by hand to see its full error output if you are using an external engine.
- Run the tool by hand to see its full error output.
## "xz binary not found" ## "xz binary not found"
+1 -1
View File
@@ -227,7 +227,7 @@ The mpv plugin accepts these script messages:
script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug
``` ```
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts. The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-managed-playlist-entries`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata. While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata.
+1
View File
@@ -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. - `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 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. - `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/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/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 `<config dir>/plugins/<id>/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:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` 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. - `src/core/services/plugins/` owns user plugins: discovery from `<config dir>/plugins/<id>/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:<id>/<name>`, CLI `--plugin-action <id>/<name>`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `<config dir>/plugin-data/<id>/` 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.
+1
View File
@@ -73,6 +73,7 @@ Read when: you need to find the owner module for a behavior or test surface
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair. - TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`, - Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
assembled by `src/main/assemblies/jellyfin.ts` assembled by `src/main/assemblies/jellyfin.ts`
The episode playlist (`jellyfin-episode-playlist.ts`) inserts the playing episode's series neighbors into mpv's playlist after the item's first time-pos, so it never delays startup. mpv starts those entries itself; `adoptQueuedEpisode` in `jellyfin-playback-launch.ts` recognizes them from mpv's `path` and switches Jellyfin reporting, stats metadata, and subtitles without a `loadfile`. It runs from the media-path handler before the immersion sync, because stats metadata must exist before the session starts. The `subminer-managed-playlist-entries` script message tells the plugin which paths the app manages, so its start-file handling skips subtitle rearm and overlay auto-start for them. Entries need a playlist title (the URL carries the API key) plus per-file options. mpv 0.42+ takes both from `loadfile` and `playlist/N/title`. Older mpv cannot write titles, so when the plugin sets `user-data/subminer/playlist-entry-options`, the app loads each entry as an in-memory m3u (`loadlist`, `#EXTINF` title), and the plugin's `on_load` hook applies the options it got through `subminer-playlist-entry-options`.
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`, - YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
`src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts` `src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts`
- User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), assembled by `src/main/assemblies/plugins.ts`; `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/` - User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), assembled by `src/main/assemblies/plugins.ts`; `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/`
+136
View File
@@ -0,0 +1,136 @@
import { once } from 'node:events';
import fs from 'node:fs';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
export type FakeJellyfinEpisode = { id: string; name: string; mediaPath: string };
export type FakeJellyfinReport = {
kind: 'playing' | 'progress' | 'stopped';
itemId: string;
positionTicks: number;
};
export type FakeJellyfin = {
url: string;
userId: string;
accessToken: string;
/** Every playback report the app sent, in arrival order. */
reports: FakeJellyfinReport[];
stop: () => Promise<void>;
};
const SERIES_ID = 'e2e-series';
const REPORT_KINDS: Record<string, FakeJellyfinReport['kind']> = {
'/Sessions/Playing': 'playing',
'/Sessions/Playing/Progress': 'progress',
'/Sessions/Playing/Stopped': 'stopped',
};
// Serves one file with Range support, since mpv probes and seeks over HTTP.
function serveFile(request: http.IncomingMessage, response: http.ServerResponse, file: string) {
const size = fs.statSync(file).size;
const range = /^bytes=(\d+)-(\d*)$/.exec(request.headers.range ?? '');
const start = range ? Number(range[1]) : 0;
const end = Math.min(range?.[2] ? Number(range[2]) : size - 1, size - 1);
response.writeHead(range ? 206 : 200, {
'content-type': 'video/x-matroska',
'accept-ranges': 'bytes',
'content-length': end - start + 1,
...(range ? { 'content-range': `bytes ${start}-${end}/${size}` } : {}),
});
fs.createReadStream(file, { start, end }).pipe(response);
}
/**
* A Jellyfin stand-in holding one series of `episodes`, in order. It answers the item, episode
* list, PlaybackInfo, and stream requests direct play needs, and records playback reports.
*/
export async function startFakeJellyfin(episodes: FakeJellyfinEpisode[]): Promise<FakeJellyfin> {
const reports: FakeJellyfinReport[] = [];
const byId = new Map(episodes.map((episode, index) => [episode.id, { episode, index }]));
const itemJson = (id: string) => {
const found = byId.get(id);
if (!found) return null;
return {
Id: id,
Name: found.episode.name,
Type: 'Episode',
SeriesName: 'E2E Show',
SeriesId: SERIES_ID,
ParentIndexNumber: 1,
IndexNumber: found.index + 1,
LocationType: 'FileSystem',
UserData: { PlaybackPositionTicks: 0 },
MediaSources: [
{
Id: id,
Container: 'mkv',
SupportsDirectStream: true,
SupportsTranscoding: false,
MediaStreams: [],
},
],
};
};
const server = http.createServer((request, response) => {
const url = new URL(request.url ?? '/', 'http://fake-jellyfin');
const json = (status: number, body: unknown) => {
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
};
const stream = /^\/Videos\/([^/]+)\/stream$/.exec(url.pathname);
if (request.method === 'GET' && stream) {
const found = byId.get(stream[1]!);
if (!found) return json(404, {});
return serveFile(request, response, found.episode.mediaPath);
}
const chunks: Buffer[] = [];
request.on('data', (chunk: Buffer) => chunks.push(chunk));
request.on('end', () => {
const reportKind = REPORT_KINDS[url.pathname];
if (request.method === 'POST' && reportKind) {
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
reports.push({
kind: reportKind,
itemId: String(body.ItemId ?? ''),
positionTicks: Number(body.PositionTicks ?? 0),
});
response.writeHead(204);
return response.end();
}
const item = /^\/Users\/[^/]+\/Items\/([^/]+)$/.exec(url.pathname);
if (request.method === 'GET' && item) {
const body = itemJson(item[1]!);
return body ? json(200, body) : json(404, {});
}
const playbackInfo = /^\/Items\/([^/]+)\/PlaybackInfo$/.exec(url.pathname);
if (request.method === 'POST' && playbackInfo) {
return json(200, { MediaSources: itemJson(playbackInfo[1]!)?.MediaSources ?? [] });
}
if (request.method === 'GET' && url.pathname === `/Shows/${SERIES_ID}/Episodes`) {
return json(200, { Items: episodes.map((episode) => itemJson(episode.id)) });
}
json(404, {});
});
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address() as AddressInfo;
return {
url: `http://127.0.0.1:${port}`,
userId: 'e2e-user',
accessToken: 'e2e-token',
reports,
stop: async () => {
server.closeAllConnections();
server.close();
await once(server, 'close');
},
};
}
+3
View File
@@ -30,6 +30,8 @@ export type E2eSessionOptions = {
config?: JsonObject; config?: JsonObject;
/** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */ /** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */
files?: Record<string, string>; files?: Record<string, string>;
/** Extra environment for every app launch, e.g. a Jellyfin session. */
env?: Record<string, string>;
}; };
export type AppTarget = { export type AppTarget = {
@@ -241,6 +243,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
SUBMINER_APP_LOG: path.join(root, 'app.log'), SUBMINER_APP_LOG: path.join(root, 'app.log'),
// Stay attached instead of re-spawning detached, so the harness owns the process. // Stay attached instead of re-spawning detached, so the harness owns the process.
SUBMINER_BACKGROUND_CHILD: '1', SUBMINER_BACKGROUND_CHILD: '1',
...options.env,
}, },
unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'], unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'],
}; };
+143
View File
@@ -0,0 +1,143 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test, { after } from 'node:test';
import { startFakeJellyfin, type FakeJellyfin } from './harness/fake-jellyfin';
import { generateFixtureClip } from './harness/fixtures';
import { startE2eSession, type E2eSession } from './harness/session';
import { waitUntil } from './harness/wait';
const TEST_TIMEOUT_MS = 180_000;
const EPISODE_IDS = ['ep1', 'ep2', 'ep3'];
let clipsDir: string | undefined;
let jellyfin: FakeJellyfin | undefined;
let session: E2eSession | undefined;
after(async () => {
await session?.dispose();
await jellyfin?.stop();
if (clipsDir) fs.rmSync(clipsDir, { recursive: true, force: true });
});
type PlaylistEntry = { filename: string; current?: boolean; title?: string };
// The episode ids in mpv's playlist, the current one marked with `*`.
async function playlistIds(mpv: E2eSession['mpv']): Promise<string[]> {
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
return playlist.map((entry) => {
const id = /\/Videos\/([^/]+)\/stream/.exec(entry.filename)?.[1] ?? entry.filename;
return entry.current ? `${id}*` : id;
});
}
// `playlist/N/title` is writable from mpv 0.42.
async function supportsPlaylistTitles(mpv: E2eSession['mpv']): Promise<boolean> {
const version = String(await mpv.command('get_property', 'mpv-version'));
const [major = 0, minor = 0] = (/v?(\d+)\.(\d+)/.exec(version) ?? []).slice(1).map(Number);
return major > 0 || minor >= 42;
}
async function mainPid(started: E2eSession): Promise<number> {
const main = await started.mainProcess();
try {
return await main.evaluate<number>('process.pid');
} finally {
main.close();
}
}
test(
'Jellyfin playback moves through queued series episodes in the same session',
{ timeout: TEST_TIMEOUT_MS },
async () => {
clipsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-e2e-jellyfin-'));
const episodes = EPISODE_IDS.map((id, index) => ({
id,
name: `Episode ${index + 1}`,
mediaPath: path.join(clipsDir!, `${id}.mkv`),
}));
await Promise.all(episodes.map((episode) => generateFixtureClip(episode.mediaPath)));
jellyfin = await startFakeJellyfin(episodes);
session = await startE2eSession({
config: {
jellyfin: {
enabled: true,
serverUrl: jellyfin.url,
remoteControlEnabled: false,
episodePlaylist: { enabled: true, maxEpisodes: 3 },
},
},
env: {
SUBMINER_JELLYFIN_ACCESS_TOKEN: jellyfin.accessToken,
SUBMINER_JELLYFIN_USER_ID: jellyfin.userId,
},
});
const { mpv } = session;
const pid = await mainPid(session);
const reports = jellyfin.reports;
const reported = (kind: string, itemId: string) =>
reports.findIndex((report) => report.kind === kind && report.itemId === itemId);
await session.runAppCommand('--jellyfin-play', '--jellyfin-item-id=ep2');
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
description: 'the episodes around ep2 queued in the mpv playlist',
timeoutMs: 30_000,
});
// The start report is fire-and-forget, so it can land after the playlist fills.
await waitUntil(() => reported('playing', 'ep2') >= 0, {
description: 'Jellyfin to hear ep2 start',
timeoutMs: 30_000,
});
// mpv's playlist lists entry titles, not stream URLs carrying the API key. Entry titles
// became writable in mpv 0.42. Older players need the SubMiner plugin's loadlist path,
// which this plugin-less mpv does not load, so they keep listing URLs here.
const titles = [
'E2E Show S01E01 Episode 1',
'E2E Show S01E02 Episode 2',
'E2E Show S01E03 Episode 3',
];
if (await supportsPlaylistTitles(mpv)) {
await waitUntil(
async () => {
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
return playlist.map((entry) => entry.title).join('|') === titles.join('|');
},
{
description: 'queued playlist entries titled like the playing episode',
timeoutMs: 10_000,
},
);
}
await mpv.command('playlist-next');
await waitUntil(() => reported('playing', 'ep3') >= 0, {
description: 'Jellyfin to hear ep3 start after playlist-next',
timeoutMs: 30_000,
});
const stoppedEp2 = reported('stopped', 'ep2');
assert.ok(stoppedEp2 >= 0, 'Jellyfin hears ep2 stop');
assert.ok(stoppedEp2 < reported('playing', 'ep3'), 'ep2 stops before ep3 starts');
assert.equal(await mpv.command('get_property', 'media-title'), 'E2E Show S01E03 Episode 3');
// At the end of the series the window shifts back so it stays full.
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2,ep3*', {
description: 'the playlist window re-centered on ep3',
timeoutMs: 30_000,
});
await mpv.command('playlist-prev');
await waitUntil(
() =>
reports.filter((report) => report.kind === 'playing' && report.itemId === 'ep2').length ===
2,
{ description: 'Jellyfin to hear ep2 start again after playlist-prev', timeoutMs: 30_000 },
);
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
description: 'the playlist window re-centered on ep2',
timeoutMs: 30_000,
});
assert.equal(await mainPid(session), pid, 'the app keeps running across episode switches');
},
);
+25 -1
View File
@@ -210,8 +210,17 @@ function M.create(ctx)
}) })
end end
local function is_app_managed_playlist_entry()
local path = mp.get_property("path")
local managed_paths = state.app_managed_playlist_paths or {}
return type(path) == "string" and managed_paths[path] == true
end
local function on_start_file() local function on_start_file()
if should_show_overlay_loading_osd() then if is_app_managed_playlist_entry() then
state.skip_managed_subtitle_rearm_once = true
state.app_managed_playback_pending = true
elseif should_show_overlay_loading_osd() then
process.start_overlay_loading_osd() process.start_overlay_loading_osd()
end end
if state.pending_reload_media_identity ~= nil then if state.pending_reload_media_identity ~= nil then
@@ -322,12 +331,27 @@ function M.create(ctx)
state.pending_reload_reason = nil state.pending_reload_reason = nil
state.app_managed_playback_pending = false state.app_managed_playback_pending = false
state.app_managed_playback_active = false state.app_managed_playback_active = false
state.app_managed_playlist_paths = {}
state.app_playlist_entry_options = {}
end
-- Applies the app's per-file options to an entry it loaded with loadlist, the way loadfile
-- options would apply.
local function apply_app_playlist_entry_options()
local path = mp.get_property("path")
local options = type(path) == "string" and state.app_playlist_entry_options[path] or nil
for _, option in ipairs(options or {}) do
mp.set_property("file-local-options/" .. option[1], option[2])
end
end end
local function register_lifecycle_hooks() local function register_lifecycle_hooks()
mp.register_event("start-file", on_start_file) mp.register_event("start-file", on_start_file)
mp.register_event("file-loaded", on_file_loaded) mp.register_event("file-loaded", on_file_loaded)
mp.register_event("shutdown", on_shutdown) mp.register_event("shutdown", on_shutdown)
mp.add_hook("on_load", 50, apply_app_playlist_entry_options)
-- Tells the app it can rely on the hook above (read as PLUGIN_ENTRY_OPTIONS_USER_DATA).
mp.set_property_native("user-data/subminer/playlist-entry-options", true)
mp.register_event("end-file", function(event) mp.register_event("end-file", function(event)
process.stop_overlay_loading_osd() process.stop_overlay_loading_osd()
process.disarm_auto_play_ready_gate() process.disarm_auto_play_ready_gate()
+28
View File
@@ -27,6 +27,34 @@ function M.create(ctx)
state.skip_managed_subtitle_rearm_once = true state.skip_managed_subtitle_rearm_once = true
state.app_managed_playback_pending = true state.app_managed_playback_pending = true
end) end)
-- Playlist entries the app queued (Jellyfin neighbor episodes). mpv starts them on its own,
-- so start-file recognizes them by path instead of waiting for subminer-managed-subtitles-loading.
mp.register_script_message("subminer-managed-playlist-entries", function(...)
local paths = {}
for _, path in ipairs({ ... }) do
paths[path] = true
end
state.app_managed_playlist_paths = paths
-- Options belong to queued entries; drop those the app no longer queues.
for path in pairs(state.app_playlist_entry_options) do
if not paths[path] then
state.app_playlist_entry_options[path] = nil
end
end
end)
-- `<path> <name> <value> ...`: options for an entry the app loads with loadlist, where mpv
-- (before 0.42) cannot take both a playlist title and per-file options.
mp.register_script_message("subminer-playlist-entry-options", function(path, ...)
if type(path) ~= "string" or path == "" then
return
end
local args = { ... }
local options = {}
for index = 1, #args - 1, 2 do
options[#options + 1] = { args[index], args[index + 1] }
end
state.app_playlist_entry_options[path] = options
end)
mp.register_script_message("subminer-menu", function() mp.register_script_message("subminer-menu", function()
ui.show_menu() ui.show_menu()
end) end)
+3
View File
@@ -34,6 +34,9 @@ function M.new()
pending_reload_reason = nil, pending_reload_reason = nil,
app_managed_playback_pending = false, app_managed_playback_pending = false,
app_managed_playback_active = false, app_managed_playback_active = false,
app_managed_playlist_paths = {},
-- path -> { { name, value }, ... }: per-file options the on_load hook applies (mpv < 0.42).
app_playlist_entry_options = {},
auto_start_retry_generation = 0, auto_start_retry_generation = 0,
session_binding_generation = 0, session_binding_generation = 0,
session_binding_names = {}, session_binding_names = {},
+106 -1
View File
@@ -6,6 +6,7 @@ local function run_plugin_scenario(config)
sync_calls = {}, sync_calls = {},
script_messages = {}, script_messages = {},
events = {}, events = {},
hooks = {},
observers = {}, observers = {},
key_bindings = {}, key_bindings = {},
osd = {}, osd = {},
@@ -185,7 +186,9 @@ local function run_plugin_scenario(config)
end end
recorded.events[name][#recorded.events[name] + 1] = fn recorded.events[name][#recorded.events[name] + 1] = fn
end end
function mp.add_hook(_name, _prio, _fn) end function mp.add_hook(name, _prio, fn)
recorded.hooks[name] = fn
end
function mp.observe_property(name, _kind, fn) function mp.observe_property(name, _kind, fn)
if recorded.observers[name] == nil then if recorded.observers[name] == nil then
recorded.observers[name] = {} recorded.observers[name] = {}
@@ -1042,6 +1045,108 @@ do
) )
end end
do
local scenario = {
process_list = "",
option_overrides = {
binary_path = binary_path,
auto_start = "yes",
auto_start_visible_overlay = "yes",
auto_start_pause_until_ready = "yes",
socket_path = "/tmp/subminer-socket",
},
input_ipc_server = "/tmp/subminer-socket",
path = "https://jellyfin.example/Videos/ep1/stream",
media_title = "Jellyfin Episode 1",
files = {
[binary_path] = true,
},
}
local recorded, err = run_plugin_scenario(scenario)
assert_true(recorded ~= nil, "plugin failed to load for managed playlist entry scenario: " .. tostring(err))
recorded.script_messages["subminer-managed-playlist-entries"](
"https://jellyfin.example/Videos/ep1/stream",
"https://jellyfin.example/Videos/ep2/stream"
)
fire_event(recorded, "end-file", { reason = "eof" })
scenario.path = "https://jellyfin.example/Videos/ep2/stream"
scenario.media_title = "Jellyfin Episode 2"
fire_event(recorded, "start-file")
fire_event(recorded, "file-loaded")
assert_true(
not has_property_set(recorded.property_sets, "sid", "auto"),
"an app-queued playlist entry should keep the app's subtitle selection"
)
assert_true(
count_start_calls(recorded.async_calls) == 0,
"an app-queued playlist entry should not auto-start the overlay"
)
assert_true(
count_property_set(recorded.property_sets, "pause", true) == 0,
"an app-queued playlist entry should not arm the plugin pause gate"
)
assert_true(
not has_osd_message(recorded.osd, "SubMiner: Overlay loading |"),
"an app-queued playlist entry should not show the overlay loading spinner"
)
fire_event(recorded, "end-file", { reason = "stop" })
scenario.path = "/media/local-episode.mkv"
scenario.media_title = "Local Episode"
fire_event(recorded, "start-file")
fire_event(recorded, "file-loaded")
assert_true(
count_property_set(recorded.property_sets, "sid", "auto") == 1,
"a path the app did not queue should get the normal subtitle rearm"
)
assert_true(
count_start_calls(recorded.async_calls) == 1,
"a path the app did not queue should auto-start the overlay"
)
end
do
local scenario = {
process_list = "",
option_overrides = {
binary_path = binary_path,
auto_start = "no",
},
path = "https://jellyfin.example/Videos/ep2/stream",
files = {
[binary_path] = true,
},
}
local recorded, err = run_plugin_scenario(scenario)
assert_true(recorded ~= nil, "plugin failed to load for playlist entry options scenario: " .. tostring(err))
assert_true(
has_property_set(recorded.property_sets, "user-data/subminer/playlist-entry-options", true),
"plugin should tell the app it applies playlist entry options"
)
recorded.script_messages["subminer-playlist-entry-options"](
"https://jellyfin.example/Videos/ep2/stream",
"start",
"12.5",
"force-media-title",
"Show S01E02, Part 1"
)
recorded.hooks["on_load"]()
assert_true(
has_property_set(recorded.property_sets, "file-local-options/start", "12.5"),
"on_load should apply the entry's start position"
)
assert_true(
has_property_set(recorded.property_sets, "file-local-options/force-media-title", "Show S01E02, Part 1"),
"on_load should apply the entry's title verbatim"
)
recorded.script_messages["subminer-managed-playlist-entries"]("https://jellyfin.example/Videos/ep3/stream")
recorded.property_sets = {}
recorded.hooks["on_load"]()
assert_true(
not has_property_set(recorded.property_sets, "file-local-options/start", "12.5"),
"options for an entry the app no longer queues should be dropped"
)
end
do do
local recorded, err = run_plugin_scenario({ local recorded, err = run_plugin_scenario({
process_list = "", process_list = "",
+87
View File
@@ -173,3 +173,90 @@ test('a failed source lookup skips plugin events without stopping counting or en
assert.deepEqual(h.ready, []); assert.deepEqual(h.ready, []);
assert.equal(h.warnings.length, 2); assert.equal(h.warnings.length, 2);
}); });
/** A runner whose `findNotes` read stays pending until `finishRead`, sharing one update lock. */
function makeSlowReadRunner() {
const state = { updating: false, processed: [] as number[], tracked: new Set<number>() };
let finishRead: (noteIds: number[]) => void = () => undefined;
const runner = new PollingRunner({
getDeck: () => 'Mining',
getPollingRate: () => 3000,
findNotes: (query) =>
query.includes('tag:')
? Promise.resolve([])
: new Promise<number[]>((resolve) => {
finishRead = resolve;
}),
shouldAutoUpdateNewCards: () => true,
processNewCard: async (noteId) => {
state.processed.push(noteId);
},
isUpdateInProgress: () => state.updating,
setUpdateInProgress: (value) => {
state.updating = value;
},
getTrackedNoteIds: () => state.tracked,
setTrackedNoteIds: (noteIds) => {
state.tracked = noteIds;
},
showStatusNotification: () => undefined,
logDebug: () => undefined,
logInfo: () => undefined,
logWarn: () => undefined,
});
return {
runner,
state,
finishRead: (noteIds: number[]) => finishRead(noteIds),
/** The first poll only records the notes already in the deck. */
initialize: async () => {
const poll = runner.pollOnce();
finishRead([10]);
await poll;
},
};
}
test('a poll waiting on Anki leaves the update lock free for mining', async () => {
const h = makeSlowReadRunner();
await h.initialize();
const poll = h.runner.pollOnce();
assert.equal(h.state.updating, false, 'mining can start while the read is pending');
h.finishRead([10, 11]);
await poll;
assert.deepEqual(h.state.processed, [11]);
assert.equal(h.state.updating, false);
});
test('a poll leaves new notes alone when mining starts during its read', async () => {
const h = makeSlowReadRunner();
await h.initialize();
const poll = h.runner.pollOnce();
// Mining takes the lock and adds note 11 while the poll's read is in flight.
h.state.updating = true;
h.finishRead([10, 11]);
await poll;
assert.deepEqual(h.state.processed, []);
assert.deepEqual([...h.state.tracked], [10]);
assert.equal(h.state.updating, true, 'the poll must not release a lock it never took');
});
test('the first poll keeps notes mined while its read was pending', async () => {
const h = makeSlowReadRunner();
const init = h.runner.pollOnce();
// Mining finishes during the initial read and tracks note 11, which the read missed.
h.state.tracked.add(11);
h.finishRead([10]);
await init;
const poll = h.runner.pollOnce();
h.finishRead([10, 11]);
await poll;
assert.deepEqual(h.state.processed, []);
});
+16 -3
View File
@@ -26,6 +26,8 @@ export interface PollingRunnerDeps {
export class PollingRunner { export class PollingRunner {
private pollingInterval: ReturnType<typeof setInterval> | null = null; private pollingInterval: ReturnType<typeof setInterval> | null = null;
// Keeps interval ticks from stacking up behind a slow read, now that reads skip the update lock.
private pollInFlight = false;
private initialized = false; private initialized = false;
private backoffMs = 200; private backoffMs = 200;
private maxBackoffMs = 5000; private maxBackoffMs = 5000;
@@ -56,19 +58,29 @@ export class PollingRunner {
} }
async pollOnce(): Promise<void> { async pollOnce(): Promise<void> {
if (this.deps.isUpdateInProgress()) return; if (this.pollInFlight || this.deps.isUpdateInProgress()) return;
if (Date.now() < this.nextPollTime) return; if (Date.now() < this.nextPollTime) return;
this.deps.setUpdateInProgress(true); this.pollInFlight = true;
let holdsUpdateLock = false;
try { try {
const query = this.deps.getDeck() ? `"deck:${this.deps.getDeck()}" added:1` : 'added:1'; const query = this.deps.getDeck() ? `"deck:${this.deps.getDeck()}" added:1` : 'added:1';
// The read runs without the update lock: mining checks that lock and gives up when it is
// held, so holding it for a routine poll would drop a card mined at the wrong moment.
const noteIds = await this.deps.findNotes(query, { const noteIds = await this.deps.findNotes(query, {
maxRetries: 0, maxRetries: 0,
}); });
// An update started during the read (its creator tracks any note it adds), so leave the
// new notes to the next poll.
if (this.deps.isUpdateInProgress()) return;
this.deps.setUpdateInProgress(true);
holdsUpdateLock = true;
const currentNoteIds = new Set(noteIds); const currentNoteIds = new Set(noteIds);
const previousNoteIds = this.deps.getTrackedNoteIds(); const previousNoteIds = this.deps.getTrackedNoteIds();
if (!this.initialized) { if (!this.initialized) {
// Keep notes mined while the read was pending; the read may have started before they existed.
for (const noteId of previousNoteIds) currentNoteIds.add(noteId);
this.deps.setTrackedNoteIds(currentNoteIds); this.deps.setTrackedNoteIds(currentNoteIds);
this.initialized = true; this.initialized = true;
this.deps.logInfo(`AnkiConnect initialized with ${currentNoteIds.size} existing cards`); this.deps.logInfo(`AnkiConnect initialized with ${currentNoteIds.size} existing cards`);
@@ -140,7 +152,8 @@ export class PollingRunner {
} }
this.deps.logWarn((error as Error).message); this.deps.logWarn((error as Error).message);
} finally { } finally {
this.deps.setUpdateInProgress(false); this.pollInFlight = false;
if (holdsUpdateLock) this.deps.setUpdateInProgress(false);
} }
} }
+1
View File
@@ -137,6 +137,7 @@ export const CORE_DEFAULT_CONFIG: Pick<
}, },
}, },
subsync: { subsync: {
mode: 'auto',
alass_path: '', alass_path: '',
ffsubsync_path: '', ffsubsync_path: '',
ffmpeg_path: '', ffmpeg_path: '',
@@ -160,6 +160,10 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
directPlayPreferred: true, directPlayPreferred: true,
directPlayContainers: ['mkv', 'mp4', 'webm', 'mov', 'flac', 'mp3', 'aac'], directPlayContainers: ['mkv', 'mp4', 'webm', 'mov', 'flac', 'mp3', 'aac'],
transcodeVideoCodec: 'h264', transcodeVideoCodec: 'h264',
episodePlaylist: {
enabled: true,
maxEpisodes: 5,
},
}, },
discordPresence: { discordPresence: {
enabled: true, enabled: true,
+8
View File
@@ -611,6 +611,14 @@ export function buildCoreConfigOptionRegistry(
defaultValue: defaultConfig.annotationWebsocket.port, defaultValue: defaultConfig.annotationWebsocket.port,
description: 'Annotated subtitle websocket server 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', path: 'subsync.replace',
kind: 'boolean', kind: 'boolean',
@@ -704,6 +704,20 @@ export function buildIntegrationConfigOptionRegistry(
defaultValue: defaultConfig.jellyfin.transcodeVideoCodec, defaultValue: defaultConfig.jellyfin.transcodeVideoCodec,
description: 'Preferred transcode video codec when direct play is unavailable.', description: 'Preferred transcode video codec when direct play is unavailable.',
}, },
{
path: 'jellyfin.episodePlaylist.enabled',
kind: 'boolean',
defaultValue: defaultConfig.jellyfin.episodePlaylist.enabled,
description:
"Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes.",
},
{
path: 'jellyfin.episodePlaylist.maxEpisodes',
kind: 'number',
defaultValue: defaultConfig.jellyfin.episodePlaylist.maxEpisodes,
description:
'Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).',
},
{ {
path: 'discordPresence.enabled', path: 'discordPresence.enabled',
kind: 'boolean', kind: 'boolean',
+8 -3
View File
@@ -62,9 +62,14 @@ export function getConfigHotReloadField(path: string): string | null {
// These consumers read the current config when the next operation starts. // These consumers read the current config when the next operation starts.
if ( if (
['jimaku', 'tmdb', 'subsync', 'notifications', 'subtitleGeneration'].some((root) => [
pathStartsWith(path, root), 'jimaku',
) 'tmdb',
'subsync',
'notifications',
'subtitleGeneration',
'jellyfin.episodePlaylist',
].some((root) => pathStartsWith(path, root))
) { ) {
return path; return path;
} }
+5
View File
@@ -397,6 +397,11 @@ export function applyCoreDomainConfig(context: ResolveContext): void {
} }
if (isObject(src.subsync)) { 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); const alass = asString(src.subsync.alass_path);
if (alass !== undefined) resolved.subsync.alass_path = alass; if (alass !== undefined) resolved.subsync.alass_path = alass;
const ffsubsync = asString(src.subsync.ffsubsync_path); const ffsubsync = asString(src.subsync.ffsubsync_path);
+43
View File
@@ -372,6 +372,49 @@ export function applyIntegrationConfig(context: ResolveContext): void {
); );
} }
if (isObject(src.jellyfin.episodePlaylist)) {
const episodePlaylist = src.jellyfin.episodePlaylist;
const playlistEnabled = asBoolean(episodePlaylist.enabled);
if (playlistEnabled !== undefined) {
resolved.jellyfin.episodePlaylist.enabled = playlistEnabled;
} else if (episodePlaylist.enabled !== undefined) {
warn(
'jellyfin.episodePlaylist.enabled',
episodePlaylist.enabled,
resolved.jellyfin.episodePlaylist.enabled,
'Expected boolean.',
);
}
const maxEpisodes = asNumber(episodePlaylist.maxEpisodes);
if (maxEpisodes !== undefined) {
const normalized = Math.min(25, Math.max(3, Math.floor(maxEpisodes)));
if (normalized !== maxEpisodes) {
warn(
'jellyfin.episodePlaylist.maxEpisodes',
episodePlaylist.maxEpisodes,
normalized,
'Out of range; clamped to 3..25.',
);
}
resolved.jellyfin.episodePlaylist.maxEpisodes = normalized;
} else if (episodePlaylist.maxEpisodes !== undefined) {
warn(
'jellyfin.episodePlaylist.maxEpisodes',
episodePlaylist.maxEpisodes,
resolved.jellyfin.episodePlaylist.maxEpisodes,
'Expected number.',
);
}
} else if (src.jellyfin.episodePlaylist !== undefined) {
warn(
'jellyfin.episodePlaylist',
src.jellyfin.episodePlaylist,
resolved.jellyfin.episodePlaylist,
'Expected object.',
);
}
if (Array.isArray(src.jellyfin.recentServers)) { if (Array.isArray(src.jellyfin.recentServers)) {
const seenRecentServers = new Set<string>(); const seenRecentServers = new Set<string>();
resolved.jellyfin.recentServers = src.jellyfin.recentServers resolved.jellyfin.recentServers = src.jellyfin.recentServers
+23
View File
@@ -165,3 +165,26 @@ test('yomitan externalProfilePath expands leading tilde to the current home dire
path.join(homeDir, '.config', 'gsm_overlay'), path.join(homeDir, '.config', 'gsm_overlay'),
); );
}); });
test('jellyfin episodePlaylist resolves the toggle and clamps the episode cap', () => {
const { context, warnings } = createResolveContext({
jellyfin: {
episodePlaylist: { enabled: false, maxEpisodes: 400 },
},
});
applyIntegrationConfig(context);
assert.deepEqual(context.resolved.jellyfin.episodePlaylist, { enabled: false, maxEpisodes: 25 });
assert.ok(warnings.some((warning) => warning.path === 'jellyfin.episodePlaylist.maxEpisodes'));
});
test('jellyfin episodePlaylist raises an episode cap below 3', () => {
const { context } = createResolveContext({
jellyfin: { episodePlaylist: { maxEpisodes: 2 } },
});
applyIntegrationConfig(context);
assert.equal(context.resolved.jellyfin.episodePlaylist.maxEpisodes, 3);
});
+4
View File
@@ -223,6 +223,7 @@ const SUBSECTION_ORDER = new Map<string, number>(
'Toggle & Visibility', 'Toggle & Visibility',
'Open Panels', 'Open Panels',
'Playback', 'Playback',
'Episode Playlist',
'Default Fold State', 'Default Fold State',
].map((subsection, index) => [subsection, index]), ].map((subsection, index) => [subsection, index]),
); );
@@ -629,6 +630,9 @@ function subsectionForPath(path: string): string | undefined {
if (path === 'mpv.aniskipButtonKey') { if (path === 'mpv.aniskipButtonKey') {
return 'Playback'; return 'Playback';
} }
if (path.startsWith('jellyfin.episodePlaylist.')) {
return 'Episode Playlist';
}
if (path.startsWith('shortcuts.')) { if (path.startsWith('shortcuts.')) {
const leaf = path.split('.').at(-1) ?? ''; const leaf = path.split('.').at(-1) ?? '';
if ( if (
@@ -2949,6 +2949,68 @@ test('Jellyfin metadata refresh preserves a manual episode assignment', async ()
} }
}); });
test('mpv media-title updates do not overwrite a Jellyfin video title', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath });
const streamUrl = 'http://jellyfin.local/Videos/item-3/stream?static=true&api_key=token';
tracker.recordJellyfinPlaybackMetadata({
mediaPath: streamUrl,
displayTitle: 'Show S01E03 Third',
itemTitle: 'Third',
seriesTitle: 'Show',
seasonNumber: 1,
episodeNumber: 3,
itemId: 'item-3',
});
tracker.handleMediaChange(streamUrl, 'Show S01E03 Third');
// mpv restores the previous episode's title as it leaves this playlist entry.
tracker.handleMediaTitleUpdate('Show S01E02 Second');
tracker.handleMediaChange(streamUrl, 'Show S01E02 Second');
const row = (tracker as unknown as { db: DatabaseSync }).db
.prepare('SELECT canonical_title AS title FROM imm_videos')
.get() as { title: string };
assert.equal(row.title, 'Show S01E03 Third');
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('a stale mpv title on the first media change keeps the Jellyfin video title', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath });
const streamUrl = 'http://jellyfin.local/Videos/item-3/stream?static=true&api_key=token';
tracker.recordJellyfinPlaybackMetadata({
mediaPath: streamUrl,
displayTitle: 'Show S01E03 Third',
itemTitle: 'Third',
seriesTitle: 'Show',
seasonNumber: 1,
episodeNumber: 3,
itemId: 'item-3',
});
// mpv switched to this entry but media-title still names the previous episode.
tracker.handleMediaChange(streamUrl, 'Show S01E02 Second');
const row = (tracker as unknown as { db: DatabaseSync }).db
.prepare('SELECT canonical_title AS title FROM imm_videos')
.get() as { title: string };
assert.equal(row.title, 'Show S01E03 Third');
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('startup repairs existing Jellyfin stream video links to metadata rows', async () => { test('startup repairs existing Jellyfin stream video links to metadata rows', async () => {
const dbPath = makeDbPath(); const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null; let tracker: ImmersionTrackerService | null = null;
+19 -1
View File
@@ -1767,6 +1767,16 @@ export class ImmersionTrackerService {
return row?.parserSource === 'jellyfin'; return row?.parserSource === 'jellyfin';
} }
/** The stored title of a Jellyfin-linked video, or null when the key has no Jellyfin row. */
private getJellyfinCanonicalTitle(videoKey: string): string | null {
const row = this.db
.prepare(
"SELECT canonical_title AS title FROM imm_videos WHERE video_key = ? AND parser_source = 'jellyfin'",
)
.get(videoKey) as { title: string | null } | null;
return row?.title || null;
}
handleMediaChange(mediaPath: string | null, mediaTitle: string | null): void { handleMediaChange(mediaPath: string | null, mediaTitle: string | null): void {
const rawPath = normalizeMediaPath(mediaPath); const rawPath = normalizeMediaPath(mediaPath);
const normalizedPath = const normalizedPath =
@@ -1797,7 +1807,12 @@ export class ImmersionTrackerService {
const sourceType = isRemoteSource(normalizedPath) ? SOURCE_TYPE_REMOTE : SOURCE_TYPE_LOCAL; const sourceType = isRemoteSource(normalizedPath) ? SOURCE_TYPE_REMOTE : SOURCE_TYPE_LOCAL;
const videoKey = buildVideoKey(normalizedPath, sourceType); const videoKey = buildVideoKey(normalizedPath, sourceType);
const canonicalTitle = normalizedTitle || deriveCanonicalTitle(normalizedPath); // Jellyfin's title is authoritative: mpv's media-title can still name the previous playlist
// entry when the path switches, and getOrCreateVideoRecord rewrites an existing row's title.
const canonicalTitle =
this.getJellyfinCanonicalTitle(videoKey) ||
normalizedTitle ||
deriveCanonicalTitle(normalizedPath);
const sourcePath = sourceType === SOURCE_TYPE_LOCAL ? normalizedPath : null; const sourcePath = sourceType === SOURCE_TYPE_LOCAL ? normalizedPath : null;
const sourceUrl = sourceType === SOURCE_TYPE_REMOTE ? normalizedPath : null; const sourceUrl = sourceType === SOURCE_TYPE_REMOTE ? normalizedPath : null;
@@ -2464,6 +2479,9 @@ export class ImmersionTrackerService {
private updateVideoTitleForActiveSession(canonicalTitle: string): void { private updateVideoTitleForActiveSession(canonicalTitle: string): void {
if (!this.sessionState) return; if (!this.sessionState) return;
// Jellyfin's title is authoritative. mpv's media-title can still name the previous playlist
// entry while it switches files, so it must not overwrite a Jellyfin video's title.
if (this.hasJellyfinMetadata(this.sessionState.videoId)) return;
updateVideoTitleRecord(this.db, this.sessionState.videoId, canonicalTitle); updateVideoTitleRecord(this.db, this.sessionState.videoId, canonicalTitle);
} }
} }
+6 -1
View File
@@ -121,13 +121,18 @@ export { handleMpvCommandFromIpc } from './ipc-command';
export { createFieldGroupingOverlayRuntime } from './field-grouping-overlay'; export { createFieldGroupingOverlayRuntime } from './field-grouping-overlay';
export { createNumericShortcutRuntime } from './numeric-shortcut'; export { createNumericShortcutRuntime } from './numeric-shortcut';
export { runStartupBootstrapRuntime } from './startup'; export { runStartupBootstrapRuntime } from './startup';
export { runSubsyncManualFromIpcRuntime, triggerSubsyncFromConfigRuntime } from './subsync-runner'; export {
openSubsyncManualPickerRuntime,
runSubsyncManualFromIpcRuntime,
triggerSubsyncFromConfigRuntime,
} from './subsync-runner';
export { registerAnkiJimakuIpcRuntime } from './anki-jimaku'; export { registerAnkiJimakuIpcRuntime } from './anki-jimaku';
export { ImmersionTrackerService } from './immersion-tracker-service'; export { ImmersionTrackerService } from './immersion-tracker-service';
export { export {
authenticateWithPassword as authenticateWithPasswordRuntime, authenticateWithPassword as authenticateWithPasswordRuntime,
listItems as listJellyfinItemsRuntime, listItems as listJellyfinItemsRuntime,
listLibraries as listJellyfinLibrariesRuntime, listLibraries as listJellyfinLibrariesRuntime,
listSeriesEpisodeIds as listJellyfinSeriesEpisodeIdsRuntime,
listSubtitleTracks as listJellyfinSubtitleTracksRuntime, listSubtitleTracks as listJellyfinSubtitleTracksRuntime,
resolvePlaybackPlan as resolveJellyfinPlaybackPlanRuntime, resolvePlaybackPlan as resolveJellyfinPlaybackPlanRuntime,
ticksToSeconds as jellyfinTicksToSecondsRuntime, ticksToSeconds as jellyfinTicksToSecondsRuntime,
+14
View File
@@ -102,6 +102,8 @@ export interface IpcServiceDeps {
focusMainWindow: () => void; focusMainWindow: () => void;
activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise<boolean>; activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise<boolean>;
runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>; runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
openSubsyncManual?: () => Promise<void>;
pickSubsyncReferenceFile?: () => Promise<string | null>;
onYoutubePickerResolve: ( onYoutubePickerResolve: (
request: YoutubePickerResolveRequest, request: YoutubePickerResolveRequest,
) => Promise<YoutubePickerResolveResult>; ) => Promise<YoutubePickerResolveResult>;
@@ -373,6 +375,8 @@ export interface IpcDepsRuntimeOptions {
focusMainWindow: () => void; focusMainWindow: () => void;
activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise<boolean>; activatePlaybackWindowForOverlayInteraction?: () => boolean | Promise<boolean>;
runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>; runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
openSubsyncManual?: () => Promise<void>;
pickSubsyncReferenceFile?: () => Promise<string | null>;
onYoutubePickerResolve: ( onYoutubePickerResolve: (
request: YoutubePickerResolveRequest, request: YoutubePickerResolveRequest,
) => Promise<YoutubePickerResolveResult>; ) => Promise<YoutubePickerResolveResult>;
@@ -457,6 +461,8 @@ export function createIpcDepsRuntime(options: IpcDepsRuntimeOptions): IpcService
activatePlaybackWindowForOverlayInteraction: activatePlaybackWindowForOverlayInteraction:
options.activatePlaybackWindowForOverlayInteraction ?? (() => false), options.activatePlaybackWindowForOverlayInteraction ?? (() => false),
runSubsyncManual: options.runSubsyncManual, runSubsyncManual: options.runSubsyncManual,
openSubsyncManual: options.openSubsyncManual,
pickSubsyncReferenceFile: options.pickSubsyncReferenceFile,
onYoutubePickerResolve: options.onYoutubePickerResolve, onYoutubePickerResolve: options.onYoutubePickerResolve,
previewMediaTimingReview: options.previewMediaTimingReview, previewMediaTimingReview: options.previewMediaTimingReview,
getMediaTimingReviewFrame: options.getMediaTimingReviewFrame, getMediaTimingReviewFrame: options.getMediaTimingReviewFrame,
@@ -819,6 +825,14 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
return await deps.runSubsyncManual(parsedRequest); 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, () => { ipc.handle(IPC_CHANNELS.request.getRuntimeOptions, () => {
return deps.getRuntimeOptions(); return deps.getRuntimeOptions();
}); });
+35
View File
@@ -4,6 +4,7 @@ import {
authenticateWithPassword, authenticateWithPassword,
listItems, listItems,
listLibraries, listLibraries,
listSeriesEpisodeIds,
listSubtitleTracks, listSubtitleTracks,
resolvePlaybackPlan, resolvePlaybackPlan,
ticksToSeconds, ticksToSeconds,
@@ -886,3 +887,37 @@ test('toJellyfinOriginalStreamUrl maps direct and transcoded playback to the ori
assert.equal(toJellyfinOriginalStreamUrl('https://jf/Videos/item-1/stream', 'item-1'), null); assert.equal(toJellyfinOriginalStreamUrl('https://jf/Videos/item-1/stream', 'item-1'), null);
assert.equal(toJellyfinOriginalStreamUrl('/media/item-1.mkv', 'item-1'), null); assert.equal(toJellyfinOriginalStreamUrl('/media/item-1.mkv', 'item-1'), null);
}); });
test('listSeriesEpisodeIds returns playable episodes in series order', async () => {
const originalFetch = globalThis.fetch;
let requestedUrl = '';
globalThis.fetch = (async (input) => {
requestedUrl = String(input);
return new Response(
JSON.stringify({
Items: [
{ Id: 'ep-1', LocationType: 'FileSystem' },
{ Id: 'ep-2', LocationType: 'Virtual' },
{ Id: 'ep-3', LocationType: 'FileSystem' },
{ Name: 'no id' },
],
}),
{ status: 200 },
);
}) as typeof fetch;
try {
const ids = await listSeriesEpisodeIds(
{ serverUrl: 'http://jellyfin.local', accessToken: 'token', userId: 'u1', username: 'kyle' },
clientInfo,
'series-1',
);
assert.deepEqual(ids, ['ep-1', 'ep-3']);
const url = new URL(requestedUrl);
assert.equal(url.pathname, '/Shows/series-1/Episodes');
assert.equal(url.searchParams.get('UserId'), 'u1');
assert.equal(url.searchParams.get('IsMissing'), 'false');
} finally {
globalThis.fetch = originalFetch;
}
});
+32
View File
@@ -29,6 +29,8 @@ export interface JellyfinPlaybackPlan {
title: string; title: string;
itemTitle: string; itemTitle: string;
seriesTitle: string | null; seriesTitle: string | null;
/** Set for episodes; lets playback queue the series' neighboring episodes. */
seriesId: string | null;
seasonNumber: number | null; seasonNumber: number | null;
episodeNumber: number | null; episodeNumber: number | null;
startTimeTicks: number; startTimeTicks: number;
@@ -89,6 +91,8 @@ interface JellyfinItem {
Name?: string; Name?: string;
Type?: string; Type?: string;
SeriesName?: string; SeriesName?: string;
SeriesId?: string;
LocationType?: string;
ParentIndexNumber?: number; ParentIndexNumber?: number;
IndexNumber?: number; IndexNumber?: number;
UserData?: JellyfinItemUserData; UserData?: JellyfinItemUserData;
@@ -579,6 +583,7 @@ export async function resolvePlaybackPlan(
title: getDisplayTitle(item), title: getDisplayTitle(item),
itemTitle, itemTitle,
seriesTitle, seriesTitle,
seriesId: item.Type === 'Episode' ? ensureString(item.SeriesId).trim() || null : null,
seasonNumber: item.Type === 'Episode' ? asIntegerOrNull(item.ParentIndexNumber) : null, seasonNumber: item.Type === 'Episode' ? asIntegerOrNull(item.ParentIndexNumber) : null,
episodeNumber: item.Type === 'Episode' ? asIntegerOrNull(item.IndexNumber) : null, episodeNumber: item.Type === 'Episode' ? asIntegerOrNull(item.IndexNumber) : null,
startTimeTicks, startTimeTicks,
@@ -611,6 +616,33 @@ export async function resolvePlaybackPlan(
}; };
} }
/**
* Lists a series' episode ids in playback order. The order runs across season boundaries and
* skips episodes the server only knows from metadata.
*/
export async function listSeriesEpisodeIds(
session: JellyfinAuthSession,
client: JellyfinClientInfo,
seriesId: string,
): Promise<string[]> {
const query = new URLSearchParams({
UserId: session.userId,
IsMissing: 'false',
EnableImages: 'false',
EnableUserData: 'false',
});
const payload = await jellyfinRequestJson<JellyfinItemsResponse>(
`/Shows/${encodeURIComponent(seriesId)}/Episodes?${query.toString()}`,
{ method: 'GET' },
session,
client,
);
return (Array.isArray(payload.Items) ? payload.Items : [])
.filter((item) => item.LocationType !== 'Virtual')
.map((item) => ensureString(item.Id))
.filter((id) => id.length > 0);
}
export function ticksToSeconds(ticks: number): number { export function ticksToSeconds(ticks: number): number {
return Math.max(0, Math.floor(ticks / JELLYFIN_TICKS_PER_SECOND)); return Math.max(0, Math.floor(ticks / JELLYFIN_TICKS_PER_SECOND));
} }
+29
View File
@@ -2,7 +2,9 @@ import { SubsyncManualPayload, SubsyncManualRunRequest, SubsyncResult } from '..
import { SubsyncResolvedConfig } from '../../subsync/utils'; import { SubsyncResolvedConfig } from '../../subsync/utils';
import { runSubsyncManualFromIpc } from './ipc-command'; import { runSubsyncManualFromIpc } from './ipc-command';
import { import {
SubsyncVadPaths,
TriggerSubsyncFromConfigDeps, TriggerSubsyncFromConfigDeps,
openSubsyncManualPicker,
runSubsyncManual, runSubsyncManual,
triggerSubsyncFromConfig, triggerSubsyncFromConfig,
} from './subsync'; } from './subsync';
@@ -19,6 +21,8 @@ interface MpvClientLike {
export interface SubsyncRuntimeDeps { export interface SubsyncRuntimeDeps {
getMpvClient: () => MpvClientLike | null; getMpvClient: () => MpvClientLike | null;
getResolvedSubsyncConfig: () => SubsyncResolvedConfig; getResolvedSubsyncConfig: () => SubsyncResolvedConfig;
getVadPaths?: () => SubsyncVadPaths;
canPickReferenceFile?: () => boolean;
isSubsyncInProgress: () => boolean; isSubsyncInProgress: () => boolean;
setSubsyncInProgress: (inProgress: boolean) => void; setSubsyncInProgress: (inProgress: boolean) => void;
showMpvOsd: (text: string) => void; showMpvOsd: (text: string) => void;
@@ -47,6 +51,8 @@ function buildTriggerSubsyncDeps(deps: SubsyncRuntimeDeps): TriggerSubsyncFromCo
return { return {
getMpvClient: deps.getMpvClient, getMpvClient: deps.getMpvClient,
getResolvedConfig: deps.getResolvedSubsyncConfig, getResolvedConfig: deps.getResolvedSubsyncConfig,
getVadPaths: deps.getVadPaths,
canPickReferenceFile: deps.canPickReferenceFile,
isSubsyncInProgress: deps.isSubsyncInProgress, isSubsyncInProgress: deps.isSubsyncInProgress,
setSubsyncInProgress: deps.setSubsyncInProgress, setSubsyncInProgress: deps.setSubsyncInProgress,
showMpvOsd: deps.showMpvOsd, showMpvOsd: deps.showMpvOsd,
@@ -60,6 +66,29 @@ export async function triggerSubsyncFromConfigRuntime(deps: SubsyncRuntimeDeps):
await triggerSubsyncFromConfig(buildTriggerSubsyncDeps(deps)); await triggerSubsyncFromConfig(buildTriggerSubsyncDeps(deps));
} }
export async function openSubsyncManualPickerRuntime(deps: SubsyncRuntimeDeps): Promise<void> {
const triggerDeps = buildTriggerSubsyncDeps(deps);
if (triggerDeps.isSubsyncInProgress()) {
triggerDeps.showMpvOsd('Subsync already running');
return;
}
triggerDeps.setSubsyncInProgress(true);
try {
const opened = await triggerDeps.runWithSubsyncSpinner(() =>
openSubsyncManualPicker(triggerDeps, {
guidanceMessage: null,
}),
);
if (opened) {
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( export async function runSubsyncManualFromIpcRuntime(
request: SubsyncManualRunRequest, request: SubsyncManualRunRequest,
deps: SubsyncRuntimeDeps, deps: SubsyncRuntimeDeps,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+25
View File
@@ -744,6 +744,8 @@ const configDerivedRuntime = createConfigDerivedRuntime({
const subsyncRuntime = createMainSubsyncRuntime({ const subsyncRuntime = createMainSubsyncRuntime({
getMpvClient: () => appState.mpvClient, getMpvClient: () => appState.mpvClient,
getResolvedConfig: () => configService.getConfig(), getResolvedConfig: () => configService.getConfig(),
getSubtitleGenerationModelDirectory,
canPickReferenceFile: () => true,
getSubsyncInProgress: () => appState.subsyncInProgress, getSubsyncInProgress: () => appState.subsyncInProgress,
setSubsyncInProgress: (inProgress) => { setSubsyncInProgress: (inProgress) => {
appState.subsyncInProgress = inProgress; appState.subsyncInProgress = inProgress;
@@ -1516,6 +1518,29 @@ const { registerIpcRuntimeHandlers } = composeIpcRuntimeHandlers({
...stats.ipc, ...stats.ipc,
...playlistBrowserMainDeps, ...playlistBrowserMainDeps,
// App-level handlers with no owning assembly. // 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), onYoutubePickerResolve: (request) => youtube.flow.resolveActivePicker(request),
handleOverlayNotificationAction: (notificationId, actionId, noteId) => { handleOverlayNotificationAction: (notificationId, actionId, noteId) => {
if ( if (
+35
View File
@@ -8,6 +8,7 @@ import {
JellyfinPlaybackReporter, JellyfinPlaybackReporter,
JellyfinRemoteSessionService, JellyfinRemoteSessionService,
jellyfinTicksToSecondsRuntime, jellyfinTicksToSecondsRuntime,
listJellyfinSeriesEpisodeIdsRuntime,
listJellyfinItemsRuntime, listJellyfinItemsRuntime,
listJellyfinLibrariesRuntime, listJellyfinLibrariesRuntime,
listJellyfinSubtitleTracksRuntime, listJellyfinSubtitleTracksRuntime,
@@ -28,6 +29,7 @@ import {
mergeJellyfinRecentServers, mergeJellyfinRecentServers,
parseJellyfinSetupSubmissionUrl, parseJellyfinSetupSubmissionUrl,
persistJellyfinAuthSession, persistJellyfinAuthSession,
markJellyfinRemotePlaybackLoaded,
type ActiveJellyfinRemotePlaybackState, type ActiveJellyfinRemotePlaybackState,
} from '../runtime/domains/jellyfin'; } from '../runtime/domains/jellyfin';
import { detectInstalledMpvPlugin } from '../runtime/first-run-setup-plugin'; import { detectInstalledMpvPlugin } from '../runtime/first-run-setup-plugin';
@@ -37,6 +39,10 @@ import {
createHostDerivedJellyfinDeviceId, createHostDerivedJellyfinDeviceId,
resolveJellyfinRemoteDeviceName, resolveJellyfinRemoteDeviceName,
} from '../runtime/jellyfin-device-identity'; } from '../runtime/jellyfin-device-identity';
import {
chooseMpvEntryLoadMode,
PLUGIN_ENTRY_OPTIONS_USER_DATA,
} from '../runtime/jellyfin-episode-playlist';
import { createJellyfinSubtitleCacheIo } from '../runtime/jellyfin-subtitle-cache-io'; import { createJellyfinSubtitleCacheIo } from '../runtime/jellyfin-subtitle-cache-io';
import { clearJellyfinAuthSessionAndRefreshTray as clearJellyfinAuthSessionAndRefreshTrayRuntime } from '../runtime/jellyfin-tray-discovery'; import { clearJellyfinAuthSessionAndRefreshTray as clearJellyfinAuthSessionAndRefreshTrayRuntime } from '../runtime/jellyfin-tray-discovery';
import { resolveMpvExecutablePath, spawnMpvProcess } from '../runtime/mpv-process'; import { resolveMpvExecutablePath, spawnMpvProcess } from '../runtime/mpv-process';
@@ -140,6 +146,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
runJellyfinCommand, runJellyfinCommand,
openJellyfinSetupWindow, openJellyfinSetupWindow,
ensureMpvConnectedForPlayback, ensureMpvConnectedForPlayback,
playJellyfinItemInMpv,
} = composeJellyfinRuntimeHandlers({ } = composeJellyfinRuntimeHandlers({
getResolvedJellyfinConfigMainDeps: { getResolvedJellyfinConfigMainDeps: {
getResolvedConfig: () => configService.getConfig(), getResolvedConfig: () => configService.getConfig(),
@@ -237,6 +244,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
setTimeout(callback, delayMs); setTimeout(callback, delayMs);
}, },
convertTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks), convertTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks),
getActivePlayback: () => activeJellyfinRemotePlayback,
setActivePlayback: (state) => { setActivePlayback: (state) => {
activeJellyfinRemotePlayback = { activeJellyfinRemotePlayback = {
...(state as ActiveJellyfinRemotePlaybackState), ...(state as ActiveJellyfinRemotePlaybackState),
@@ -270,6 +278,24 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
deps.ensureImmersionTrackerStarted(); deps.ensureImmersionTrackerStarted();
appState.immersionTracker?.recordJellyfinPlaybackMetadata(metadata); appState.immersionTracker?.recordJellyfinPlaybackMetadata(metadata);
}, },
getEpisodePlaylistSettings: () => configService.getConfig().jellyfin.episodePlaylist,
listSeriesEpisodeIds: ({ session, clientInfo, seriesId }) =>
listJellyfinSeriesEpisodeIdsRuntime(session, clientInfo, seriesId),
readMpvPlaylist: async () => appState.mpvClient?.requestProperty('playlist') ?? [],
resolveEntryLoadMode: async () => {
const client = appState.mpvClient;
if (!client) return 'loadfile';
// The user-data key is unset (an error) unless the SubMiner plugin is loaded.
const [mpvVersion, pluginAppliesEntryOptions] = await Promise.all([
client.requestProperty('mpv-version').catch(() => null),
client.requestProperty(PLUGIN_ENTRY_OPTIONS_USER_DATA).then(
(value) => value === true,
() => false,
),
]);
return chooseMpvEntryLoadMode(mpvVersion, pluginAppliesEntryOptions);
},
logDebug: (message, error) => logger.debug(message, error),
}, },
remoteComposerOptions: { remoteComposerOptions: {
getConfiguredSession: () => getConfiguredJellyfinSession(getResolvedJellyfinConfig()), getConfiguredSession: () => getConfiguredJellyfinSession(getResolvedJellyfinConfig()),
@@ -452,6 +478,15 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
ensureMpvConnectedForPlayback, ensureMpvConnectedForPlayback,
getTrayDiscoveryDeps: getJellyfinTrayDiscoveryDeps, getTrayDiscoveryDeps: getJellyfinTrayDiscoveryDeps,
getActivePlayback: () => activeJellyfinRemotePlayback, getActivePlayback: () => activeJellyfinRemotePlayback,
/**
* Called with each new mpv path: takes over a queued Jellyfin episode mpv started from its
* playlist, otherwise marks the active playback loaded. Must run before the immersion sync.
*/
handleMediaPathLoaded: (path: string) => {
if (playJellyfinItemInMpv.adoptQueuedEpisode(path)) return;
markJellyfinRemotePlaybackLoaded(activeJellyfinRemotePlayback, path);
},
handlePlaybackTimePos: () => playJellyfinItemInMpv.handlePlaybackTimePos(),
getQuitOnDisconnectArmed: () => jellyfinPlayQuitOnDisconnectArmed, getQuitOnDisconnectArmed: () => jellyfinPlayQuitOnDisconnectArmed,
}; };
} }
+2
View File
@@ -111,6 +111,8 @@ function makeDeps(recorder: Recorder): PlaybackAssemblyDeps {
reportJellyfinRemoteStopped: spy('jellyfin.reportStopped', resolved), reportJellyfinRemoteStopped: spy('jellyfin.reportStopped', resolved),
reportJellyfinRemoteProgress: spy('jellyfin.reportProgress', resolved), reportJellyfinRemoteProgress: spy('jellyfin.reportProgress', resolved),
getActivePlayback: spy('jellyfin.getActivePlayback', () => null), getActivePlayback: spy('jellyfin.getActivePlayback', () => null),
handleMediaPathLoaded: spy('jellyfin.handleMediaPathLoaded', noop),
handlePlaybackTimePos: spy('jellyfin.handlePlaybackTimePos', noop),
startJellyfinRemoteSession: spy('jellyfin.startRemoteSession', resolved), startJellyfinRemoteSession: spy('jellyfin.startRemoteSession', resolved),
}, },
anilist: { anilist: {
+6 -6
View File
@@ -21,10 +21,7 @@ import { createAutoplayTokenizationWarmRelease } from '../runtime/autoplay-token
import { composeMpvRuntimeHandlers } from '../runtime/composers'; import { composeMpvRuntimeHandlers } from '../runtime/composers';
import { createCurrentMediaTokenizationGate } from '../runtime/current-media-tokenization-gate'; import { createCurrentMediaTokenizationGate } from '../runtime/current-media-tokenization-gate';
import { createCachedInternalSubtitleTrackExtractor } from '../runtime/internal-subtitle-extraction'; import { createCachedInternalSubtitleTrackExtractor } from '../runtime/internal-subtitle-extraction';
import { import { shouldAutoLoadSecondarySubTrackForJellyfinPlayback } from '../runtime/jellyfin-remote-playback';
markJellyfinRemotePlaybackLoaded as markJellyfinRemotePlaybackLoadedState,
shouldAutoLoadSecondarySubTrackForJellyfinPlayback,
} from '../runtime/jellyfin-remote-playback';
import { createJimakuAutoOpenRuntime } from '../runtime/jimaku-auto-open'; import { createJimakuAutoOpenRuntime } from '../runtime/jimaku-auto-open';
import { createManagedLocalSubtitleSelectionRuntime } from '../runtime/local-subtitle-selection'; import { createManagedLocalSubtitleSelectionRuntime } from '../runtime/local-subtitle-selection';
import { focusMacOSOverlayWindow } from '../runtime/macos-overlay-window-focus'; import { focusMacOSOverlayWindow } from '../runtime/macos-overlay-window-focus';
@@ -164,6 +161,8 @@ export interface PlaybackAssemblyDeps {
| 'reportJellyfinRemoteStopped' | 'reportJellyfinRemoteStopped'
| 'reportJellyfinRemoteProgress' | 'reportJellyfinRemoteProgress'
| 'getActivePlayback' | 'getActivePlayback'
| 'handleMediaPathLoaded'
| 'handlePlaybackTimePos'
| 'startJellyfinRemoteSession' | 'startJellyfinRemoteSession'
>; >;
anilist: Pick< anilist: Pick<
@@ -838,8 +837,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
immersionMediaRuntime.syncFromCurrentMediaState(); immersionMediaRuntime.syncFromCurrentMediaState();
}, },
signalAutoplayReadyIfWarm: (path) => signalAutoplayReadyFromWarmTokenization?.(path), signalAutoplayReadyIfWarm: (path) => signalAutoplayReadyFromWarmTokenization?.(path),
markJellyfinRemotePlaybackLoaded: (path) => { handleJellyfinMediaPathLoaded: (path) => {
markJellyfinRemotePlaybackLoadedState(jellyfin.getActivePlayback(), path); jellyfin.handleMediaPathLoaded(path);
}, },
scheduleCharacterDictionarySync: () => { scheduleCharacterDictionarySync: () => {
if ( if (
@@ -862,6 +861,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
}, },
consumeExplicitSeek: () => consumeExplicitSeekIntent(), consumeExplicitSeek: () => consumeExplicitSeekIntent(),
onTimePosUpdate: (time) => { onTimePosUpdate: (time) => {
jellyfin.handlePlaybackTimePos();
const delta = time - lastObservedTimePos; const delta = time - lastObservedTimePos;
if (subtitlePrefetchService && (delta > SEEK_THRESHOLD_SECONDS || delta < 0)) { if (subtitlePrefetchService && (delta > SEEK_THRESHOLD_SECONDS || delta < 0)) {
subtitlePrefetchService.onSeek(time); subtitlePrefetchService.onSeek(time);
+8
View File
@@ -16,6 +16,8 @@ export interface RuntimeOptionsIpcDepsParams {
export interface SubsyncRuntimeDepsParams { export interface SubsyncRuntimeDepsParams {
getMpvClient: () => ReturnType<SubsyncRuntimeDeps['getMpvClient']>; getMpvClient: () => ReturnType<SubsyncRuntimeDeps['getMpvClient']>;
getResolvedSubsyncConfig: () => SubsyncResolvedConfig; getResolvedSubsyncConfig: () => SubsyncResolvedConfig;
getVadPaths?: SubsyncRuntimeDeps['getVadPaths'];
canPickReferenceFile?: SubsyncRuntimeDeps['canPickReferenceFile'];
isSubsyncInProgress: () => boolean; isSubsyncInProgress: () => boolean;
setSubsyncInProgress: (inProgress: boolean) => void; setSubsyncInProgress: (inProgress: boolean) => void;
showMpvOsd: (text: string) => void; showMpvOsd: (text: string) => void;
@@ -37,6 +39,8 @@ export function createSubsyncRuntimeDeps(params: SubsyncRuntimeDepsParams): Subs
return { return {
getMpvClient: params.getMpvClient, getMpvClient: params.getMpvClient,
getResolvedSubsyncConfig: params.getResolvedSubsyncConfig, getResolvedSubsyncConfig: params.getResolvedSubsyncConfig,
getVadPaths: params.getVadPaths,
canPickReferenceFile: params.canPickReferenceFile,
isSubsyncInProgress: params.isSubsyncInProgress, isSubsyncInProgress: params.isSubsyncInProgress,
setSubsyncInProgress: params.setSubsyncInProgress, setSubsyncInProgress: params.setSubsyncInProgress,
showMpvOsd: params.showMpvOsd, showMpvOsd: params.showMpvOsd,
@@ -84,6 +88,8 @@ export interface MainIpcRuntimeServiceDepsParams {
getSecondarySubMode: IpcDepsRuntimeOptions['getSecondarySubMode']; getSecondarySubMode: IpcDepsRuntimeOptions['getSecondarySubMode'];
getMpvClient: IpcDepsRuntimeOptions['getMpvClient']; getMpvClient: IpcDepsRuntimeOptions['getMpvClient'];
runSubsyncManual: IpcDepsRuntimeOptions['runSubsyncManual']; runSubsyncManual: IpcDepsRuntimeOptions['runSubsyncManual'];
openSubsyncManual?: IpcDepsRuntimeOptions['openSubsyncManual'];
pickSubsyncReferenceFile?: IpcDepsRuntimeOptions['pickSubsyncReferenceFile'];
getRuntimeOptions: IpcDepsRuntimeOptions['getRuntimeOptions']; getRuntimeOptions: IpcDepsRuntimeOptions['getRuntimeOptions'];
setRuntimeOption: IpcDepsRuntimeOptions['setRuntimeOption']; setRuntimeOption: IpcDepsRuntimeOptions['setRuntimeOption'];
reportOverlayContentBounds: IpcDepsRuntimeOptions['reportOverlayContentBounds']; reportOverlayContentBounds: IpcDepsRuntimeOptions['reportOverlayContentBounds'];
@@ -267,6 +273,8 @@ export function createMainIpcRuntimeServiceDeps(
getSecondarySubMode: params.getSecondarySubMode, getSecondarySubMode: params.getSecondarySubMode,
getMpvClient: params.getMpvClient, getMpvClient: params.getMpvClient,
runSubsyncManual: params.runSubsyncManual, runSubsyncManual: params.runSubsyncManual,
openSubsyncManual: params.openSubsyncManual,
pickSubsyncReferenceFile: params.pickSubsyncReferenceFile,
getRuntimeOptions: params.getRuntimeOptions, getRuntimeOptions: params.getRuntimeOptions,
setRuntimeOption: params.setRuntimeOption, setRuntimeOption: params.setRuntimeOption,
reportOverlayContentBounds: params.reportOverlayContentBounds, reportOverlayContentBounds: params.reportOverlayContentBounds,
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { ActiveJellyfinRemotePlaybackState } from '../jellyfin-remote-commands';
import { composeJellyfinRemoteHandlers } from './jellyfin-remote-composer';
function makeHandlers() {
return composeJellyfinRemoteHandlers({
getConfiguredSession: () => null,
getClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1', deviceId: 'did' }),
getJellyfinConfig: () => ({}),
playJellyfinItem: async () => {},
logWarn: () => {},
getMpvClient: () => null,
sendMpvCommand: () => {},
jellyfinTicksToSeconds: (ticks) => ticks / 10_000_000,
getActivePlayback: () => null,
clearActivePlayback: () => {},
getNow: () => 0,
getLastProgressAtMs: () => 0,
setLastProgressAtMs: () => {},
progressIntervalMs: 3000,
ticksPerSecond: 10_000_000,
logDebug: () => {},
});
}
test('a tracked episode start holds its own stop and the next transition', async () => {
const handlers = makeHandlers();
const events: string[] = [];
const playback: ActiveJellyfinRemotePlaybackState = {
itemId: 'ep1',
playMethod: 'DirectPlay',
reporter: {
reportPlaying: async () => {},
reportProgress: async () => {},
reportStopped: async () => void events.push('stopped:ep1'),
},
};
let finishStart = () => {};
handlers.trackJellyfinPlaybackStart(
new Promise<void>((resolve) => {
finishStart = () => {
events.push('started:ep1');
resolve();
};
}),
playback,
);
const stopped = handlers.reportJellyfinPlaybackSuperseded(playback);
const transitionsDone = handlers.waitForJellyfinTransitionReports().then(() => {
events.push('transitions settled');
});
await Promise.resolve();
assert.deepEqual(events, [], 'the stop and the next start wait for the start in flight');
finishStart();
await Promise.all([stopped, transitionsDone]);
assert.deepEqual(events, ['started:ep1', 'stopped:ep1', 'transitions settled']);
});
@@ -5,6 +5,7 @@ import {
createJellyfinRemoteReportTracker, createJellyfinRemoteReportTracker,
createReportJellyfinRemoteProgressHandler, createReportJellyfinRemoteProgressHandler,
createReportJellyfinRemoteStoppedHandler, createReportJellyfinRemoteStoppedHandler,
createReportSupersededJellyfinPlaybackHandler,
type JellyfinRemoteGeneralCommandHandlerDeps, type JellyfinRemoteGeneralCommandHandlerDeps,
type JellyfinRemotePlayHandlerDeps, type JellyfinRemotePlayHandlerDeps,
type JellyfinRemotePlaystateHandlerDeps, type JellyfinRemotePlaystateHandlerDeps,
@@ -40,6 +41,16 @@ export type JellyfinRemoteComposerOptions = ComposerInputs<{
export type JellyfinRemoteComposerResult = ComposerOutputs<{ export type JellyfinRemoteComposerResult = ComposerOutputs<{
reportJellyfinRemoteProgress: ReturnType<typeof createReportJellyfinRemoteProgressHandler>; reportJellyfinRemoteProgress: ReturnType<typeof createReportJellyfinRemoteProgressHandler>;
reportJellyfinRemoteStopped: ReturnType<typeof createReportJellyfinRemoteStoppedHandler>; reportJellyfinRemoteStopped: ReturnType<typeof createReportJellyfinRemoteStoppedHandler>;
reportJellyfinPlaybackSuperseded: ReturnType<
typeof createReportSupersededJellyfinPlaybackHandler
>;
/** Resolves once no episode start or stop report is in flight. */
waitForJellyfinTransitionReports: () => Promise<void>;
/** Tracks an episode start report, so its own stop and later starts wait for it. */
trackJellyfinPlaybackStart: (
report: Promise<void>,
playback: Parameters<ReturnType<typeof createReportSupersededJellyfinPlaybackHandler>>[0],
) => void;
handleJellyfinRemotePlay: (payload: RemotePlayPayload) => Promise<void>; handleJellyfinRemotePlay: (payload: RemotePlayPayload) => Promise<void>;
handleJellyfinRemotePlaystate: (payload: RemotePlaystatePayload) => Promise<void>; handleJellyfinRemotePlaystate: (payload: RemotePlaystatePayload) => Promise<void>;
handleJellyfinRemoteGeneralCommand: (payload: RemoteGeneralPayload) => Promise<void>; handleJellyfinRemoteGeneralCommand: (payload: RemoteGeneralPayload) => Promise<void>;
@@ -61,7 +72,10 @@ export function composeJellyfinRemoteHandlers(
logDebug: options.logDebug, logDebug: options.logDebug,
reportTracker, reportTracker,
}); });
const reportJellyfinRemoteStopped = createReportJellyfinRemoteStoppedHandler({ // Every episode start and stop report in flight. Jellyfin keeps whichever start arrives last
// as the now-playing item and clears it on any stop, so a start waits for all of these.
const transitionReportTracker = createJellyfinRemoteReportTracker();
const reportStopped = createReportJellyfinRemoteStoppedHandler({
getActivePlayback: options.getActivePlayback, getActivePlayback: options.getActivePlayback,
clearActivePlayback: options.clearActivePlayback, clearActivePlayback: options.clearActivePlayback,
getMpvClient: options.getMpvClient, getMpvClient: options.getMpvClient,
@@ -71,10 +85,35 @@ export function composeJellyfinRemoteHandlers(
logWarn: options.logWarn, logWarn: options.logWarn,
reportTracker, reportTracker,
}); });
const reportSuperseded = createReportSupersededJellyfinPlaybackHandler({
ticksPerSecond: options.ticksPerSecond,
logDebug: options.logDebug,
logWarn: options.logWarn,
reportTracker,
});
const reportJellyfinRemoteStopped = (): Promise<void> => {
const report = reportStopped();
transitionReportTracker.track(report, null);
return report;
};
const reportJellyfinPlaybackSuperseded = (
playback: Parameters<typeof reportSuperseded>[0],
): Promise<void> => {
const report = reportSuperseded(playback);
transitionReportTracker.track(report, playback);
return report;
};
return { return {
reportJellyfinRemoteProgress, reportJellyfinRemoteProgress,
reportJellyfinRemoteStopped, reportJellyfinRemoteStopped,
reportJellyfinPlaybackSuperseded,
waitForJellyfinTransitionReports: () => transitionReportTracker.settled(),
trackJellyfinPlaybackStart: (report, playback) => {
// Tagged with its playback in the shared tracker, so that playback's stop waits for it.
reportTracker.track(report, playback);
transitionReportTracker.track(report, playback);
},
handleJellyfinRemotePlay: createHandleJellyfinRemotePlay({ handleJellyfinRemotePlay: createHandleJellyfinRemotePlay({
getConfiguredSession: options.getConfiguredSession, getConfiguredSession: options.getConfiguredSession,
getClientInfo: options.getClientInfo, getClientInfo: options.getClientInfo,
@@ -50,7 +50,11 @@ export type JellyfinRuntimeComposerOptions = ComposerInputs<{
>[0]; >[0];
playJellyfinItemInMpvMainDeps: Omit< playJellyfinItemInMpvMainDeps: Omit<
PlayJellyfinItemMainDeps, PlayJellyfinItemMainDeps,
'ensureMpvConnectedForPlayback' | 'preloadExternalSubtitles' | 'ensureMpvConnectedForPlayback'
| 'preloadExternalSubtitles'
| 'reportPlaybackSuperseded'
| 'waitForTransitionReports'
| 'trackPlaybackStart'
>; >;
remoteComposerOptions: Omit< remoteComposerOptions: Omit<
JellyfinRemoteComposerOptions, JellyfinRemoteComposerOptions,
@@ -157,11 +161,18 @@ export function composeJellyfinRuntimeHandlers(
preloadExternalSubtitles: (params) => { preloadExternalSubtitles: (params) => {
void preloadJellyfinExternalSubtitles(params); void preloadJellyfinExternalSubtitles(params);
}, },
// The remote handlers are built below and share the report tracker with the stop handler.
reportPlaybackSuperseded: (playback) => reportJellyfinPlaybackSuperseded(playback),
waitForTransitionReports: () => waitForJellyfinTransitionReports(),
trackPlaybackStart: (report, playback) => trackJellyfinPlaybackStart(report, playback),
}); });
const { const {
reportJellyfinRemoteProgress, reportJellyfinRemoteProgress,
reportJellyfinRemoteStopped, reportJellyfinRemoteStopped,
reportJellyfinPlaybackSuperseded,
waitForJellyfinTransitionReports,
trackJellyfinPlaybackStart,
handleJellyfinRemotePlay, handleJellyfinRemotePlay,
handleJellyfinRemotePlaystate, handleJellyfinRemotePlaystate,
handleJellyfinRemoteGeneralCommand, handleJellyfinRemoteGeneralCommand,
@@ -0,0 +1,289 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildMpvEntryLoadCommands,
chooseMpvEntryLoadMode,
createJellyfinEpisodePlaylist,
selectEpisodeWindow,
type JellyfinEpisodePlaylistSettings,
type JellyfinPlaylistEntry,
type MpvEntryLoadMode,
} from './jellyfin-episode-playlist';
const EPISODES = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6'];
test('selectEpisodeWindow centers on the current episode and stays full at series edges', () => {
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e3', 3), {
previousIds: ['e2'],
nextIds: ['e4'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e3', 4), {
previousIds: ['e2'],
nextIds: ['e4', 'e5'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e1', 3), {
previousIds: [],
nextIds: ['e2', 'e3'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e6', 3), {
previousIds: ['e4', 'e5'],
nextIds: [],
});
assert.deepEqual(selectEpisodeWindow(['e1', 'e2'], 'e1', 5), {
previousIds: [],
nextIds: ['e2'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'missing', 3), { previousIds: [], nextIds: [] });
});
type Entry = JellyfinPlaylistEntry;
const url = (itemId: string) => `https://jf.example/Videos/${itemId}/stream`;
const entry = (itemId: string): Entry => ({
itemId,
seriesId: 'series',
playbackUrl: url(itemId),
fileOptions: [['start', itemId]],
title: `Show ${itemId}`,
});
/** mpv's playlist, kept in sync with the commands the queue sends. */
function makeHarness(
settings: JellyfinEpisodePlaylistSettings = { enabled: true, maxEpisodes: 3 },
mode: MpvEntryLoadMode = 'loadfile',
) {
const playlist: Array<{ filename: string; current: boolean; title?: string }> = [];
const commands: Array<Array<string | number>> = [];
let episodeListCalls = 0;
let afterRead: (() => void) | undefined;
const queue = createJellyfinEpisodePlaylist<null, Entry>({
getSettings: () => settings,
listSeriesEpisodeIds: async () => {
episodeListCalls += 1;
return EPISODES;
},
prepareEntry: async (_context, itemId) => entry(itemId),
getEntryLoadMode: () => mode,
readMpvPlaylist: async () => {
const snapshot = playlist.map((item) => ({ ...item }));
// Lets a test move mpv on after the read, like a keypress landing mid-run.
afterRead?.();
return snapshot;
},
sendMpvCommand: (command) => {
commands.push(command);
if (command[0] === 'playlist-remove') playlist.splice(Number(command[1]), 1);
if (command[0] === 'loadfile') {
playlist.splice(Number(command[3]), 0, { filename: String(command[1]), current: false });
}
if (command[0] === 'loadlist') {
const [, title, filename] = /#EXTINF:0,(.*)\n(.*)\n$/.exec(String(command[1])) ?? [];
playlist.splice(Number(command[3]), 0, { filename: filename!, current: false, title });
}
const titleIndex = /^playlist\/(\d+)\/title$/.exec(String(command[1]))?.[1];
if (command[0] === 'set_property' && titleIndex !== undefined) {
playlist[Number(titleIndex)]!.title = String(command[2]);
}
},
logDebug: () => {},
});
const playing = (itemId: string) => {
for (const item of playlist) item.current = item.filename === url(itemId);
if (!playlist.some((item) => item.current)) {
playlist.splice(0, playlist.length, { filename: url(itemId), current: true });
}
};
return {
queue,
commands,
playlist,
playing,
episodeListCalls: () => episodeListCalls,
setAfterRead: (callback: (() => void) | undefined) => {
afterRead = callback;
},
filenames: () => playlist.map((item) => item.filename),
titles: () => playlist.map((item) => item.title),
};
}
test('queueNeighbors inserts the episode window around the current entry', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), [url('e2'), url('e3'), url('e4')]);
assert.deepEqual(
harness.commands.filter((command) => command[0] === 'loadfile'),
[
['loadfile', url('e4'), 'insert-at', 1, 'start=e4'],
['loadfile', url('e2'), 'insert-at', 0, 'start=e2'],
],
);
const managedAt = harness.commands.findIndex(
(command) => command[1] === 'subminer-managed-playlist-entries',
);
assert.deepEqual(harness.commands[managedAt], [
'script-message',
'subminer-managed-playlist-entries',
url('e3'),
url('e4'),
url('e2'),
]);
assert.ok(
managedAt < harness.commands.findIndex((command) => command[0] === 'loadfile'),
'the plugin learns the managed paths before mpv can start an inserted entry',
);
assert.deepEqual(harness.titles(), ['Show e2', 'Show e3', 'Show e4']);
assert.equal(harness.queue.find(url('e4'))?.entry.itemId, 'e4');
assert.equal(harness.queue.find(url('e5')), null);
});
test('queueNeighbors slides the window when mpv moves to a queued episode', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
await harness.queue.queueNeighbors(null, entry('e4'));
assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]);
assert.deepEqual(harness.titles(), ['Show e3', 'Show e4', 'Show e5']);
assert.equal(harness.queue.find(url('e2')), null);
assert.equal(harness.episodeListCalls(), 1, 'series order is reused while navigating');
});
test('queueNeighbors keeps entries still in the window and edits only its far ends', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
const commandsBefore = harness.commands.length;
await harness.queue.queueNeighbors(null, entry('e4'));
assert.deepEqual(
harness.commands
.slice(commandsBefore)
.filter((command) => command[0] === 'loadfile' || command[0] === 'playlist-remove'),
[
['playlist-remove', 0],
['loadfile', url('e5'), 'insert-at', 2, 'start=e5'],
],
);
});
test('queueNeighbors never undoes a navigation that lands after its playlist read', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
// The read sees e4 playing; the user steps back to e3 before the edits arrive.
harness.setAfterRead(() => harness.playing('e3'));
await harness.queue.queueNeighbors(null, entry('e4'));
assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3'));
assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]);
});
test('queueNeighbors keeps the episode just left even with the smallest configured window', async () => {
const harness = makeHarness({ enabled: true, maxEpisodes: 2 });
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
// The read sees e4 playing; the user steps back to e3 before the edits arrive.
harness.setAfterRead(() => harness.playing('e3'));
await harness.queue.queueNeighbors(null, entry('e4'));
assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3'));
assert.ok(harness.filenames().includes(url('e3')));
});
test('queueNeighbors leaves the playlist alone once mpv has moved past the item', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
const before = harness.filenames();
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), before);
});
test('queueNeighbors drops queued entries and adds none when the playlist is disabled', async () => {
const settings = { enabled: true, maxEpisodes: 3 };
const harness = makeHarness(settings);
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
settings.enabled = false;
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), [url('e3')]);
});
test('reset cancels a queue run that is still resolving episodes', async () => {
const harness = makeHarness();
harness.playing('e3');
const pending = harness.queue.queueNeighbors(null, entry('e3'));
harness.queue.reset();
await pending;
assert.deepEqual(harness.filenames(), [url('e3')]);
assert.equal(harness.queue.find(url('e3')), null);
});
test('queueNeighbors titles entries through an m3u on mpv without writable playlist titles', async () => {
const harness = makeHarness(undefined, 'loadlist');
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), [url('e2'), url('e3'), url('e4')]);
assert.deepEqual(harness.titles(), ['Show e2', undefined, 'Show e4']);
assert.equal(
harness.commands.some((command) => command[0] === 'loadfile' || command[0] === 'set_property'),
false,
);
// The plugin hears each entry's options before mpv can start it.
const optionsAt = harness.commands.findIndex(
(command) => command[0] === 'script-message' && command[2] === url('e4'),
);
assert.deepEqual(harness.commands[optionsAt], [
'script-message',
'subminer-playlist-entry-options',
url('e4'),
'start',
'e4',
]);
assert.equal(harness.commands[optionsAt + 1]?.[0], 'loadlist');
});
test('buildMpvEntryLoadCommands keeps a title on one m3u line and quotes loadfile values', () => {
const titled = {
...entry('e1'),
title: 'A, B\nC',
fileOptions: [['force-media-title', 'A, B']] as const,
};
assert.deepEqual(buildMpvEntryLoadCommands(titled, 'loadlist', { kind: 'replace' })[1], [
'loadlist',
`memory://#EXTM3U\n#EXTINF:0,A, B C\n${url('e1')}\n`,
'replace',
]);
assert.deepEqual(buildMpvEntryLoadCommands(titled, 'loadfile', { kind: 'replace' }), [
['loadfile', url('e1'), 'replace', -1, 'force-media-title=%4%A, B'],
]);
});
test('chooseMpvEntryLoadMode uses loadlist only on mpv before 0.42 with the plugin hook', () => {
assert.equal(chooseMpvEntryLoadMode('mpv v0.41.0', true), 'loadlist');
assert.equal(chooseMpvEntryLoadMode('mpv v0.41.0', false), 'loadfile');
assert.equal(chooseMpvEntryLoadMode('mpv v0.42.0', true), 'loadfile');
assert.equal(chooseMpvEntryLoadMode('mpv v1.0.0', true), 'loadfile');
assert.equal(chooseMpvEntryLoadMode(null, true), 'loadfile');
});
@@ -0,0 +1,299 @@
/** What the episode playlist needs from a prepared Jellyfin item. */
export type JellyfinPlaylistEntry = {
itemId: string;
/** Set for episodes; the playlist only queues neighbors within a series. */
seriesId: string | null;
/** The URL handed to mpv, which mpv reports back as `path` when it starts the entry. */
playbackUrl: string;
/** Per-file mpv options as name/value pairs, applied whenever mpv starts this entry. */
fileOptions: ReadonlyArray<readonly [name: string, value: string]>;
/** Shown in mpv's playlist, which otherwise lists the stream URL and its API key. */
title: string;
};
/**
* How entries get into mpv's playlist with their title and per-file options.
* - `loadfile`: options ride on `loadfile`, and the title is set through `playlist/N/title`,
* which mpv accepts from 0.42.
* - `loadlist`: an in-memory m3u carries the title (`#EXTINF`), which older mpv shows too, and
* the SubMiner mpv plugin applies the options from its `on_load` hook.
*/
export type MpvEntryLoadMode = 'loadfile' | 'loadlist';
/** Set by the mpv plugin when its `on_load` hook applies `ENTRY_OPTIONS_SCRIPT_MESSAGE` options. */
export const PLUGIN_ENTRY_OPTIONS_USER_DATA = 'user-data/subminer/playlist-entry-options';
/** `<path> <name> <value> ...`: per-file options the mpv plugin applies when `path` loads. */
export const ENTRY_OPTIONS_SCRIPT_MESSAGE = 'subminer-playlist-entry-options';
/** Picks `loadlist` only where it is needed (mpv before 0.42) and the plugin can apply options. */
export function chooseMpvEntryLoadMode(
mpvVersion: unknown,
pluginAppliesEntryOptions: boolean,
): MpvEntryLoadMode {
const match = /(\d+)\.(\d+)/.exec(String(mpvVersion ?? ''));
if (!match || !pluginAppliesEntryOptions) return 'loadfile';
const [major, minor] = [Number(match[1]), Number(match[2])];
return major === 0 && minor < 42 ? 'loadlist' : 'loadfile';
}
// mpv's `%<bytes>%value` quoting takes any value verbatim, commas and colons included.
function formatLoadfileOptions(options: JellyfinPlaylistEntry['fileOptions']): string {
return options
.map(([name, value]) =>
/^[\w.-]*$/.test(value)
? `${name}=${value}`
: `${name}=%${Buffer.byteLength(value, 'utf8')}%${value}`,
)
.join(',');
}
type MpvPlaylistPlacement = { kind: 'replace' } | { kind: 'insert-at'; index: number };
/** The mpv commands that load `entry` with its title and options at `placement`. */
export function buildMpvEntryLoadCommands(
entry: JellyfinPlaylistEntry,
mode: MpvEntryLoadMode,
placement: MpvPlaylistPlacement,
): Array<Array<string | number>> {
if (mode === 'loadlist') {
const title = entry.title.replace(/[\r\n]+/g, ' ');
const m3u = `memory://#EXTM3U\n#EXTINF:0,${title}\n${entry.playbackUrl}\n`;
return [
[
'script-message',
ENTRY_OPTIONS_SCRIPT_MESSAGE,
entry.playbackUrl,
...entry.fileOptions.flat(),
],
placement.kind === 'replace'
? ['loadlist', m3u, 'replace']
: ['loadlist', m3u, 'insert-at', placement.index],
];
}
const options = formatLoadfileOptions(entry.fileOptions);
if (placement.kind === 'replace')
return [['loadfile', entry.playbackUrl, 'replace', -1, options]];
return [
['loadfile', entry.playbackUrl, 'insert-at', placement.index, options],
// Sent while the entry is still at that index.
['set_property', `playlist/${placement.index}/title`, entry.title],
];
}
export type JellyfinEpisodePlaylistSettings = {
enabled: boolean;
/** Most entries kept in mpv's playlist, the current one included. Raised to at least 3. */
maxEpisodes: number;
};
/**
* A window of 3 or more always holds the current episode's immediate neighbors (it only shifts
* at a series edge, where that neighbor does not exist). Removals then stay at least two steps
* from the playing entry, so a queue run cannot remove the episode a user just stepped back to.
*/
const MIN_WINDOW_EPISODES = 3;
export type JellyfinQueuedEpisode<Context, Entry> = {
context: Context;
entry: Entry;
};
/** Tells the mpv plugin which playlist entries the app starts itself, so it skips its own startup. */
export const MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE = 'subminer-managed-playlist-entries';
type MpvPlaylistItem = { filename: string; current: boolean };
function parseMpvPlaylist(raw: unknown): MpvPlaylistItem[] {
if (!Array.isArray(raw)) return [];
return raw.map((item: unknown) => {
const record = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
return {
filename: typeof record.filename === 'string' ? record.filename : '',
current: record.current === true,
};
});
}
/**
* Picks up to `maxEpisodes` ids around `currentId`, centered on it (an extra slot goes forward)
* and shifted inward at either end of the series so the window stays full.
*/
export function selectEpisodeWindow(
episodeIds: readonly string[],
currentId: string,
maxEpisodes: number,
): { previousIds: string[]; nextIds: string[] } {
const index = episodeIds.indexOf(currentId);
const size = Math.min(episodeIds.length, Math.max(1, Math.floor(maxEpisodes)));
if (index < 0 || size <= 1) return { previousIds: [], nextIds: [] };
const start = Math.min(Math.max(0, index - Math.floor((size - 1) / 2)), episodeIds.length - size);
return {
previousIds: episodeIds.slice(start, index),
nextIds: episodeIds.slice(index + 1, start + size),
};
}
/**
* Keeps the episodes around the playing Jellyfin item in mpv's playlist, so mpv's own playlist
* navigation (and end-of-file advance) moves through the series. mpv starts those entries by
* itself; `find` lets the playback handler recognize them from mpv's `path`.
*/
export function createJellyfinEpisodePlaylist<Context, Entry extends JellyfinPlaylistEntry>(deps: {
getSettings: () => JellyfinEpisodePlaylistSettings;
listSeriesEpisodeIds: (context: Context, seriesId: string) => Promise<string[]>;
prepareEntry: (context: Context, itemId: string) => Promise<Entry>;
readMpvPlaylist: () => Promise<unknown>;
/** The mode of the explicit playback this playlist follows. */
getEntryLoadMode: () => MpvEntryLoadMode;
sendMpvCommand: (command: Array<string | number>) => void;
logDebug: (message: string, error?: unknown) => void;
}) {
let queued = new Map<string, JellyfinQueuedEpisode<Context, Entry>>();
// Episode order per series, fetched once per explicit playback and reused while navigating.
let seriesEpisodeIds = new Map<string, Promise<string[]>>();
// Bumped by every reset and queue run, so a slow run never edits a playlist that moved on.
let generation = 0;
function getSeriesEpisodeIds(context: Context, seriesId: string): Promise<string[]> {
let ids = seriesEpisodeIds.get(seriesId);
if (!ids) {
ids = deps.listSeriesEpisodeIds(context, seriesId);
seriesEpisodeIds.set(seriesId, ids);
// A failed lookup is retried on the next queue run.
ids.catch(() => seriesEpisodeIds.delete(seriesId));
}
return ids;
}
async function prepareEntries(context: Context, itemIds: string[]): Promise<Map<string, Entry>> {
const prepared = new Map<string, Entry>();
await Promise.all(
itemIds.map((itemId) =>
deps.prepareEntry(context, itemId).then(
(entry) => {
prepared.set(itemId, entry);
},
(error: unknown) => {
deps.logDebug(`Failed to prepare Jellyfin episode ${itemId} for the playlist`, error);
},
),
),
);
return prepared;
}
async function queueNeighbors(context: Context, current: Entry): Promise<void> {
const run = ++generation;
const settings = deps.getSettings();
let windowIds = [current.itemId];
if (settings.enabled && current.seriesId) {
const episodeIds = await getSeriesEpisodeIds(context, current.seriesId);
const window = selectEpisodeWindow(
episodeIds,
current.itemId,
Math.max(MIN_WINDOW_EPISODES, settings.maxEpisodes),
);
windowIds = [...window.previousIds, current.itemId, ...window.nextIds];
}
// Entries already queued stay where they are, so only the missing ones are resolved.
const queuedItemIds = new Set([...queued.values()].map(({ entry }) => entry.itemId));
const prepared = await prepareEntries(
context,
windowIds.filter((itemId) => itemId !== current.itemId && !queuedItemIds.has(itemId)),
);
if (run !== generation) return;
const playlist = parseMpvPlaylist(await deps.readMpvPlaylist());
if (run !== generation) return;
const currentIndex = playlist.findIndex((item) => item.current);
// mpv already left this item, so the run that follows it owns the playlist.
if (playlist[currentIndex]?.filename !== current.playbackUrl) return;
// mpv may have moved on since the read, so this only touches entries outside the window
// and never removes one the user could have just navigated to. `model` mirrors mpv's
// playlist by item id (null for entries the app did not queue) as the commands edit it.
const model = playlist.map((item) =>
item.filename === current.playbackUrl
? current.itemId
: (queued.get(item.filename)?.entry.itemId ?? null),
);
for (let index = model.length - 1; index >= 0; index -= 1) {
const itemId = model[index];
if (itemId === null || itemId === undefined || windowIds.includes(itemId)) continue;
deps.sendMpvCommand(['playlist-remove', index]);
model.splice(index, 1);
}
const nextQueued = new Map<string, JellyfinQueuedEpisode<Context, Entry>>();
for (const queuedEpisode of queued.values()) {
if (model.includes(queuedEpisode.entry.itemId)) {
nextQueued.set(queuedEpisode.entry.playbackUrl, queuedEpisode);
}
}
nextQueued.set(current.playbackUrl, { context, entry: current });
const currentAt = windowIds.indexOf(current.itemId);
const nextIds = windowIds.slice(currentAt + 1);
const previousIds = windowIds.slice(0, currentAt).reverse();
// Every prepared entry is missing from mpv's playlist, so each one gets inserted below.
for (const itemId of [...nextIds, ...previousIds]) {
const entry = prepared.get(itemId);
if (entry) nextQueued.set(entry.playbackUrl, { context, entry });
}
queued = nextQueued;
// Sent before the inserts, so the plugin already knows an entry when mpv starts it.
deps.sendMpvCommand([
'script-message',
MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE,
...queued.keys(),
]);
const mode = deps.getEntryLoadMode();
const insertEntry = (entry: Entry, index: number) => {
for (const command of buildMpvEntryLoadCommands(entry, mode, { kind: 'insert-at', index })) {
deps.sendMpvCommand(command);
}
model.splice(index, 0, entry.itemId);
};
// A `loadlist` entry already has its title from the m3u.
if (mode === 'loadfile') {
deps.sendMpvCommand([
'set_property',
`playlist/${model.indexOf(current.itemId)}/title`,
current.title,
]);
}
// Walk outward from the current entry, inserting each missing episode beside its
// neighbor in the window.
let anchor = model.indexOf(current.itemId);
for (const itemId of nextIds) {
const entry = prepared.get(itemId);
if (model.includes(itemId)) anchor = model.indexOf(itemId);
else if (entry) insertEntry(entry, ++anchor);
}
anchor = model.indexOf(current.itemId);
for (const itemId of previousIds) {
const entry = prepared.get(itemId);
if (model.includes(itemId)) anchor = model.indexOf(itemId);
else if (entry) insertEntry(entry, anchor);
}
}
return {
/** Forgets queued entries and cancels queue runs in flight, for a new explicit playback. */
reset(): void {
generation += 1;
queued = new Map();
seriesEpisodeIds = new Map();
},
/** The queued episode whose playback URL mpv reports as `path`, if any. */
find(path: string): JellyfinQueuedEpisode<Context, Entry> | null {
return queued.get(path) ?? null;
},
/** Fills mpv's playlist with the episodes around `current`, mpv's current entry. */
queueNeighbors: (context: Context, current: Entry): Promise<void> =>
queueNeighbors(context, current).catch((error: unknown) => {
deps.logDebug('Failed to queue adjacent Jellyfin episodes', error);
}),
};
}
@@ -3,6 +3,10 @@ import test from 'node:test';
import type { JellyfinPlaybackPlan } from '../../core/services/jellyfin'; import type { JellyfinPlaybackPlan } from '../../core/services/jellyfin';
import type { JellyfinTimelinePlaybackState } from '../../core/services/jellyfin-playback-reporter'; import type { JellyfinTimelinePlaybackState } from '../../core/services/jellyfin-playback-reporter';
import { createPlayJellyfinItemInMpvHandler } from './jellyfin-playback-launch'; import { createPlayJellyfinItemInMpvHandler } from './jellyfin-playback-launch';
import type {
ActiveJellyfinRemotePlaybackState,
JellyfinPlaybackReporterLike,
} from './jellyfin-remote-commands';
type Deps = Parameters<typeof createPlayJellyfinItemInMpvHandler>[0]; type Deps = Parameters<typeof createPlayJellyfinItemInMpvHandler>[0];
type PlayParams = Parameters<ReturnType<typeof createPlayJellyfinItemInMpvHandler>>[0]; type PlayParams = Parameters<ReturnType<typeof createPlayJellyfinItemInMpvHandler>>[0];
@@ -30,6 +34,7 @@ function makePlan(overrides: Partial<JellyfinPlaybackPlan> = {}): JellyfinPlayba
title: 'Episode 1', title: 'Episode 1',
itemTitle: 'Episode 1', itemTitle: 'Episode 1',
seriesTitle: null, seriesTitle: null,
seriesId: null,
seasonNumber: null, seasonNumber: null,
episodeNumber: null, episodeNumber: null,
startTimeTicks: 0, startTimeTicks: 0,
@@ -49,11 +54,13 @@ function makeHarness(options: { plan?: Partial<JellyfinPlaybackPlan>; deps?: Par
const activeStates: Array<Parameters<Deps['setActivePlayback']>[0]> = []; const activeStates: Array<Parameters<Deps['setActivePlayback']>[0]> = [];
const reports: JellyfinTimelinePlaybackState[] = []; const reports: JellyfinTimelinePlaybackState[] = [];
const reporterParams: Array<Parameters<Deps['createPlaybackReporter']>[0]> = []; const reporterParams: Array<Parameters<Deps['createPlaybackReporter']>[0]> = [];
const reporter = { // A new reporter per playback, as in the app; the handler tells playbacks apart by it.
const reporters: JellyfinPlaybackReporterLike[] = [];
const createReporter = (): JellyfinPlaybackReporterLike => ({
reportPlaying: async (state: JellyfinTimelinePlaybackState) => void reports.push(state), reportPlaying: async (state: JellyfinTimelinePlaybackState) => void reports.push(state),
reportProgress: async () => {}, reportProgress: async () => {},
reportStopped: async () => {}, reportStopped: async () => {},
}; });
const handler = createPlayJellyfinItemInMpvHandler({ const handler = createPlayJellyfinItemInMpvHandler({
ensureMpvConnectedForPlayback: async () => true, ensureMpvConnectedForPlayback: async () => true,
@@ -73,21 +80,33 @@ function makeHarness(options: { plan?: Partial<JellyfinPlaybackPlan>; deps?: Par
activeStates.push(state); activeStates.push(state);
events.push(`active:${String(state.loadedMediaPath)}`); events.push(`active:${String(state.loadedMediaPath)}`);
}, },
getActivePlayback: () => activeStates.at(-1) ?? null,
setLastProgressAtMs: () => {}, setLastProgressAtMs: () => {},
createPlaybackReporter: (params) => { createPlaybackReporter: (params) => {
reporterParams.push(params); reporterParams.push(params);
const reporter = createReporter();
reporters.push(reporter);
return reporter; return reporter;
}, },
reportPlaybackSuperseded: async () => {},
waitForTransitionReports: async () => {},
trackPlaybackStart: () => {},
getEpisodePlaylistSettings: () => ({ enabled: true, maxEpisodes: 3 }),
listSeriesEpisodeIds: async () => [],
readMpvPlaylist: async () => [],
resolveEntryLoadMode: async () => 'loadfile',
showMpvOsd: () => {}, showMpvOsd: () => {},
logDebug: () => {},
...options.deps, ...options.deps,
}); });
return { return {
handler,
commands, commands,
events, events,
activeStates, activeStates,
reports, reports,
reporter, reporters,
reporterParams, reporterParams,
play: (params: Partial<PlayParams> = {}) => play: (params: Partial<PlayParams> = {}) =>
handler({ handler({
@@ -141,19 +160,18 @@ test('playback handler disables mpv subtitle selection, then loads media and rep
['set_property', 'sub-visibility', 'no'], ['set_property', 'sub-visibility', 'no'],
['set_property', 'secondary-sub-visibility', 'no'], ['set_property', 'secondary-sub-visibility', 'no'],
['script-message', 'subminer-managed-subtitles-loading'], ['script-message', 'subminer-managed-subtitles-loading'],
['set_property', 'force-media-title', 'Episode 1'],
[ [
'loadfile', 'loadfile',
'https://stream.example/video.m3u8', 'https://stream.example/video.m3u8',
'replace', 'replace',
-1, -1,
`${SUPPRESSED_SUBTITLE_OPTIONS},start=1.2`, `${SUPPRESSED_SUBTITLE_OPTIONS},start=1.2,force-media-title=%9%Episode 1`,
], ],
]); ]);
assert.equal(harness.activeStates.length, 1); assert.equal(harness.activeStates.length, 1);
assert.equal(harness.activeStates[0]?.playMethod, 'DirectPlay'); assert.equal(harness.activeStates[0]?.playMethod, 'DirectPlay');
assert.equal(harness.activeStates[0]?.lastKnownPositionSeconds, 1.2); assert.equal(harness.activeStates[0]?.lastKnownPositionSeconds, 1.2);
assert.equal(harness.activeStates[0]?.reporter, harness.reporter); assert.equal(harness.activeStates[0]?.reporter, harness.reporters[0]);
assert.deepEqual(harness.reporterParams, [{ session: baseSession, clientInfo: baseClientInfo }]); assert.deepEqual(harness.reporterParams, [{ session: baseSession, clientInfo: baseClientInfo }]);
assert.equal(harness.reports.length, 1); assert.equal(harness.reports.length, 1);
assert.equal(harness.reports[0]?.eventName, 'start'); assert.equal(harness.reports[0]?.eventName, 'start');
@@ -296,12 +314,39 @@ test('playback handler publishes Jellyfin title before loading tokenized stream
const loadIndex = harness.events.indexOf('cmd:loadfile'); const loadIndex = harness.events.indexOf('cmd:loadfile');
assert.ok(titleIndex >= 0); assert.ok(titleIndex >= 0);
assert.ok(titleIndex < loadIndex); assert.ok(titleIndex < loadIndex);
const mpvTitleIndex = harness.commands.findIndex((command) => command[1] === 'force-media-title'); // mpv gets the title as a per-file option, so it never falls back to the URL.
assert.ok( assert.ok(
mpvTitleIndex >= 0 && mpvTitleIndex < harness.commands.findIndex((c) => c[0] === 'loadfile'), String(harness.loadfile()?.[4]).endsWith(
',force-media-title=%30%Galaxy Quest S02E07 A New Hope',
),
); );
}); });
test('playback handler loads a titled m3u when mpv cannot set playlist titles', async () => {
const harness = makeHarness({
plan: { startTimeTicks: 12_000_000 },
deps: { resolveEntryLoadMode: async () => 'loadlist' },
});
await harness.play();
assert.equal(harness.loadfile(), undefined);
assert.deepEqual(harness.commands.slice(-2), [
[
'script-message',
'subminer-playlist-entry-options',
'https://stream.example/video.m3u8',
...['sid', 'no', 'secondary-sid', 'no', 'sub-auto', 'no', 'sub-visibility', 'no'],
...['secondary-sub-visibility', 'no', 'start', '1.2', 'force-media-title', 'Episode 1'],
],
[
'loadlist',
'memory://#EXTM3U\n#EXTINF:0,Episode 1\nhttps://stream.example/video.m3u8\n',
'replace',
],
]);
});
test('playback handler arms unloaded active playback before loading mpv media', async () => { test('playback handler arms unloaded active playback before loading mpv media', async () => {
const harness = makeHarness(); const harness = makeHarness();
@@ -355,7 +400,217 @@ for (const c of HOOK_FAILURE_CASES) {
'https://stream.example/video.m3u8', 'https://stream.example/video.m3u8',
'replace', 'replace',
-1, -1,
SUPPRESSED_SUBTITLE_OPTIONS, `${SUPPRESSED_SUBTITLE_OPTIONS},force-media-title=%9%Episode 1`,
]); ]);
}); });
} }
/**
* A series of three episodes where `item-1` plays first. mpv's playlist and the active playback
* follow the commands the handler sends, the way mpv and the Jellyfin assembly would.
*/
function makeSeriesHarness() {
const streamUrl = (itemId: string) => `https://jf.example/Videos/${itemId}/stream`;
const playlist: Array<{ filename: string; current: boolean }> = [];
const statsMetadata: Array<{ itemId: string }> = [];
const superseded: string[] = [];
const startsTracked: string[] = [];
let active: ActiveJellyfinRemotePlaybackState | null = null;
// Stop reports in flight, from the superseded handler or `startGenericStop`.
const stopsInFlight = new Set<Promise<void>>();
const pendingSupersededStops: Array<() => void> = [];
const trackStop = () => {
let release = () => {};
const stop = new Promise<void>((resolve) => {
release = resolve;
});
stopsInFlight.add(stop);
void stop.then(() => stopsInFlight.delete(stop));
pendingSupersededStops.push(release);
return stop;
};
const harness = makeHarness({
deps: {
resolvePlaybackPlan: async ({ itemId }) =>
makePlan({
url: streamUrl(itemId),
title: `${itemId}: 前編, 1`,
seriesId: 'series-1',
}),
listSeriesEpisodeIds: async () => ['item-0', 'item-1', 'item-2'],
readMpvPlaylist: async () => playlist.map((item) => ({ ...item })),
getActivePlayback: () => active,
setActivePlayback: (state) => {
active = { ...state };
},
reportPlaybackSuperseded: (playback) => {
superseded.push(playback.itemId);
return trackStop();
},
trackPlaybackStart: (_report, playback) => void startsTracked.push(playback.itemId),
waitForTransitionReports: async () => {
while (stopsInFlight.size > 0) await Promise.all([...stopsInFlight]);
},
recordJellyfinPlaybackMetadata: (metadata) => void statsMetadata.push(metadata),
},
});
const sendMpvCommand = harness.commands.push.bind(harness.commands);
harness.commands.push = (...commands) => {
for (const command of commands) {
if (command[0] === 'loadfile' && command[2] === 'replace') {
playlist.splice(0, playlist.length, { filename: String(command[1]), current: true });
} else if (command[0] === 'loadfile') {
playlist.splice(Number(command[3]), 0, { filename: String(command[1]), current: false });
}
}
return sendMpvCommand(...commands);
};
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
return {
...harness,
streamUrl,
playlist,
statsMetadata,
superseded,
startsTracked,
active: () => active,
// Completes the oldest stop report still in flight.
releaseSupersededStop: () => pendingSupersededStops.shift()?.(),
// The generic stop handler, run when mpv reports an empty path between files: it clears
// the active playback and reports its stop on its own.
startGenericStop: () => {
active = null;
void trackStop();
},
// What the Jellyfin assembly does with each new mpv path.
mpvPathChanged: (path: string) => {
if (harness.handler.adoptQueuedEpisode(path)) return;
if (active) active.loadedMediaPath = path;
},
flush,
};
}
test('playback handler queues neighbor episodes only once mpv plays the item', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.handler.handlePlaybackTimePos();
await harness.flush();
assert.equal(harness.playlist.length, 1, 'nothing is queued before mpv reports the item');
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
assert.deepEqual(
harness.playlist.map((item) => item.filename),
[harness.streamUrl('item-0'), harness.streamUrl('item-1'), harness.streamUrl('item-2')],
);
const queuedNext = harness.commands.find(
(command) => command[0] === 'loadfile' && command[1] === harness.streamUrl('item-2'),
);
assert.deepEqual(queuedNext, [
'loadfile',
harness.streamUrl('item-2'),
'insert-at',
1,
`${SUPPRESSED_SUBTITLE_OPTIONS},force-media-title=%17%item-2: 前編, 1`,
]);
});
test('playback handler takes over a queued episode mpv starts from its playlist', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
const commandsBefore = harness.commands.length;
harness.mpvPathChanged(harness.streamUrl('item-2'));
// Synchronous, so the immersion tracker that runs next already sees the episode's metadata.
assert.deepEqual(
harness.statsMetadata.map((metadata) => metadata.itemId),
['item-1', 'item-2'],
);
assert.equal(harness.active()?.itemId, 'item-2');
assert.equal(harness.active()?.loadedMediaPath, harness.streamUrl('item-2'));
assert.equal(
harness.commands.slice(commandsBefore).some((command) => command[2] === 'replace'),
false,
'mpv already loads the entry, so the handler must not load it again',
);
await harness.flush();
assert.deepEqual(harness.superseded, ['item-1']);
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1'],
'the new start waits for the previous stop',
);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1', 'item-2'],
);
assert.deepEqual(harness.startsTracked, ['item-1', 'item-2'], 'each start is tracked');
assert.equal(harness.handler.adoptQueuedEpisode(harness.streamUrl('item-2')), false);
assert.equal(harness.handler.adoptQueuedEpisode('https://elsewhere.example/video.mkv'), false);
});
test('playback handler starts an episode only after every stop in flight and skips switched-away ones', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
harness.mpvPathChanged(harness.streamUrl('item-2'));
harness.mpvPathChanged(harness.streamUrl('item-1'));
await harness.flush();
assert.deepEqual(harness.superseded, ['item-1', 'item-2']);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1'],
'the start waits for the stop still in flight',
);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1', 'item-1'],
'the skipped-over episode never reports playing; the one mpv returned to does',
);
});
test('playback handler waits for a stop the empty path between files triggered', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
// Past the startup grace, mpv's empty path stops item-1 before item-2's path arrives.
harness.startGenericStop();
harness.mpvPathChanged(harness.streamUrl('item-2'));
await harness.flush();
assert.deepEqual(harness.superseded, [], 'nothing was active to supersede');
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1'],
);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1', 'item-2'],
);
});
+297 -88
View File
@@ -1,7 +1,17 @@
import type { JellyfinAuthSession, JellyfinPlaybackPlan } from '../../core/services/jellyfin'; import type { JellyfinAuthSession, JellyfinPlaybackPlan } from '../../core/services/jellyfin';
import type { JellyfinConfig } from '../../types'; import type { JellyfinConfig } from '../../types';
import type { MpvRuntimeClientLike } from '../../core/services/mpv'; import type { MpvRuntimeClientLike } from '../../core/services/mpv';
import type { JellyfinPlaybackReporterLike } from './jellyfin-remote-commands'; import {
buildMpvEntryLoadCommands,
createJellyfinEpisodePlaylist,
type JellyfinEpisodePlaylistSettings,
type JellyfinPlaylistEntry,
type MpvEntryLoadMode,
} from './jellyfin-episode-playlist';
import type {
ActiveJellyfinRemotePlaybackState,
JellyfinPlaybackReporterLike,
} from './jellyfin-remote-commands';
type JellyfinClientInfo = { type JellyfinClientInfo = {
clientName: string; clientName: string;
@@ -9,6 +19,12 @@ type JellyfinClientInfo = {
deviceId: string; deviceId: string;
}; };
type JellyfinPlaybackContext = {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
jellyfinConfig: JellyfinConfig;
};
type ActivePlaybackState = { type ActivePlaybackState = {
itemId: string; itemId: string;
reporter: JellyfinPlaybackReporterLike; reporter: JellyfinPlaybackReporterLike;
@@ -31,13 +47,13 @@ export type JellyfinPlaybackStatsMetadata = {
itemId: string; itemId: string;
}; };
const JELLYFIN_LOADFILE_SUBTITLE_SUPPRESSION_OPTIONS = [ const JELLYFIN_SUBTITLE_SUPPRESSION_OPTIONS = [
'sid=no', ['sid', 'no'],
'secondary-sid=no', ['secondary-sid', 'no'],
'sub-auto=no', ['sub-auto', 'no'],
'sub-visibility=no', ['sub-visibility', 'no'],
'secondary-sub-visibility=no', ['secondary-sub-visibility', 'no'],
]; ] as const;
function runBestEffortPlaybackHook(callback: () => void | Promise<void>): void { function runBestEffortPlaybackHook(callback: () => void | Promise<void>): void {
try { try {
@@ -104,14 +120,91 @@ function resolveEffectiveStartTimeTicks(
return Math.max(0, planStartTimeTicks); return Math.max(0, planStartTimeTicks);
} }
function buildJellyfinLoadfileOptions(plan: JellyfinPlaybackPlan, startSeconds: number): string { /** A resolved Jellyfin item in the form mpv loads it. */
const options = [...JELLYFIN_LOADFILE_SUBTITLE_SUPPRESSION_OPTIONS]; type JellyfinPreparedPlayback = {
if (plan.mode === 'direct' && startSeconds > 0) { itemId: string;
options.push(`start=${startSeconds}`); seriesId: string | null;
} title: string;
return options.join(','); plan: JellyfinPlaybackPlan;
playbackUrl: string;
fileOptions: JellyfinPlaylistEntry['fileOptions'];
startTimeTicks: number;
startSeconds: number;
playMethod: 'DirectPlay' | 'Transcode';
};
// The title is a per-file option, so mpv never shows the tokenized stream URL as the title, and
// no global title is left behind for the next playlist entry to fall back to.
function buildJellyfinFileOptions(
plan: JellyfinPlaybackPlan,
startSeconds: number,
): JellyfinPlaylistEntry['fileOptions'] {
return [
...JELLYFIN_SUBTITLE_SUPPRESSION_OPTIONS,
...(plan.mode === 'direct' && startSeconds > 0
? [['start', String(startSeconds)] as const]
: []),
['force-media-title', plan.title],
];
} }
function prepareJellyfinPlayback(
itemId: string,
plan: JellyfinPlaybackPlan,
convertTicksToSeconds: (ticks: number) => number,
options: {
startTimeTicksOverride?: number;
fallbackToPlanStartTimeOnZeroOverride?: boolean;
} = {},
): JellyfinPreparedPlayback {
const startTimeTicks = resolveEffectiveStartTimeTicks(
plan.startTimeTicks,
options.startTimeTicksOverride,
options.fallbackToPlanStartTimeOnZeroOverride,
);
const startSeconds = startTimeTicks > 0 ? Math.max(0, convertTicksToSeconds(startTimeTicks)) : 0;
const playbackUrlBase =
plan.mode === 'direct'
? stripStartTimeTicksFromPlaybackUrl(plan.url)
: applyStartTimeTicksToPlaybackUrl(plan.url, startTimeTicks);
return {
itemId,
seriesId: plan.seriesId,
title: plan.title,
plan,
playbackUrl: stripManagedSubtitleStreamFromPlaybackUrl(playbackUrlBase),
fileOptions: buildJellyfinFileOptions(plan, startSeconds),
startTimeTicks,
startSeconds,
playMethod: plan.mode === 'direct' ? 'DirectPlay' : 'Transcode',
};
}
export type PlayJellyfinItemInMpvHandler = ((params: {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
jellyfinConfig: JellyfinConfig;
itemId: string;
audioStreamIndex?: number | null;
subtitleStreamIndex?: number | null;
startTimeTicksOverride?: number;
fallbackToPlanStartTimeOnZeroOverride?: boolean;
setQuitOnDisconnectArm?: boolean;
}) => Promise<void>) & {
/**
* Takes over a queued neighbor episode that mpv started from its playlist, given mpv's new
* `path`. Returns false when the path is not one, or is already the active playback. Runs
* synchronously up to recording stats metadata, so call it before the immersion tracker sees
* the path.
*/
adoptQueuedEpisode: (path: string) => boolean;
/**
* Called on mpv time-pos updates. The first one for a just-started item queues its neighbor
* episodes, so that work never competes with opening the stream.
*/
handlePlaybackTimePos: () => void;
};
export function createPlayJellyfinItemInMpvHandler(deps: { export function createPlayJellyfinItemInMpvHandler(deps: {
ensureMpvConnectedForPlayback: () => Promise<boolean>; ensureMpvConnectedForPlayback: () => Promise<boolean>;
getMpvClient: () => MpvRuntimeClientLike | null; getMpvClient: () => MpvRuntimeClientLike | null;
@@ -134,6 +227,7 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
clientInfo: JellyfinClientInfo; clientInfo: JellyfinClientInfo;
itemId: string; itemId: string;
}) => void | Promise<void>; }) => void | Promise<void>;
getActivePlayback: () => ActiveJellyfinRemotePlaybackState | null;
setActivePlayback: (state: ActivePlaybackState) => void; setActivePlayback: (state: ActivePlaybackState) => void;
setLastProgressAtMs: (value: number) => void; setLastProgressAtMs: (value: number) => void;
// Reports go out as the device and account that started this playback, for CLI play and // Reports go out as the device and account that started this playback, for CLI play and
@@ -142,23 +236,146 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
session: JellyfinAuthSession; session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo; clientInfo: JellyfinClientInfo;
}) => JellyfinPlaybackReporterLike; }) => JellyfinPlaybackReporterLike;
/** Reports the stop of a playback mpv left for a queued neighbor episode. */
reportPlaybackSuperseded: (playback: ActiveJellyfinRemotePlaybackState) => Promise<void>;
/** Resolves once no Jellyfin episode start or stop report is in flight, whoever sent it. */
waitForTransitionReports: () => Promise<void>;
/** Tracks a start report, so the playback's own stop and later starts wait for it. */
trackPlaybackStart: (report: Promise<void>, playback: ActiveJellyfinRemotePlaybackState) => void;
/** Read on every queue run, so edits apply from the next episode change. */
getEpisodePlaylistSettings: () => JellyfinEpisodePlaylistSettings;
listSeriesEpisodeIds: (params: {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
seriesId: string;
}) => Promise<string[]>;
readMpvPlaylist: () => Promise<unknown>;
/** Asked once per explicit playback; its episode playlist keeps that mode. */
resolveEntryLoadMode: () => Promise<MpvEntryLoadMode>;
showMpvOsd: (text: string) => void; showMpvOsd: (text: string) => void;
recordJellyfinPlaybackMetadata?: ( recordJellyfinPlaybackMetadata?: (
metadata: JellyfinPlaybackStatsMetadata, metadata: JellyfinPlaybackStatsMetadata,
) => void | Promise<void>; ) => void | Promise<void>;
updateCurrentMediaTitle?: (title: string) => void | Promise<void>; updateCurrentMediaTitle?: (title: string) => void | Promise<void>;
}) { logDebug: (message: string, error?: unknown) => void;
return async (params: { }): PlayJellyfinItemInMpvHandler {
session: JellyfinAuthSession; let entryLoadMode: MpvEntryLoadMode = 'loadfile';
clientInfo: JellyfinClientInfo; const episodePlaylist = createJellyfinEpisodePlaylist<
jellyfinConfig: JellyfinConfig; JellyfinPlaybackContext,
itemId: string; JellyfinPreparedPlayback
audioStreamIndex?: number | null; >({
subtitleStreamIndex?: number | null; getSettings: () => deps.getEpisodePlaylistSettings(),
startTimeTicksOverride?: number; listSeriesEpisodeIds: (context, seriesId) =>
fallbackToPlanStartTimeOnZeroOverride?: boolean; deps.listSeriesEpisodeIds({
setQuitOnDisconnectArm?: boolean; session: context.session,
}): Promise<void> => { clientInfo: context.clientInfo,
seriesId,
}),
prepareEntry: async (context, itemId) =>
prepareJellyfinPlayback(
itemId,
await deps.resolvePlaybackPlan({ ...context, itemId }),
deps.convertTicksToSeconds,
),
readMpvPlaylist: () => deps.readMpvPlaylist(),
getEntryLoadMode: () => entryLoadMode,
sendMpvCommand: (command) => deps.sendMpvCommand(command),
logDebug: (message, error) => deps.logDebug(message, error),
});
// Records stats metadata and makes `prepared` the active playback. Synchronous, so a caller
// reacting to mpv's path change finishes it before the immersion tracker sees that path.
const beginPlayback = (
context: JellyfinPlaybackContext,
prepared: JellyfinPreparedPlayback,
loadedMediaPath: string | null,
): JellyfinPlaybackReporterLike => {
const { plan } = prepared;
runBestEffortPlaybackHook(() => deps.updateCurrentMediaTitle?.(plan.title));
runBestEffortPlaybackHook(() =>
deps.recordJellyfinPlaybackMetadata?.({
mediaPath: prepared.playbackUrl,
displayTitle: plan.title,
itemTitle: plan.itemTitle,
seriesTitle: plan.seriesTitle,
seasonNumber: plan.seasonNumber,
episodeNumber: plan.episodeNumber,
itemId: prepared.itemId,
}),
);
const reporter = deps.createPlaybackReporter({
session: context.session,
clientInfo: context.clientInfo,
});
deps.setActivePlayback({
itemId: prepared.itemId,
reporter,
mediaSourceId: undefined,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
playMethod: prepared.playMethod,
loadedMediaPath,
lastKnownPositionSeconds: prepared.startSeconds > 0 ? prepared.startSeconds : undefined,
});
deps.setLastProgressAtMs(0);
return reporter;
};
// The item whose neighbors get queued once mpv reports it playing.
let pendingNeighborQueue: {
context: JellyfinPlaybackContext;
prepared: JellyfinPreparedPlayback;
} | null = null;
// Runs once mpv has the item: subtitles, overlay, and the Jellyfin start report. Its
// neighbors are queued later, from the first time-pos update.
const finishPlaybackStartup = async (
context: JellyfinPlaybackContext,
prepared: JellyfinPreparedPlayback,
reporter: JellyfinPlaybackReporterLike,
): Promise<void> => {
const { plan } = prepared;
// Each start makes a new reporter, so it identifies this playback even when the same
// episode comes back. A later switch that took over does its own reporting.
const ownsPlayback = () => deps.getActivePlayback()?.reporter === reporter;
await awaitBestEffortPlaybackHook(() =>
deps.preloadExternalSubtitles({
session: context.session,
clientInfo: context.clientInfo,
itemId: prepared.itemId,
}),
);
if (!ownsPlayback()) return;
deps.showVisibleOverlay();
pendingNeighborQueue = { context, prepared };
// Jellyfin clears a session's now-playing item on any stop and keeps whichever start lands
// last, so this start waits for every start and stop in flight, including the generic stop
// mpv's empty path between files can trigger.
await deps.waitForTransitionReports();
const playback = deps.getActivePlayback();
if (playback?.reporter !== reporter) return;
const started = reporter.reportPlaying({
itemId: prepared.itemId,
mediaSourceId: undefined,
playMethod: prepared.playMethod,
positionTicks: prepared.startTimeTicks,
isPaused: false,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
eventName: 'start',
});
deps.trackPlaybackStart(
started.then(
() => undefined,
(error: unknown) => deps.logDebug('Failed to report Jellyfin playback start', error),
),
playback,
);
deps.showMpvOsd(`Jellyfin ${plan.mode}: ${plan.title}`);
};
const play = async (params: Parameters<PlayJellyfinItemInMpvHandler>[0]): Promise<void> => {
const connected = await deps.ensureMpvConnectedForPlayback(); const connected = await deps.ensureMpvConnectedForPlayback();
const mpvClient = deps.getMpvClient(); const mpvClient = deps.getMpvClient();
if (!connected || !mpvClient) { if (!connected || !mpvClient) {
@@ -176,80 +393,72 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
subtitleStreamIndex: params.subtitleStreamIndex, subtitleStreamIndex: params.subtitleStreamIndex,
}); });
entryLoadMode = await deps.resolveEntryLoadMode().catch((error: unknown) => {
deps.logDebug('Failed to detect how mpv takes playlist titles', error);
return 'loadfile' as const;
});
deps.applyJellyfinMpvDefaults(mpvClient); deps.applyJellyfinMpvDefaults(mpvClient);
deps.sendMpvCommand(['set_property', 'sub-auto', 'no']); deps.sendMpvCommand(['set_property', 'sub-auto', 'no']);
deps.sendMpvCommand(['set_property', 'sid', 'no']); deps.sendMpvCommand(['set_property', 'sid', 'no']);
deps.sendMpvCommand(['set_property', 'secondary-sid', 'no']); deps.sendMpvCommand(['set_property', 'secondary-sid', 'no']);
deps.sendMpvCommand(['set_property', 'sub-visibility', 'no']); deps.sendMpvCommand(['set_property', 'sub-visibility', 'no']);
deps.sendMpvCommand(['set_property', 'secondary-sub-visibility', 'no']); deps.sendMpvCommand(['set_property', 'secondary-sub-visibility', 'no']);
const startTimeTicks = resolveEffectiveStartTimeTicks( const prepared = prepareJellyfinPlayback(params.itemId, plan, deps.convertTicksToSeconds, {
plan.startTimeTicks, startTimeTicksOverride: params.startTimeTicksOverride,
params.startTimeTicksOverride, fallbackToPlanStartTimeOnZeroOverride: params.fallbackToPlanStartTimeOnZeroOverride,
params.fallbackToPlanStartTimeOnZeroOverride, });
); const context: JellyfinPlaybackContext = {
const startSeconds =
startTimeTicks > 0 ? Math.max(0, deps.convertTicksToSeconds(startTimeTicks)) : 0;
const playbackUrlBase =
plan.mode === 'direct'
? stripStartTimeTicksFromPlaybackUrl(plan.url)
: applyStartTimeTicksToPlaybackUrl(plan.url, startTimeTicks);
const playbackUrl = stripManagedSubtitleStreamFromPlaybackUrl(playbackUrlBase);
const loadfileOptions = buildJellyfinLoadfileOptions(plan, startSeconds);
const playMethod = plan.mode === 'direct' ? 'DirectPlay' : 'Transcode';
runBestEffortPlaybackHook(() => deps.updateCurrentMediaTitle?.(plan.title));
runBestEffortPlaybackHook(() =>
deps.recordJellyfinPlaybackMetadata?.({
mediaPath: playbackUrl,
displayTitle: plan.title,
itemTitle: plan.itemTitle,
seriesTitle: plan.seriesTitle,
seasonNumber: plan.seasonNumber,
episodeNumber: plan.episodeNumber,
itemId: params.itemId,
}),
);
const reporter = deps.createPlaybackReporter({
session: params.session, session: params.session,
clientInfo: params.clientInfo, clientInfo: params.clientInfo,
}); jellyfinConfig: params.jellyfinConfig,
deps.setActivePlayback({ };
itemId: params.itemId, // Replacing mpv's playlist takes the old neighbors with it.
reporter, episodePlaylist.reset();
mediaSourceId: undefined, pendingNeighborQueue = null;
audioStreamIndex: plan.audioStreamIndex, const reporter = beginPlayback(context, prepared, null);
subtitleStreamIndex: plan.subtitleStreamIndex,
playMethod,
loadedMediaPath: null,
lastKnownPositionSeconds: startSeconds > 0 ? startSeconds : undefined,
});
deps.setLastProgressAtMs(0);
deps.sendMpvCommand(['script-message', 'subminer-managed-subtitles-loading']); deps.sendMpvCommand(['script-message', 'subminer-managed-subtitles-loading']);
// Set mpv's title before loadfile can emit a URL-derived media-title event. for (const command of buildMpvEntryLoadCommands(prepared, entryLoadMode, { kind: 'replace' })) {
deps.sendMpvCommand(['set_property', 'force-media-title', plan.title]); deps.sendMpvCommand(command);
deps.sendMpvCommand(['loadfile', playbackUrl, 'replace', -1, loadfileOptions]); }
if (params.setQuitOnDisconnectArm !== false) { if (params.setQuitOnDisconnectArm !== false) {
deps.armQuitOnDisconnect(); deps.armQuitOnDisconnect();
} }
await awaitBestEffortPlaybackHook(() => await finishPlaybackStartup(context, prepared, reporter);
deps.preloadExternalSubtitles({
session: params.session,
clientInfo: params.clientInfo,
itemId: params.itemId,
}),
);
deps.showVisibleOverlay();
void reporter.reportPlaying({
itemId: params.itemId,
mediaSourceId: undefined,
playMethod,
positionTicks: startTimeTicks,
isPaused: false,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
eventName: 'start',
});
deps.showMpvOsd(`Jellyfin ${plan.mode}: ${plan.title}`);
}; };
const adoptQueuedEpisode = (path: string): boolean => {
const queued = episodePlaylist.find(path);
if (!queued) return false;
const previous = deps.getActivePlayback();
if (previous?.itemId === queued.entry.itemId) return false;
const reporter = beginPlayback(queued.context, queued.entry, path);
if (previous) {
void deps.reportPlaybackSuperseded(previous).catch((error: unknown) => {
deps.logDebug('Failed to report the previous Jellyfin episode stopped', error);
});
}
void finishPlaybackStartup(queued.context, queued.entry, reporter).catch((error: unknown) => {
deps.logDebug('Failed to start the queued Jellyfin episode', error);
});
return true;
};
const handlePlaybackTimePos = (): void => {
const pending = pendingNeighborQueue;
if (!pending) return;
const active = deps.getActivePlayback();
// time-pos can still belong to the file mpv is leaving until it reports the new path.
if (
active?.itemId !== pending.prepared.itemId ||
active.loadedMediaPath !== pending.prepared.playbackUrl
) {
return;
}
pendingNeighborQueue = null;
void episodePlaylist.queueNeighbors(pending.context, pending.prepared);
};
return Object.assign(play, { adoptQueuedEpisode, handlePlaybackTimePos });
} }
@@ -5,6 +5,7 @@ import {
createJellyfinRemoteReportTracker, createJellyfinRemoteReportTracker,
createReportJellyfinRemoteProgressHandler, createReportJellyfinRemoteProgressHandler,
createReportJellyfinRemoteStoppedHandler, createReportJellyfinRemoteStoppedHandler,
createReportSupersededJellyfinPlaybackHandler,
secondsToJellyfinTicks, secondsToJellyfinTicks,
shouldAutoLoadSecondarySubTrackForJellyfinPlayback, shouldAutoLoadSecondarySubTrackForJellyfinPlayback,
} from './jellyfin-remote-playback'; } from './jellyfin-remote-playback';
@@ -233,6 +234,7 @@ test('createReportJellyfinRemoteStoppedHandler reports stop and clears playback'
makePlayback({ makePlayback({
itemId: 'item-2', itemId: 'item-2',
playMethod: 'Transcode', playMethod: 'Transcode',
loadedMediaPath: 'https://stream.example/item-2.m3u8',
reporter: makeReporter({ reporter: makeReporter({
reportStopped: async (payload) => { reportStopped: async (payload) => {
stoppedPayload = { stoppedPayload = {
@@ -248,6 +250,7 @@ test('createReportJellyfinRemoteStoppedHandler reports stop and clears playback'
}, },
getMpvClient: () => ({ getMpvClient: () => ({
currentTimePos: 12.5, currentTimePos: 12.5,
currentVideoPath: 'https://stream.example/item-2.m3u8',
requestProperty: async () => { requestProperty: async () => {
throw new Error('unloaded'); throw new Error('unloaded');
}, },
@@ -264,6 +267,33 @@ test('createReportJellyfinRemoteStoppedHandler reports stop and clears playback'
assert.equal(cleared, true); assert.equal(cleared, true);
}); });
test('createReportJellyfinRemoteStoppedHandler ignores the position of a file mpv moved on to', async () => {
let stoppedTicks: number | undefined;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
makeStoppedDeps({
getActivePlayback: () =>
makePlayback({
itemId: 'item-1',
loadedMediaPath: 'https://stream.example/item-1.m3u8',
lastKnownPositionSeconds: 1410,
reporter: makeReporter({
reportStopped: async (payload) => {
stoppedTicks = payload.positionTicks;
},
}),
}),
getMpvClient: () => ({
currentTimePos: 42,
currentVideoPath: 'https://stream.example/item-2.m3u8',
}),
}),
);
await reportStopped();
assert.equal(stoppedTicks, 14_100_000_000);
});
test('createReportJellyfinRemoteStoppedHandler clears aborted playback that never loaded', async () => { test('createReportJellyfinRemoteStoppedHandler clears aborted playback that never loaded', async () => {
let cleared = false; let cleared = false;
const reportStopped = createReportJellyfinRemoteStoppedHandler( const reportStopped = createReportJellyfinRemoteStoppedHandler(
@@ -289,6 +319,32 @@ test('createReportJellyfinRemoteStoppedHandler clears aborted playback that neve
assert.equal(cleared, true); assert.equal(cleared, true);
}); });
test('createReportJellyfinRemoteStoppedHandler keeps unloaded playback armed while the previous file unloads', async () => {
let cleared = false;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
makeStoppedDeps({
getActivePlayback: () =>
makePlayback({
loadedMediaPath: null,
stopReportsAfterMs: 10_000,
reporter: makeReporter({
reportStopped: async () => {
throw new Error('should not report stopped for unloaded media');
},
}),
}),
clearActivePlayback: () => {
cleared = true;
},
getNow: () => 5_000,
}),
);
await reportStopped();
assert.equal(cleared, false);
});
test('createReportJellyfinRemoteStoppedHandler uses cached position after mpv unload reset', async () => { test('createReportJellyfinRemoteStoppedHandler uses cached position after mpv unload reset', async () => {
let cleared = false; let cleared = false;
const calls: Array<{ event: string; positionTicks?: number }> = []; const calls: Array<{ event: string; positionTicks?: number }> = [];
@@ -445,3 +501,68 @@ test('createReportJellyfinRemoteStoppedHandler clears playback before reporting
'stopped:cleared', 'stopped:cleared',
]); ]);
}); });
test('createReportSupersededJellyfinPlaybackHandler waits only for the superseded playback reports', async () => {
const events: string[] = [];
const tracker = createJellyfinRemoteReportTracker();
const superseded = makePlayback({
itemId: 'item-1',
lastKnownPositionSeconds: 1410,
reporter: makeReporter({
reportStopped: async (payload) => {
events.push(`stopped:${payload.itemId}@${payload.positionTicks}`);
},
}),
});
let finishOldProgress = () => {};
tracker.track(
new Promise<void>((resolve) => {
finishOldProgress = () => {
events.push('old progress done');
resolve();
};
}),
superseded,
);
// The new episode's progress stays in flight for the whole test.
tracker.track(new Promise<void>(() => {}), makePlayback({ itemId: 'item-2' }));
const reportSuperseded = createReportSupersededJellyfinPlaybackHandler({
ticksPerSecond: TICKS_PER_SECOND,
logDebug: () => {},
reportTracker: tracker,
});
const reported = reportSuperseded(superseded);
await Promise.resolve();
assert.deepEqual(events, [], 'the stop waits for its own progress already in flight');
finishOldProgress();
await reported;
assert.deepEqual(events, ['old progress done', 'stopped:item-1@14100000000']);
});
test('createReportJellyfinRemoteStoppedHandler is not held by reports for another playback', async () => {
const tracker = createJellyfinRemoteReportTracker();
// The next episode's progress stays in flight for the whole test.
tracker.track(new Promise<void>(() => {}), makePlayback({ itemId: 'item-2' }));
let stopped = false;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
makeStoppedDeps({
getActivePlayback: () =>
makePlayback({
loadedMediaPath: 'https://stream.example/item-1.m3u8',
lastKnownPositionSeconds: 30,
reporter: makeReporter({
reportStopped: async () => {
stopped = true;
},
}),
}),
reportTracker: tracker,
}),
);
await reportStopped();
assert.equal(stopped, true);
});
+86 -35
View File
@@ -2,6 +2,7 @@ import type { ActiveJellyfinRemotePlaybackState } from './jellyfin-remote-comman
type MpvClientLike = { type MpvClientLike = {
currentTimePos?: number; currentTimePos?: number;
currentVideoPath?: string;
requestProperty?: (name: string) => Promise<unknown>; requestProperty?: (name: string) => Promise<unknown>;
}; };
@@ -112,22 +113,26 @@ function isSeekLikePositionJump(
// Jellyfin re-creates a session's NowPlayingItem from any progress report, so a progress // Jellyfin re-creates a session's NowPlayingItem from any progress report, so a progress
// tick that lands after the stop report leaves the server showing playback forever. The // tick that lands after the stop report leaves the server showing playback forever. The
// tracker lets the stop handler wait for reports that are already in flight. // tracker lets the stop handler wait for reports that are already in flight. Each report is
// tagged with the playback it describes, so stopping one playback can skip another's reports.
export type JellyfinRemoteReportTracker = { export type JellyfinRemoteReportTracker = {
track: (report: Promise<void>) => void; track: (report: Promise<void>, playback: ActiveJellyfinRemotePlaybackState | null) => void;
settled: () => Promise<void>; /** Waits for in-flight reports: every one, or only those tagged with `playback`. */
settled: (playback?: ActiveJellyfinRemotePlaybackState) => Promise<void>;
}; };
export function createJellyfinRemoteReportTracker(): JellyfinRemoteReportTracker { export function createJellyfinRemoteReportTracker(): JellyfinRemoteReportTracker {
const active = new Set<Promise<void>>(); const active = new Map<Promise<void>, ActiveJellyfinRemotePlaybackState | null>();
const pending = (playback?: ActiveJellyfinRemotePlaybackState) =>
[...active].filter(([, owner]) => !playback || owner === playback).map(([report]) => report);
return { return {
track: (report) => { track: (report, playback) => {
active.add(report); active.set(report, playback);
void report.finally(() => active.delete(report)); void report.finally(() => active.delete(report));
}, },
settled: async () => { settled: async (playback) => {
while (active.size > 0) { for (let reports = pending(playback); reports.length > 0; reports = pending(playback)) {
await Promise.allSettled([...active]); await Promise.allSettled(reports);
} }
}, },
}; };
@@ -151,8 +156,10 @@ export function createReportJellyfinRemoteProgressHandler(
) { ) {
let lastReportedPositionSeconds: number | null = null; let lastReportedPositionSeconds: number | null = null;
const report = async (force: boolean): Promise<void> => { const report = async (
const playback = deps.getActivePlayback(); playback: ActiveJellyfinRemotePlaybackState | null,
force: boolean,
): Promise<void> => {
if (!playback) return; if (!playback) return;
const now = deps.getNow(); const now = deps.getNow();
try { try {
@@ -191,8 +198,9 @@ export function createReportJellyfinRemoteProgressHandler(
}; };
return async (force = false): Promise<void> => { return async (force = false): Promise<void> => {
const pending = report(force); const playback = deps.getActivePlayback();
deps.reportTracker?.track(pending); const pending = report(playback, force);
deps.reportTracker?.track(pending, playback);
await pending; await pending;
}; };
} }
@@ -208,28 +216,17 @@ export type JellyfinRemoteStoppedReporterDeps = {
reportTracker?: JellyfinRemoteReportTracker; reportTracker?: JellyfinRemoteReportTracker;
}; };
export function createReportJellyfinRemoteStoppedHandler(deps: JellyfinRemoteStoppedReporterDeps) { type JellyfinStopReportDeps = {
return async (): Promise<void> => { ticksPerSecond: number;
const playback = deps.getActivePlayback(); logDebug: (message: string, error: unknown) => void;
if (!playback) return; logWarn?: (message: string) => void;
if (playback.loadedMediaPath === null) { };
deps.clearActivePlayback();
return; async function sendJellyfinStopReports(
} deps: JellyfinStopReportDeps,
if ( playback: ActiveJellyfinRemotePlaybackState,
typeof playback.stopReportsAfterMs === 'number' && positionSeconds: number,
Number.isFinite(playback.stopReportsAfterMs) && ): Promise<void> {
(deps.getNow?.() ?? Date.now()) < playback.stopReportsAfterMs
) {
return;
}
// Clear before any network call so progress ticks fired during the stop find nothing to
// report, then let reports already in flight finish so none can arrive after the stop.
deps.clearActivePlayback();
await deps.reportTracker?.settled();
try {
const observedPositionSeconds = await readMpvPositionSecondsOrFallback(deps.getMpvClient());
const positionSeconds = resolveReportablePositionSeconds(playback, observedPositionSeconds);
const positionTicks = secondsToJellyfinTicks(positionSeconds, deps.ticksPerSecond); const positionTicks = secondsToJellyfinTicks(positionSeconds, deps.ticksPerSecond);
try { try {
await playback.reporter.reportProgress({ await playback.reporter.reportProgress({
@@ -260,6 +257,60 @@ export function createReportJellyfinRemoteStoppedHandler(deps: JellyfinRemoteSto
`Jellyfin did not accept the playback stop report for item ${playback.itemId}; the server may keep showing it as playing.`, `Jellyfin did not accept the playback stop report for item ${playback.itemId}; the server may keep showing it as playing.`,
); );
} }
}
export function createReportJellyfinRemoteStoppedHandler(deps: JellyfinRemoteStoppedReporterDeps) {
return async (): Promise<void> => {
const playback = deps.getActivePlayback();
if (!playback) return;
const withinStartupGrace =
typeof playback.stopReportsAfterMs === 'number' &&
Number.isFinite(playback.stopReportsAfterMs) &&
(deps.getNow?.() ?? Date.now()) < playback.stopReportsAfterMs;
if (playback.loadedMediaPath === null) {
// Playback is armed before `loadfile`, so an empty path this soon belongs to the file
// being replaced and the new item's path is still coming. Later, the load never happened.
if (!withinStartupGrace) deps.clearActivePlayback();
return;
}
if (withinStartupGrace) return;
// Clear before any network call so progress ticks fired during the stop find nothing to
// report, then let reports already in flight finish so none can arrive after the stop.
deps.clearActivePlayback();
// Only this playback's reports: mpv may already be reporting the next episode.
await deps.reportTracker?.settled(playback);
try {
// mpv may have moved to another file while reports drained, and its position would then
// overwrite this item's resume point. Off its file, the last position observed for it
// (cached on every time-pos update) stands in.
const mpvClient = deps.getMpvClient();
const stillOnItem =
Boolean(playback.loadedMediaPath) &&
mpvClient?.currentVideoPath?.trim() === playback.loadedMediaPath?.trim();
const observedPositionSeconds = stillOnItem
? await readMpvPositionSecondsOrFallback(mpvClient)
: 0;
const positionSeconds = resolveReportablePositionSeconds(playback, observedPositionSeconds);
await sendJellyfinStopReports(deps, playback, positionSeconds);
} catch (error) {
deps.logDebug('Failed to report Jellyfin remote stop', error);
}
};
}
/**
* Reports the stop of a playback mpv has already left for another playlist entry. mpv's position
* now belongs to the new file, so the stop carries the last position observed for this one.
* The caller has already replaced the active playback.
*/
export function createReportSupersededJellyfinPlaybackHandler(
deps: JellyfinStopReportDeps & { reportTracker?: JellyfinRemoteReportTracker },
) {
return async (playback: ActiveJellyfinRemotePlaybackState): Promise<void> => {
// Only this playback's reports: the new one keeps reporting and must not hold the stop.
await deps.reportTracker?.settled(playback);
try {
await sendJellyfinStopReports(deps, playback, playback.lastKnownPositionSeconds ?? 0);
} catch (error) { } catch (error) {
deps.logDebug('Failed to report Jellyfin remote stop', error); deps.logDebug('Failed to report Jellyfin remote stop', error);
} }
@@ -225,17 +225,19 @@ test('media path change handler schedules character dictionary once per media pa
); );
}); });
test('media path change handler marks Jellyfin remote playback loaded from media path', () => { test('media path change handler hands the path to Jellyfin before the immersion sync', () => {
const calls: string[] = []; const calls: string[] = [];
const handler = createHandleMpvMediaPathChangeHandler( const handler = createHandleMpvMediaPathChangeHandler(
createMediaPathDeps(calls, { createMediaPathDeps(calls, {
markJellyfinRemotePlaybackLoaded: (path) => calls.push(`jellyfin-loaded:${path}`), handleJellyfinMediaPathLoaded: (path) => calls.push(`jellyfin-loaded:${path}`),
}), }),
); );
handler({ path: 'https://stream.example/video.m3u8' }); handler({ path: 'https://stream.example/video.m3u8' });
assert.ok(calls.includes('jellyfin-loaded:https://stream.example/video.m3u8')); const loadedAt = calls.indexOf('jellyfin-loaded:https://stream.example/video.m3u8');
assert.ok(loadedAt >= 0);
assert.ok(loadedAt < calls.indexOf('sync'));
assert.equal(calls.includes('stopped'), false); assert.equal(calls.includes('stopped'), false);
}); });
+6 -2
View File
@@ -69,7 +69,7 @@ export function createHandleMpvMediaPathChangeHandler(deps: {
syncImmersionMediaState: () => void; syncImmersionMediaState: () => void;
scheduleCharacterDictionarySync?: () => void; scheduleCharacterDictionarySync?: () => void;
signalAutoplayReadyIfWarm?: (path: string) => void; signalAutoplayReadyIfWarm?: (path: string) => void;
markJellyfinRemotePlaybackLoaded?: (path: string) => void; handleJellyfinMediaPathLoaded?: (path: string) => void;
flushPlaybackPositionOnMediaPathClear?: (mediaPath: string) => void; flushPlaybackPositionOnMediaPathClear?: (mediaPath: string) => void;
refreshDiscordPresence: () => void; refreshDiscordPresence: () => void;
}) { }) {
@@ -94,9 +94,13 @@ export function createHandleMpvMediaPathChangeHandler(deps: {
deps.maybeProbeAnilistDuration(mediaKey); deps.maybeProbeAnilistDuration(mediaKey);
deps.ensureAnilistMediaGuess(mediaKey); deps.ensureAnilistMediaGuess(mediaKey);
} }
// Runs before the immersion sync: a Jellyfin episode mpv started from its playlist records
// its stats metadata here, and the session that sync starts must already see it.
if (trimmedPath.length > 0) {
deps.handleJellyfinMediaPathLoaded?.(normalizedPath);
}
deps.syncImmersionMediaState(); deps.syncImmersionMediaState();
if (trimmedPath.length > 0) { if (trimmedPath.length > 0) {
deps.markJellyfinRemotePlaybackLoaded?.(normalizedPath);
if (trimmedPath !== lastCharacterDictionarySyncMediaPath) { if (trimmedPath !== lastCharacterDictionarySyncMediaPath) {
lastCharacterDictionarySyncMediaPath = trimmedPath; lastCharacterDictionarySyncMediaPath = trimmedPath;
deps.scheduleCharacterDictionarySync?.(); deps.scheduleCharacterDictionarySync?.();
@@ -82,7 +82,7 @@ export function createMpvMainEventBindingDeps(deps: {
ensureAnilistMediaGuess: (mediaKey: string) => void; ensureAnilistMediaGuess: (mediaKey: string) => void;
syncImmersionMediaState: () => void; syncImmersionMediaState: () => void;
signalAutoplayReadyIfWarm?: (path: string) => void; signalAutoplayReadyIfWarm?: (path: string) => void;
markJellyfinRemotePlaybackLoaded?: (path: string) => void; handleJellyfinMediaPathLoaded?: (path: string) => void;
scheduleCharacterDictionarySync?: () => void; scheduleCharacterDictionarySync?: () => void;
updateCurrentMediaTitle: (title: string) => void; updateCurrentMediaTitle: (title: string) => void;
resetAnilistMediaGuessState: () => void; resetAnilistMediaGuessState: () => void;
@@ -329,8 +329,7 @@ export function createMpvMainEventBindingDeps(deps: {
ensureAnilistMediaGuess: (mediaKey: string) => deps.ensureAnilistMediaGuess(mediaKey), ensureAnilistMediaGuess: (mediaKey: string) => deps.ensureAnilistMediaGuess(mediaKey),
syncImmersionMediaState: () => deps.syncImmersionMediaState(), syncImmersionMediaState: () => deps.syncImmersionMediaState(),
signalAutoplayReadyIfWarm: (path: string) => deps.signalAutoplayReadyIfWarm?.(path), signalAutoplayReadyIfWarm: (path: string) => deps.signalAutoplayReadyIfWarm?.(path),
markJellyfinRemotePlaybackLoaded: (path: string) => handleJellyfinMediaPathLoaded: (path: string) => deps.handleJellyfinMediaPathLoaded?.(path),
deps.markJellyfinRemotePlaybackLoaded?.(path),
scheduleCharacterDictionarySync: () => deps.scheduleCharacterDictionarySync?.(), scheduleCharacterDictionarySync: () => deps.scheduleCharacterDictionarySync?.(),
updateCurrentMediaTitle: (title: string) => deps.updateCurrentMediaTitle(title), updateCurrentMediaTitle: (title: string) => deps.updateCurrentMediaTitle(title),
resetAnilistMediaGuessState: () => deps.resetAnilistMediaGuessState(), resetAnilistMediaGuessState: () => deps.resetAnilistMediaGuessState(),
+2 -2
View File
@@ -65,7 +65,7 @@ export function createBindMpvMainEventHandlersHandler(deps: {
ensureAnilistMediaGuess: (mediaKey: string) => void; ensureAnilistMediaGuess: (mediaKey: string) => void;
syncImmersionMediaState: () => void; syncImmersionMediaState: () => void;
signalAutoplayReadyIfWarm?: (path: string) => void; signalAutoplayReadyIfWarm?: (path: string) => void;
markJellyfinRemotePlaybackLoaded?: (path: string) => void; handleJellyfinMediaPathLoaded?: (path: string) => void;
flushPlaybackPositionOnMediaPathClear?: (mediaPath: string) => void; flushPlaybackPositionOnMediaPathClear?: (mediaPath: string) => void;
updateCurrentMediaTitle: (title: string) => void; updateCurrentMediaTitle: (title: string) => void;
@@ -148,7 +148,7 @@ export function createBindMpvMainEventHandlersHandler(deps: {
flushPlaybackPositionOnMediaPathClear: (mediaPath) => flushPlaybackPositionOnMediaPathClear: (mediaPath) =>
deps.flushPlaybackPositionOnMediaPathClear?.(mediaPath), deps.flushPlaybackPositionOnMediaPathClear?.(mediaPath),
signalAutoplayReadyIfWarm: (path) => deps.signalAutoplayReadyIfWarm?.(path), signalAutoplayReadyIfWarm: (path) => deps.signalAutoplayReadyIfWarm?.(path),
markJellyfinRemotePlaybackLoaded: (path) => deps.markJellyfinRemotePlaybackLoaded?.(path), handleJellyfinMediaPathLoaded: (path) => deps.handleJellyfinMediaPathLoaded?.(path),
scheduleCharacterDictionarySync: () => deps.scheduleCharacterDictionarySync?.(), scheduleCharacterDictionarySync: () => deps.scheduleCharacterDictionarySync?.(),
refreshDiscordPresence: () => deps.refreshDiscordPresence(), refreshDiscordPresence: () => deps.refreshDiscordPresence(),
}); });
+35 -1
View File
@@ -1,20 +1,26 @@
import * as path from 'node:path';
import type { MpvIpcClient } from '../../core/services/mpv'; import type { MpvIpcClient } from '../../core/services/mpv';
import { import {
openSubsyncManualPickerRuntime,
runSubsyncManualFromIpcRuntime, runSubsyncManualFromIpcRuntime,
triggerSubsyncFromConfigRuntime, triggerSubsyncFromConfigRuntime,
} from '../../core/services/subsync-runner'; } 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 { import type {
SubsyncResult, SubsyncResult,
SubsyncManualPayload, SubsyncManualPayload,
SubsyncManualRunRequest, SubsyncManualRunRequest,
ResolvedConfig, ResolvedConfig,
} from '../../types'; } from '../../types';
import { getSubsyncConfig } from '../../subsync/utils'; import { fileExists, findSubsyncExecutable, getSubsyncConfig } from '../../subsync/utils';
import { createSubsyncRuntimeServiceInputFromState } from '../subsync-runtime'; import { createSubsyncRuntimeServiceInputFromState } from '../subsync-runtime';
export type MainSubsyncRuntimeDeps = { export type MainSubsyncRuntimeDeps = {
getMpvClient: () => MpvIpcClient | null; getMpvClient: () => MpvIpcClient | null;
getResolvedConfig: () => ResolvedConfig; getResolvedConfig: () => ResolvedConfig;
getSubtitleGenerationModelDirectory?: () => string;
canPickReferenceFile?: () => boolean;
getSubsyncInProgress: () => boolean; getSubsyncInProgress: () => boolean;
setSubsyncInProgress: (inProgress: boolean) => void; setSubsyncInProgress: (inProgress: boolean) => void;
showMpvOsd: (text: string) => void; showMpvOsd: (text: string) => void;
@@ -23,12 +29,37 @@ export type MainSubsyncRuntimeDeps = {
export function createMainSubsyncRuntime(deps: MainSubsyncRuntimeDeps): { export function createMainSubsyncRuntime(deps: MainSubsyncRuntimeDeps): {
triggerFromConfig: () => Promise<void>; triggerFromConfig: () => Promise<void>;
openManualPicker: () => Promise<void>;
runManualFromIpc: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>; runManualFromIpc: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
} { } {
const resolveVadPaths = () => {
const config = deps.getResolvedConfig();
const gen = config.subtitleGeneration;
const vadExecutablePath = findSubsyncExecutable(gen?.vadPath, [
'whisper-vad-speech-segments',
'vad-speech-segments',
]);
let vadModelPath: string | null = null;
const configuredModel = gen?.vadModelPath?.trim() ?? '';
if (configuredModel) {
const expanded = path.resolve(expandSubtitleGenerationPath(configuredModel));
if (fileExists(expanded)) vadModelPath = expanded;
} else if (deps.getSubtitleGenerationModelDirectory) {
const managedModel = path.join(
deps.getSubtitleGenerationModelDirectory(),
SUBTITLE_GENERATION_VAD_MODEL.filename,
);
if (fileExists(managedModel)) vadModelPath = managedModel;
}
return { vadExecutablePath, vadModelPath };
};
const getRuntimeServiceParams = () => const getRuntimeServiceParams = () =>
createSubsyncRuntimeServiceInputFromState({ createSubsyncRuntimeServiceInputFromState({
getMpvClient: () => deps.getMpvClient(), getMpvClient: () => deps.getMpvClient(),
getResolvedSubsyncConfig: () => getSubsyncConfig(deps.getResolvedConfig().subsync), getResolvedSubsyncConfig: () => getSubsyncConfig(deps.getResolvedConfig().subsync),
getVadPaths: resolveVadPaths,
canPickReferenceFile: deps.canPickReferenceFile,
getSubsyncInProgress: () => deps.getSubsyncInProgress(), getSubsyncInProgress: () => deps.getSubsyncInProgress(),
setSubsyncInProgress: (inProgress: boolean) => deps.setSubsyncInProgress(inProgress), setSubsyncInProgress: (inProgress: boolean) => deps.setSubsyncInProgress(inProgress),
showMpvOsd: (text: string) => deps.showMpvOsd(text), showMpvOsd: (text: string) => deps.showMpvOsd(text),
@@ -39,6 +70,9 @@ export function createMainSubsyncRuntime(deps: MainSubsyncRuntimeDeps): {
triggerFromConfig: async (): Promise<void> => { triggerFromConfig: async (): Promise<void> => {
await triggerSubsyncFromConfigRuntime(getRuntimeServiceParams()); await triggerSubsyncFromConfigRuntime(getRuntimeServiceParams());
}, },
openManualPicker: async (): Promise<void> => {
await openSubsyncManualPickerRuntime(getRuntimeServiceParams());
},
runManualFromIpc: async (request: SubsyncManualRunRequest): Promise<SubsyncResult> => runManualFromIpc: async (request: SubsyncManualRunRequest): Promise<SubsyncResult> =>
runSubsyncManualFromIpcRuntime(request, getRuntimeServiceParams()), runSubsyncManualFromIpcRuntime(request, getRuntimeServiceParams()),
}; };
+13
View File
@@ -3,6 +3,7 @@ import type { SubsyncManualPayload, SubsyncManualRunRequest, SubsyncResult } fro
import type { SubsyncRuntimeDeps } from '../core/services/subsync-runner'; import type { SubsyncRuntimeDeps } from '../core/services/subsync-runner';
import { createSubsyncRuntimeDeps } from './dependencies'; import { createSubsyncRuntimeDeps } from './dependencies';
import { import {
openSubsyncManualPickerRuntime as openSubsyncManualPickerRuntimeCore,
runSubsyncManualFromIpcRuntime as runSubsyncManualFromIpcRuntimeCore, runSubsyncManualFromIpcRuntime as runSubsyncManualFromIpcRuntimeCore,
triggerSubsyncFromConfigRuntime as triggerSubsyncFromConfigRuntimeCore, triggerSubsyncFromConfigRuntime as triggerSubsyncFromConfigRuntimeCore,
} from '../core/services'; } from '../core/services';
@@ -10,6 +11,8 @@ import {
export interface SubsyncRuntimeServiceInput { export interface SubsyncRuntimeServiceInput {
getMpvClient: SubsyncRuntimeDeps['getMpvClient']; getMpvClient: SubsyncRuntimeDeps['getMpvClient'];
getResolvedSubsyncConfig: () => SubsyncResolvedConfig; getResolvedSubsyncConfig: () => SubsyncResolvedConfig;
getVadPaths?: SubsyncRuntimeDeps['getVadPaths'];
canPickReferenceFile?: SubsyncRuntimeDeps['canPickReferenceFile'];
isSubsyncInProgress: SubsyncRuntimeDeps['isSubsyncInProgress']; isSubsyncInProgress: SubsyncRuntimeDeps['isSubsyncInProgress'];
setSubsyncInProgress: SubsyncRuntimeDeps['setSubsyncInProgress']; setSubsyncInProgress: SubsyncRuntimeDeps['setSubsyncInProgress'];
showMpvOsd: SubsyncRuntimeDeps['showMpvOsd']; showMpvOsd: SubsyncRuntimeDeps['showMpvOsd'];
@@ -19,6 +22,8 @@ export interface SubsyncRuntimeServiceInput {
export interface SubsyncRuntimeServiceStateInput { export interface SubsyncRuntimeServiceStateInput {
getMpvClient: SubsyncRuntimeServiceInput['getMpvClient']; getMpvClient: SubsyncRuntimeServiceInput['getMpvClient'];
getResolvedSubsyncConfig: SubsyncRuntimeServiceInput['getResolvedSubsyncConfig']; getResolvedSubsyncConfig: SubsyncRuntimeServiceInput['getResolvedSubsyncConfig'];
getVadPaths?: SubsyncRuntimeServiceInput['getVadPaths'];
canPickReferenceFile?: SubsyncRuntimeServiceInput['canPickReferenceFile'];
getSubsyncInProgress: () => boolean; getSubsyncInProgress: () => boolean;
setSubsyncInProgress: SubsyncRuntimeServiceInput['setSubsyncInProgress']; setSubsyncInProgress: SubsyncRuntimeServiceInput['setSubsyncInProgress'];
showMpvOsd: SubsyncRuntimeServiceInput['showMpvOsd']; showMpvOsd: SubsyncRuntimeServiceInput['showMpvOsd'];
@@ -31,6 +36,8 @@ export function createSubsyncRuntimeServiceInputFromState(
return { return {
getMpvClient: input.getMpvClient, getMpvClient: input.getMpvClient,
getResolvedSubsyncConfig: input.getResolvedSubsyncConfig, getResolvedSubsyncConfig: input.getResolvedSubsyncConfig,
getVadPaths: input.getVadPaths,
canPickReferenceFile: input.canPickReferenceFile,
isSubsyncInProgress: input.getSubsyncInProgress, isSubsyncInProgress: input.getSubsyncInProgress,
setSubsyncInProgress: input.setSubsyncInProgress, setSubsyncInProgress: input.setSubsyncInProgress,
showMpvOsd: input.showMpvOsd, showMpvOsd: input.showMpvOsd,
@@ -44,6 +51,8 @@ export function createSubsyncRuntimeServiceDeps(
return createSubsyncRuntimeDeps({ return createSubsyncRuntimeDeps({
getMpvClient: params.getMpvClient, getMpvClient: params.getMpvClient,
getResolvedSubsyncConfig: params.getResolvedSubsyncConfig, getResolvedSubsyncConfig: params.getResolvedSubsyncConfig,
getVadPaths: params.getVadPaths,
canPickReferenceFile: params.canPickReferenceFile,
isSubsyncInProgress: params.isSubsyncInProgress, isSubsyncInProgress: params.isSubsyncInProgress,
setSubsyncInProgress: params.setSubsyncInProgress, setSubsyncInProgress: params.setSubsyncInProgress,
showMpvOsd: params.showMpvOsd, showMpvOsd: params.showMpvOsd,
@@ -55,6 +64,10 @@ export function triggerSubsyncFromConfigRuntime(params: SubsyncRuntimeServiceInp
return triggerSubsyncFromConfigRuntimeCore(createSubsyncRuntimeServiceDeps(params)); return triggerSubsyncFromConfigRuntimeCore(createSubsyncRuntimeServiceDeps(params));
} }
export function openSubsyncManualPickerRuntime(params: SubsyncRuntimeServiceInput): Promise<void> {
return openSubsyncManualPickerRuntimeCore(createSubsyncRuntimeServiceDeps(params));
}
export async function runSubsyncManualFromIpcRuntime( export async function runSubsyncManualFromIpcRuntime(
request: SubsyncManualRunRequest, request: SubsyncManualRunRequest,
params: SubsyncRuntimeServiceInput, params: SubsyncRuntimeServiceInput,
+4
View File
@@ -428,6 +428,10 @@ const electronAPI: ElectronAPI = {
onSubsyncManualOpen: onSubsyncManualOpenEvent, onSubsyncManualOpen: onSubsyncManualOpenEvent,
runSubsyncManual: (request: SubsyncManualRunRequest): Promise<SubsyncResult> => runSubsyncManual: (request: SubsyncManualRunRequest): Promise<SubsyncResult> =>
ipcRenderer.invoke(IPC_CHANNELS.request.runSubsyncManual, request), ipcRenderer.invoke(IPC_CHANNELS.request.runSubsyncManual, request),
openSubsyncManual: (): Promise<void> =>
ipcRenderer.invoke(IPC_CHANNELS.request.openSubsyncManual),
pickSubsyncReferenceFile: (): Promise<string | null> =>
ipcRenderer.invoke(IPC_CHANNELS.request.pickSubsyncReferenceFile),
onKikuFieldGroupingRequest: onKikuFieldGroupingRequestEvent, onKikuFieldGroupingRequest: onKikuFieldGroupingRequestEvent,
onKikuFieldGroupingCancel: onKikuFieldGroupingCancelEvent, onKikuFieldGroupingCancel: onKikuFieldGroupingCancelEvent,
+45 -3
View File
@@ -868,26 +868,60 @@
<button id="subsyncClose" class="modal-close" type="button">Close</button> <button id="subsyncClose" class="modal-close" type="button">Close</button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<div id="subsyncGuidance" class="subsync-guidance hidden" role="status"></div>
<div class="subsync-form"> <div class="subsync-form">
<div class="subsync-field"> <div class="subsync-field">
<span>Engine</span> <span>Engine</span>
<div class="subsync-radio-group">
<label class="subsync-radio"> <label class="subsync-radio">
<input id="subsyncEngineAlass" type="radio" name="subsyncEngine" checked /> <input id="subsyncEngineBuiltin" type="radio" name="subsyncEngine" checked />
alass Built-in (alass)
</label>
<label class="subsync-radio">
<input id="subsyncEngineAlass" type="radio" name="subsyncEngine" />
External alass
</label> </label>
<label class="subsync-radio"> <label class="subsync-radio">
<input id="subsyncEngineFfsubsync" type="radio" name="subsyncEngine" /> <input id="subsyncEngineFfsubsync" type="radio" name="subsyncEngine" />
ffsubsync ffsubsync
</label> </label>
<label class="subsync-radio">
<input id="subsyncEngineOffset" type="radio" name="subsyncEngine" />
Manual offset
</label>
</div>
</div> </div>
<label id="subsyncReferenceLabel" class="subsync-field"> <label id="subsyncReferenceLabel" class="subsync-field">
<span>Reference (correct timing, for alass)</span> <span>Reference (correct timing)</span>
<div class="subsync-reference-row">
<select id="subsyncReferenceSelect"></select> <select id="subsyncReferenceSelect"></select>
<button
id="subsyncBrowseReference"
class="kiku-cancel-button subsync-browse-button hidden"
type="button"
>
Browse…
</button>
</div>
</label> </label>
<label id="subsyncTargetLabel" class="subsync-field"> <label id="subsyncTargetLabel" class="subsync-field">
<span>Out-of-sync Subtitle (gets retimed)</span> <span>Out-of-sync Subtitle (gets retimed)</span>
<select id="subsyncTargetSelect"></select> <select id="subsyncTargetSelect"></select>
</label> </label>
<div id="subsyncOptionsGroup" class="subsync-options">
<label class="subsync-checkbox">
<input id="subsyncStripSigns" type="checkbox" checked />
Ignore signs &amp; songs
</label>
<label id="subsyncAllowSplitsLabel" class="subsync-checkbox">
<input id="subsyncAllowSplits" type="checkbox" checked />
Allow scene cuts &amp; ad-break splits
</label>
</div>
<label id="subsyncOffsetLabel" class="subsync-field hidden">
<span>Shift offset (milliseconds, e.g. -1200 or +850)</span>
<input id="subsyncOffsetInput" type="number" step="50" value="0" />
</label>
</div> </div>
<div id="subsyncStatus" class="runtime-options-status"></div> <div id="subsyncStatus" class="runtime-options-status"></div>
<div class="subsync-footer"> <div class="subsync-footer">
@@ -962,6 +996,14 @@
<div id="subtitleSidebarContent" class="modal-content subtitle-sidebar-content"> <div id="subtitleSidebarContent" class="modal-content subtitle-sidebar-content">
<div class="modal-header"> <div class="modal-header">
<div class="modal-title">Subtitle Sidebar</div> <div class="modal-title">Subtitle Sidebar</div>
<button
id="subtitleSidebarSync"
class="modal-close"
type="button"
title="Sync subtitles automatically (Shift+click for options)"
>
Sync
</button>
<button id="subtitleSidebarCopy" class="modal-close" type="button" hidden>Copy</button> <button id="subtitleSidebarCopy" class="modal-close" type="button" hidden>Copy</button>
<button id="subtitleSidebarClose" class="modal-close" type="button">Close</button> <button id="subtitleSidebarClose" class="modal-close" type="button">Close</button>
</div> </div>
+122
View File
@@ -421,3 +421,125 @@ test('subsync modal hides the reference picker for ffsubsync but keeps the targe
harness.restoreGlobals(); harness.restoreGlobals();
} }
}); });
test('guided subsync modal shows guidance banner, ranked candidates, browse file, and built-in options', async () => {
let request: SubsyncManualRunRequest | null = null;
const harness = createTestHarness(async (nextRequest) => {
request = nextRequest;
return { ok: true, message: 'ok' };
});
const guidanceClassList = createClassList();
guidanceClassList.add('hidden');
const optionsClassList = createClassList();
const allowSplitsClassList = createClassList();
const offsetLabelClassList = createClassList();
offsetLabelClassList.add('hidden');
const browseClassList = createClassList();
browseClassList.add('hidden');
const engineBuiltinEvents = createEventTarget();
const engineOffsetEvents = createEventTarget();
const browseEvents = createEventTarget();
const subsyncEngineBuiltin = {
checked: true,
disabled: false,
addEventListener: engineBuiltinEvents.addEventListener,
dispatch: engineBuiltinEvents.dispatch,
};
const subsyncEngineOffset = {
checked: false,
disabled: false,
addEventListener: engineOffsetEvents.addEventListener,
dispatch: engineOffsetEvents.dispatch,
};
const subsyncBrowseReferenceButton = {
classList: browseClassList,
addEventListener: browseEvents.addEventListener,
dispatch: browseEvents.dispatch,
};
const subsyncGuidance = {
textContent: '',
classList: guidanceClassList,
};
const subsyncStripSignsCheckbox = { checked: true };
const subsyncAllowSplitsCheckbox = { checked: true };
const subsyncOffsetInput = { value: '0' };
Object.assign(harness.ctx.dom, {
subsyncGuidance,
subsyncEngineBuiltin,
subsyncEngineOffset,
subsyncBrowseReferenceButton,
subsyncOptionsGroup: { classList: optionsClassList },
subsyncStripSignsCheckbox,
subsyncAllowSplitsLabel: { classList: allowSplitsClassList },
subsyncAllowSplitsCheckbox,
subsyncOffsetLabel: { classList: offsetLabelClassList },
subsyncOffsetInput,
});
(
globalThis as unknown as { window: { electronAPI: Record<string, unknown> } }
).window.electronAPI.pickSubsyncReferenceFile = async () => '/tmp/browsed-ref.srt';
try {
harness.modal.wireDomEvents();
harness.modal.openSubsyncModal(
payloadWith({
mediaPath: '/tmp/ep01.mkv',
guidanceMessage: 'Loaded English track appears +2.4s off audio.',
defaultEngine: 'builtin',
builtinAvailable: true,
alassAvailable: false,
canPickReferenceFile: true,
referenceCandidates: [
{
key: 'track:2',
kind: 'track',
label: 'External #2 - eng (secondary)',
detail: '+2.4s off audio',
trackId: 2,
},
{
key: 'video',
kind: 'video',
label: 'Video audio (built-in speech detection)',
recommended: true,
},
],
defaultReferenceKey: 'video',
}),
);
assert.equal(guidanceClassList.contains('hidden'), false);
assert.equal(subsyncGuidance.textContent, 'Loaded English track appears +2.4s off audio.');
assert.equal(subsyncEngineBuiltin.checked, true);
assert.equal(harness.ctx.dom.subsyncEngineAlass.disabled, true);
assert.equal(browseClassList.contains('hidden'), false);
assert.equal(harness.referenceSelect.value, 'video');
// Browse a custom file from disk and submit built-in sync with it.
subsyncBrowseReferenceButton.dispatch('click');
await flushMicrotasks();
assert.equal(harness.referenceSelect.value, 'file:/tmp/browsed-ref.srt');
subsyncAllowSplitsCheckbox.checked = false;
harness.runButton.dispatch('click');
await flushMicrotasks();
assert.deepEqual(request, {
engine: 'builtin',
mediaPath: '/tmp/ep01.mkv',
targetTrackId: 1,
referenceMode: 'file',
referenceTrackId: null,
referenceFilePath: '/tmp/browsed-ref.srt',
stripSigns: true,
allowSplits: false,
});
} finally {
harness.restoreGlobals();
}
});
+308 -32
View File
@@ -1,12 +1,22 @@
import type { SubsyncManualPayload, SubsyncManualRunRequest } from '../../types'; import type {
SubsyncEngine,
SubsyncManualPayload,
SubsyncManualRunRequest,
SubsyncReferenceCandidate,
} from '../../types';
import type { ModalStateReader, RendererContext } from '../context'; import type { ModalStateReader, RendererContext } from '../context';
const VIDEO_REFERENCE_VALUE = 'video'; const VIDEO_REFERENCE_VALUE = 'video';
const TRACK_PREFIX = 'track:';
const FILE_PREFIX = 'file:';
interface SubsyncSelection { interface SubsyncSelection {
engine: 'alass' | 'ffsubsync'; engine: SubsyncEngine;
referenceValue: string; referenceValue: string;
targetTrackId: number | null; targetTrackId: number | null;
stripSigns: boolean;
allowSplits: boolean;
offsetMs: number;
} }
export function createSubsyncModal( export function createSubsyncModal(
@@ -17,24 +27,81 @@ export function createSubsyncModal(
}, },
) { ) {
let currentPayload: SubsyncManualPayload | null = null; let currentPayload: SubsyncManualPayload | null = null;
let customFileCandidates: SubsyncReferenceCandidate[] = [];
function setSubsyncStatus(message: string, isError = false): void { function setSubsyncStatus(message: string, isError = false): void {
ctx.dom.subsyncStatus.textContent = message; ctx.dom.subsyncStatus.textContent = message;
ctx.dom.subsyncStatus.classList.toggle('error', isError); ctx.dom.subsyncStatus.classList.toggle('error', isError);
} }
function hasBuiltinEngineUi(): boolean {
return Boolean(ctx.dom.subsyncEngineBuiltin);
}
function hasBuiltinReference(): boolean {
if (!currentPayload) return false;
if (currentPayload.builtinAvailable === false) return false;
return (
currentPayload.audioReferenceAvailable === true ||
currentPayload.videoReferenceAvailable ||
currentPayload.subtitleTracks.length > 1 ||
(currentPayload.referenceCandidates?.length ?? 0) > 0 ||
customFileCandidates.length > 0 ||
currentPayload.canPickReferenceFile === true
);
}
function hasAlassReference(): boolean { function hasAlassReference(): boolean {
if (!currentPayload) return false; if (!currentPayload) return false;
return currentPayload.videoReferenceAvailable || currentPayload.subtitleTracks.length > 1; if (currentPayload.alassAvailable === false) return false;
return (
currentPayload.videoReferenceAvailable ||
currentPayload.subtitleTracks.length > 1 ||
(currentPayload.referenceCandidates?.some((c) => c.kind !== 'video') ?? false) ||
customFileCandidates.length > 0
);
}
function hasOffsetEngine(): boolean {
return Boolean(ctx.dom.subsyncEngineOffset) && ctx.state.subsyncSubtitleTracks.length > 0;
}
function getSelectedEngine(): SubsyncEngine | null {
if (ctx.dom.subsyncEngineBuiltin?.checked) return 'builtin';
if (ctx.dom.subsyncEngineAlass.checked) return 'alass';
if (ctx.dom.subsyncEngineFfsubsync.checked) return 'ffsubsync';
if (ctx.dom.subsyncEngineOffset?.checked) return 'offset';
return null;
}
function setSelectedEngine(engine: SubsyncEngine | null): void {
if (ctx.dom.subsyncEngineBuiltin) {
ctx.dom.subsyncEngineBuiltin.checked = engine === 'builtin';
}
ctx.dom.subsyncEngineAlass.checked = engine === 'alass';
ctx.dom.subsyncEngineFfsubsync.checked = engine === 'ffsubsync';
if (ctx.dom.subsyncEngineOffset) {
ctx.dom.subsyncEngineOffset.checked = engine === 'offset';
}
} }
function updateSubsyncFieldVisibility(): void { function updateSubsyncFieldVisibility(): void {
const useAlass = ctx.dom.subsyncEngineAlass.checked; const engine = getSelectedEngine();
ctx.dom.subsyncReferenceLabel.classList.toggle('hidden', !useAlass); const usesReference = engine === 'builtin' || engine === 'alass';
const isOffset = engine === 'offset';
ctx.dom.subsyncReferenceLabel.classList.toggle('hidden', !usesReference);
ctx.dom.subsyncTargetLabel.classList.toggle( ctx.dom.subsyncTargetLabel.classList.toggle(
'hidden', 'hidden',
ctx.state.subsyncSubtitleTracks.length === 0, ctx.state.subsyncSubtitleTracks.length === 0,
); );
ctx.dom.subsyncOptionsGroup?.classList.toggle('hidden', !usesReference);
ctx.dom.subsyncAllowSplitsLabel?.classList.toggle('hidden', engine !== 'builtin');
ctx.dom.subsyncOffsetLabel?.classList.toggle('hidden', !isOffset);
ctx.dom.subsyncBrowseReferenceButton?.classList.toggle(
'hidden',
!usesReference || !currentPayload?.canPickReferenceFile,
);
} }
function appendOption(select: HTMLSelectElement, value: string, label: string): void { function appendOption(select: HTMLSelectElement, value: string, label: string): void {
@@ -68,32 +135,88 @@ export function createSubsyncModal(
} }
} }
function formatCandidateOptionLabel(candidate: SubsyncReferenceCandidate): string {
const prefix = candidate.recommended ? '★ ' : '';
const detail = candidate.detail ? ` · ${candidate.detail}` : '';
return `${prefix}${candidate.label}${detail}`;
}
function buildReferenceOptions(): Array<{ value: string; label: string }> {
const targetTrackId = getSelectedTargetTrackId();
const options: Array<{ value: string; label: string }> = [];
const seen = new Set<string>();
// When rich candidates are supplied, preserve their diagnostic ranking while
// ensuring any non-target track in subtitleTracks is also reachable.
if (currentPayload?.referenceCandidates && currentPayload.referenceCandidates.length > 0) {
for (const candidate of [...customFileCandidates, ...currentPayload.referenceCandidates]) {
if (candidate.kind === 'track' && candidate.trackId === targetTrackId) continue;
if (seen.has(candidate.key)) continue;
seen.add(candidate.key);
options.push({
value: candidate.key,
label: formatCandidateOptionLabel(candidate),
});
}
for (const track of ctx.state.subsyncSubtitleTracks) {
if (track.id === targetTrackId) continue;
const key = `${TRACK_PREFIX}${track.id}`;
if (seen.has(key)) continue;
seen.add(key);
options.push({ value: key, label: track.label });
}
return options;
}
// Legacy / simplified payload format (used by minimal payloads & existing tests).
for (const candidate of customFileCandidates) {
if (seen.has(candidate.key)) continue;
seen.add(candidate.key);
options.push({
value: candidate.key,
label: formatCandidateOptionLabel(candidate),
});
}
for (const track of ctx.state.subsyncSubtitleTracks) {
if (track.id === targetTrackId) continue;
const value = String(track.id);
if (seen.has(value)) continue;
seen.add(value);
options.push({ value, label: track.label });
}
if (currentPayload?.videoReferenceAvailable) {
options.push({ value: VIDEO_REFERENCE_VALUE, label: 'Video file (audio reference)' });
}
return options;
}
function renderReferenceTracks(preferredValue: string | null): void { function renderReferenceTracks(preferredValue: string | null): void {
const select = ctx.dom.subsyncReferenceSelect; const select = ctx.dom.subsyncReferenceSelect;
const targetTrackId = getSelectedTargetTrackId(); const items = buildReferenceOptions();
const values: string[] = []; const values = items.map((item) => item.value);
select.innerHTML = ''; select.innerHTML = '';
select.value = ''; select.value = '';
for (const track of ctx.state.subsyncSubtitleTracks) { for (const item of items) {
if (track.id === targetTrackId) continue; appendOption(select, item.value, item.label);
appendOption(select, String(track.id), track.label);
values.push(String(track.id));
}
if (currentPayload?.videoReferenceAvailable) {
appendOption(select, VIDEO_REFERENCE_VALUE, 'Video file (audio reference)');
values.push(VIDEO_REFERENCE_VALUE);
} }
select.disabled = values.length === 0; select.disabled = values.length === 0;
const preferred = preferredValue && values.includes(preferredValue) ? preferredValue : null; const preferred = preferredValue && values.includes(preferredValue) ? preferredValue : null;
const defaultKey =
currentPayload?.defaultReferenceKey && values.includes(currentPayload.defaultReferenceKey)
? currentPayload.defaultReferenceKey
: null;
const defaultTrackValue = const defaultTrackValue =
currentPayload?.defaultReferenceTrackId !== null && currentPayload?.defaultReferenceTrackId !== null &&
currentPayload?.defaultReferenceTrackId !== undefined currentPayload?.defaultReferenceTrackId !== undefined
? values.includes(`${TRACK_PREFIX}${currentPayload.defaultReferenceTrackId}`)
? `${TRACK_PREFIX}${currentPayload.defaultReferenceTrackId}`
: values.includes(String(currentPayload.defaultReferenceTrackId))
? String(currentPayload.defaultReferenceTrackId) ? String(currentPayload.defaultReferenceTrackId)
: null
: null; : null;
const fallback = const fallback = defaultKey ?? defaultTrackValue ?? values[0];
defaultTrackValue && values.includes(defaultTrackValue) ? defaultTrackValue : values[0];
const selected = preferred ?? fallback; const selected = preferred ?? fallback;
if (selected) { if (selected) {
select.value = selected; select.value = selected;
@@ -102,7 +225,11 @@ export function createSubsyncModal(
function describeSubsyncState(): string { function describeSubsyncState(): string {
if (!currentPayload) return ''; if (!currentPayload) return '';
const builtinReady = hasBuiltinEngineUi() && hasBuiltinReference();
const alassReady = hasAlassReference(); const alassReady = hasAlassReference();
if (builtinReady) {
return 'Choose reference and options, or switch engines, then run.';
}
if (alassReady && currentPayload.ffsubsyncAvailable) { if (alassReady && currentPayload.ffsubsyncAvailable) {
return 'Choose engine, reference and out-of-sync subtitle, then run.'; return 'Choose engine, reference and out-of-sync subtitle, then run.';
} }
@@ -112,6 +239,9 @@ export function createSubsyncModal(
if (currentPayload.ffsubsyncAvailable) { if (currentPayload.ffsubsyncAvailable) {
return 'No reference available for alass. Use ffsubsync.'; return 'No reference available for alass. Use ffsubsync.';
} }
if (hasOffsetEngine()) {
return 'Apply a manual offset or browse for a reference subtitle file.';
}
return 'No sync engine available for current media.'; return 'No sync engine available for current media.';
} }
@@ -130,18 +260,75 @@ export function createSubsyncModal(
} }
} }
function chooseInitialEngine(
payload: SubsyncManualPayload,
selection?: SubsyncSelection,
): SubsyncEngine | null {
const builtinReady = hasBuiltinEngineUi() && hasBuiltinReference();
const alassReady = hasAlassReference();
const ffsubsyncReady = payload.ffsubsyncAvailable;
const offsetReady = hasOffsetEngine();
const isEngineAvailable = (engine: SubsyncEngine): boolean => {
if (engine === 'builtin') return builtinReady;
if (engine === 'alass') return alassReady;
if (engine === 'ffsubsync') return ffsubsyncReady;
if (engine === 'offset') return offsetReady;
return false;
};
if (selection && isEngineAvailable(selection.engine)) {
return selection.engine;
}
if (payload.defaultEngine && isEngineAvailable(payload.defaultEngine)) {
return payload.defaultEngine;
}
if (builtinReady) return 'builtin';
if (alassReady) return 'alass';
if (ffsubsyncReady) return 'ffsubsync';
if (offsetReady) return 'offset';
return null;
}
function openSubsyncModal(payload: SubsyncManualPayload, selection?: SubsyncSelection): void { function openSubsyncModal(payload: SubsyncManualPayload, selection?: SubsyncSelection): void {
ctx.state.subsyncSubmitting = false; ctx.state.subsyncSubmitting = false;
ctx.state.subsyncSubtitleTracks = payload.subtitleTracks; ctx.state.subsyncSubtitleTracks = payload.subtitleTracks;
currentPayload = payload; currentPayload = payload;
if (!selection) {
customFileCandidates = [];
}
const builtinReady = hasBuiltinEngineUi() && hasBuiltinReference();
const alassReady = hasAlassReference(); const alassReady = hasAlassReference();
const useAlass = selection ? selection.engine === 'alass' && alassReady : alassReady; const offsetReady = hasOffsetEngine();
ctx.dom.subsyncEngineAlass.checked = useAlass; const chosenEngine = chooseInitialEngine(payload, selection);
ctx.dom.subsyncEngineFfsubsync.checked = !useAlass && payload.ffsubsyncAvailable;
setSelectedEngine(chosenEngine);
if (ctx.dom.subsyncEngineBuiltin) {
ctx.dom.subsyncEngineBuiltin.disabled = !builtinReady;
}
ctx.dom.subsyncEngineAlass.disabled = !alassReady; ctx.dom.subsyncEngineAlass.disabled = !alassReady;
ctx.dom.subsyncEngineFfsubsync.disabled = !payload.ffsubsyncAvailable; ctx.dom.subsyncEngineFfsubsync.disabled = !payload.ffsubsyncAvailable;
ctx.dom.subsyncRunButton.disabled = !alassReady && !payload.ffsubsyncAvailable; if (ctx.dom.subsyncEngineOffset) {
ctx.dom.subsyncEngineOffset.disabled = !offsetReady;
}
ctx.dom.subsyncRunButton.disabled = chosenEngine === null;
if (ctx.dom.subsyncGuidance) {
const guidance = payload.guidanceMessage?.trim() ?? '';
ctx.dom.subsyncGuidance.textContent = guidance;
ctx.dom.subsyncGuidance.classList.toggle('hidden', guidance.length === 0);
}
if (ctx.dom.subsyncStripSignsCheckbox) {
ctx.dom.subsyncStripSignsCheckbox.checked = selection ? selection.stripSigns : true;
}
if (ctx.dom.subsyncAllowSplitsCheckbox) {
ctx.dom.subsyncAllowSplitsCheckbox.checked = selection ? selection.allowSplits : true;
}
if (ctx.dom.subsyncOffsetInput) {
ctx.dom.subsyncOffsetInput.value = String(selection ? selection.offsetMs : 0);
}
renderTargetTracks( renderTargetTracks(
selection selection
@@ -170,46 +357,126 @@ export function createSubsyncModal(
window.electronAPI.notifyOverlayModalOpened('subsync'); window.electronAPI.notifyOverlayModalOpened('subsync');
} }
async function browseReferenceFile(): Promise<void> {
if (!window.electronAPI.pickSubsyncReferenceFile) return;
const picked = await window.electronAPI.pickSubsyncReferenceFile();
if (!picked) return;
const key = `${FILE_PREFIX}${picked}`;
const filename = picked.split(/[\\/]/).pop() ?? picked;
customFileCandidates = [
{
key,
kind: 'file',
label: `File - ${filename}`,
detail: 'selected from disk',
filePath: picked,
},
...customFileCandidates.filter((c) => c.key !== key),
];
if (ctx.dom.subsyncEngineBuiltin && ctx.dom.subsyncEngineBuiltin.disabled) {
ctx.dom.subsyncEngineBuiltin.disabled = false;
setSelectedEngine('builtin');
ctx.dom.subsyncRunButton.disabled = false;
}
renderReferenceTracks(key);
updateSubsyncFieldVisibility();
}
function parseReferenceValue(referenceValue: string): {
referenceMode: 'track' | 'video' | 'file';
referenceTrackId: number | null;
referenceFilePath: string | null;
} {
if (referenceValue === VIDEO_REFERENCE_VALUE) {
return { referenceMode: 'video', referenceTrackId: null, referenceFilePath: null };
}
if (referenceValue.startsWith(FILE_PREFIX)) {
return {
referenceMode: 'file',
referenceTrackId: null,
referenceFilePath: referenceValue.slice(FILE_PREFIX.length),
};
}
const rawId = referenceValue.startsWith(TRACK_PREFIX)
? referenceValue.slice(TRACK_PREFIX.length)
: referenceValue;
return {
referenceMode: 'track',
referenceTrackId: Number.parseInt(rawId, 10),
referenceFilePath: null,
};
}
async function runSubsyncManualFromModal(): Promise<void> { async function runSubsyncManualFromModal(): Promise<void> {
if (ctx.state.subsyncSubmitting) return; if (ctx.state.subsyncSubmitting) return;
if (ctx.dom.subsyncRunButton.disabled) return; if (ctx.dom.subsyncRunButton.disabled) return;
if (!currentPayload) return; if (!currentPayload) return;
const useAlass = ctx.dom.subsyncEngineAlass.checked; const engine = getSelectedEngine();
const useFfsubsync = ctx.dom.subsyncEngineFfsubsync.checked; if (!engine) {
if (!useAlass && !useFfsubsync) {
setSubsyncStatus('No sync engine available for current media.', true); setSubsyncStatus('No sync engine available for current media.', true);
return; return;
} }
const engine = useAlass ? 'alass' : 'ffsubsync';
const referenceValue = ctx.dom.subsyncReferenceSelect.value; const referenceValue = ctx.dom.subsyncReferenceSelect.value;
const targetTrackId = getSelectedTargetTrackId(); const targetTrackId = getSelectedTargetTrackId();
const stripSigns = ctx.dom.subsyncStripSignsCheckbox?.checked ?? true;
const allowSplits = ctx.dom.subsyncAllowSplitsCheckbox?.checked ?? true;
const offsetMs = Number.parseInt(ctx.dom.subsyncOffsetInput?.value ?? '0', 10) || 0;
if (targetTrackId === null) { if (targetTrackId === null) {
setSubsyncStatus('Select the out-of-sync subtitle track to retime.', true); setSubsyncStatus('Select the out-of-sync subtitle track to retime.', true);
return; return;
} }
if (engine === 'alass' && !referenceValue) { if ((engine === 'builtin' || engine === 'alass') && !referenceValue) {
setSubsyncStatus('Select a reference for alass.', true); setSubsyncStatus(
engine === 'builtin' ? 'Select a reference source.' : 'Select a reference for alass.',
true,
);
return;
}
if (engine === 'offset' && offsetMs === 0) {
setSubsyncStatus('Enter a non-zero offset in milliseconds.', true);
return; return;
} }
const useVideoReference = referenceValue === VIDEO_REFERENCE_VALUE;
const request: SubsyncManualRunRequest = { const request: SubsyncManualRunRequest = {
engine, engine,
targetTrackId, targetTrackId,
...(currentPayload.mediaPath ? { mediaPath: currentPayload.mediaPath } : {}),
}; };
if (engine === 'alass') { if (engine === 'builtin' || engine === 'alass') {
request.referenceMode = useVideoReference ? 'video' : 'track'; const parsed = parseReferenceValue(referenceValue);
request.referenceTrackId = useVideoReference ? null : Number.parseInt(referenceValue, 10); request.referenceMode = parsed.referenceMode;
request.referenceTrackId = parsed.referenceTrackId;
if (parsed.referenceFilePath !== null) {
request.referenceFilePath = parsed.referenceFilePath;
}
if (ctx.dom.subsyncStripSignsCheckbox) {
request.stripSigns = stripSigns;
}
if (engine === 'builtin' && ctx.dom.subsyncAllowSplitsCheckbox) {
request.allowSplits = allowSplits;
}
} else if (engine === 'offset') {
request.offsetMs = offsetMs;
} }
const payloadSnapshot: SubsyncManualPayload = { const payloadSnapshot: SubsyncManualPayload = {
...currentPayload, ...currentPayload,
subtitleTracks: currentPayload.subtitleTracks.map((track) => ({ ...track })), subtitleTracks: currentPayload.subtitleTracks.map((track) => ({ ...track })),
referenceCandidates: currentPayload.referenceCandidates?.map((candidate) => ({
...candidate,
})),
};
const selection: SubsyncSelection = {
engine,
referenceValue,
targetTrackId,
stripSigns,
allowSplits,
offsetMs,
}; };
const selection: SubsyncSelection = { engine, referenceValue, targetTrackId };
ctx.state.subsyncSubmitting = true; ctx.state.subsyncSubmitting = true;
ctx.dom.subsyncRunButton.disabled = true; ctx.dom.subsyncRunButton.disabled = true;
@@ -251,12 +518,21 @@ export function createSubsyncModal(
ctx.dom.subsyncCloseButton.addEventListener('click', () => { ctx.dom.subsyncCloseButton.addEventListener('click', () => {
closeSubsyncModal(); closeSubsyncModal();
}); });
ctx.dom.subsyncEngineBuiltin?.addEventListener('change', () => {
updateSubsyncFieldVisibility();
});
ctx.dom.subsyncEngineAlass.addEventListener('change', () => { ctx.dom.subsyncEngineAlass.addEventListener('change', () => {
updateSubsyncFieldVisibility(); updateSubsyncFieldVisibility();
}); });
ctx.dom.subsyncEngineFfsubsync.addEventListener('change', () => { ctx.dom.subsyncEngineFfsubsync.addEventListener('change', () => {
updateSubsyncFieldVisibility(); updateSubsyncFieldVisibility();
}); });
ctx.dom.subsyncEngineOffset?.addEventListener('change', () => {
updateSubsyncFieldVisibility();
});
ctx.dom.subsyncBrowseReferenceButton?.addEventListener('click', () => {
void browseReferenceFile();
});
ctx.dom.subsyncTargetSelect.addEventListener('change', () => { ctx.dom.subsyncTargetSelect.addEventListener('change', () => {
renderReferenceTracks(ctx.dom.subsyncReferenceSelect.value || null); renderReferenceTracks(ctx.dom.subsyncReferenceSelect.value || null);
}); });
+7
View File
@@ -759,6 +759,13 @@ export function createSubtitleSidebarModal(
ctx.dom.subtitleSidebarClose.addEventListener('click', () => { ctx.dom.subtitleSidebarClose.addEventListener('click', () => {
closeSubtitleSidebarModal(); closeSubtitleSidebarModal();
}); });
ctx.dom.subtitleSidebarSync?.addEventListener('click', (event) => {
if (event.shiftKey && window.electronAPI.openSubsyncManual) {
void window.electronAPI.openSubsyncManual();
return;
}
void window.electronAPI.dispatchSessionAction('triggerSubsync');
});
ctx.dom.subtitleSidebarList.addEventListener('click', (event) => { ctx.dom.subtitleSidebarList.addEventListener('click', (event) => {
if (hasSubtitleSidebarSelection(ctx.dom.subtitleSidebarList)) return; if (hasSubtitleSidebarSelection(ctx.dom.subtitleSidebarList)) return;
const target = event.target; const target = event.target;
+54 -4
View File
@@ -3197,6 +3197,17 @@ iframe[id^='yomitan-popup'],
display: none; display: none;
} }
.subsync-guidance {
margin-bottom: 12px;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid rgba(249, 226, 175, 0.35);
background: rgba(249, 226, 175, 0.08);
color: var(--ctp-yellow);
font-size: 12.5px;
line-height: 1.45;
}
.subsync-form { .subsync-form {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -3211,16 +3222,54 @@ iframe[id^='yomitan-popup'],
color: var(--ctp-subtext1); color: var(--ctp-subtext1);
} }
.subsync-radio-group {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
}
.subsync-radio { .subsync-radio {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 8px; gap: 6px;
margin-right: 14px;
font-size: 13px; font-size: 13px;
color: var(--ctp-subtext1); color: var(--ctp-subtext1);
} }
.subsync-field select { .subsync-reference-row {
display: flex;
gap: 8px;
align-items: stretch;
}
.subsync-reference-row select {
flex: 1 1 auto;
min-width: 0;
}
.subsync-browse-button {
flex: 0 0 auto;
padding: 6px 12px;
font-size: 12.5px;
}
.subsync-options {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
padding-top: 2px;
}
.subsync-checkbox {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
color: var(--ctp-subtext1);
}
.subsync-field select,
.subsync-field input[type='number'] {
background: rgba(24, 25, 38, 0.9); background: rgba(24, 25, 38, 0.9);
border: 1px solid rgba(110, 115, 141, 0.2); border: 1px solid rgba(110, 115, 141, 0.2);
border-radius: 6px; border-radius: 6px;
@@ -3228,7 +3277,8 @@ iframe[id^='yomitan-popup'],
padding: 8px 10px; padding: 8px 10px;
} }
.subsync-field select:focus-visible { .subsync-field select:focus-visible,
.subsync-field input[type='number']:focus-visible {
outline: 2px solid var(--ctp-blue); outline: 2px solid var(--ctp-blue);
outline-offset: 2px; outline-offset: 2px;
} }
+22
View File
@@ -142,12 +142,22 @@ export type RendererDom = {
subsyncModal: HTMLDivElement; subsyncModal: HTMLDivElement;
subsyncCloseButton: HTMLButtonElement; subsyncCloseButton: HTMLButtonElement;
subsyncGuidance: HTMLDivElement;
subsyncEngineBuiltin: HTMLInputElement;
subsyncEngineAlass: HTMLInputElement; subsyncEngineAlass: HTMLInputElement;
subsyncEngineFfsubsync: HTMLInputElement; subsyncEngineFfsubsync: HTMLInputElement;
subsyncEngineOffset: HTMLInputElement;
subsyncReferenceLabel: HTMLLabelElement; subsyncReferenceLabel: HTMLLabelElement;
subsyncReferenceSelect: HTMLSelectElement; subsyncReferenceSelect: HTMLSelectElement;
subsyncBrowseReferenceButton: HTMLButtonElement;
subsyncTargetLabel: HTMLLabelElement; subsyncTargetLabel: HTMLLabelElement;
subsyncTargetSelect: HTMLSelectElement; subsyncTargetSelect: HTMLSelectElement;
subsyncOptionsGroup: HTMLDivElement;
subsyncStripSignsCheckbox: HTMLInputElement;
subsyncAllowSplitsLabel: HTMLLabelElement;
subsyncAllowSplitsCheckbox: HTMLInputElement;
subsyncOffsetLabel: HTMLLabelElement;
subsyncOffsetInput: HTMLInputElement;
subsyncRunButton: HTMLButtonElement; subsyncRunButton: HTMLButtonElement;
subsyncStatus: HTMLDivElement; subsyncStatus: HTMLDivElement;
@@ -172,6 +182,7 @@ export type RendererDom = {
subtitleSidebarModal: HTMLDivElement; subtitleSidebarModal: HTMLDivElement;
subtitleSidebarContent: HTMLDivElement; subtitleSidebarContent: HTMLDivElement;
subtitleSidebarClose: HTMLButtonElement; subtitleSidebarClose: HTMLButtonElement;
subtitleSidebarSync: HTMLButtonElement;
subtitleSidebarCopy: HTMLButtonElement; subtitleSidebarCopy: HTMLButtonElement;
subtitleSidebarStatus: HTMLDivElement; subtitleSidebarStatus: HTMLDivElement;
subtitleSidebarList: HTMLUListElement; subtitleSidebarList: HTMLUListElement;
@@ -419,12 +430,22 @@ export function resolveRendererDom(): RendererDom {
subsyncModal: getRequiredElement<HTMLDivElement>('subsyncModal'), subsyncModal: getRequiredElement<HTMLDivElement>('subsyncModal'),
subsyncCloseButton: getRequiredElement<HTMLButtonElement>('subsyncClose'), subsyncCloseButton: getRequiredElement<HTMLButtonElement>('subsyncClose'),
subsyncGuidance: getRequiredElement<HTMLDivElement>('subsyncGuidance'),
subsyncEngineBuiltin: getRequiredElement<HTMLInputElement>('subsyncEngineBuiltin'),
subsyncEngineAlass: getRequiredElement<HTMLInputElement>('subsyncEngineAlass'), subsyncEngineAlass: getRequiredElement<HTMLInputElement>('subsyncEngineAlass'),
subsyncEngineFfsubsync: getRequiredElement<HTMLInputElement>('subsyncEngineFfsubsync'), subsyncEngineFfsubsync: getRequiredElement<HTMLInputElement>('subsyncEngineFfsubsync'),
subsyncEngineOffset: getRequiredElement<HTMLInputElement>('subsyncEngineOffset'),
subsyncReferenceLabel: getRequiredElement<HTMLLabelElement>('subsyncReferenceLabel'), subsyncReferenceLabel: getRequiredElement<HTMLLabelElement>('subsyncReferenceLabel'),
subsyncReferenceSelect: getRequiredElement<HTMLSelectElement>('subsyncReferenceSelect'), subsyncReferenceSelect: getRequiredElement<HTMLSelectElement>('subsyncReferenceSelect'),
subsyncBrowseReferenceButton: getRequiredElement<HTMLButtonElement>('subsyncBrowseReference'),
subsyncTargetLabel: getRequiredElement<HTMLLabelElement>('subsyncTargetLabel'), subsyncTargetLabel: getRequiredElement<HTMLLabelElement>('subsyncTargetLabel'),
subsyncTargetSelect: getRequiredElement<HTMLSelectElement>('subsyncTargetSelect'), subsyncTargetSelect: getRequiredElement<HTMLSelectElement>('subsyncTargetSelect'),
subsyncOptionsGroup: getRequiredElement<HTMLDivElement>('subsyncOptionsGroup'),
subsyncStripSignsCheckbox: getRequiredElement<HTMLInputElement>('subsyncStripSigns'),
subsyncAllowSplitsLabel: getRequiredElement<HTMLLabelElement>('subsyncAllowSplitsLabel'),
subsyncAllowSplitsCheckbox: getRequiredElement<HTMLInputElement>('subsyncAllowSplits'),
subsyncOffsetLabel: getRequiredElement<HTMLLabelElement>('subsyncOffsetLabel'),
subsyncOffsetInput: getRequiredElement<HTMLInputElement>('subsyncOffsetInput'),
subsyncRunButton: getRequiredElement<HTMLButtonElement>('subsyncRun'), subsyncRunButton: getRequiredElement<HTMLButtonElement>('subsyncRun'),
subsyncStatus: getRequiredElement<HTMLDivElement>('subsyncStatus'), subsyncStatus: getRequiredElement<HTMLDivElement>('subsyncStatus'),
@@ -453,6 +474,7 @@ export function resolveRendererDom(): RendererDom {
subtitleSidebarModal: getRequiredElement<HTMLDivElement>('subtitleSidebarModal'), subtitleSidebarModal: getRequiredElement<HTMLDivElement>('subtitleSidebarModal'),
subtitleSidebarContent: getRequiredElement<HTMLDivElement>('subtitleSidebarContent'), subtitleSidebarContent: getRequiredElement<HTMLDivElement>('subtitleSidebarContent'),
subtitleSidebarClose: getRequiredElement<HTMLButtonElement>('subtitleSidebarClose'), subtitleSidebarClose: getRequiredElement<HTMLButtonElement>('subtitleSidebarClose'),
subtitleSidebarSync: getRequiredElement<HTMLButtonElement>('subtitleSidebarSync'),
subtitleSidebarCopy: getRequiredElement<HTMLButtonElement>('subtitleSidebarCopy'), subtitleSidebarCopy: getRequiredElement<HTMLButtonElement>('subtitleSidebarCopy'),
subtitleSidebarStatus: getRequiredElement<HTMLDivElement>('subtitleSidebarStatus'), subtitleSidebarStatus: getRequiredElement<HTMLDivElement>('subtitleSidebarStatus'),
subtitleSidebarList: getRequiredElement<HTMLUListElement>('subtitleSidebarList'), subtitleSidebarList: getRequiredElement<HTMLUListElement>('subtitleSidebarList'),
+2
View File
@@ -82,6 +82,8 @@ export const IPC_CHANNELS = {
focusMainWindow: 'focus-main-window', focusMainWindow: 'focus-main-window',
activatePlaybackWindowForOverlayInteraction: 'overlay:activate-playback-window', activatePlaybackWindowForOverlayInteraction: 'overlay:activate-playback-window',
runSubsyncManual: 'subsync:run-manual', runSubsyncManual: 'subsync:run-manual',
openSubsyncManual: 'subsync:open-manual-request',
pickSubsyncReferenceFile: 'subsync:pick-reference-file',
getRuntimeOptions: 'runtime-options:get', getRuntimeOptions: 'runtime-options:get',
setRuntimeOption: 'runtime-options:set', setRuntimeOption: 'runtime-options:set',
getAnilistStatus: 'anilist:get-status', getAnilistStatus: 'anilist:get-status',
+24 -1
View File
@@ -4,7 +4,11 @@ import test from 'node:test';
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions'; import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions';
import { compileSessionBindings } from '../../core/services/session-bindings'; import { compileSessionBindings } from '../../core/services/session-bindings';
import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config'; import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config';
import { parseSessionActionDispatchRequest, parseUnforwardedMpvKeyReport } from './validators'; import {
parseSessionActionDispatchRequest,
parseSubsyncManualRunRequest,
parseUnforwardedMpvKeyReport,
} from './validators';
// Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the // Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the
// SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to // SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to
@@ -46,3 +50,22 @@ test('unforwarded mpv key reports accept known reasons only', () => {
assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null); assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null);
assert.equal(parseUnforwardedMpvKeyReport(null), null); assert.equal(parseUnforwardedMpvKeyReport(null), null);
}); });
test('parseSubsyncManualRunRequest validates optional mediaPath', () => {
const parsed = parseSubsyncManualRunRequest({
engine: 'builtin',
mediaPath: '/tmp/ep01.mkv',
referenceMode: 'track',
referenceTrackId: 2,
targetTrackId: 1,
});
assert.equal(parsed?.mediaPath, '/tmp/ep01.mkv');
assert.equal(
parseSubsyncManualRunRequest({
engine: 'builtin',
mediaPath: 123,
targetTrackId: 1,
}),
null,
);
});
+45 -3
View File
@@ -315,9 +315,29 @@ export function parseControllerConfigUpdate(value: unknown): ControllerConfigUpd
export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRequest | null { export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRequest | null {
if (!isObject(value)) return null; if (!isObject(value)) return null;
const { engine, referenceMode, referenceTrackId, targetTrackId } = value; const {
if (engine !== 'alass' && engine !== 'ffsubsync') return null; engine,
if (referenceMode !== undefined && referenceMode !== 'track' && referenceMode !== 'video') { mediaPath,
referenceMode,
referenceTrackId,
referenceFilePath,
targetTrackId,
stripSigns,
allowSplits,
offsetMs,
} = value;
if (engine !== 'builtin' && engine !== 'alass' && engine !== 'ffsubsync' && engine !== 'offset') {
return null;
}
if (mediaPath !== undefined && mediaPath !== null && typeof mediaPath !== 'string') {
return null;
}
if (
referenceMode !== undefined &&
referenceMode !== 'track' &&
referenceMode !== 'video' &&
referenceMode !== 'file'
) {
return null; return null;
} }
@@ -331,11 +351,33 @@ export function parseSubsyncManualRunRequest(value: unknown): SubsyncManualRunRe
const parsedTargetTrackId = parseOptionalTrackId(targetTrackId); const parsedTargetTrackId = parseOptionalTrackId(targetTrackId);
if (parsedReferenceTrackId === false || parsedTargetTrackId === false) return null; if (parsedReferenceTrackId === false || parsedTargetTrackId === false) return null;
if (
referenceFilePath !== undefined &&
referenceFilePath !== null &&
typeof referenceFilePath !== 'string'
) {
return null;
}
if (stripSigns !== undefined && typeof stripSigns !== 'boolean') return null;
if (allowSplits !== undefined && typeof allowSplits !== 'boolean') return null;
if (
offsetMs !== undefined &&
offsetMs !== null &&
(typeof offsetMs !== 'number' || !Number.isFinite(offsetMs))
) {
return null;
}
return { return {
engine, engine,
...(mediaPath !== undefined ? { mediaPath } : {}),
referenceMode, referenceMode,
referenceTrackId: parsedReferenceTrackId, referenceTrackId: parsedReferenceTrackId,
referenceFilePath: typeof referenceFilePath === 'string' ? referenceFilePath : null,
targetTrackId: parsedTargetTrackId, targetTrackId: parsedTargetTrackId,
stripSigns,
allowSplits,
offsetMs: typeof offsetMs === 'number' ? Math.round(offsetMs) : null,
}; };
} }
+256
View File
@@ -0,0 +1,256 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
alignNoSplit,
alignSubtitleFileToReferenceSpans,
evaluateReferenceAlignmentToAudio,
evaluateReferenceAlignmentToSampledAudio,
joinSpans,
wrappedCoverage,
type SampledAudioWindow,
} from './alass-align';
import {
formatSrtTimestamp,
parseSubtitleFileContent,
type SubtitleTimeSpan,
} from './subtitle-lines';
function generateDialogueRhythm(seedInit: bigint, step: bigint): SubtitleTimeSpan[] {
const out: SubtitleTimeSpan[] = [];
let seed = seedInit;
const mask = (1n << 64n) - 1n;
let t = 5.0;
while (t < 1300.0) {
seed = (seed * 6364136223846793005n + step) & mask;
const len = 0.8 + (Number(seed >> 33n) / Number(1n << 31n)) * 3.0;
const gap = 0.4 + (Number((seed >> 13n) & 0xffffn) / 65536.0) * 4.0;
out.push({ start: t, end: t + len });
t += len + gap;
}
return out;
}
function spansToSrtFile(spans: readonly SubtitleTimeSpan[]): string {
return spans
.map(
(s, i) =>
`${i + 1}\n${formatSrtTimestamp(Math.max(0, s.start))} --> ${formatSrtTimestamp(Math.max(0.05, s.end))}\nセリフ ${i + 1}\n`,
)
.join('\n');
}
test('joinSpans merges overlapping spans so stacked karaoke lines count once', () => {
const merged = joinSpans([
{ start: 10, end: 15 },
{ start: 10, end: 15 },
{ start: 12, end: 18 },
{ start: 20, end: 22 },
]);
assert.deepEqual(merged, [
{ start: 10, end: 18 },
{ start: 20, end: 22 },
]);
});
test('alignNoSplit finds exact large and small offsets', () => {
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
const shifted = ref.map((s) => ({ start: s.start + 42.35, end: s.end + 42.35 }));
const delta = alignNoSplit(joinSpans(ref), shifted);
assert.ok(Math.abs(delta + 42.35) <= 0.05, `expected ~-42.35s, got ${delta}`);
});
test('alignSubtitleFileToReferenceSpans recovers fixed shift and ignores stacked songs in reference', () => {
const dialogue = generateDialogueRhythm(7n, 1442695040888963407n);
const refWithSong: SubtitleTimeSpan[] = [...dialogue];
// Simulate 8 simultaneous stacked karaoke lines during an ending song.
for (let i = 0; i < 8; i += 1) {
refWithSong.push({ start: 1310, end: 1400 });
}
const targetSpans = dialogue.map((s) => ({
start: s.start + 2.5 - 0.08,
end: s.end + 2.5 + 0.15,
}));
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(targetSpans), 'ep01.ja.srt');
const result = alignSubtitleFileToReferenceSpans(parsedTarget, refWithSong, {
calibration: 'clean',
lengthSec: 1420,
});
assert.equal(result.confident, true);
assert.ok(result.confidence >= 0.8, `expected high confidence, got ${result.confidence}`);
assert.ok(Math.abs(result.offsetMs + 2500) <= 120, `expected ~-2500ms, got ${result.offsetMs}`);
assert.equal(result.segments, 1);
});
test('alignSubtitleFileToReferenceSpans corrects PAL 25fps speed-up automatically', () => {
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
const palRatio = 23.976 / 25.0;
const palSpans = ref.map((s) => ({
start: s.start / palRatio + 1.2,
end: s.end / palRatio + 1.2,
}));
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(palSpans), 'pal.ja.srt');
const result = alignSubtitleFileToReferenceSpans(parsedTarget, ref, {
calibration: 'clean',
lengthSec: 1320,
});
assert.equal(result.confident, true);
assert.ok(
Math.abs(result.ratio - palRatio) < 1e-5,
`expected ratio ${palRatio}, got ${result.ratio}`,
);
});
test('alignSubtitleFileToReferenceSpans handles TV broadcast ad breaks in pieces', () => {
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
const broadcastSpans = ref.map((s) => {
const adOffset = s.start < 430 ? 30 : s.start < 870 ? 120 : 195;
return { start: s.start + adOffset, end: s.end + adOffset };
});
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(broadcastSpans), 'tv.ja.srt');
const result = alignSubtitleFileToReferenceSpans(parsedTarget, ref, {
calibration: 'clean',
lengthSec: 1320,
allowSplits: true,
});
assert.equal(result.cut, true);
assert.equal(result.segments, 3);
assert.equal(result.confident, true);
const retimed = parseSubtitleFileContent(result.rewrittenContent, 'tv.ja.srt');
for (let i = 0; i < ref.length; i += 1) {
assert.ok(
Math.abs(retimed.events[i]!.start - ref[i]!.start) < 0.25,
`line ${i} misaligned: got ${retimed.events[i]!.start}, expected ${ref[i]!.start}`,
);
}
});
test('alignSubtitleFileToReferenceSpans rejects an unrelated episode with low confidence', () => {
const ref = generateDialogueRhythm(7n, 1442695040888963407n);
const otherEpisode = generateDialogueRhythm(12345n, 0x9e3779b97f4a7c15n);
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(otherEpisode), 'wrong.ja.srt');
const result = alignSubtitleFileToReferenceSpans(parsedTarget, ref, {
calibration: 'clean',
lengthSec: 1320,
});
assert.equal(result.confident, false);
assert.ok(result.confidence < 0.4, `expected low confidence, got ${result.confidence}`);
});
test('evaluateReferenceAlignmentToAudio distinguishes aligned vs shifted English reference tracks', () => {
const audioSpeech = generateDialogueRhythm(7n, 1442695040888963407n);
// Well-aligned English track (leads audio by ~0.1s).
const goodEng = audioSpeech.map((s) => ({ start: Math.max(0, s.start - 0.1), end: s.end + 0.1 }));
// Misaligned English track (shifted +2.8s off audio).
const badEng = audioSpeech.map((s) => ({ start: s.start + 2.8, end: s.end + 2.8 }));
const goodEval = evaluateReferenceAlignmentToAudio(goodEng, audioSpeech, {
audioCalibration: 'noisy',
lengthSec: 1320,
});
const badEval = evaluateReferenceAlignmentToAudio(badEng, audioSpeech, {
audioCalibration: 'noisy',
lengthSec: 1320,
});
assert.equal(goodEval.status, 'aligned');
assert.ok(
Math.abs(goodEval.offsetMs) <= 300,
`expected near-0ms offset, got ${goodEval.offsetMs}`,
);
assert.equal(badEval.status, 'misaligned');
assert.ok(
Math.abs(badEval.offsetMs + 2900) <= 300,
`expected ~-2900ms offset, got ${badEval.offsetMs}`,
);
});
test('evaluateReferenceAlignmentToSampledAudio verifies aligned vs misaligned refs and marks huge shifts unverified', () => {
const fullSpeech = generateDialogueRhythm(7n, 1442695040888963407n);
const windowStarts = [160, 460, 780, 1080];
const windowDur = 60;
const windows: SampledAudioWindow[] = windowStarts.map((startSec) => ({
startSec,
durationSec: windowDur,
speechSpans: fullSpeech
.filter((s) => s.end > startSec && s.start < startSec + windowDur)
.map((s) => ({
start: Math.max(0, s.start - startSec),
end: Math.min(windowDur, s.end - startSec),
})),
}));
const alignedRef = fullSpeech.map((s) => ({
start: Math.max(0, s.start - 0.1),
end: s.end + 0.1,
}));
const shiftedRef = fullSpeech.map((s) => ({ start: s.start + 3.2, end: s.end + 3.2 }));
const hugeShiftRef = fullSpeech.map((s) => ({ start: s.start + 45.0, end: s.end + 45.0 }));
const alignedEval = evaluateReferenceAlignmentToSampledAudio(alignedRef, windows);
assert.equal(alignedEval.status, 'aligned');
assert.ok(Math.abs(alignedEval.offsetMs) <= 350, `got ${alignedEval.offsetMs}`);
const shiftedEval = evaluateReferenceAlignmentToSampledAudio(shiftedRef, windows);
assert.equal(shiftedEval.status, 'misaligned');
assert.ok(Math.abs(shiftedEval.offsetMs + 3300) <= 350, `got ${shiftedEval.offsetMs}`);
// A 45s shift is outside the ±12s sample window search radius -> returns 'unverified' so caller escalates to full audio.
const hugeEval = evaluateReferenceAlignmentToSampledAudio(hugeShiftRef, windows);
assert.equal(hugeEval.status, 'unverified');
});
test('wrappedCoverage counts both fragments of a cue crossing the wrap boundary', () => {
const line = [{ start: 54, end: 58 }];
const ref = [
{ start: 0, end: 3 },
{ start: 59, end: 60 },
];
// Shifting [54, 58] by +5s in a 60s window wraps to [59, 60] (1s) + [0, 3] (3s) = 4s / 4s = 1.0.
assert.equal(wrappedCoverage(line, 4, ref, 5, 60), 1);
// Also works for shifts larger than the window length and negative shifts.
assert.equal(wrappedCoverage(line, 4, ref, 65, 60), 1);
assert.equal(
wrappedCoverage(
[{ start: 1, end: 5 }],
4,
[
{ start: 0, end: 2 },
{ start: 58, end: 60 },
],
-3,
60,
),
1,
);
});
test('alignSubtitleFileToReferenceSpans rejects broadcast pieces that collapse onto the same reference section', () => {
const actPattern = generateDialogueRhythm(7n, 1442695040888963407n).filter((s) => s.end < 120);
// Two identical target acts separated by a long pause within the standing shift range,
// while the reference only contains one matching section.
const repeatedTarget = [
...actPattern,
...actPattern.map((s) => ({ start: s.start + 150, end: s.end + 150 })),
];
const parsedTarget = parseSubtitleFileContent(spansToSrtFile(repeatedTarget), 'dup-acts.ja.srt');
const result = alignSubtitleFileToReferenceSpans(parsedTarget, actPattern, {
calibration: 'clean',
lengthSec: 320,
allowSplits: true,
});
assert.equal(result.cut, false);
assert.equal(result.confident, false);
});
File diff suppressed because it is too large. Load diff
+142
View File
@@ -0,0 +1,142 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
clearAudioSpeechCache,
detectSpeechSpansFromPcm,
extractAudioSpeechSpans,
getCachedAudioSpeechSpans,
parseRawSileroVadSegments,
} from './audio-speech';
test('detectSpeechSpansFromPcm detects voice-band bursts separated by quiet background', () => {
const sampleRate = 8000;
const totalSec = 20;
const samples = new Int16Array(sampleRate * totalSec);
const expectedSpans: Array<[number, number]> = [
[2.0, 4.0],
[7.5, 9.5],
[13.0, 15.5],
];
// Fill quiet ambient floor across whole clip.
for (let i = 0; i < samples.length; i += 1) {
const t = i / sampleRate;
samples[i] = Math.round(Math.sin(2 * Math.PI * 500 * t) * 180);
}
// Overlay speech-like multi-frequency formant signal inside expected spans.
for (const [start, end] of expectedSpans) {
const sIdx = Math.floor(start * sampleRate);
const eIdx = Math.floor(end * sampleRate);
for (let i = sIdx; i < eIdx; i += 1) {
const t = i / sampleRate;
const sig =
0.5 * Math.sin(2 * Math.PI * 420 * t) +
0.3 * Math.sin(2 * Math.PI * 1150 * t) +
0.2 * Math.sin(2 * Math.PI * 2100 * t);
samples[i] = Math.round(sig * 12000);
}
}
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, sampleRate);
assert.equal(durationSec, totalSec);
assert.equal(spans.length, expectedSpans.length);
for (let i = 0; i < expectedSpans.length; i += 1) {
assert.ok(Math.abs(spans[i]!.start - expectedSpans[i]![0]) <= 0.15);
assert.ok(Math.abs(spans[i]!.end - expectedSpans[i]![1]) <= 0.25);
}
});
test('parseRawSileroVadSegments parses fine-grained speech segments from whisper-vad output', () => {
const stdout = [
'Detected 2 speech segments:',
'Speech segment 0: start = 125.00, end = 340.00',
'Speech segment 1: start = 510.50, end = 690.00',
].join('\n');
assert.deepEqual(parseRawSileroVadSegments(stdout), [
{ start: 1.25, end: 3.4 },
{ start: 5.105, end: 6.9 },
]);
});
test('audio speech cache keys distinguish built-in VAD from Silero VAD config', async () => {
if (process.platform === 'win32') return;
clearAudioSpeechCache();
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-vad-cache-'));
const videoPath = path.join(tmpDir, 'ep01.mkv');
const modelPath = path.join(tmpDir, 'silero.bin');
const ffmpegScript = path.join(tmpDir, 'ffmpeg.sh');
const vadScript = path.join(tmpDir, 'whisper-vad.sh');
fs.writeFileSync(videoPath, 'video');
fs.writeFileSync(modelPath, 'model');
// Fake ffmpeg outputs silence for pipe:1 (built-in VAD) and a tiny WAV when given an output file (Silero).
fs.writeFileSync(
ffmpegScript,
`#!/bin/sh
last=""
for arg in "$@"; do last="$arg"; done
if [ "$last" = "pipe:1" ]; then
dd if=/dev/zero bs=1600 count=1 2>/dev/null
else
printf 'RIFF....WAVEdata................................................' > "$last"
fi
exit 0
`,
{ mode: 0o755 },
);
fs.chmodSync(ffmpegScript, 0o755);
fs.writeFileSync(
vadScript,
`#!/bin/sh
echo "Speech segment 0: start = 100.00, end = 300.00"
exit 0
`,
{ mode: 0o755 },
);
fs.chmodSync(vadScript, 0o755);
try {
const builtin = await extractAudioSpeechSpans({
ffmpegPath: ffmpegScript,
videoPath,
audioStreamIndex: 1,
});
assert.equal(builtin.source, 'builtin-vad');
assert.equal(builtin.spans.length, 0);
assert.ok(getCachedAudioSpeechSpans(videoPath, 1) !== null);
assert.equal(
getCachedAudioSpeechSpans(videoPath, 1, {
vadExecutablePath: vadScript,
vadModelPath: modelPath,
}),
null,
);
const silero = await extractAudioSpeechSpans({
ffmpegPath: ffmpegScript,
videoPath,
audioStreamIndex: 1,
vadExecutablePath: vadScript,
vadModelPath: modelPath,
});
assert.equal(silero.source, 'silero-vad');
assert.deepEqual(silero.spans, [{ start: 1.0, end: 3.0 }]);
assert.equal(
getCachedAudioSpeechSpans(videoPath, 1, {
vadExecutablePath: vadScript,
vadModelPath: modelPath,
})?.source,
'silero-vad',
);
} finally {
clearAudioSpeechCache();
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
+863
View File
@@ -0,0 +1,863 @@
import * as childProcess from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import type { SampledAudioWindow } from './alass-align';
import {
decodeSubtitleBytes,
parseSubtitleFileContent,
type ParsedSubtitleFile,
type SubtitleTimeSpan,
} from './subtitle-lines';
import { extensionToFfmpegMuxer, fileExists, resolveCommandInvocation, runCommand } from './utils';
const PCM_VAD_SAMPLE_RATE = 8000;
const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400';
const AUDIO_EXTRACT_TIMEOUT_MS = 180_000;
const SAMPLED_WINDOW_TIMEOUT_MS = 30_000;
const SAMPLED_WINDOW_DURATION_SEC = 60;
const SAMPLED_MIN_MEDIA_DURATION_SEC = 300;
const SAMPLED_WINDOW_FRACTIONS = [0.12, 0.35, 0.6, 0.82] as const;
const MAX_CACHED_AUDIO_SPEECH_ENTRIES = 3;
export type AudioSpeechSource = 'silero-vad' | 'builtin-vad';
export interface AudioSpeechResult {
spans: SubtitleTimeSpan[];
durationSec: number;
calibration: 'clean' | 'noisy';
source: AudioSpeechSource;
}
export interface ExtractAudioSpeechOptions {
ffmpegPath: string;
videoPath: string;
audioStreamIndex: number | null;
vadExecutablePath?: string | null;
vadModelPath?: string | null;
signal?: AbortSignal;
}
export interface EmbeddedTrackSpec {
ffIndex: number;
extension: string;
}
export interface SinglePassRipMediaOptions extends ExtractAudioSpeechOptions {
embeddedTracks: readonly EmbeddedTrackSpec[];
includeAudio: boolean;
}
export interface SinglePassRipMediaResult {
audioSpeech: AudioSpeechResult | null;
embeddedSubtitles: Map<number, ParsedSubtitleFile>;
}
const audioSpeechCache = new Map<string, AudioSpeechResult>();
const sampledAudioCache = new Map<string, SampledAudioWindow[]>();
const embeddedSubtitlesCache = new Map<string, Map<number, ParsedSubtitleFile>>();
export function clearAudioSpeechCache(): void {
audioSpeechCache.clear();
sampledAudioCache.clear();
embeddedSubtitlesCache.clear();
}
function buildFileSignatureKey(videoPath: string): string | null {
try {
const stat = fs.statSync(videoPath);
if (!stat.isFile()) return null;
return `${videoPath}\0${stat.size}\0${stat.mtimeMs}`;
} catch {
return null;
}
}
function buildVadConfigKey(
vadExecutablePath?: string | null,
vadModelPath?: string | null,
): string {
const exec = vadExecutablePath?.trim() ?? '';
const model = vadModelPath?.trim() ?? '';
if (exec.length > 0 && model.length > 0 && fileExists(model)) {
return `silero:${exec}\0${model}`;
}
return 'builtin';
}
function buildAudioCacheKey(
videoPath: string,
audioStreamIndex: number | null,
vadConfigKey = 'builtin',
): string | null {
const sig = buildFileSignatureKey(videoPath);
if (!sig) return null;
return `${sig}\0${audioStreamIndex ?? 'default'}\0${vadConfigKey}`;
}
export function getCachedAudioSpeechSpans(
videoPath: string,
audioStreamIndex: number | null,
vadConfig?: { vadExecutablePath?: string | null; vadModelPath?: string | null } | null,
): AudioSpeechResult | null {
const vadKey = buildVadConfigKey(vadConfig?.vadExecutablePath, vadConfig?.vadModelPath);
const key = buildAudioCacheKey(videoPath, audioStreamIndex, vadKey);
return key ? (audioSpeechCache.get(key) ?? null) : null;
}
function rememberLru<T>(cache: Map<string, T>, key: string | null, value: T): void {
if (!key) return;
if (cache.has(key)) {
cache.delete(key);
}
cache.set(key, value);
while (cache.size > MAX_CACHED_AUDIO_SPEECH_ENTRIES) {
const oldestKey = cache.keys().next().value;
if (oldestKey === undefined) break;
cache.delete(oldestKey);
}
}
function rememberAudioSpeech(key: string | null, result: AudioSpeechResult): void {
rememberLru(audioSpeechCache, key, result);
}
/**
* Pure-TypeScript voice-band speech activity detector operating on 16-bit mono
* PCM (expected 8 kHz, voice band-passed 200 to 3400 Hz). Uses a global dynamic-range
* histogram with hysteresis, zero-crossing gating, hangover, and short-gap bridging.
*/
export function detectSpeechSpansFromPcm(
samples: Int16Array,
sampleRate = PCM_VAD_SAMPLE_RATE,
): { spans: SubtitleTimeSpan[]; durationSec: number } {
const durationSec = sampleRate > 0 ? samples.length / sampleRate : 0;
const frameSamples = Math.max(1, Math.round(sampleRate * 0.01)); // 10ms frames
const frameCount = Math.floor(samples.length / frameSamples);
if (frameCount === 0) {
return { spans: [], durationSec };
}
const frameDb = new Float32Array(frameCount);
const frameZcr = new Float32Array(frameCount);
// Histogram from -90 dB to 0 dB in 0.5 dB bins (181 bins) for O(N) percentiles.
const HIST_MIN = -90;
const HIST_BINS = 181;
const hist = new Int32Array(HIST_BINS);
let activeFrames = 0;
for (let f = 0; f < frameCount; f += 1) {
const base = f * frameSamples;
let sumSq = 0;
let crossings = 0;
let prevSign = samples[base]! >= 0 ? 1 : -1;
for (let i = 0; i < frameSamples; i += 1) {
const s = samples[base + i]! / 32768;
sumSq += s * s;
const sign = samples[base + i]! >= 0 ? 1 : -1;
if (i > 0 && sign !== prevSign) crossings += 1;
prevSign = sign;
}
const rms = Math.sqrt(sumSq / frameSamples);
const db = rms > 1e-6 ? 20 * Math.log10(rms) : -100;
frameDb[f] = db;
frameZcr[f] = crossings / frameSamples;
if (db > -88) {
const bin = Math.max(0, Math.min(HIST_BINS - 1, Math.round((db - HIST_MIN) * 2)));
hist[bin] = hist[bin]! + 1;
activeFrames += 1;
}
}
if (activeFrames < 10) {
return { spans: [], durationSec };
}
const percentileDb = (fraction: number): number => {
const target = Math.max(1, Math.floor(activeFrames * fraction));
let acc = 0;
for (let b = 0; b < HIST_BINS; b += 1) {
acc += hist[b]!;
if (acc >= target) {
return HIST_MIN + b * 0.5;
}
}
return 0;
};
const p20 = percentileDb(0.2);
const p85 = percentileDb(0.85);
const dynamicRange = Math.max(0, p85 - p20);
// Set onset threshold cleanly between background noise floor and speech peak.
const onsetDb =
dynamicRange >= 8 ? Math.max(p20 + dynamicRange * 0.45, p20 + 5.5) : Math.max(p85 - 5.0, -52);
const releaseDb = onsetDb - Math.min(4.0, Math.max(2.0, dynamicRange * 0.15));
// Hysteresis + 120ms hangover.
const HANGOVER_FRAMES = 12;
const MIN_SPEECH_FRAMES = 8; // 80ms
const BRIDGE_GAP_FRAMES = 12; // 120ms
const voiced = new Uint8Array(frameCount);
let inSpeech = false;
let hangover = 0;
for (let f = 0; f < frameCount; f += 1) {
const db = frameDb[f]!;
const zcr = frameZcr[f]!;
const speechLikeZcr = zcr >= 0.015 && zcr <= 0.65;
if (!inSpeech) {
if (db >= onsetDb && speechLikeZcr) {
inSpeech = true;
hangover = HANGOVER_FRAMES;
voiced[f] = 1;
}
} else if (db >= releaseDb && speechLikeZcr) {
hangover = HANGOVER_FRAMES;
voiced[f] = 1;
} else if (hangover > 0) {
hangover -= 1;
voiced[f] = 1;
} else {
inSpeech = false;
}
}
// Extract raw spans and bridge tiny gaps.
const rawSpans: SubtitleTimeSpan[] = [];
let startFrame = -1;
for (let f = 0; f < frameCount; f += 1) {
if (voiced[f] === 1) {
if (startFrame === -1) startFrame = f;
} else if (startFrame !== -1) {
if (f - startFrame >= MIN_SPEECH_FRAMES) {
rawSpans.push({ start: startFrame * 0.01, end: f * 0.01 });
}
startFrame = -1;
}
}
if (startFrame !== -1 && frameCount - startFrame >= MIN_SPEECH_FRAMES) {
rawSpans.push({ start: startFrame * 0.01, end: frameCount * 0.01 });
}
const bridged: SubtitleTimeSpan[] = [];
const maxBridgeSec = BRIDGE_GAP_FRAMES * 0.01;
for (const span of rawSpans) {
const prev = bridged.at(-1);
if (prev && span.start - prev.end <= maxBridgeSec) {
prev.end = span.end;
} else {
bridged.push({ ...span });
}
}
return { spans: bridged, durationSec };
}
/**
* Parse raw Silero speech segments emitted by `whisper-vad-speech-segments`
* without grouping into 20-second transcription passages.
*/
export function parseRawSileroVadSegments(output: string): SubtitleTimeSpan[] {
const spans: SubtitleTimeSpan[] = [];
for (const line of output.split(/\r?\n/)) {
const match = /^Speech segment \d+: start = (\d+(?:\.\d+)?), end = (\d+(?:\.\d+)?)$/.exec(
line.trim(),
);
if (!match) continue;
const start = Number(match[1]) / 100;
const end = Number(match[2]) / 100;
if (Number.isFinite(start) && Number.isFinite(end) && end > start) {
spans.push({ start, end });
}
}
return spans;
}
function streamFfmpegPcm(
ffmpegPath: string,
videoPath: string,
audioStreamIndex: number | null,
signal?: AbortSignal,
): Promise<Buffer> {
return new Promise((resolve, reject) => {
const args = [
'-hide_banner',
'-nostdin',
'-loglevel',
'error',
'-i',
videoPath,
'-vn',
'-sn',
'-dn',
];
if (audioStreamIndex !== null && Number.isInteger(audioStreamIndex) && audioStreamIndex >= 0) {
args.push('-map', `0:${audioStreamIndex}`);
} else {
args.push('-map', '0:a:0');
}
args.push(
'-ac',
'1',
'-ar',
String(PCM_VAD_SAMPLE_RATE),
'-af',
PCM_VAD_FILTER,
'-f',
's16le',
'pipe:1',
);
const invocation = resolveCommandInvocation(ffmpegPath, args);
const child = childProcess.spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'],
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
});
const chunks: Buffer[] = [];
let stderr = '';
let settled = false;
const finishError = (err: Error): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
reject(err);
};
const onAbort = (): void => {
child.kill('SIGKILL');
finishError(new Error('Audio extraction aborted'));
};
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(() => {
child.kill('SIGKILL');
finishError(new Error('Timed out while reading video audio with ffmpeg'));
}, AUDIO_EXTRACT_TIMEOUT_MS);
child.stdout.on('data', (chunk: Buffer) => {
chunks.push(chunk);
});
child.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
});
child.on('error', (error: Error) => {
finishError(error);
});
child.on('close', (code: number | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
if (code !== 0) {
reject(new Error(`ffmpeg audio read failed (code=${code ?? 'n/a'}): ${stderr.trim()}`));
return;
}
resolve(Buffer.concat(chunks));
});
});
}
async function trySileroVadSpeech(
options: ExtractAudioSpeechOptions,
): Promise<AudioSpeechResult | null> {
const vadExec = options.vadExecutablePath?.trim();
const vadModel = options.vadModelPath?.trim();
if (!vadExec || !vadModel || !fileExists(vadModel)) {
return null;
}
let tempDir: string | null = null;
try {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-vad-'));
const wavPath = path.join(tempDir, 'audio.wav');
const ffmpegArgs = [
'-hide_banner',
'-nostdin',
'-y',
'-loglevel',
'error',
'-i',
options.videoPath,
'-vn',
'-sn',
'-dn',
];
if (
options.audioStreamIndex !== null &&
Number.isInteger(options.audioStreamIndex) &&
options.audioStreamIndex >= 0
) {
ffmpegArgs.push('-map', `0:${options.audioStreamIndex}`);
} else {
ffmpegArgs.push('-map', '0:a:0');
}
ffmpegArgs.push('-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', wavPath);
const wavRes = await runCommand(options.ffmpegPath, ffmpegArgs, AUDIO_EXTRACT_TIMEOUT_MS);
if (!wavRes.ok || !fileExists(wavPath)) return null;
const wavStats = fs.statSync(wavPath);
const durationSec = Math.max(0, (wavStats.size - 44) / (16000 * 2));
const vadRes = await runCommand(
vadExec,
[
'-f',
wavPath,
'-vm',
vadModel,
'-vt',
'0.35',
'--vad-min-speech-duration-ms',
'120',
'--vad-min-silence-duration-ms',
'250',
'-vp',
'100',
'-np',
],
AUDIO_EXTRACT_TIMEOUT_MS,
);
if (!vadRes.ok) return null;
const spans = parseRawSileroVadSegments(`${vadRes.stdout}\n${vadRes.stderr}`);
if (spans.length === 0) return null;
return {
spans,
durationSec: Math.max(durationSec, spans[spans.length - 1]!.end),
calibration: 'clean',
source: 'silero-vad',
};
} catch {
return null;
} finally {
if (tempDir) {
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch {
// Best-effort cleanup.
}
}
}
}
export async function extractAudioSpeechSpans(
options: ExtractAudioSpeechOptions,
): Promise<AudioSpeechResult> {
const vadKey = buildVadConfigKey(options.vadExecutablePath, options.vadModelPath);
const cacheKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex, vadKey);
if (cacheKey) {
const cached = audioSpeechCache.get(cacheKey);
if (cached) return cached;
}
// Tier 1: Prefer Silero VAD if whisper-vad-speech-segments + model are available.
const silero = await trySileroVadSpeech(options);
if (silero) {
rememberAudioSpeech(cacheKey, silero);
return silero;
}
// Tier 2: Built-in voice-band PCM speech detector via ffmpeg (zero extra dependencies).
const pcmBuffer = await streamFfmpegPcm(
options.ffmpegPath,
options.videoPath,
options.audioStreamIndex,
options.signal,
);
const sampleCount = Math.floor(pcmBuffer.byteLength / 2);
const samples = new Int16Array(pcmBuffer.buffer, pcmBuffer.byteOffset, sampleCount);
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, PCM_VAD_SAMPLE_RATE);
const result: AudioSpeechResult = {
spans,
durationSec,
calibration: 'noisy',
source: 'builtin-vad',
};
rememberAudioSpeech(cacheKey, result);
return result;
}
function spawnFfmpegWithStdout(
ffmpegPath: string,
args: string[],
timeoutMs: number,
signal?: AbortSignal,
): Promise<Buffer> {
return new Promise((resolve, reject) => {
const invocation = resolveCommandInvocation(ffmpegPath, args);
const child = childProcess.spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'],
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
});
const chunks: Buffer[] = [];
let stderr = '';
let settled = false;
const finishError = (err: Error): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
reject(err);
};
const onAbort = (): void => {
child.kill('SIGKILL');
finishError(new Error('ffmpeg operation aborted'));
};
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(() => {
child.kill('SIGKILL');
finishError(new Error('ffmpeg operation timed out'));
}, timeoutMs);
child.stdout.on('data', (chunk: Buffer) => {
chunks.push(chunk);
});
child.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString();
});
child.on('error', (error: Error) => {
finishError(error);
});
child.on('close', (code: number | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
if (code !== 0) {
reject(new Error(`ffmpeg failed (code=${code ?? 'n/a'}): ${stderr.trim()}`));
return;
}
resolve(Buffer.concat(chunks));
});
});
}
function audioMapArg(audioStreamIndex: number | null): string {
return audioStreamIndex !== null && Number.isInteger(audioStreamIndex) && audioStreamIndex >= 0
? `0:${audioStreamIndex}`
: '0:a:0';
}
/**
* Sample 4 seeked 60-second audio windows across a media file in parallel using
* fast input-side `-ss` seeks. Used to verify external reference subtitles in
* ~0.2-0.5s without decoding the entire episode or movie.
*/
export async function extractSampledAudioWindows(options: {
ffmpegPath: string;
videoPath: string;
audioStreamIndex: number | null;
durationSec: number;
signal?: AbortSignal;
}): Promise<SampledAudioWindow[] | null> {
if (
!Number.isFinite(options.durationSec) ||
options.durationSec < SAMPLED_MIN_MEDIA_DURATION_SEC
) {
return null;
}
const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex);
const sampleKey = audioKey ? `${audioKey}\0${Math.round(options.durationSec)}` : null;
if (sampleKey) {
const cached = sampledAudioCache.get(sampleKey);
if (cached) return cached;
}
const maxStart = Math.max(0, options.durationSec - SAMPLED_WINDOW_DURATION_SEC - 5);
const starts: number[] = [];
for (const frac of SAMPLED_WINDOW_FRACTIONS) {
const startSec = Math.round(Math.min(maxStart, Math.max(0, options.durationSec * frac)));
if (starts.every((prev) => Math.abs(prev - startSec) >= SAMPLED_WINDOW_DURATION_SEC)) {
starts.push(startSec);
}
}
if (starts.length < 2) return null;
const mapSpec = audioMapArg(options.audioStreamIndex);
const maxBytes = SAMPLED_WINDOW_DURATION_SEC * PCM_VAD_SAMPLE_RATE * 2;
const settled = await Promise.all(
starts.map(async (startSec): Promise<SampledAudioWindow | null> => {
try {
const pcmBuffer = await spawnFfmpegWithStdout(
options.ffmpegPath,
[
'-hide_banner',
'-nostdin',
'-loglevel',
'error',
'-ss',
String(startSec),
'-t',
String(SAMPLED_WINDOW_DURATION_SEC),
'-i',
options.videoPath,
'-vn',
'-sn',
'-dn',
'-map',
mapSpec,
'-ac',
'1',
'-ar',
String(PCM_VAD_SAMPLE_RATE),
'-af',
PCM_VAD_FILTER,
'-f',
's16le',
'pipe:1',
],
SAMPLED_WINDOW_TIMEOUT_MS,
options.signal,
);
const clampedLen = Math.min(pcmBuffer.byteLength, maxBytes);
const sampleCount = Math.floor(clampedLen / 2);
if (sampleCount < PCM_VAD_SAMPLE_RATE * 10) return null;
const samples = new Int16Array(pcmBuffer.buffer, pcmBuffer.byteOffset, sampleCount);
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, PCM_VAD_SAMPLE_RATE);
if (spans.length === 0) return null;
return {
startSec,
durationSec: Math.min(SAMPLED_WINDOW_DURATION_SEC, durationSec),
speechSpans: spans,
};
} catch {
return null;
}
}),
);
const valid = settled.filter((w): w is SampledAudioWindow => w !== null);
if (valid.length < 2) return null;
rememberLru(sampledAudioCache, sampleKey, valid);
return valid;
}
/**
* Extract multiple embedded text subtitle tracks AND (optionally) audio speech
* in ONE single `ffmpeg` demux pass, avoiding N+1 full-file reads on multi-track
* MKVs and caching results for subsequent modal retries.
* Returns `null` if the multi-output ffmpeg pass fails so callers can fall back.
*/
export async function extractSinglePassRipMedia(
options: SinglePassRipMediaOptions,
): Promise<SinglePassRipMediaResult | null> {
const fileKey = buildFileSignatureKey(options.videoPath);
const vadKey = buildVadConfigKey(options.vadExecutablePath, options.vadModelPath);
const audioKey = buildAudioCacheKey(options.videoPath, options.audioStreamIndex, vadKey);
const cachedSubs =
(fileKey ? embeddedSubtitlesCache.get(fileKey) : undefined) ??
new Map<number, ParsedSubtitleFile>();
const cachedAudio = audioKey ? (audioSpeechCache.get(audioKey) ?? null) : null;
const missingTracks = options.embeddedTracks.filter((t) => !cachedSubs.has(t.ffIndex));
const needAudio = options.includeAudio && cachedAudio === null;
if (missingTracks.length === 0 && !needAudio) {
return {
audioSpeech: options.includeAudio ? cachedAudio : null,
embeddedSubtitles: new Map(cachedSubs),
};
}
const vadExec = options.vadExecutablePath?.trim() ?? '';
const vadModel = options.vadModelPath?.trim() ?? '';
const useSilero = needAudio && vadExec.length > 0 && vadModel.length > 0 && fileExists(vadModel);
let tempDir: string | null = null;
try {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-rip-'));
const wavPath = path.join(tempDir, 'audio.wav');
const args: string[] = [
'-hide_banner',
'-nostdin',
'-y',
'-loglevel',
'error',
'-i',
options.videoPath,
];
const trackOutputs: Array<{ ffIndex: number; outPath: string }> = [];
for (const track of missingTracks) {
const outPath = path.join(tempDir, `track_${track.ffIndex}.${track.extension}`);
args.push(
'-vn',
'-an',
'-map',
`0:${track.ffIndex}`,
'-f',
extensionToFfmpegMuxer(track.extension),
outPath,
);
trackOutputs.push({ ffIndex: track.ffIndex, outPath });
}
if (needAudio) {
const mapSpec = audioMapArg(options.audioStreamIndex);
if (useSilero) {
args.push(
'-vn',
'-sn',
'-dn',
'-map',
mapSpec,
'-ac',
'1',
'-ar',
'16000',
'-c:a',
'pcm_s16le',
wavPath,
);
} else {
args.push(
'-vn',
'-sn',
'-dn',
'-map',
mapSpec,
'-ac',
'1',
'-ar',
String(PCM_VAD_SAMPLE_RATE),
'-af',
PCM_VAD_FILTER,
'-f',
's16le',
'pipe:1',
);
}
}
const stdoutBuf = await spawnFfmpegWithStdout(
options.ffmpegPath,
args,
AUDIO_EXTRACT_TIMEOUT_MS,
options.signal,
);
const updatedSubs = new Map<number, ParsedSubtitleFile>(cachedSubs);
for (const { ffIndex, outPath } of trackOutputs) {
if (!fileExists(outPath)) continue;
try {
const bytes = fs.readFileSync(outPath);
const parsed = parseSubtitleFileContent(decodeSubtitleBytes(bytes), outPath);
updatedSubs.set(ffIndex, parsed);
} catch {
// Ignore individual unparseable track.
}
}
if (updatedSubs.size > 0) {
rememberLru(embeddedSubtitlesCache, fileKey, updatedSubs);
}
let audioSpeech: AudioSpeechResult | null = options.includeAudio ? cachedAudio : null;
if (needAudio) {
if (useSilero && fileExists(wavPath)) {
const wavStats = fs.statSync(wavPath);
const durationSec = Math.max(0, (wavStats.size - 44) / (16000 * 2));
const vadRes = await runCommand(
vadExec,
[
'-f',
wavPath,
'-vm',
vadModel,
'-vt',
'0.35',
'--vad-min-speech-duration-ms',
'120',
'--vad-min-silence-duration-ms',
'250',
'-vp',
'100',
'-np',
],
AUDIO_EXTRACT_TIMEOUT_MS,
);
if (vadRes.ok) {
const spans = parseRawSileroVadSegments(`${vadRes.stdout}\n${vadRes.stderr}`);
if (spans.length > 0) {
audioSpeech = {
spans,
durationSec: Math.max(durationSec, spans[spans.length - 1]!.end),
calibration: 'clean',
source: 'silero-vad',
};
}
}
// If Silero returned no spans, fall back cleanly to built-in PCM VAD.
if (!audioSpeech) {
try {
audioSpeech = await extractAudioSpeechSpans({
ffmpegPath: options.ffmpegPath,
videoPath: options.videoPath,
audioStreamIndex: options.audioStreamIndex,
signal: options.signal,
});
} catch {
audioSpeech = null;
}
}
} else if (!useSilero) {
const sampleCount = Math.floor(stdoutBuf.byteLength / 2);
if (sampleCount > 0) {
const samples = new Int16Array(stdoutBuf.buffer, stdoutBuf.byteOffset, sampleCount);
const { spans, durationSec } = detectSpeechSpansFromPcm(samples, PCM_VAD_SAMPLE_RATE);
if (spans.length > 0) {
audioSpeech = {
spans,
durationSec,
calibration: 'noisy',
source: 'builtin-vad',
};
}
}
}
if (audioSpeech) {
rememberAudioSpeech(audioKey, audioSpeech);
}
}
return {
audioSpeech,
embeddedSubtitles: updatedSubs,
};
} catch {
return null;
} finally {
if (tempDir) {
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch {
// Best-effort cleanup.
}
}
}
}
+103
View File
@@ -0,0 +1,103 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
discoverSidecarReferenceFiles,
rankReferenceCandidates,
type EvaluatedSubtitleReference,
} from './reference-discovery';
test('discoverSidecarReferenceFiles finds unloaded sidecar subtitle files and skips target/retimed/loaded', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-sidecars-'));
try {
const videoPath = path.join(dir, 'Episode 01.mkv');
const targetPath = path.join(dir, 'Episode 01.ja.srt');
const loadedEngPath = path.join(dir, 'Episode 01.en.srt');
const unloadedAssPath = path.join(dir, 'Episode 01.eng.full.ass');
const retimedPath = path.join(dir, 'Episode 01.ja_retimed.srt');
const otherEpPath = path.join(dir, 'Episode 02.en.srt');
for (const p of [
videoPath,
targetPath,
loadedEngPath,
unloadedAssPath,
retimedPath,
otherEpPath,
]) {
fs.writeFileSync(p, 'test');
}
const found = discoverSidecarReferenceFiles(videoPath, [targetPath, loadedEngPath]);
assert.deepEqual(
found.map((f) => f.filename),
['Episode 01.eng.full.ass'],
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('rankReferenceCandidates prefers audio-aligned unloaded track over misaligned secondary track', () => {
const misalignedSecondary: EvaluatedSubtitleReference = {
key: 'track:2',
kind: 'track',
trackId: 2,
filePath: null,
label: 'External #2 - eng (secondary)',
isSecondary: true,
isEmbedded: false,
isEnglish: true,
isFullDialogueHint: true,
isSignsOnly: false,
dialogueCount: 300,
signCount: 10,
audioStatus: 'misaligned',
audioOffsetMs: 2400,
audioConfidence: 0.92,
};
const alignedUnloaded: EvaluatedSubtitleReference = {
key: 'track:4',
kind: 'track',
trackId: 4,
filePath: null,
label: 'Internal #4 - eng - Full Dialogue',
isSecondary: false,
isEmbedded: true,
isEnglish: true,
isFullDialogueHint: true,
isSignsOnly: false,
dialogueCount: 295,
signCount: 20,
audioStatus: 'aligned',
audioOffsetMs: 40,
audioConfidence: 0.9,
};
const signsOnly: EvaluatedSubtitleReference = {
key: 'track:3',
kind: 'track',
trackId: 3,
filePath: null,
label: 'Internal #3 - eng - Signs & Songs',
isSecondary: false,
isEmbedded: true,
isEnglish: true,
isFullDialogueHint: false,
isSignsOnly: true,
dialogueCount: 12,
signCount: 180,
audioStatus: 'unverified',
audioOffsetMs: null,
audioConfidence: 0,
};
const ranked = rankReferenceCandidates([misalignedSecondary, signsOnly, alignedUnloaded]);
assert.deepEqual(
ranked.map((r) => r.key),
['track:4', 'track:3', 'track:2'],
);
});
+203
View File
@@ -0,0 +1,203 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import type { ReferenceAudioStatus } from './alass-align';
import { isSignsOrSongsTrackMeta } from './subtitle-lines';
import type { MpvTrack } from './utils';
const SIDECAR_SUBTITLE_EXTENSIONS = new Set(['.srt', '.ass', '.ssa', '.vtt']);
export interface SidecarSubtitleFile {
path: string;
filename: string;
languageHint: string;
isSignsOnly: boolean;
}
export interface EvaluatedSubtitleReference {
key: string;
kind: 'track' | 'sidecar';
trackId: number | null;
filePath: string | null;
label: string;
isSecondary: boolean;
isEmbedded: boolean;
isEnglish: boolean;
isFullDialogueHint: boolean;
isSignsOnly: boolean;
dialogueCount: number;
signCount: number;
audioStatus: ReferenceAudioStatus;
audioOffsetMs: number | null;
audioConfidence: number;
}
function normalizePathKey(filePath: string): string {
const resolved = path.resolve(filePath).replace(/\\/g, '/');
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
export function isEnglishReferenceMeta(meta: {
lang?: string;
title?: string;
filename?: string;
}): boolean {
const lang = (meta.lang ?? '').trim();
if (/^(?:en|eng|english)(?:[-_]|$)/i.test(lang)) return true;
const combined = `${meta.title ?? ''} ${meta.filename ?? ''}`;
return /(?:^|[\s.\[(_-])(?:en|eng|english)(?=$|[\s.\])_-])/i.test(combined);
}
export function isFullDialogueHintMeta(meta: { title?: string; filename?: string }): boolean {
const combined = `${meta.title ?? ''} ${meta.filename ?? ''}`;
return /\b(?:full|dialogue|dialog|complete|main)\b/i.test(combined);
}
function inferLanguageHintFromFilename(filename: string, videoStem: string): string {
const parsed = path.parse(filename);
const remainder = parsed.name.startsWith(videoStem)
? parsed.name.slice(videoStem.length).replace(/^[.\s_-]+/, '')
: parsed.name;
return remainder || parsed.ext.slice(1);
}
/**
* Scan the video's directory for unloaded sidecar subtitle files matching the
* video's stem, excluding the target subtitle, `_retimed` files, and paths
* already present in mpv's track list.
*/
export function discoverSidecarReferenceFiles(
videoPath: string,
loadedPaths: readonly string[],
): SidecarSubtitleFile[] {
const parsedVideo = path.parse(videoPath);
if (!parsedVideo.dir || !parsedVideo.name) return [];
let entries: string[];
try {
entries = fs.readdirSync(parsedVideo.dir);
} catch {
return [];
}
const excluded = new Set(loadedPaths.map(normalizePathKey));
const stemLower = parsedVideo.name.toLowerCase();
const candidates: SidecarSubtitleFile[] = [];
for (const entry of entries) {
const parsedEntry = path.parse(entry);
const ext = parsedEntry.ext.toLowerCase();
if (!SIDECAR_SUBTITLE_EXTENSIONS.has(ext)) continue;
const nameLower = parsedEntry.name.toLowerCase();
if (nameLower.endsWith('_retimed')) continue;
if (
nameLower !== stemLower &&
!nameLower.startsWith(`${stemLower}.`) &&
!nameLower.startsWith(`${stemLower}_`) &&
!nameLower.startsWith(`${stemLower}-`) &&
!nameLower.startsWith(`${stemLower} `)
) {
continue;
}
const fullPath = path.join(parsedVideo.dir, entry);
if (excluded.has(normalizePathKey(fullPath))) continue;
try {
if (!fs.statSync(fullPath).isFile()) continue;
} catch {
continue;
}
candidates.push({
path: fullPath,
filename: entry,
languageHint: inferLanguageHintFromFilename(entry, parsedVideo.name),
isSignsOnly: isSignsOrSongsTrackMeta({ 'external-filename': fullPath }),
});
}
return candidates.sort((a, b) => a.filename.localeCompare(b.filename));
}
export function formatReferenceCandidateDetail(candidate: EvaluatedSubtitleReference): string {
const parts: string[] = [];
if (candidate.audioStatus === 'aligned') {
const pct = Math.round(candidate.audioConfidence * 100);
parts.push(`aligned with audio${pct > 0 ? ` (${pct}%)` : ''}`);
} else if (candidate.audioStatus === 'misaligned' && candidate.audioOffsetMs !== null) {
const sec = (candidate.audioOffsetMs / 1000).toFixed(1);
const signed = candidate.audioOffsetMs >= 0 ? `+${sec}s` : `${sec}s`;
parts.push(`${signed} off audio`);
}
if (candidate.isSignsOnly) {
parts.push('signs/songs');
} else if (candidate.signCount > 0 && candidate.dialogueCount > 0) {
parts.push(`${candidate.dialogueCount} dialogue, ${candidate.signCount} signs/songs stripped`);
} else if (candidate.dialogueCount > 0) {
parts.push(`${candidate.dialogueCount} lines`);
}
if (candidate.kind === 'sidecar') {
parts.push('unloaded sidecar');
} else if (!candidate.isSecondary && !candidate.isEmbedded) {
parts.push('external');
}
return parts.join(' · ');
}
/**
* Score candidate subtitle references so the best audio-verified dialogue track
* wins even when it isn't the currently loaded secondary subtitle.
*/
export function scoreReferenceCandidate(candidate: EvaluatedSubtitleReference): number {
let score = 0;
// Audio verification dominates when available: an aligned track ALWAYS beats a misaligned one.
if (candidate.audioStatus === 'aligned') {
score += 10_000;
score += Math.round(candidate.audioConfidence * 1000);
if (candidate.audioOffsetMs !== null) {
// Closer to 0ms offset against audio is better.
score -= Math.min(500, Math.abs(candidate.audioOffsetMs));
}
} else if (candidate.audioStatus === 'unverified') {
score += 2_000;
} else {
// Explicitly misaligned with audio: push well below aligned and unverified.
score -= 5_000;
}
// Signs/songs-only tracks or tiny dialogue counts are poor references.
if (candidate.isSignsOnly) score -= 4_000;
if (candidate.dialogueCount < 20) score -= 3_000;
// Embedded tracks in the container are usually authored for this exact video rip.
if (candidate.isEmbedded) score += 250;
if (candidate.isFullDialogueHint) score += 150;
if (candidate.isEnglish) score += 100;
if (candidate.isSecondary) score += 40;
// Prefer dialogue-rich tracks (capped so huge karaoke tracks don't skew score).
score += Math.min(200, Math.floor(candidate.dialogueCount / 5));
return score;
}
export function rankReferenceCandidates(
candidates: readonly EvaluatedSubtitleReference[],
): EvaluatedSubtitleReference[] {
return [...candidates].sort((a, b) => scoreReferenceCandidate(b) - scoreReferenceCandidate(a));
}
export function buildTrackReferenceLabel(track: MpvTrack, isSecondary: boolean): string {
const id = typeof track.id === 'number' ? track.id : -1;
const source = track.external ? 'External' : 'Internal';
const parts: string[] = [];
if (track.lang) parts.push(track.lang);
if (track.title && track.title !== track.lang) parts.push(track.title);
if (parts.length === 0 && track.external && track['external-filename']) {
parts.push(path.basename(track['external-filename']));
}
const descriptor = parts.length > 0 ? parts.join(' - ') : 'unknown';
const role = isSecondary ? ' (secondary)' : '';
return `${source} #${id} - ${descriptor}${role}`;
}
+182
View File
@@ -0,0 +1,182 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
applyTimingToSubtitleFile,
decodeSubtitleBytes,
decodeSubtitleBytesWithStatus,
extractSpansFromParsedSubtitle,
formatSpansAsSrt,
isSignStyleOrEffect,
isSignsOrSongsTrackMeta,
parseSubtitleFileContent,
} from './subtitle-lines';
test('isSignStyleOrEffect separates signs/songs styles from dialogue styles', () => {
for (const dialogueStyle of [
'Default',
'Subtitle',
'Subtitles',
'Notebook',
'Main Top',
'DefaultItalics',
'Edward',
]) {
assert.equal(isSignStyleOrEffect(dialogueStyle), false, `${dialogueStyle} should be dialogue`);
}
for (const signStyle of [
'Sign',
'Signs',
'sign_0423_EpTitle',
'Title',
'Episode Title',
'OP Kara',
'ED-Romaji',
'OPRomaji',
'TLNote',
'TL Note',
'Insert Song',
'Lyrics',
'Typeset',
]) {
assert.equal(isSignStyleOrEffect(signStyle), true, `${signStyle} should be a sign/song`);
}
});
test('isSignsOrSongsTrackMeta flags signs, songs, lyrics, and forced tracks', () => {
assert.equal(isSignsOrSongsTrackMeta({ forced: true, title: 'English' }), true);
assert.equal(isSignsOrSongsTrackMeta({ title: 'English (Signs & Songs)' }), true);
assert.equal(isSignsOrSongsTrackMeta({ title: 'S&S' }), true);
assert.equal(isSignsOrSongsTrackMeta({ 'external-filename': '/tmp/ep01.forced.ass' }), true);
assert.equal(isSignsOrSongsTrackMeta({ title: 'English [Full Dialogue]' }), false);
assert.equal(isSignsOrSongsTrackMeta({ title: 'Japanese' }), false);
});
test('parseSubtitleFileContent classifies ASS signs, drawings, karaoke, and preserves format on rewrite', () => {
const ass = [
'[Script Info]',
'Title: Test Episode',
'',
'[V4+ Styles]',
'Format: Name, Fontname',
'Style: Default,Arial',
'',
'[Events]',
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
'Comment: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,keep this comment',
'Dialogue: 0,0:00:10.00,0:00:12.50,Default,,0,0,0,,{\\an8}待って!',
'Dialogue: 0,0:00:11.00,0:00:13.00,Sign,,0,0,0,,{\\pos(100,200)}木ノ葉病院',
'Dialogue: 0,0:00:13.00,0:00:15.00,Default,,0,0,0,,{\\pos(320,40)}看板',
'Dialogue: 0,0:00:16.00,0:00:18.00,OPRomaji,,0,0,0,,{\\k20}ha{\\k30}ru',
'Dialogue: 0,0:00:19.00,0:00:21.00,Default,,0,0,0,,{\\p1}m 0 0 l 100 0{\\p0}',
'Dialogue: 0,0:00:22.00,0:00:24.00,Default,,0,0,0,,そうか, わかった',
].join('\r\n');
const parsed = parseSubtitleFileContent(ass, 'ep01.ass');
assert.equal(parsed.format, 'ass');
assert.equal(parsed.eol, '\r\n');
assert.equal(parsed.events.length, 6);
const { spans, dialogueIndices, dialogueCount, signCount } = extractSpansFromParsedSubtitle(
parsed,
{ stripSigns: true },
);
assert.equal(dialogueCount, 2);
assert.equal(signCount, 4);
assert.deepEqual(dialogueIndices, [0, 5]);
assert.deepEqual(spans, [
{ start: 10, end: 12.5 },
{ start: 22, end: 24 },
]);
// Apply different shifts to the two dialogue lines (+2s and +5s) and verify signs follow nearest dialogue.
const rewritten = applyTimingToSubtitleFile(parsed, dialogueIndices, [2.0, 5.0], 1.0);
assert.ok(
rewritten.includes('Comment: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,keep this comment'),
);
assert.ok(
rewritten.includes('Dialogue: 0,0:00:12.00,0:00:14.50,Default,,0,0,0,,{\\an8}待って!'),
);
// Sign at 11s is nearest to dialogue 0 (10s) -> +2s => 13s..15s
assert.ok(
rewritten.includes('Dialogue: 0,0:00:13.00,0:00:15.00,Sign,,0,0,0,,{\\pos(100,200)}木ノ葉病院'),
);
// Drawing at 19s is nearest to dialogue 5 (22s) -> +5s => 24s..26s
assert.ok(
rewritten.includes(
'Dialogue: 0,0:00:24.00,0:00:26.00,Default,,0,0,0,,{\\p1}m 0 0 l 100 0{\\p0}',
),
);
// Commas inside Text field stay intact!
assert.ok(
rewritten.includes('Dialogue: 0,0:00:27.00,0:00:29.00,Default,,0,0,0,,そうか, わかった'),
);
assert.ok(rewritten.includes('\r\n'));
});
test('parseSubtitleFileContent keeps positioned ASS lines as dialogue when most lines use \\pos', () => {
const ass = [
'[Events]',
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
'Dialogue: 0,0:00:01.00,0:00:03.00,Default,,0,0,0,,{\\pos(640,680)}もしもし',
'Dialogue: 0,0:00:04.00,0:00:06.00,Default,,0,0,0,,{\\pos(640,40)}元気?',
].join('\n');
const parsed = parseSubtitleFileContent(ass, 'all-pos.ass');
const extracted = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
assert.equal(extracted.dialogueCount, 2);
assert.equal(extracted.signCount, 0);
});
test('parseSubtitleFileContent preserves SRT/VTT cue settings and strips music-only lines', () => {
const vtt = [
'WEBVTT',
'',
'00:01.000 --> 00:02.500 align:center line:90%',
'こんにちは',
'',
'00:03.000 --> 00:05.000',
'♪ La la la ♪',
'',
'00:06.000 --> 00:08.000',
'元気ですか?',
].join('\n');
const parsed = parseSubtitleFileContent(vtt, 'ep01.vtt');
assert.equal(parsed.format, 'vtt');
const extracted = extractSpansFromParsedSubtitle(parsed, { stripSigns: true });
assert.equal(extracted.dialogueCount, 2);
assert.equal(extracted.signCount, 1);
const rewritten = applyTimingToSubtitleFile(parsed, extracted.dialogueIndices, [1.5, 1.5], 1.0);
assert.ok(rewritten.includes('WEBVTT'));
assert.ok(rewritten.includes('00:00:02.500 --> 00:00:04.000 align:center line:90%'));
assert.ok(rewritten.includes('00:00:04.500 --> 00:00:06.500\n♪ La la la ♪'));
});
test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable bytes accurately', () => {
const bomBytes = new Uint8Array([0xef, 0xbb, 0xbf, ...Buffer.from('hello', 'utf8')]);
assert.equal(decodeSubtitleBytes(bomBytes), 'hello');
assert.deepEqual(decodeSubtitleBytesWithStatus(bomBytes), { text: 'hello', lossless: true });
// Bytes invalid in UTF-8, Shift_JIS, and EUC-JP trigger lossy fallback.
const corrupt = new Uint8Array([0x80, 0xff, 0xfe, 0x80]);
const lossy = decodeSubtitleBytesWithStatus(corrupt);
assert.equal(lossy.lossless, false);
// Ambiguous bytes valid in both Shift_JIS and EUC-JP (e.g. EUC-JP 'あ' = A4 A2) must not be marked lossless.
const ambiguousEucJp = new Uint8Array([0xa4, 0xa2]);
const ambiguousResult = decodeSubtitleBytesWithStatus(ambiguousEucJp);
assert.equal(ambiguousResult.lossless, false);
// Unambiguous Shift_JIS bytes (0x82 0xA0 = 'あ', invalid in UTF-8 and EUC-JP) remain lossless.
const unambiguousSjis = new Uint8Array([0x82, 0xa0]);
assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), { text: 'あ', lossless: true });
const srt = formatSpansAsSrt([
{ start: 5.5, end: 7.0 },
{ start: 1.25, end: 2.75 },
]);
assert.ok(srt.includes('00:00:01,250 --> 00:00:02,750'));
assert.ok(srt.includes('00:00:05,500 --> 00:00:07,000'));
});
+612
View File
@@ -0,0 +1,612 @@
export type SubtitleFileFormat = 'ass' | 'srt' | 'vtt';
export interface SubtitleTimeSpan {
start: number;
end: number;
}
export interface ParsedSubtitleLine {
/** Line index in the original file's `lines` array (0-based). */
lineIndex: number;
start: number;
end: number;
text: string;
sign: boolean;
/** ASS field positions for format-preserving timestamp rewrite. */
assStartFieldIndex?: number;
assEndFieldIndex?: number;
assFieldCount?: number;
/** SRT/VTT suffix after the end timestamp (e.g., VTT cue settings). */
timingSuffix?: string;
/** SRT/VTT leading indentation before start timestamp. */
timingPrefix?: string;
}
export interface ParsedSubtitleFile {
format: SubtitleFileFormat;
eol: '\r\n' | '\n';
rawLines: string[];
events: ParsedSubtitleLine[];
/** False when byte decoding fell back to lossy replacement (e.g. U+FFFD). */
lossless?: boolean;
}
const SIGN_STYLE_WORDS = new Set([
'sign',
'signs',
'signage',
'typeset',
'ts',
'title',
'titles',
'logo',
'screen',
'onscreen',
'insert',
'song',
'songs',
'lyric',
'lyrics',
'karaoke',
'kara',
'kfx',
'fx',
'op',
'ed',
'opening',
'ending',
'note',
'notes',
'tl',
'tn',
'credit',
'credits',
'eyecatch',
'next',
'preview',
'caption',
'banner',
]);
const TRACK_SIGNS_OR_SONGS_PATTERN =
/(?:^|[^\p{L}\p{N}])(?:signs?(?:\s*(?:&|and|\+|\/|-|_)\s*songs?)?|songs?|lyrics?|karaoke|forced|s[\s&+_-]*s|op|ed|opening|ending)(?=$|[^\p{L}\p{N}])|看板|歌詞/iu;
const SRT_VTT_TIMING_LINE_PATTERN =
/^(\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(\s*-->\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(.*)$/;
const ASS_DRAWING_PATTERN = /\{[^}]*\\p[1-9][^}]*\}[^{]*/g;
const ASS_TAG_PATTERN = /\{[^}]*\}/g;
const ASS_KARAOKE_TAG_PATTERN = /\{[^}]*\\(?:k|kf|ko|K)\d+[^}]*\}/;
const HTML_TAG_PATTERN = /<\/?[a-zA-Z][^>]*>/g;
const MUSIC_ONLY_TEXT_PATTERN =
/^(?:[♪♫♩♬\s~~\-–—()()[\]【】]*|(?:[\[((](?:music|song|singing|lyrics?|instrumental|op|ed|opening|ending|bgm|音楽|歌|歌唱)[\]))]\s*)+)$/iu;
function tryDecode(bytes: Uint8Array, encoding: string, fatal: boolean): string | null {
try {
return new TextDecoder(encoding, { fatal }).decode(bytes);
} catch {
return null;
}
}
export interface DecodedSubtitleBytes {
text: string;
lossless: boolean;
}
export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitleBytes {
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
const rest = bytes.subarray(3);
const strict = tryDecode(rest, 'utf-8', true);
if (strict !== null) return { text: strict, lossless: true };
return { text: new TextDecoder('utf-8').decode(rest), lossless: false };
}
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
const strict = tryDecode(bytes, 'utf-16le', true);
if (strict !== null) return { text: strict, lossless: true };
return {
text: tryDecode(bytes, 'utf-16le', false) ?? new TextDecoder('utf-8').decode(bytes),
lossless: false,
};
}
if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
const strict = tryDecode(bytes, 'utf-16be', true);
if (strict !== null) return { text: strict, lossless: true };
return {
text: tryDecode(bytes, 'utf-16be', false) ?? new TextDecoder('utf-8').decode(bytes),
lossless: false,
};
}
const strictUtf8 = tryDecode(bytes, 'utf-8', true);
if (strictUtf8 !== null) {
return { text: strictUtf8, lossless: true };
}
const shiftJis = tryDecode(bytes, 'shift_jis', true);
const eucJp = tryDecode(bytes, 'euc-jp', true);
if (shiftJis !== null && eucJp === null) {
return { text: shiftJis, lossless: true };
}
if (eucJp !== null && shiftJis === null) {
return { text: eucJp, lossless: true };
}
if (shiftJis !== null && eucJp !== null) {
if (shiftJis === eucJp) {
return { text: shiftJis, lossless: true };
}
return { text: eucJp, lossless: false };
}
return { text: new TextDecoder('utf-8').decode(bytes), lossless: false };
}
export function decodeSubtitleBytes(bytes: Uint8Array): string {
return decodeSubtitleBytesWithStatus(bytes).text;
}
/**
* Split a style or effect name into lowercase word tokens so camelCase / snake_case /
* kebab-case names like "OPRomaji", "TLNote", "sign_0423_EpTitle" match cleanly while
* dialogue styles like "Subtitle", "Notebook", or "Edward" do not.
*/
export function splitStyleWords(name: string): string[] {
const words: string[] = [];
let word = '';
for (let i = 0; i < name.length; i += 1) {
const ch = name[i]!;
const isAlphaNum = /[A-Za-z0-9]/.test(ch);
if (!isAlphaNum) {
if (word) {
words.push(word);
word = '';
}
continue;
}
if (word) {
const prev = name[i - 1]!;
const next = name[i + 1] ?? '';
const prevLower = /[a-z]/.test(prev);
const prevUpper = /[A-Z]/.test(prev);
const prevDigit = /[0-9]/.test(prev);
const currUpper = /[A-Z]/.test(ch);
const currDigit = /[0-9]/.test(ch);
const nextLower = /[a-z]/.test(next);
if (
(prevLower && currUpper) ||
(prevUpper && currUpper && nextLower) ||
prevDigit !== currDigit
) {
words.push(word);
word = '';
}
}
word += ch.toLowerCase();
}
if (word) {
words.push(word);
}
return words;
}
export function isSignStyleOrEffect(value: string): boolean {
if (!value.trim()) return false;
return splitStyleWords(value).some((word) => SIGN_STYLE_WORDS.has(word));
}
export function isSignsOrSongsTrackMeta(track: {
forced?: boolean;
title?: string;
'external-filename'?: string;
}): boolean {
if (track.forced === true) return true;
const combined = `${track.title ?? ''} ${track['external-filename'] ? (track['external-filename'].split(/[\\/]/).pop() ?? '') : ''}`;
return TRACK_SIGNS_OR_SONGS_PATTERN.test(combined);
}
export function parseSubtitleTimestamp(raw: string): number | null {
const normalized = raw.trim().replace(',', '.');
const parts = normalized.split(':');
if (parts.length === 3) {
const h = Number(parts[0]);
const m = Number(parts[1]);
const s = Number(parts[2]);
if (!Number.isFinite(h) || !Number.isFinite(m) || !Number.isFinite(s)) return null;
return h * 3600 + m * 60 + s;
}
if (parts.length === 2) {
const m = Number(parts[0]);
const s = Number(parts[1]);
if (!Number.isFinite(m) || !Number.isFinite(s)) return null;
return m * 60 + s;
}
return null;
}
function cleanCuePlainText(raw: string): string {
return raw
.replace(ASS_DRAWING_PATTERN, '')
.replace(ASS_TAG_PATTERN, '')
.replace(HTML_TAG_PATTERN, '')
.replace(/\\N|\\n/g, '\n')
.replace(/\\h/g, ' ')
.replace(/\u200B/g, '')
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.join('\n');
}
function isMusicOrLyricText(plainText: string, rawText: string): boolean {
if (!plainText) return true;
if (/[♪♫]/u.test(plainText)) return true;
if (MUSIC_ONLY_TEXT_PATTERN.test(plainText)) return true;
if (ASS_KARAOKE_TAG_PATTERN.test(rawText)) return true;
return false;
}
function detectFormat(text: string, filename?: string): SubtitleFileFormat {
const lowerName = (filename ?? '').toLowerCase();
if (
/^\[events\]/im.test(text) ||
/^dialogue:/im.test(text) ||
lowerName.endsWith('.ass') ||
lowerName.endsWith('.ssa')
) {
return 'ass';
}
if (/^\s*WEBVTT\b/m.test(text) || lowerName.endsWith('.vtt')) {
return 'vtt';
}
return 'srt';
}
function splitAssDialogueFields(rest: string, fieldCount: number): string[] {
const fields: string[] = [];
let start = 0;
for (let i = 0; i < fieldCount - 1; i += 1) {
const comma = rest.indexOf(',', start);
if (comma === -1) {
fields.push(rest.slice(start));
return fields;
}
fields.push(rest.slice(start, comma));
start = comma + 1;
}
fields.push(rest.slice(start));
return fields;
}
function parseAssSubtitle(rawLines: string[], eol: '\r\n' | '\n'): ParsedSubtitleFile {
interface RawAssEntry {
lineIndex: number;
start: number;
end: number;
text: string;
namedSign: boolean;
placed: boolean;
musicOrEmpty: boolean;
startFieldIndex: number;
endFieldIndex: number;
fieldCount: number;
}
let inEvents = false;
let format: string[] = [];
const rawEntries: RawAssEntry[] = [];
for (let i = 0; i < rawLines.length; i += 1) {
const trimmed = rawLines[i]!.trim();
if (trimmed.startsWith('[')) {
inEvents = trimmed.toLowerCase() === '[events]';
continue;
}
if (!inEvents) continue;
if (/^format:/i.test(trimmed)) {
format = trimmed
.slice(trimmed.indexOf(':') + 1)
.split(',')
.map((field) => field.trim().toLowerCase());
continue;
}
if (!/^dialogue:/i.test(trimmed)) continue;
if (format.length === 0) {
format = [
'layer',
'start',
'end',
'style',
'name',
'marginl',
'marginr',
'marginv',
'effect',
'text',
];
}
const colonIndex = rawLines[i]!.indexOf(':');
const rest = rawLines[i]!.slice(colonIndex + 1);
const fields = splitAssDialogueFields(rest, format.length);
const startIdx = format.indexOf('start');
const endIdx = format.indexOf('end');
const styleIdx = format.indexOf('style');
const effectIdx = format.indexOf('effect');
const textIdx = format.indexOf('text');
if (startIdx < 0 || endIdx < 0 || textIdx < 0) continue;
const start = parseSubtitleTimestamp(fields[startIdx] ?? '');
const end = parseSubtitleTimestamp(fields[endIdx] ?? '');
if (start === null || end === null || end <= start) continue;
const style = (fields[styleIdx] ?? '').trim();
const effect = (fields[effectIdx] ?? '').trim();
const rawBody = fields[textIdx] ?? '';
const plainText = cleanCuePlainText(rawBody);
const namedSign = isSignStyleOrEffect(style) || isSignStyleOrEffect(effect);
const placed = /\\(?:pos|move)\(/.test(rawBody);
const musicOrEmpty = isMusicOrLyricText(plainText, rawBody);
rawEntries.push({
lineIndex: i,
start,
end,
text: plainText,
namedSign,
placed,
musicOrEmpty,
startFieldIndex: startIdx,
endFieldIndex: endIdx,
fieldCount: format.length,
});
}
// Only treat \pos / \move as sign indicators when fewer than half of the
// non-named lines are positioned (some conversion scripts position every line).
let unnamedCount = 0;
let placedUnnamedCount = 0;
for (const entry of rawEntries) {
if (!entry.namedSign && !entry.musicOrEmpty) {
unnamedCount += 1;
if (entry.placed) placedUnnamedCount += 1;
}
}
const placingMarksSigns = placedUnnamedCount * 2 <= unnamedCount;
const events: ParsedSubtitleLine[] = rawEntries.map((entry) => ({
lineIndex: entry.lineIndex,
start: entry.start,
end: entry.end,
text: entry.text,
sign: entry.namedSign || entry.musicOrEmpty || (entry.placed && placingMarksSigns),
assStartFieldIndex: entry.startFieldIndex,
assEndFieldIndex: entry.endFieldIndex,
assFieldCount: entry.fieldCount,
}));
return { format: 'ass', eol, rawLines, events };
}
function parseSrtOrVttSubtitle(
rawLines: string[],
eol: '\r\n' | '\n',
format: 'srt' | 'vtt',
): ParsedSubtitleFile {
const events: ParsedSubtitleLine[] = [];
for (let i = 0; i < rawLines.length; i += 1) {
const match = SRT_VTT_TIMING_LINE_PATTERN.exec(rawLines[i]!);
if (!match) continue;
const start = parseSubtitleTimestamp(match[2]!);
const end = parseSubtitleTimestamp(match[4]!);
if (start === null || end === null || end <= start) continue;
const bodyLines: string[] = [];
let j = i + 1;
while (j < rawLines.length && rawLines[j]!.trim() !== '') {
if (SRT_VTT_TIMING_LINE_PATTERN.test(rawLines[j]!)) break;
bodyLines.push(rawLines[j]!);
j += 1;
}
const rawBody = bodyLines.join('\n');
const plainText = cleanCuePlainText(rawBody);
events.push({
lineIndex: i,
start,
end,
text: plainText,
sign: isMusicOrLyricText(plainText, rawBody),
timingPrefix: match[1] ?? '',
timingSuffix: match[5] ?? '',
});
i = j - 1;
}
return { format, eol, rawLines, events };
}
export function parseSubtitleFileContent(content: string, filename?: string): ParsedSubtitleFile {
const cleanContent = content.startsWith('\uFEFF') ? content.slice(1) : content;
const eol: '\r\n' | '\n' = cleanContent.includes('\r\n') ? '\r\n' : '\n';
const rawLines = cleanContent.split(/\r?\n/);
const format = detectFormat(cleanContent, filename);
if (format === 'ass') {
return parseAssSubtitle(rawLines, eol);
}
return parseSrtOrVttSubtitle(rawLines, eol, format);
}
export function extractSpansFromParsedSubtitle(
parsed: ParsedSubtitleFile,
options: { stripSigns?: boolean } = {},
): {
spans: SubtitleTimeSpan[];
dialogueIndices: number[];
dialogueCount: number;
signCount: number;
} {
const stripSigns = options.stripSigns !== false;
const dialogueIndices: number[] = [];
let signCount = 0;
for (let i = 0; i < parsed.events.length; i += 1) {
const event = parsed.events[i]!;
if (event.sign) {
signCount += 1;
if (stripSigns) continue;
}
dialogueIndices.push(i);
}
// Fallback: if stripping signs left zero lines in an unusual file, keep all lines.
const activeIndices =
dialogueIndices.length > 0 ? dialogueIndices : parsed.events.map((_, idx) => idx);
const spans = activeIndices.map((idx) => {
const ev = parsed.events[idx]!;
return { start: ev.start, end: ev.end };
});
return {
spans,
dialogueIndices: activeIndices,
dialogueCount: parsed.events.length - signCount,
signCount,
};
}
export function formatAssTimestamp(seconds: number): string {
const clamped = Math.max(0, seconds);
const totalCentiseconds = Math.round(clamped * 100);
const cs = totalCentiseconds % 100;
const totalSeconds = Math.floor(totalCentiseconds / 100);
const sec = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const min = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return `${hours}:${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')}.${String(cs).padStart(2, '0')}`;
}
export function formatSrtTimestamp(seconds: number): string {
const clamped = Math.max(0, seconds);
const totalMs = Math.round(clamped * 1000);
const ms = totalMs % 1000;
const totalSeconds = Math.floor(totalMs / 1000);
const sec = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const min = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return `${String(hours).padStart(2, '0')}:${String(min).padStart(2, '0')}:${String(sec).padStart(2, '0')},${String(ms).padStart(3, '0')}`;
}
export function formatVttTimestamp(seconds: number): string {
return formatSrtTimestamp(seconds).replace(',', '.');
}
function findNearestDialogueMoveIndex(
eventIndex: number,
dialogueIndices: readonly number[],
events: readonly ParsedSubtitleLine[],
): number {
if (dialogueIndices.length === 0) return 0;
let lo = 0;
let hi = dialogueIndices.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (dialogueIndices[mid]! < eventIndex) {
lo = mid + 1;
} else {
hi = mid;
}
}
if (lo === 0) return 0;
if (lo >= dialogueIndices.length) return dialogueIndices.length - 1;
const eventStart = events[eventIndex]!.start;
const prevStart = events[dialogueIndices[lo - 1]!]!.start;
const nextStart = events[dialogueIndices[lo]!]!.start;
return Math.abs(eventStart - prevStart) <= Math.abs(nextStart - eventStart) ? lo - 1 : lo;
}
/**
* Rewrite only the timestamps of the original subtitle file, preserving all ASS
* styles/headers/tags/comments, SRT cue numbers, and VTT settings. Non-dialogue
* signs/songs follow the shift of the dialogue line nearest them in time.
*/
export function applyTimingToSubtitleFile(
parsed: ParsedSubtitleFile,
dialogueIndices: readonly number[],
movesSec: readonly number[],
ratio: number,
): string {
if (parsed.events.length === 0 || dialogueIndices.length === 0 || movesSec.length === 0) {
return parsed.rawLines.join(parsed.eol);
}
const outLines = [...parsed.rawLines];
const dialogueMoveByEventIndex = new Map<number, number>();
for (let k = 0; k < dialogueIndices.length; k += 1) {
dialogueMoveByEventIndex.set(dialogueIndices[k]!, movesSec[k] ?? 0);
}
for (let i = 0; i < parsed.events.length; i += 1) {
const ev = parsed.events[i]!;
const directMove = dialogueMoveByEventIndex.get(i);
const shift =
directMove !== undefined
? directMove
: (movesSec[findNearestDialogueMoveIndex(i, dialogueIndices, parsed.events)] ?? 0);
const newStart = Math.max(0, ev.start * ratio + shift);
const newEnd = Math.max(newStart + 0.05, ev.end * ratio + shift);
if (parsed.format === 'ass') {
const rawLine = outLines[ev.lineIndex]!;
const colonIndex = rawLine.indexOf(':');
const prefix = rawLine.slice(0, colonIndex + 1);
const rest = rawLine.slice(colonIndex + 1);
const fieldCount = ev.assFieldCount ?? 10;
const fields = splitAssDialogueFields(rest, fieldCount);
if (
ev.assStartFieldIndex !== undefined &&
ev.assEndFieldIndex !== undefined &&
ev.assStartFieldIndex < fields.length &&
ev.assEndFieldIndex < fields.length
) {
fields[ev.assStartFieldIndex] = formatAssTimestamp(newStart);
fields[ev.assEndFieldIndex] = formatAssTimestamp(newEnd);
outLines[ev.lineIndex] = `${prefix}${fields.join(',')}`;
}
} else if (parsed.format === 'vtt') {
outLines[ev.lineIndex] =
`${ev.timingPrefix ?? ''}${formatVttTimestamp(newStart)} --> ${formatVttTimestamp(newEnd)}${ev.timingSuffix ?? ''}`;
} else {
outLines[ev.lineIndex] =
`${ev.timingPrefix ?? ''}${formatSrtTimestamp(newStart)} --> ${formatSrtTimestamp(newEnd)}${ev.timingSuffix ?? ''}`;
}
}
return outLines.join(parsed.eol);
}
/**
* Emit a clean dialogue-only SRT file from spans, useful when feeding a cleaned
* reference subtitle into external `alass`.
*/
export function formatSpansAsSrt(spans: readonly SubtitleTimeSpan[]): string {
const valid = spans
.filter(
(span) => Number.isFinite(span.start) && Number.isFinite(span.end) && span.end > span.start,
)
.sort((a, b) => a.start - b.start || a.end - b.end);
return valid
.map(
(span, index) =>
`${index + 1}\n${formatSrtTimestamp(span.start)} --> ${formatSrtTimestamp(span.end)}\nDialogue ${index + 1}\n`,
)
.join('\n');
}
+73 -1
View File
@@ -1,12 +1,25 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { codecToExtension, getSubsyncConfig } from './utils'; import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
candidateExecutableNames,
codecToExtension,
extensionToFfmpegMuxer,
findSubsyncExecutable,
getSubsyncConfig,
resolveCommandInvocation,
} from './utils';
test('codecToExtension maps stream/web formats to ffmpeg extractable extensions', () => { test('codecToExtension maps stream/web formats to ffmpeg extractable extensions', () => {
assert.equal(codecToExtension('subrip'), 'srt'); assert.equal(codecToExtension('subrip'), 'srt');
assert.equal(codecToExtension('webvtt'), 'vtt'); assert.equal(codecToExtension('webvtt'), 'vtt');
assert.equal(codecToExtension('vtt'), 'vtt'); assert.equal(codecToExtension('vtt'), 'vtt');
assert.equal(codecToExtension('ttml'), 'ttml'); assert.equal(codecToExtension('ttml'), 'ttml');
assert.equal(extensionToFfmpegMuxer('vtt'), 'webvtt');
assert.equal(extensionToFfmpegMuxer('srt'), 'srt');
assert.equal(extensionToFfmpegMuxer('ass'), 'ass');
}); });
test('codecToExtension returns null for unsupported codecs', () => { test('codecToExtension returns null for unsupported codecs', () => {
@@ -22,3 +35,62 @@ test('getSubsyncConfig respects explicit replace value', () => {
assert.equal(getSubsyncConfig({ replace: false }).replace, false); assert.equal(getSubsyncConfig({ replace: false }).replace, false);
assert.equal(getSubsyncConfig({ replace: true }).replace, true); assert.equal(getSubsyncConfig({ replace: true }).replace, true);
}); });
test('getSubsyncConfig defaults mode to auto and respects manual mode', () => {
assert.equal(getSubsyncConfig(undefined).mode, 'auto');
assert.equal(getSubsyncConfig({}).mode, 'auto');
assert.equal(getSubsyncConfig({ mode: 'manual' }).mode, 'manual');
});
test('findSubsyncExecutable skips non-executable files on POSIX and resolves bare overrides', () => {
if (process.platform === 'win32') return;
const dirA = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-path-a-'));
const dirB = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-path-b-'));
const prevPath = process.env.PATH;
try {
const nonExec = path.join(dirA, 'my-custom-tool');
const execFile = path.join(dirB, 'my-custom-tool');
fs.writeFileSync(nonExec, '#!/bin/sh\nexit 0\n', { mode: 0o644 });
fs.chmodSync(nonExec, 0o644);
fs.writeFileSync(execFile, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
fs.chmodSync(execFile, 0o755);
process.env.PATH = `${dirA}${path.delimiter}${dirB}`;
assert.equal(findSubsyncExecutable('my-custom-tool', ['my-custom-tool']), execFile);
assert.equal(getSubsyncConfig({ ffmpeg_path: 'my-custom-tool' }).ffmpegPath, execFile);
assert.equal(
getSubsyncConfig({ ffmpeg_path: 'missing-custom-tool' }).ffmpegPath,
'missing-custom-tool',
);
} finally {
process.env.PATH = prevPath;
fs.rmSync(dirA, { recursive: true, force: true });
fs.rmSync(dirB, { recursive: true, force: true });
}
});
test('Windows candidate discovery excludes extensionless shims and escapes cmd.exe batch arguments', () => {
assert.deepEqual(candidateExecutableNames('ffsubsync', 'win32', '.COM;.EXE;.BAT;.CMD'), [
'ffsubsync.COM',
'ffsubsync.EXE',
'ffsubsync.BAT',
'ffsubsync.CMD',
]);
assert.deepEqual(candidateExecutableNames('ffsubsync.exe', 'win32', '.EXE;.CMD'), [
'ffsubsync.exe',
]);
const invocation = resolveCommandInvocation(
'C:\\Tools\\ffsubsync.cmd',
['C:\\Videos\\Show & (Remix) [1080p].mkv', '-i', 'C:\\Subs\\ep1.srt'],
'win32',
);
assert.equal(invocation.windowsVerbatimArguments, true);
assert.equal(invocation.args[0], '/d');
assert.equal(invocation.args[1], '/s');
assert.equal(invocation.args[2], '/v:off');
assert.equal(invocation.args[3], '/c');
assert.ok(invocation.args[4]!.includes('^&'));
assert.ok(invocation.args[4]!.includes('^('));
assert.ok(invocation.args[4]!.includes('^)'));
});
+122 -9
View File
@@ -2,13 +2,19 @@ import * as fs from 'fs';
import * as childProcess from 'child_process'; import * as childProcess from 'child_process';
import * as path from 'path'; import * as path from 'path';
import { DEFAULT_CONFIG } from '../config'; import { DEFAULT_CONFIG } from '../config';
import { SubsyncConfig } from '../types'; import {
buildWindowsShimInvocation,
isWindowsCommandShim,
} from '../core/utils/windows-command-shim';
import { SubsyncConfig, SubsyncMode } from '../types';
export interface MpvTrack { export interface MpvTrack {
id?: number; id?: number;
type?: string; type?: string;
selected?: boolean; selected?: boolean;
external?: boolean; external?: boolean;
forced?: boolean;
default?: boolean;
lang?: string; lang?: string;
title?: string; title?: string;
codec?: string; codec?: string;
@@ -17,6 +23,7 @@ export interface MpvTrack {
} }
export interface SubsyncResolvedConfig { export interface SubsyncResolvedConfig {
mode?: SubsyncMode;
alassPath: string; alassPath: string;
ffsubsyncPath: string; ffsubsyncPath: string;
ffmpegPath: string; ffmpegPath: string;
@@ -29,8 +36,78 @@ const DEFAULT_SUBSYNC_EXECUTABLE_PATHS = {
ffmpeg: '/usr/bin/ffmpeg', ffmpeg: '/usr/bin/ffmpeg',
} as const; } as const;
const COMMON_BIN_DIRS = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'];
const WINDOWS_RUNNABLE_EXTENSIONS = new Set(['.exe', '.com', '.cmd', '.bat', '.ps1', '.sh']);
function isExecutablePath(filePath: string): boolean {
try {
if (!fs.statSync(filePath).isFile()) return false;
if (process.platform !== 'win32') {
fs.accessSync(filePath, fs.constants.X_OK);
}
return true;
} catch {
return false;
}
}
export function candidateExecutableNames(
name: string,
platform: NodeJS.Platform = process.platform,
pathExt: string | undefined = process.env.PATHEXT,
): string[] {
if (platform !== 'win32' || path.extname(name)) return [name];
const extensions = (pathExt ?? '.COM;.EXE;.BAT;.CMD')
.split(';')
.map((ext) => ext.trim())
.filter((ext) => ext.length > 0 && WINDOWS_RUNNABLE_EXTENSIONS.has(ext.toLowerCase()));
const effective = extensions.length > 0 ? extensions : ['.exe', '.com', '.cmd', '.bat'];
return effective.map((ext) => `${name}${ext}`);
}
/**
* Find an executable on PATH (or common install dirs), honoring an explicit
* configured override first. Returns null if not found.
*/
export function findSubsyncExecutable(
configuredPath: string | undefined,
names: readonly string[],
): string | null {
const trimmed = configuredPath?.trim() ?? '';
if (trimmed) {
if (hasPathSeparators(trimmed)) {
return isExecutablePath(trimmed) ? trimmed : null;
}
const foundConfigured = findSubsyncExecutable(undefined, [trimmed]);
return foundConfigured;
}
const dirs = [
...(process.env.PATH ?? '')
.split(path.delimiter)
.map((entry) => entry.trim())
.filter(Boolean),
...(process.platform === 'win32' ? [] : COMMON_BIN_DIRS),
];
const seen = new Set<string>();
for (const dir of dirs) {
if (seen.has(dir)) continue;
seen.add(dir);
for (const name of names) {
for (const candidateName of candidateExecutableNames(name)) {
const candidate = path.join(dir, candidateName);
if (isExecutablePath(candidate)) return candidate;
}
}
}
return null;
}
export interface SubsyncContext { export interface SubsyncContext {
videoPath: string; videoPath: string;
workingDirectory?: string | null;
durationSec?: number | null;
primaryTrack: MpvTrack; primaryTrack: MpvTrack;
secondaryTrack: MpvTrack | null; secondaryTrack: MpvTrack | null;
/** Every usable subtitle track, including the primary one. */ /** Every usable subtitle track, including the primary one. */
@@ -46,11 +123,12 @@ export interface CommandResult {
error?: string; error?: string;
} }
function resolveCommandInvocation( export function resolveCommandInvocation(
executable: string, executable: string,
args: string[], args: string[],
): { command: string; args: string[] } { platform: NodeJS.Platform = process.platform,
if (process.platform !== 'win32') { ): { command: string; args: string[]; windowsVerbatimArguments?: boolean } {
if (platform !== 'win32') {
return { command: executable, args }; return { command: executable, args };
} }
@@ -65,6 +143,14 @@ function resolveCommandInvocation(
return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`; return `/mnt/${driveLetter!.toLowerCase()}/${remainder}`;
}; };
const extension = path.extname(executable).toLowerCase(); const extension = path.extname(executable).toLowerCase();
if (isWindowsCommandShim(executable)) {
const shim = buildWindowsShimInvocation(executable, args, process.env);
return {
command: shim.file,
args: shim.args,
windowsVerbatimArguments: true,
};
}
if (extension === '.ps1') { if (extension === '.ps1') {
return { return {
command: 'powershell.exe', command: 'powershell.exe',
@@ -83,15 +169,36 @@ function resolveCommandInvocation(
} }
export function getSubsyncConfig(config: SubsyncConfig | undefined): SubsyncResolvedConfig { export function getSubsyncConfig(config: SubsyncConfig | undefined): SubsyncResolvedConfig {
const resolvePath = (value: string | undefined, fallback: string): string => { const resolvePath = (
value: string | undefined,
names: readonly string[],
fallback: string,
): string => {
const trimmed = value?.trim(); const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : fallback; if (trimmed && trimmed.length > 0) {
if (hasPathSeparators(trimmed)) return trimmed;
return findSubsyncExecutable(trimmed, [trimmed]) ?? trimmed;
}
return findSubsyncExecutable(undefined, names) ?? fallback;
}; };
return { return {
alassPath: resolvePath(config?.alass_path, DEFAULT_SUBSYNC_EXECUTABLE_PATHS.alass), mode: config?.mode ?? DEFAULT_CONFIG.subsync.mode,
ffsubsyncPath: resolvePath(config?.ffsubsync_path, DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffsubsync), alassPath: resolvePath(
ffmpegPath: resolvePath(config?.ffmpeg_path, DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffmpeg), config?.alass_path,
['alass', 'alass-cli'],
DEFAULT_SUBSYNC_EXECUTABLE_PATHS.alass,
),
ffsubsyncPath: resolvePath(
config?.ffsubsync_path,
['ffsubsync'],
DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffsubsync,
),
ffmpegPath: resolvePath(
config?.ffmpeg_path,
['ffmpeg'],
DEFAULT_SUBSYNC_EXECUTABLE_PATHS.ffmpeg,
),
replace: config?.replace ?? DEFAULT_CONFIG.subsync.replace, replace: config?.replace ?? DEFAULT_CONFIG.subsync.replace,
}; };
} }
@@ -138,6 +245,11 @@ export function codecToExtension(codec: string | undefined): string | null {
return null; return null;
} }
export function extensionToFfmpegMuxer(extension: string): string {
if (extension === 'vtt') return 'webvtt';
return extension;
}
export function runCommand( export function runCommand(
executable: string, executable: string,
args: string[], args: string[],
@@ -147,6 +259,7 @@ export function runCommand(
const invocation = resolveCommandInvocation(executable, args); const invocation = resolveCommandInvocation(executable, args);
const child = childProcess.spawn(invocation.command, invocation.args, { const child = childProcess.spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'], stdio: ['ignore', 'pipe', 'pipe'],
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
}); });
let stdout = ''; let stdout = '';
let stderr = ''; let stderr = '';
+7
View File
@@ -77,7 +77,10 @@ export interface MpvConfig {
aniskipButtonKey?: string; aniskipButtonKey?: string;
} }
export type SubsyncMode = 'auto' | 'manual';
export interface SubsyncConfig { export interface SubsyncConfig {
mode?: SubsyncMode;
alass_path?: string; alass_path?: string;
ffsubsync_path?: string; ffsubsync_path?: string;
ffmpeg_path?: string; ffmpeg_path?: string;
@@ -389,6 +392,10 @@ export interface ResolvedConfig {
directPlayPreferred: boolean; directPlayPreferred: boolean;
directPlayContainers: string[]; directPlayContainers: string[];
transcodeVideoCodec: string; transcodeVideoCodec: string;
episodePlaylist: {
enabled: boolean;
maxEpisodes: number;
};
}; };
discordPresence: { discordPresence: {
enabled: boolean; enabled: boolean;
+4
View File
@@ -93,6 +93,10 @@ export interface JellyfinConfig {
directPlayPreferred?: boolean; directPlayPreferred?: boolean;
directPlayContainers?: string[]; directPlayContainers?: string[];
transcodeVideoCodec?: string; transcodeVideoCodec?: string;
episodePlaylist?: {
enabled?: boolean;
maxEpisodes?: number;
};
} }
export type DiscordPresenceStylePreset = 'default' | 'meme' | 'japanese' | 'minimal'; export type DiscordPresenceStylePreset = 'default' | 'meme' | 'japanese' | 'minimal';
+44 -3
View File
@@ -97,28 +97,67 @@ export interface MpvClient {
send(command: { command: unknown[]; request_id?: number }): boolean; send(command: { command: unknown[]; request_id?: number }): boolean;
} }
export type SubsyncEngine = 'builtin' | 'alass' | 'ffsubsync' | 'offset';
export interface SubsyncSubtitleTrack { export interface SubsyncSubtitleTrack {
id: number; id: number;
label: string; label: string;
} }
export interface SubsyncReferenceCandidate {
/** Unique option value used in the modal picker (`track:<id>`, `file:<path>`, or `video`). */
key: string;
kind: 'track' | 'file' | 'video';
label: string;
detail?: string;
trackId?: number | null;
filePath?: string | null;
audioStatus?: 'aligned' | 'misaligned' | 'unverified';
audioOffsetMs?: number | null;
isSignsOnly?: boolean;
recommended?: boolean;
}
export interface SubsyncManualPayload { export interface SubsyncManualPayload {
subtitleTracks: SubsyncSubtitleTrack[]; subtitleTracks: SubsyncSubtitleTrack[];
defaultReferenceTrackId: number | null; defaultReferenceTrackId: number | null;
defaultTargetTrackId: number | null; defaultTargetTrackId: number | null;
videoReferenceAvailable: boolean; videoReferenceAvailable: boolean;
ffsubsyncAvailable: boolean; ffsubsyncAvailable: boolean;
/** Normalized media path this picker payload was built for. */
mediaPath?: string | null;
/** Optional guidance shown when automatic sync hands off to the modal. */
guidanceMessage?: string | null;
/** Ranked candidate references (loaded tracks, unloaded tracks, sidecar files, audio). */
referenceCandidates?: SubsyncReferenceCandidate[];
/** Key of the recommended reference candidate in `referenceCandidates`. */
defaultReferenceKey?: string | null;
/** Default engine to select when the modal opens. */
defaultEngine?: SubsyncEngine;
builtinAvailable?: boolean;
alassAvailable?: boolean;
audioReferenceAvailable?: boolean;
canPickReferenceFile?: boolean;
} }
export type SubsyncReferenceMode = 'track' | 'video'; export type SubsyncReferenceMode = 'track' | 'video' | 'file';
export interface SubsyncManualRunRequest { export interface SubsyncManualRunRequest {
engine: 'alass' | 'ffsubsync'; engine: SubsyncEngine;
/** alass reference source: another subtitle track, or the loaded media file itself. */ /** Media path captured when the picker opened, verified against the active video before running. */
mediaPath?: string | null;
/** Reference source: another subtitle track, the loaded video/audio, or a local file on disk. */
referenceMode?: SubsyncReferenceMode; referenceMode?: SubsyncReferenceMode;
referenceTrackId?: number | null; referenceTrackId?: number | null;
referenceFilePath?: string | null;
/** Subtitle track to retime. Defaults to the active primary track. */ /** Subtitle track to retime. Defaults to the active primary track. */
targetTrackId?: number | null; targetTrackId?: number | null;
/** Ignore signs, songs, karaoke, and typesets while computing alignment (default true). */
stripSigns?: boolean;
/** Allow scene-cut / broadcast ad-break split alignment (default true). */
allowSplits?: boolean;
/** Direct offset in milliseconds when `engine === 'offset'`. */
offsetMs?: number | null;
} }
export interface SubsyncResult { export interface SubsyncResult {
@@ -654,6 +693,8 @@ export interface ElectronAPI {
) => Promise<void>; ) => Promise<void>;
onSubsyncManualOpen: (callback: (payload: SubsyncManualPayload) => void) => void; onSubsyncManualOpen: (callback: (payload: SubsyncManualPayload) => void) => void;
runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>; runSubsyncManual: (request: SubsyncManualRunRequest) => Promise<SubsyncResult>;
openSubsyncManual?: () => Promise<void>;
pickSubsyncReferenceFile?: () => Promise<string | null>;
onKikuFieldGroupingRequest: (callback: (data: KikuFieldGroupingRequestData) => void) => void; onKikuFieldGroupingRequest: (callback: (data: KikuFieldGroupingRequestData) => void) => void;
onKikuFieldGroupingCancel: (callback: () => void) => void; onKikuFieldGroupingCancel: (callback: () => void) => void;
kikuBuildMergePreview: (request: KikuMergePreviewRequest) => Promise<KikuMergePreviewResponse>; kikuBuildMergePreview: (request: KikuMergePreviewRequest) => Promise<KikuMergePreviewResponse>;