Compare commits

...
Author SHA1 Message Date
sudacode 935af26cca fix(jellyfin): keep episode titles from leaking across playlist entries
- Pass force-media-title as a per-file loadfile option for every Jellyfin play instead of setting it globally first
- Skip mpv media-title updates for Jellyfin videos in the immersion tracker so a stale title can't replace the canonical one
2026-11-23 03:07:32 -08:00
sudacode 24cd8cae88 fix(jellyfin): drain only the stopped playback's reports in the generic stop
The generic stop waited for every tracked report, including progress for
the next queued episode, which could delay the stop and the start waiting
on it. It now waits only for reports tagged with the playback it stops.
2026-11-23 02:27:54 -08:00
sudacode 0cae6b96fb fix(jellyfin): order episode start reports and guard stop positions
- Track each episode's start report: the playback's own stop waits for it,
  and the next start waits for every start and stop in flight, so Jellyfin
  never keeps an older episode as now-playing.
- The generic stop handler takes mpv's position only while mpv still has
  the stopped item loaded; otherwise it uses the item's last observed
  position, so a stop cannot overwrite the resume point with the next
  episode's position.
2026-11-23 02:13:38 -08:00
sudacode 172c771d97 fix(jellyfin): keep the episode playlist window at least 3 long
With a 2-episode window the episode just left falls outside the next
window, so a queue run could remove it while the user stepped back to it.
mpv's IPC cannot check-and-remove atomically; a window of 3 or more always
keeps both immediate neighbors, so removals stay two steps from the
playing entry. maxEpisodes now clamps to 3..25.
2026-11-23 02:03:11 -08:00
sudacode b0446833e6 fix(jellyfin): start queued episodes after every in-flight stop report
Past the startup grace, mpv's empty path between playlist files makes the
generic stop handler report the old episode, and the queued one is then
adopted with nothing to supersede. Its start report did not wait for that
stop, so Jellyfin could get playing(next) before stopped(previous) and
clear the new now-playing item (Windows E2E, and end-of-file auto-advance).
Both stop handlers now record their reports in one tracker, and an episode
start waits for all of them.
2026-11-23 01:57:30 -08:00
sudacode 86823aebe9 fix(jellyfin): keep in-window playlist entries in place when re-queueing
A queue run read mpv's playlist, then removed and re-added every neighbor.
A playlist-next/prev that landed between the read and the edits could
remove the entry mpv was just starting, sending playback back to the old
episode (macOS E2E). Entries still in the window now stay put; only
entries outside it are removed and only missing ones are resolved and
inserted, so a step touches just the far ends of the window.
2026-11-23 01:53:00 -08:00
sudacode 93d95538ae test(e2e): check Jellyfin playlist titles only on mpv 0.42+
playlist/N/title is read-only before mpv 0.42, so the CI runners on 0.41
keep listing stream URLs. Note the version requirement in the docs.
2026-11-23 01:42:30 -08:00
sudacode ec98118006 fix(jellyfin): keep playback armed across file unload and serialize episode stops
- An empty mpv path during the startup grace belongs to the file being
  replaced, so it no longer clears the new, not-yet-loaded playback. This
  dropped Jellyfin reporting (and the episode queue) whenever playback
  started while another file was playing, and failed E2E on all CI runners.
- Chain superseded stop reports so each episode start waits for every
  earlier stop, and skip starts a later switch already took over.
- Tag tracked reports with their playback so a superseded stop drains only
  its own in-flight progress, not the new episode's.
- E2E: clamp the fake server's range end and wait for the ep2 start report.
2026-11-23 01:36:01 -08:00
sudacode c742e9541c fix(jellyfin): title queued playlist entries instead of stream URLs
- Set playlist/N/title for the current and queued neighbor episodes so mpv's playlist doesn't show stream URLs that carry the API key
- Thread the plan title through prepared Jellyfin playback
- Cover titles in unit and e2e playlist tests
2026-11-23 01:20:54 -08:00
sudacode 8076f3faae feat(jellyfin): queue series neighbor episodes in the mpv playlist
Jellyfin playback now keeps the episodes around the playing one in mpv's
playlist, so mpv's playlist keys and end-of-file advance move through the
series (across seasons) in the same mpv and app session.

- Queue neighbors only after the first time-pos, so startup is not slowed.
- Adopt queued entries on mpv's path change without a loadfile: report the
  previous item stopped, then start reporting, stats, and subtitles for the
  new one. Runs before the immersion sync so stats metadata is recorded first.
- Tell the mpv plugin which playlist paths the app manages so start-file
  skips subtitle rearm and overlay auto-start for them.
- Add jellyfin.episodePlaylist.enabled (default on) and maxEpisodes
  (default 5, clamped 2-25), a rolling window centered on the current episode,
  under Settings > Integrations > Jellyfin > Episode Playlist.
- Add a fake-Jellyfin e2e scenario covering next/prev in one session.
2026-11-23 01:13:33 -08:00
sudacode 93045ebf9f fix(build): extract Yomitan on Windows without the Archive module
PowerShell 7's PSModulePath makes powershell.exe load the PS7 Archive
module, whose ExtractToDirectory overload is missing on .NET Framework,
so Expand-Archive silently extracted nothing on the windows-latest runner.
2026-11-23 00:20:03 -08:00
sudacode 18490c9d4f chore(release): prepare v0.22.1-beta.2 2026-11-23 00:02:21 -08:00
sudacode 78809094d2 fix(jimaku): keep the series name for stream titles containing slashes (#337) 2026-11-22 23:59:19 -08:00
sudacode 71251b8d7b feat(stats): group library seasons, movies and OVAs into franchise cards (#336) 2026-11-22 21:03:23 -08:00
sudacode 9d2057cc30 fix(anilist): resolve later seasons past split-cour halves and specials (#335) 2026-11-22 21:03:11 -08:00
sudacode ac3ceab856 feat(aniskip): detect intros and outros from file chapters and AniSkip v2 (#334) 2026-11-22 21:02:54 -08:00
sudacode ee52664655 feat(setup): download FFmpeg from first-run setup when none is usable (#333) 2026-11-22 02:09:06 -08:00
sudacode 0ae70b4ab2 fix(overlay): keep forwarding mpv keys after a Yomitan popup closes (#332)
Decide whether the Yomitan popup is open from the popup host in the DOM
instead of the cached yomitanPopupVisible flag, which can lag a close and
kept input.conf keys from reaching mpv.

Keep the imported mpv key list in place while a refresh is in flight, so a
key pressed right after the overlay regains focus is not dropped. A failed
reload still clears the list.

At --log-level debug, log why the overlay kept an mpv-bound key
(config-loading, modal, lookup-popup, interactive-target or
no-imported-bindings) over a validated IPC channel.

Refs #331
2026-11-20 18:27:11 -08:00
sudacode 0c1865f4a6 chore(release): prepare v0.22.1-beta.1 2026-11-06 19:07:54 -08:00
sudacode 6fd55053d4 fix(overlay): identify Windows mpv windows through IPC PID (#330) 2026-11-06 18:37:44 -08:00
sudacode 0360270e81 chore(release): v0.22.0 2026-11-06 00:07:01 -08:00
sudacode a8e929eb26 refactor(controller): remove unused rightStickHorizontal binding
- Drop the Alt Horizontal row from Alt+C; no action read this binding
- Remove the key from config defaults, resolver, IPC validator, and types
- Regenerate config.example.jsonc and remove the inactive-binding exemption
2026-11-05 23:33:31 -08:00
sudacode b31ddce627 feat(controller): add hold + press combos to main bindings (#328)
* feat(controller): add hold + press combos to main bindings

Main Alt+C actions can now be learned as combos such as L1 + D-pad right.
A combo fires on each press while its hold button is down, and claims its
press input so token move and popup scroll ignore it until it is released.
A plain action on a hold button fires on release, unless another bound
button was pressed during the hold.

The save path needed two changes for combos to persist. The IPC validator
rebuilt bindings field by field and dropped `hold`, so Alt+C showed a combo
from its local copy until the next reload turned it back into a plain
button. Validator and config resolver now share one parser. Saves also
replace the controller section, since the deep merge in patchRawConfig kept
the old `hold` when a combo was rebound to one button.

Also fixes Learn on the (D-pad) rows, which threw after cancel() cleared
the capture target.

* test(launcher): wait for content in background child test

The test polled for the fake app's output files to exist, but the shell
creates a redirect target before writing to it. A poll landing in that gap
read an empty env file and failed with '' !== '1', as seen once in CI.
Wait until both files have content instead.

* fix(controller): keep a diagonal push from learning as a combo

Learn took the first axis of a diagonal stick push as the hold and the
second as the press, saving a combo that one axis could never trigger. This
reached main Alt+C rows when they moved to combo capture. Axes crossing the
threshold in the same poll as the first input now count as one movement. A
second axis moved in a later poll still records a combo.

* fix(controller): only treat simultaneous axes as one movement

The diagonal push guard also blocked an axis activated in the same poll as a
button, so L1 plus a stick direction could not record the stick until it was
released and moved again. Apply the guard only when the first input is an
axis, so that input pair records as a combo again.
2026-11-05 23:23:54 -08:00
sudacode 79e5535823 fix(controller): show dialog hints only while a controller is connected
- Add createControllerHintVisibility: use the dialog window's pad, else ask main which controller the overlay is reading, at most once per second while a dialog is open
- Hide shortcut tags when controller support is on but no controller is present
- Update the Anki integration docs and changelog fragments to match
2026-11-05 00:54:25 -08:00
sudacode 5140b5e9be test(overlay): pin an X11 session for Linux assembly tests
Fullscreen recreation only runs outside Hyprland and Sway, and the tests
inherited the running session's compositor variables, so they failed when run
from a Hyprland desktop.
2026-11-04 23:31:11 -08:00
sudacode c2dac537da fix(overlay): keep popup pause working with Hachidori 0.4.0
Hachidori 0.4.0 closed its popup shadow root, so isHachidoriPopupOpen always
returned false. The popup never took over the subtitle hover pause, and moving
off the subtitle resumed playback with the popup open. Popup key and controller
routing read the same check. The sidebar kept working because its hold follows
the attention event instead of the pane.

The fork now publishes the pane state on the host element, and the renderer
reads that attribute instead of upstream's shadow root and CSS class. The unit
stubs modelled an open root and hid this, so test:dictionary:electron now drives
the real reader and asserts the attribute follows the pane.
2026-11-04 22:46:25 -08:00
sudacode bc7e82fee6 build(deps): remove @discordjs/rest undici patch
- Drop the patchedDependencies entry from package.json and bun.lock
- Delete patches/@discordjs%2Frest@2.6.1.patch, which pinned undici to 6.27.0
2026-11-04 22:05:32 -08:00
sudacode c3e672efdb refactor(plugins): remove auto-jimaku example plugin and fix docs
- Remove the auto-jimaku example, now covered by the built-in Jimaku auto-open
- Drop its plugins docs section and changelog bullet
- List the keyboard-only `C` key in Keyboard shortcuts
- Point the configuration reference to Controller support for button defaults
2026-11-04 22:02:05 -08:00
sudacode 269c0708cb feat(stats): overhaul the Trends tab (#325) 2026-11-04 21:55:18 -08:00
sudacode f89f78b861 refactor(main): move plugins, session actions and subtitle generation into assemblies (#327)
* refactor(main): build overlay geometry and pointer interaction in the overlay assembly

Inject Electron's screen (and the stats-window promotion) into the overlay geometry and
visible-overlay interaction runtimes so they load under bun test, then construct both in
createOverlayAssembly together with the overlay visibility composer and the mpv subtitle
suppression handlers. Replace the three regex tests that pinned the moved Linux input and
shape code with behaviour tests on the runtimes.

* refactor(main): move the autoplay-ready gate into the playback assembly

The autoplay-ready gate, its post-warm subtitle prime, the current-media tokenization gate and
managed local subtitle selection all read playback state, and playback signals through the
gate, so createPlaybackAssembly now builds them. The overlay reaches the gate through a getter.

Replace the last four regex guards with behaviour tests: the gate holds the release until the
visible overlay has measured the line and ignores untokenized lines during warmup (playback),
cached autoplay priming never paints raw first and the sidebar media path is tagged only after
prefetch loads (priming runtime), and dashboard mining overrides the Hachidori Anki server only
when the proxy is on (stats server runtime). main-wiring.test.ts is now empty and removed.

* refactor(main): move the plugin host, panel and windows into a plugins assembly

* refactor(main): move session action dispatch and renderer mpv commands into an assembly

createSessionActionsAssembly owns the session action dispatcher, the secondary-subtitle mode cycle, queueing the clipboard's video, and the mpv commands the overlay renderer sends. The runtime option cycle both paths used is now one function.

* refactor(main): move Whisper subtitle generation into an assembly

* refactor(main): resolve subtitle annotation options in a runtime module

The runtime-option-over-config resolution that the texthooker page and the MeCab startup decision share moves out of main.ts into createAnnotationOptions.

* test(main): cover a non-boolean runtime annotation option value

* docs: describe the plugins, session actions and subtitle generation assemblies

Update ownership for overlay geometry and pointer interaction, the autoplay-ready gate, and annotation options; point the overlay priming entry points at their new modules; the main-wiring regex debt is gone.

* build: export MpvClientEvents so declaration emit can name the plugins assembly's return type
2026-11-04 21:54:49 -08:00
YashaNoosandClaude Opus 5.5 14ef7e823c Controller: character navigation in keyboard-only mode, plain Xbox face names (#326)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-11-04 21:54:00 -08:00
sudacode a8bc585f75 chore(hachidori): update bundled Hachidori to upstream 0.4.0
- Show every pitch accent in each popup entry, drawn on the headword's reading
- Split headword furigana per kanji and add Yomitan-style definition tags
2026-11-04 21:51:06 -08:00
sudacode 5f635f3042 fix(e2e): disable mpv direct rendering on macOS to avoid loadfile hang
- Pass `--vd-lavc-dr=no` alongside `--vo=libmpv` on darwin
- cocoa-cb answers DR image requests only from its main queue, which can stall on CI runners and freeze mpv's core and IPC with no timeout
2026-11-03 23:49:06 -08:00
sudacode 7c637149dd fix(controller): keep popup pause and press handling reliable (#324) 2026-11-03 23:13:46 -08:00
33f5f890d5 feat(jimaku): auto-open modal when a video has no Japanese subtitle (#319)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Ivan Melck <ivan@spec-kitty.ai>
2026-11-03 23:12:46 -08:00
sudacode d8c2315405 perf(stats): speed up dashboard queries on large databases (#322) 2026-11-03 22:04:01 -08:00
sudacode 8976d78390 feat(controller): route status messages through notifications
- Send controller connected and disabled messages over a new IPC channel so they follow ankiConnect.behavior.notificationType
- Remove the separate controller status toast from the overlay
- Only announce connected controllers when controller.enabled is on
- Announce a controller again after it reconnects, and update usage docs
2026-11-03 21:55:55 -08:00
sudacode 1c50d249e0 fix(mpv): reset per-file state when a same-file reload skips the path clear (#323)
mpv only sends the latest value of an observed property, and only after its
IPC thread has handled queued commands and events. A same-file
`loadfile replace` can therefore arrive with no `path=null`, so path
comparisons see no change, the autoplay gate stays released for that path and
drops every ready signal, and playback stays paused.

Track an `end-file` that mpv has not followed with a different path. If it is
still pending at `file-loaded`, replay the clear and read the path back, so
consumers see the same sequence as any other load. `file-loaded` waits for the
reply so plugins can read their media snapshot during the event.

Fixes #320
2026-11-03 21:40:14 -08:00
sudacode 8e29cb3c55 fix(controller): pick up macOS presses while mpv is in front (#321) 2026-11-03 21:37:11 -08:00
sudacode fa3051f9cb feat(subtitles): add regex subtitle filters with built-in presets (#318)
- Add `subtitleFilter` config with four presets: parentheses, brackets, speaker prefix and music symbols. Custom regex rules run after the presets.
- Filter primary text where it enters the app (live `sub-text` and parsed cues), so the overlay, sidebar, mining and stats all get the same filtered text.
- Changes hot-reload: the current line is read again and the active track is parsed again, using the filter config as the prefetch parse key.
- Add a custom rule editor in Settings under Behavior → Subtitle Filters that checks patterns as you type.
- Update the config example, the configuration docs and the architecture domains doc, and add a changelog fragment.
2026-11-03 00:33:58 -08:00
351 changed files with 22206 additions and 6644 deletions

No files matched your search

+3
View File
@@ -32,6 +32,9 @@ jobs:
- name: Verify native mpv process launch
run: bun test src/main/runtime/mpv-process.test.ts
- name: Verify mpv PID lookup and Windows tracker
run: bun test src/window-trackers/mpv-process-id.test.ts src/window-trackers/windows-tracker.test.ts
- name: Verify POSIX launcher bootstrap
run: bun test src/main/runtime/posix-launcher-bootstrap.test.ts
+1 -1
View File
@@ -49,7 +49,7 @@ Start here, then leave this file.
- Build/release scripts (`scripts/**`): `bun run test:scripts`
- Internal docs, `AGENTS.md`, or repo skills: `bun run test:docs:kb`
- User-facing `docs-site/`: `bun run docs:test`, then `bun run docs:build`
- macOS mpv window helper (`scripts/get-mpv-window-macos.swift`): compile it on macOS with `bun run build`
- macOS Swift helpers (`scripts/get-mpv-window-macos.swift`, `scripts/macos-controller-watch.swift`): compile them on macOS with `bun run build`
- Test lanes are directory-discovered via `scripts/test-lanes.ts`; never hand-list test files in `package.json`
## Docs Upkeep
+50
View File
@@ -1,5 +1,55 @@
# Changelog
## v0.22.0 (2026-11-06)
### Added
- **Plugins**:
- JavaScript plugins load at startup from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
- Plugins can react to playback and mined cards, add bindable actions, run programs, and show results in overlay panels or their own windows.
- Example plugins cover AI line explanations (`ai-explain`), AnkiWeb sync (`anki-sync`), and show and episode tags on mined cards (`episode-tags`).
- Plugin authors get a versioned API with standalone types.
- **Subtitle Filters**: Remove text in parentheses, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
- **Controller Combos**: Controller actions can now be combos, such as holding `L1` and pressing D-pad right. Click **Learn** in `Alt+C`, then hold one button and press another.
- **Controller Actions**: New bindings cover previous, next, replay, and play-next subtitle, hold-to-show secondary subtitle, and previous or next Yomitan entry. All are unbound by default and can be assigned in `Alt+C`.
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be used with a controller and show button hints while one is connected. Remap both layouts per controller in `Alt+C`.
- **Controller Button Style**: Choose Xbox, Nintendo, or PlayStation button names per controller in `Alt+C`, or set a default with `controller.faceButtonLabels`.
- **Controller Clash Warnings**: `Alt+C` now warns when two actions share the same input.
- **Keyboard-Only Mode**:
- Press `C` or use the new controller binding to move by character, reaching words split by the subtitle parser.
- The new **Pause Video In Keyboard-Only Mode** setting pauses on entry and resumes on exit.
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Reopening Jimaku after the video changes now refreshes the title and episode.
### Changed
- **Stats Trends and Vocabulary**:
- Trends adds a learning section, heatmap, title timeline, custom date ranges, and a page-wide title filter.
- Vocabulary now has one searchable word table, known words by frequency band, a growth chart, and a full kanji view.
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
- Stats now explains when streamed words or lines can't be mined.
- **Bundled Hachidori**: Updated to upstream 0.4.0, adding every pitch accent in popup entries, per-kanji headword furigana, and Yomitan-style definition tags.
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Connected and disabled messages now follow your `ankiConnect.behavior.notificationType` setting.
- **Dictionary Popup**: Turning keyboard-only mode off now also closes the popup.
### Fixed
- **Controller Settings (`Alt+C`)**:
- Remaps now apply right away, and Learn works on **(D-pad)** rows.
- Clicking a row shows **Learn**, **Clear**, and **Reset** again.
- The window previews your bindings until a press, then selects the pressed controller.
- Button names are now correct on standard-layout controllers.
- **Controller Input on macOS and Windows**: One press no longer runs its action twice. On macOS, buttons now work while mpv is in front.
- **Dictionary Popup**: Keyboard and controller lookups now pause and resume playback reliably. Moving between words right after closing a popup no longer reopens it.
- **Playback**: Reloading the current file no longer leaves playback paused. The "Overlay loading" message no longer sticks or turns into a false error when a playlist advances.
- **Stats**:
- The dashboard, Vocabulary tab, and sentence search load much faster on large databases, and Trends downloads far less data.
- Trends now counts each finished episode once, and its Library totals match the selected range.
- Word totals, readings, Hide Names, and rate charts are now accurate.
- Date handling is now correct in time zones ahead of UTC.
- **AniList**: Progress sync now adds a missing show to Watching, or Completed on the final episode, when the title matches exactly or is pinned. Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
- **Anki Sentence Audio**: Generated sentence audio no longer overwrites Yomitan's word audio on default configs. If you relied on the old default, set `ankiConnect.fields.audio` to `ExpressionAudio`.
- **AppImage**: Fixed "Service Crash" notifications on quit on Ubuntu 26.04 and newer.
### Docs
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
## v0.21.1 (2026-10-26)
### Changed
+2 -2
View File
@@ -104,7 +104,7 @@ A stats dashboard tracks watch time, vocabulary growth, mining throughput, sessi
</tr>
<tr>
<td><b>Plugins</b></td>
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. The bundled example explains the current line with Codex. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
<td>Load your own JavaScript at startup to react to playback, run timers, add key-bound actions, and show results in an overlay panel. Bundled examples explain the current line with Codex, sync Anki to AnkiWeb, and tag mined cards by episode. <a href="https://docs.subminer.moe/plugins">Plugin guide</a></td>
</tr>
</table>
@@ -121,7 +121,7 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to
| mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
| ffmpeg | Recommended | Audio clips and screenshots on cards |
| ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) |
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
| yt-dlp | Optional | YouTube playback |
-51
View File
@@ -1,51 +0,0 @@
// Opens the Jimaku subtitle search when a file starts without a Japanese subtitle track.
// It waits a few seconds after the file loads so external subtitles mpv or SubMiner add count.
const DEFAULT_SETTINGS = {
// Built-in action to run, e.g. `openTsukihime` or `openSubtitleSelection`.
action: 'openJimaku',
// Track `lang` codes that count as Japanese. Track titles with "Japanese" or 日本語 count too.
languages: ['ja', 'jp', 'jpn'],
delayMs: 3_000,
// Also check http(s) streams; Jimaku can only search by name, which streams rarely have.
streams: false,
};
const JAPANESE_TITLE = /japanese|日本語/i;
function activate(ctx) {
const settings = { ...DEFAULT_SETTINGS, ...ctx.settings };
const languages = new Set(settings.languages.map((lang) => lang.toLowerCase()));
let cancelCheck = null;
let playbackId = null;
function hasJapaneseSubtitle(trackList) {
return trackList.some(
(track) =>
track?.type === 'sub' &&
(languages.has(String(track.lang ?? '').toLowerCase()) ||
JAPANESE_TITLE.test(String(track.title ?? ''))),
);
}
async function check(media) {
cancelCheck = null;
const trackList = await ctx.mpv.getProperty('track-list');
if (ctx.media.current()?.playbackId !== media.playbackId || !Array.isArray(trackList)) return;
if (hasJapaneseSubtitle(trackList)) return;
ctx.log.info(`No Japanese subtitles for ${media.path}; running ${settings.action}.`);
await ctx.actions.run(settings.action);
}
ctx.media.on('change', (media) => {
if (media?.playbackId === playbackId) return;
playbackId = media?.playbackId ?? null;
cancelCheck?.();
cancelCheck = null;
if (!media) return;
if (!settings.streams && /^[a-z]+:\/\//i.test(media.path)) return;
cancelCheck = ctx.after(settings.delayMs, () => check(media));
});
}
module.exports = { activate };
-6
View File
@@ -1,6 +0,0 @@
{
"name": "Auto Jimaku",
"version": "1.0.0",
"apiVersion": 1,
"main": "main.js"
}
-3
View File
@@ -28,9 +28,6 @@
},
},
},
"patchedDependencies": {
"@discordjs/rest@2.6.1": "patches/@discordjs%2Frest@2.6.1.patch",
},
"overrides": {
"@xmldom/xmldom": "0.8.15",
"app-builder-lib": "26.16.1",
-5
View File
@@ -1,5 +0,0 @@
type: fixed
area: overlay
- The controller settings window (`Alt+C`) no longer edits a controller it cannot see. A newly opened window cannot see any controller until you press one of its buttons (browsers hide a pad from a new window until then); it used to show and edit the global defaults meanwhile, and its status could stay stuck on "No controllers detected". Now it shows the bindings of the controller the overlay is using (or the saved one), labelled as a preview, and Learn, Clear, Reset and the button style are locked until the press.
- With several controllers connected, `Alt+C` now selects the one you just pressed, and Learn listens to that controller.
-5
View File
@@ -1,5 +0,0 @@
type: fixed
area: anilist
- AniList progress sync now adds a show to your Watching list (or Completed on the final episode) when it is not on your list yet, instead of failing with "AniList update not possible". This only happens when the file title exactly matches an AniList title or the entry is pinned with the character dictionary override; loose matches still require adding the show yourself.
- Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
+7
View File
@@ -0,0 +1,7 @@
type: fixed
area: anilist
- Later seasons now resolve to the right AniList entry when the sequel chain contains split-season halves ("Part 2", "Cour 2"), specials, or movies. Mushoku Tensei S3, Re:ZERO S4, Dr. STONE S3, KonoSuba S3, and Attack on Titan S4 used to land one season short or on a movie.
- An entry whose title names the season ("Season 3", "III", "第3期") is preferred over counting sequels.
- Episodes past the first half of a split season update the second half's AniList entry at the right episode (episode 15 of an 11 + 12 season updates the second entry to episode 4).
- Character dictionary AniList matches cached by older versions are re-resolved once.
+7
View File
@@ -0,0 +1,7 @@
type: added
area: aniskip
- Added outro skipping: the AniSkip key now also skips the ending, with its own prompt and chapter markers.
- Intro and outro detection now reads the file's own chapters first (named OP/ED chapters, or song-length chapters near the start and end) and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
- AniSkip lookups now send the episode length so the times match your TV or Blu-ray cut.
- Fixed AniSkip rate limits, server errors, and network failures being remembered as "no intro" until restart; they are now retried on the next load.
-4
View File
@@ -1,4 +0,0 @@
type: fixed
area: anki
- `ankiConnect.fields.audio` now defaults to `SentenceAudio` instead of `ExpressionAudio`, so generated sentence audio no longer overwrites Yomitan's word audio on default configs. `fields.wordAudio` still defaults to `ExpressionAudio`. If you relied on the old default, set `fields.audio` to `ExpressionAudio` explicitly.
-4
View File
@@ -1,4 +0,0 @@
type: fixed
area: linux
- Fixed AppImage builds on Ubuntu 26.04+ (uutils coreutils) releasing their mount before Chromium child processes finished shutting down, which brought back "Service Crash" notifications on quit.
-4
View File
@@ -1,4 +0,0 @@
type: fixed
area: overlay
- Controller remaps made in `Alt+C` now apply right away; before, the overlay kept the old bindings until SubMiner restarted.
@@ -1,4 +0,0 @@
type: added
area: overlay
- `Alt+C` now warns when two controller actions share an input, as the dialog layouts already did. Both rows show "⚠ Same as …", including a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: overlay
- `Alt+C` has a **Button Style** choice (Xbox, Nintendo or PlayStation), saved per controller. PlayStation is new: buttons and the review and duplicate card shortcuts show ╳ ○ □ △. `controller.faceButtonLabels` accepts `playstation` and stays the default for controllers without their own style.
-4
View File
@@ -1,4 +0,0 @@
type: fixed
area: overlay
- Clicking a row in `Alt+C` shows its **Learn**, **Clear** and **Reset** buttons again. The panel opened but was squeezed to nothing once the list was taller than the window, so **Clear** (set a binding to None) could not be reached.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: overlay
- The duplicate card (field grouping) dialog has a controller layout: the D-pad picks the original or new card, `A` continues and confirms the merge, `B` cancels or goes back from the preview, `X` turns "Delete duplicate" on or off, `Y` switches Compact / Full, and the D-pad scrolls the preview. Each control shows its shortcut, and the layout can be changed per controller in the new **Duplicate card (field grouping)** group of `Alt+C`.
@@ -1,5 +0,0 @@
type: added
area: overlay
- Added a controller layout for the media timing review dialog covering every button, with L1 / R1 + D-pad combos for the clip start and end, and D-pad actions that repeat while held. Each button shows its controller shortcut while controller support is on, and the first press in a newly opened dialog already counts. The controller's usual actions pause while the dialog is open, including in the hidden subtitle overlay behind it.
- Added `controller.faceButtonLabels` (`xbox` or `nintendo`) so fixed controller layouts and the `Alt+C` button names follow the letters printed on the pad. Use `nintendo` for controllers with A on the right and B at the bottom.
@@ -1,4 +0,0 @@
type: changed
area: overlay
- The controller's **Toggle MPV Pause** button now works without keyboard-only mode, so you can pause while just watching.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: overlay
- The media timing review controller layout can now be changed in the new **Review media timing** group of `Alt+C`. Learn records a single button or a combo (hold one button, press another), any button can be a hold button, changes are saved per controller, rows warn about clashing inputs, and **Reset all** restores the default layout. The review's button hints follow your bindings.
-5
View File
@@ -1,5 +0,0 @@
type: added
area: overlay
- Added a controller binding that shows the secondary subtitle only while a button is held (`controller.bindings.holdSecondarySub`). It is unbound by default; assign it with Learn in the `Alt+C` controller modal. It works with or without keyboard-only mode and does not change the saved secondary subtitle mode.
- Added controller bindings to select the previous or next word entry in the open Yomitan popup (`controller.bindings.previousEntry` / `nextEntry`). Mine Card mines the selected entry. Both are unbound by default; assign them with Learn in the `Alt+C` controller modal.
@@ -1,4 +0,0 @@
type: fixed
area: overlay
- The `Alt+C` controller screen now shows the right button names for controllers that report the W3C standard layout (most Xbox, PlayStation, Switch and 8BitDo pads). Previously Select and Start showed as `L3` and `R3`, and the triggers as `Back` and `Start`. Bindings themselves were unaffected.
@@ -1,4 +0,0 @@
type: added
area: overlay
- New controller actions for subtitle lines, in the **Subtitles** group of `Alt+C`: **Previous Subtitle**, **Next Subtitle**, **Replay Subtitle** and **Play Next Subtitle**, matching `Shift+H`, `Shift+L`, `Ctrl+Shift+H` and `Ctrl+Shift+L`. They are unbound by default and work with or without keyboard-only mode.
+5
View File
@@ -0,0 +1,5 @@
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.
@@ -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.
+4
View File
@@ -0,0 +1,4 @@
type: fixed
area: jimaku
- The Jimaku modal fills in the series name again for Jellyfin episodes whose name contains a "/" (for example "Under the Cherry Tree / For Now, Let's Try Stripping"). It used to show only the last part of the episode name with no season or episode. The AniList fallback guess had the same problem and is fixed too.
-4
View File
@@ -1,4 +0,0 @@
type: added
area: overlay
- New **Pause Video In Keyboard-Only Mode** setting (`subtitleStyle.autoPauseVideoOnKeyboardMode`, off by default): turning keyboard-only mode on, from the keyboard or a controller, pauses the video, and turning it off resumes it. A video that was already paused, or that you played or paused yourself in the meantime, is left as it is.
@@ -1,4 +0,0 @@
type: changed
area: overlay
- Turning keyboard-only mode off, from the keyboard or a controller, now also closes the dictionary popup.
+5
View File
@@ -0,0 +1,5 @@
type: added
area: stats
- Library lists each anime once: seasons, movies, and OVAs that AniList links as sequels, prequels, side stories, summaries, or compilations share one card, named after the first TV series. Opening it lists the parts in release order with their own stats. Spin-offs and alternative versions keep their own cards.
- A title's page has **Move to Another Anime…**, **Show On Its Own**, and **Put Back Where AniList Has It** to correct the grouping. `subminer sync` keeps the most recent choice.
+6
View File
@@ -0,0 +1,6 @@
type: fixed
area: overlay
- mpv keys from `input.conf` (for example arrow keys bound to `sub-seek`) are no longer sent to a Yomitan popup that has already closed. The overlay decided whether the popup was open from a cached flag that could lag behind a close.
- mpv keys no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
- With `--log-level debug`, the log names why the overlay kept an mpv-bound key instead of forwarding it.
@@ -1,4 +0,0 @@
type: fixed
area: mpv-plugin
- Fixed the "Overlay loading" message staying on screen when mpv moves to the next file in a playlist, then turning into "Overlay did not become ready; check SubMiner logs" after 30 seconds even though the overlay was working. The overlay window is reused between files, so the plugin no longer restarts the loading message once the overlay has reported ready.
-10
View File
@@ -1,10 +0,0 @@
type: added
area: plugins
- Added JavaScript plugins loaded at startup from `<config dir>/plugins/<id>/` and enabled under `plugins` in the config. Plugins can listen to mpv events, run timers, register actions bound with `__plugin-action:<id>/<action>` keybindings or run with `--plugin-action`, run built-in actions, react to mined Anki cards and call AnkiConnect, start mpv, run programs, keep state in a per-plugin data folder, and show results in an overlay panel or their own window.
- Added an example `ai-explain` plugin that sends the current line and its neighbors to `codex exec` and shows a translation or grammar explanation.
- Added an example `anki-sync` plugin that syncs Anki to AnkiWeb after you mine cards, once mining goes quiet or playback ends.
- Added an example `episode-tags` plugin that tags mined cards with the show and episode, such as `show::Frieren::S01E07`.
- Added an example `auto-jimaku` plugin that opens the Jimaku search when a file starts without a Japanese subtitle track.
- Added a versioned plugin API with standalone authoring types, cached playback snapshots, lifecycle cancellation and cleanup, and awaitable mpv commands. Async activation is bounded and actions wait only for their own plugin. Shutdown skips pending loads, runs each deactivation once, and blocks calls from disposed plugins.
- Mining events preserve original and kept note ids with the media and subtitle captured when mining starts, so delayed enrichment and merges into older notes keep the source episode. Stats-dashboard cards do not trigger plugin events. Plugin subtitle lookups and mining provenance account for subtitle delay and return timing on the subtitle file's timeline.
-4
View File
@@ -1,4 +0,0 @@
type: fixed
area: overlay
- Moving between words with the keyboard or a controller right after closing the dictionary popup no longer reopens it. A popup that closed under the mouse pointer was still treated as open.
+4
View File
@@ -0,0 +1,4 @@
type: added
area: setup
- First-run setup now shows whether FFmpeg and FFprobe are usable. When they are missing from `PATH`, **Download FFmpeg** saves a verified static build next to your config, and SubMiner and the `subminer` command use it whenever no system FFmpeg is found.
@@ -0,0 +1,4 @@
type: docs
area: overlay
- Explain how to collect and interpret Windows overlay attachment and readiness warnings without enabling debug logging.
@@ -0,0 +1,6 @@
type: fixed
area: overlay
- Windows overlay attachment now identifies mpv through its IPC process ID, removing the dependency on PowerShell command-line lookups and allowing the IPC socket to be configured in `mpv.conf`.
- Revalidate cached Windows mpv process IDs and expire them after sustained IPC failures so PID reuse cannot keep the overlay attached to an unrelated window.
- Diagnose stalled Windows overlays at the default warn log level, including tracking/PID state, renderer readiness, opacity, native binding errors, and recovery, with repeated warnings rate limited.
+44 -25
View File
@@ -128,59 +128,62 @@
"toggleLookup": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"closeLookup": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"toggleKeyboardOnlyMode": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"mineCard": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"quitMpv": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"previousAudio": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"nextAudio": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"playCurrentAudio": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"toggleMpvPause": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"holdSecondarySub": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"previousEntry": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"nextEntry": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"toggleCharacterNavigation": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"previousSubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"nextSubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"replaySubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"playNextSubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"leftStickHorizontal": {
"kind": "axis", // Analog binding input source kind. Values: none | axis
"axisIndex": 0, // Raw axis index captured for this analog controller action.
@@ -191,11 +194,6 @@
"axisIndex": 1, // Raw axis index captured for this analog controller action.
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
"rightStickHorizontal": {
"kind": "axis", // Analog binding input source kind. Values: none | axis
"axisIndex": 3, // Raw axis index captured for this analog controller action.
"dpadFallback": "none" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
}, // Axis binding descriptor reserved for alternate right-stick mappings. Use Alt+C learn mode or set a raw axis descriptor manually.
"rightStickVertical": {
"kind": "axis", // Analog binding input source kind. Values: none | axis
"axisIndex": 4, // Raw axis index captured for this analog controller action.
@@ -854,6 +852,22 @@
} // CSS declaration object applied to the subtitle sidebar. Includes color, background-color, and all font properties.
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
// ==========================================
// Subtitle Filters
// Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
// Applies to the overlay, sidebar, mined sentences and stats.
// Hot-reload: filter changes apply to the current subtitle file immediately.
// ==========================================
"subtitleFilter": {
"presets": {
"parentheses": false, // Remove text in () and (), such as speaker names, readings and notes. A line wrapped entirely in parentheses, usually inner thoughts, is kept. Values: true | false
"brackets": false, // Remove text in [], [], 【】 and 〔〕, such as sound effects and music cues. Values: true | false
"speakerPrefix": false, // Remove a short name followed by a colon at the start of a line, as in 山田:元気? Values: true | false
"musicSymbols": false // Remove ♪, ♫ and ♬. A line left with only symbols such as ~ is removed. Values: true | false
}, // Built-in filters. Each removes its matches and is off by default.
"customRules": [] // Your own regex rules, applied in order after the presets. Each rule is { name, pattern, replacement, enabled }; patterns use the gmu flags, so ^ and $ match per line. Leave replacement empty to remove the match.
}, // Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
// ==========================================
// Shared AI Provider
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
@@ -976,7 +990,8 @@
"apiKey": "", // Jimaku API key. Optional but recommended for higher rate limits. Get one for free at https://jimaku.cc.
"apiKeyCommand": "", // Shell command that prints the Jimaku API key to stdout. Used instead of apiKey to avoid storing the key in plain text.
"languagePreference": "ja", // Preferred language used in Jimaku search. Values: ja | en | none
"maxEntryResults": 10 // Maximum Jimaku search results returned.
"maxEntryResults": 10, // Maximum Jimaku search results returned.
"autoOpenWhenPrimarySubtitleMissing": false // Pause playback and open the Jimaku modal when a local video has no subtitle track in youtube.primarySubLanguages (Japanese by default). Values: true | false
}, // Jimaku API configuration and defaults.
// ==========================================
@@ -1065,8 +1080,8 @@
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
}, // SubMiner-managed mpv launch and bundled plugin options.
// ==========================================
@@ -1096,7 +1111,11 @@
"mp3",
"aac"
], // 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.
// ==========================================
+5 -3
View File
@@ -26,8 +26,8 @@ On Linux, the token is stored with `gnome-libsecret` by default. If your keyring
An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then:
1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint.
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels.
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode.
2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. Specials, movies, and the second half of a split season ("Part 2", "Cour 2") do not count as seasons, and an entry whose title names the season ("Season 3", "III") wins.
3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. AniList lists the second half of a split season as its own entry, so an episode past the first half goes there: episode 15 of a season split 11 + 12 is episode 4 of the second entry.
If the show is not on your list yet, SubMiner adds it as Watching, but only when the file title exactly matches an AniList title or you pinned the entry with the character dictionary's AniList override. For a looser match, add the show to Planning or Watching yourself. SubMiner never changes entries marked Completed, Paused, Dropped, or Rewatching, and it never lowers your progress.
@@ -37,7 +37,9 @@ Failed updates are saved and retried in the background, up to 8 times with growi
If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**.
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary).
If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). The override is also the fix when AniList splits a season without marking the second half in any title.
Library entries matched by older versions keep their match after an update. If one points at the wrong season, use **Change AniList Entry**.
## Commands
+11 -4
View File
@@ -1,6 +1,6 @@
# AniSkip integration
SubMiner looks up opening timestamps on [AniSkip](https://aniskip.com) so you can skip an anime's intro with one key.
SubMiner finds an anime's opening and ending so you can skip either with one key. It reads the file's own chapters first and asks [AniSkip](https://aniskip.com) for anything they lack.
## Setup
@@ -23,17 +23,24 @@ python3 -m pip install --user guessit
## Usage
When a local file loads, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the intro's timestamps. Streams and URLs are skipped.
Once a file's duration is known, SubMiner looks for the opening and ending in the file's chapters:
If AniSkip has an intro, SubMiner adds `AniSkip Intro Start` and `AniSkip Intro End` chapters. When the intro starts, mpv shows "You can skip by pressing TAB" (with your key) for 3 seconds. Press the key any time during the intro to jump to its end.
- By name: chapters called `Opening`, `OP`, `OP ...` or `オープニング`; and `Ending`, `ED`, `ED ...`, `Outro`, `End Credits`, `Closing Credits`, `エンディング`, or `Credits` in the second half of the episode.
- By length, in files with at least three chapters: a 55 to 150 second chapter in the first 30% of the episode (the one closest to 90 seconds) is the opening, and the first one after 70% is the ending.
If the chapters don't give both, SubMiner reads the title and episode from the file name, finds the show on MyAnimeList, and asks AniSkip for the rest, sending the file's length so the times match your cut (TV or Blu-ray). AniSkip lookups run for local files only; streams such as Jellyfin use their chapters alone.
For times that came from AniSkip, SubMiner adds `AniSkip Intro Start`/`End` and `AniSkip Outro Start`/`End` chapters. When the intro or outro starts, SubMiner shows "You can skip the intro by pressing TAB" (or "the outro", with your key) for 3 seconds. Press the key any time during either one to jump to its end. Nothing is skipped automatically.
With a custom key other than `TAB` or `y-k`, `y-k` also skips.
A failed lookup (AniSkip or MyAnimeList down, rate limited, or offline) is retried the next time the file loads. A show or episode AniSkip has no times for is remembered until SubMiner restarts.
## Triggering from mpv
| Command | What it does |
| ----------------------------------------- | ------------------------------------------------------- |
| `script-message subminer-skip-intro` | Skip to the end of the intro |
| `script-message subminer-skip-intro` | Skip to the end of the intro or outro that is playing |
| `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results |
Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
+3 -3
View File
@@ -8,7 +8,7 @@ For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on t
1. Install [Anki](https://apps.ankiweb.net/).
2. Install AnkiConnect (add-on code `2055492159`).
3. Install FFmpeg and make sure it is on your `PATH`. SubMiner uses it for audio and images.
3. Install FFmpeg and make sure it is on your `PATH`, or download it from first-run setup. SubMiner uses it for audio and images.
4. Keep Anki running while you mine.
If you changed AnkiConnect's port, set `ankiConnect.url` to match.
@@ -162,7 +162,7 @@ When you cancel, you can go back to editing, keep the original timing, create th
#### With a controller
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each button shows its controller shortcut. It works with or without keyboard-only mode, and the controller's usual actions pause until the dialog closes. Buttons that were already held when the dialog opened, such as the mine button, wait for a fresh press.
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each button shows its controller shortcut once SubMiner has seen a controller, which takes one button press after connecting it. It works with or without keyboard-only mode, and the controller's usual actions pause until the dialog closes. Buttons that were already held when the dialog opened, such as the mine button, wait for a fresh press.
`A`, `B`, `X` and `Y` mean the letters printed on your controller. Pick your controller's **Button Style** in `Alt+C`: choose Nintendo if A is on the right and B at the bottom (Switch-style and many 8BitDo pads). On PlayStation, `A` is ╳, `B` ○, `X` □ and `Y` △, and the shortcuts on screen show those symbols.
@@ -267,7 +267,7 @@ The manual dialog cancels itself after 90 seconds. Identical entries are not ded
### With a controller {#field-grouping-with-a-controller}
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each control shows its controller shortcut. Like the [media timing review](#with-a-controller), it works with or without keyboard-only mode, `A`/`B`/`X`/`Y` are the printed letters (set by **Button Style** in `Alt+C`), and a button already held when the dialog opens waits for a fresh press.
With [controller support](/usage#controller-support) on, the dialog has its own controller layout, and each control shows its controller shortcut once SubMiner has seen a controller. Like the [media timing review](#with-a-controller), it works with or without keyboard-only mode, `A`/`B`/`X`/`Y` are the printed letters (set by **Button Style** in `Alt+C`), and a button already held when the dialog opens waits for a fresh press.
| Controller | Choosing the card | Merge preview |
| ------------------ | --------------------------------- | ----------------------- |
+3 -3
View File
@@ -24,7 +24,7 @@ src/
preload*.ts # preload bridges (overlay, settings, stats, sync, Jellyfin setup)
main/ # main-process runtime modules and IPC/CLI wiring
boot/ # pre-ready boot helpers
assemblies/ # per-domain assemblies main.ts builds once (startup, overlay, playback, mining, stats, Yomitan, shortcuts, tray, first-run setup, YouTube, Jellyfin, AniList, settings, sync, dictionaries, overlay modals)
assemblies/ # per-domain assemblies main.ts builds once (startup, overlay, playback, mining, stats, Yomitan, shortcuts, session actions, plugins, subtitle generation, tray, first-run setup, YouTube, Jellyfin, AniList, settings, sync, dictionaries, overlay modals)
runtime/composers/ # larger runtime clusters assembled for main.ts
runtime/domains/ # domain barrels (startup, overlay, mpv, ipc, shortcuts, anilist, jellyfin, mining)
core/services/ # focused services: mpv client, overlay, tokenizer, mining, integrations, stats
@@ -46,7 +46,7 @@ A few ownership notes that are hard to guess from file names:
- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`.
- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`.
- AniSkip intro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
- Intro/outro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which reads the file's chapters, asks AniSkip for what they lack, and drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it.
## Component diagram
@@ -139,7 +139,7 @@ Runtime code uses dependency injection:
2. Build its runtime dependencies in a `src/main/` module. Pass simple dependencies inline; extract an adapter only when it adds behavior or gets reused.
3. Call the service from lifecycle or command wiring.
Domain handlers live in the barrels under `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. A domain whose runtimes share state, such as app startup, the overlay windows, mpv playback and subtitle state, card mining, stats, YouTube, Jellyfin, AniList, config settings, sync, or the character dictionary, is grouped into one assembly in `src/main/assemblies/` that owns that state and returns its runtimes. An assembly that answers renderer IPC or CLI commands also returns typed `ipc`/`cli` slices, and `main.ts` registers the handlers by combining those slices. Handlers take their dependencies as a plain object passed straight to the handler factory, which keeps side effects out of the unit under test.
Domain handlers live in the barrels under `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. A domain whose runtimes share state, such as app startup, the overlay windows, mpv playback and subtitle state, card mining, stats, plugins, YouTube, Jellyfin, AniList, config settings, sync, or the character dictionary, is grouped into one assembly in `src/main/assemblies/` that owns that state and returns its runtimes. An assembly that answers renderer IPC or CLI commands also returns typed `ipc`/`cli` slices, and `main.ts` registers the handlers by combining those slices. Handlers take their dependencies as a plain object passed straight to the handler factory, which keeps side effects out of the unit under test.
Composers declare their inputs with `ComposerInputs<T>` and results with `ComposerOutputs<T>` from `src/main/runtime/composers/contracts.ts`. A missing dependency then fails at compile time.
+58 -3
View File
@@ -1,6 +1,61 @@
# Changelog
## v0.21.1 (2026-10-26)
## v0.22.0 (2026-11-06)
**Added**
- **Plugins**:
- JavaScript plugins load at startup from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
- Plugins can react to playback and mined cards, add bindable actions, run programs, and show results in overlay panels or their own windows.
- Example plugins cover AI line explanations (`ai-explain`), AnkiWeb sync (`anki-sync`), and show and episode tags on mined cards (`episode-tags`).
- Plugin authors get a versioned API with standalone types.
- **Subtitle Filters**: Remove text in parentheses, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
- **Controller Combos**: Controller actions can now be combos, such as holding `L1` and pressing D-pad right. Click **Learn** in `Alt+C`, then hold one button and press another.
- **Controller Actions**: New bindings cover previous, next, replay, and play-next subtitle, hold-to-show secondary subtitle, and previous or next Yomitan entry. All are unbound by default and can be assigned in `Alt+C`.
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be used with a controller and show button hints while one is connected. Remap both layouts per controller in `Alt+C`.
- **Controller Button Style**: Choose Xbox, Nintendo, or PlayStation button names per controller in `Alt+C`, or set a default with `controller.faceButtonLabels`.
- **Controller Clash Warnings**: `Alt+C` now warns when two actions share the same input.
- **Keyboard-Only Mode**:
- Press `C` or use the new controller binding to move by character, reaching words split by the subtitle parser.
- The new **Pause Video In Keyboard-Only Mode** setting pauses on entry and resumes on exit.
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Reopening Jimaku after the video changes now refreshes the title and episode.
**Changed**
- **Stats Trends and Vocabulary**:
- Trends adds a learning section, heatmap, title timeline, custom date ranges, and a page-wide title filter.
- Vocabulary now has one searchable word table, known words by frequency band, a growth chart, and a full kanji view.
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
- Stats now explains when streamed words or lines can't be mined.
- **Bundled Hachidori**: Updated to upstream 0.4.0, adding every pitch accent in popup entries, per-kanji headword furigana, and Yomitan-style definition tags.
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Connected and disabled messages now follow your `ankiConnect.behavior.notificationType` setting.
- **Dictionary Popup**: Turning keyboard-only mode off now also closes the popup.
**Fixed**
- **Controller Settings (`Alt+C`)**:
- Remaps now apply right away, and Learn works on **(D-pad)** rows.
- Clicking a row shows **Learn**, **Clear**, and **Reset** again.
- The window previews your bindings until a press, then selects the pressed controller.
- Button names are now correct on standard-layout controllers.
- **Controller Input on macOS and Windows**: One press no longer runs its action twice. On macOS, buttons now work while mpv is in front.
- **Dictionary Popup**: Keyboard and controller lookups now pause and resume playback reliably. Moving between words right after closing a popup no longer reopens it.
- **Playback**: Reloading the current file no longer leaves playback paused. The "Overlay loading" message no longer sticks or turns into a false error when a playlist advances.
- **Stats**:
- The dashboard, Vocabulary tab, and sentence search load much faster on large databases, and Trends downloads far less data.
- Trends now counts each finished episode once, and its Library totals match the selected range.
- Word totals, readings, Hide Names, and rate charts are now accurate.
- Date handling is now correct in time zones ahead of UTC.
- **AniList**: Progress sync now adds a missing show to Watching, or Completed on the final episode, when the title matches exactly or is pinned. Entries marked Completed, Paused, Dropped, or Rewatching are still never changed.
- **Anki Sentence Audio**: Generated sentence audio no longer overwrites Yomitan's word audio on default configs. If you relied on the old default, set `ankiConnect.fields.audio` to `ExpressionAudio`.
- **AppImage**: Fixed "Service Crash" notifications on quit on Ubuntu 26.04 and newer.
**Docs**
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
## Previous Versions
<details>
<summary>v0.21.x</summary>
<h2>v0.21.1 (2026-10-26)</h2>
**Changed**
- **Stats Session View**: Redesigned the expanded session view in the stats dashboard.
@@ -23,7 +78,7 @@
</details>
## v0.21.0 (2026-10-24)
<h2>v0.21.0 (2026-10-24)</h2>
**Added**
- **Hachidori Dictionary Backend**:
@@ -68,7 +123,7 @@
</details>
## Previous Versions
</details>
<details>
<summary>v0.20.x</summary>
+54 -24
View File
@@ -52,7 +52,7 @@ SubMiner watches the config file while running. When it changes, live settings a
These apply live:
- `subtitleStyle`, `subtitleSidebar`, `subtitleSelection`, `keybindings`, `shortcuts`
- `subtitleStyle`, `subtitleSidebar`, `subtitleSelection`, `subtitleFilter`, `keybindings`, `shortcuts`
- `logging.level`, `logging.rotation`, `logging.files`
- `secondarySub.defaultMode`, `youtube.primarySubLanguages`, `youtube.subtitleSource`
- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey`, `stats.toggleKey`, `stats.markWatchedKey`
@@ -221,6 +221,29 @@ Sidebar custom properties: `--subtitle-sidebar-max-width` (`420px`), `--subtitle
If `embedded` layout places the video oddly on your system, switch back to `overlay`.
### Subtitle filters {#subtitle-filters}
Removes unwanted text from primary subtitles, such as speaker names, readings and sound descriptions. Filtering happens as the line arrives, so the overlay, sidebar, mined sentences and stats all see the filtered text. A line left with no words is hidden. In the settings window, find it under **Behavior → Subtitle Filters**.
| Key | Default | What it does |
| -------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------ |
| `subtitleFilter.presets.parentheses` | `false` | Remove `(…)` and `(…)` anywhere in a line. A line wrapped entirely in parentheses (inner thoughts) is kept |
| `subtitleFilter.presets.brackets` | `false` | Remove `[…]`, `[…]`, `【…】` and `〔…〕`, such as sound effects |
| `subtitleFilter.presets.speakerPrefix` | `false` | Remove a short name before a colon at the start of a line, as in `山田:` |
| `subtitleFilter.presets.musicSymbols` | `false` | Remove `♪`, `♫` and `♬` |
| `subtitleFilter.customRules` | `[]` | Your own regex rules, applied in order after the presets |
Each custom rule is `{ "name", "pattern", "replacement", "enabled" }`. Patterns are JavaScript regular expressions compiled with the `gmu` flags, so `^` and `$` match each line. An empty `replacement` removes the match.
```jsonc
{
"subtitleFilter": {
"presets": { "parentheses": true },
"customRules": [{ "name": "Join lines", "pattern": "\\n", "replacement": "", "enabled": true }],
},
}
```
### Subtitle position
You can also drag subtitles with `Right-click + drag` while watching.
@@ -291,7 +314,7 @@ Adds a modal for choosing mpv's primary and secondary subtitle tracks. Open it w
### Controller support
Gamepad input for the overlay, through the browser Gamepad API. Most actions only work while keyboard-only mode is on; the toggle for that mode, the secondary subtitle hold (`controller.bindings.holdSecondarySub`), pause (`toggleMpvPause`) and the subtitle line actions (`previousSubtitle`, `nextSubtitle`, `replaySubtitle`, `playNextSubtitle`) work either way. Use the `Alt+C` modal to pick a controller and learn bindings, and `Alt+Shift+C` to see raw button and axis values. Default button actions are on [Keyboard shortcuts](/shortcuts).
Gamepad input for the overlay, through the browser Gamepad API. Most actions only work while keyboard-only mode is on; the toggle for that mode, the secondary subtitle hold (`controller.bindings.holdSecondarySub`), pause (`toggleMpvPause`) and the subtitle line actions (`previousSubtitle`, `nextSubtitle`, `replaySubtitle`, `playNextSubtitle`) work either way. Use the `Alt+C` modal to pick a controller and learn bindings, and `Alt+Shift+C` to see raw button and axis values. Default button actions are in [Controller support](/usage#controller-support).
| Key | Default | What it does |
| ---------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -306,7 +329,11 @@ Gamepad input for the overlay, through the browser Gamepad API. Most actions onl
| `controller.repeatDelayMs` | `320` | Delay before a held button repeats |
| `controller.repeatIntervalMs` | `120` | Repeat interval for held buttons |
Bindings, including the media timing review and duplicate card dialog layouts, are set with `Alt+C` learn mode, which saves them per controller.
Bindings, including the media timing review and duplicate card dialog layouts, are set with `Alt+C` learn mode, which saves them per controller. Learn can also record a [combo](/usage#controller-support), saved on the binding as an optional `hold` input in the same form:
```jsonc
"nextAudio": { "kind": "button", "buttonIndex": 15, "hold": { "kind": "button", "buttonIndex": 4 } }
```
## Anki integration
@@ -448,13 +475,14 @@ When SubMiner fills the sentence on a word card, it sets one card-type flag and
Search and download Japanese subtitles from [Jimaku](https://jimaku.cc). See [Jimaku integration](/jimaku-integration).
| Key | Default | What it does |
| --------------------------- | --------------------- | ---------------------------------------------------------- |
| `jimaku.apiKey` | `""` | API key. Optional, but raises your rate limit |
| `jimaku.apiKeyCommand` | `""` | Shell command that prints the key. Use instead of `apiKey` |
| `jimaku.apiBaseUrl` | `"https://jimaku.cc"` | API base URL |
| `jimaku.languagePreference` | `"ja"` | Preferred language: `ja`, `en`, or `none` |
| `jimaku.maxEntryResults` | `10` | Maximum search results |
| Key | Default | What it does |
| ------------------------------------------- | --------------------- | --------------------------------------------------------------------------------- |
| `jimaku.apiKey` | `""` | API key. Optional, but raises your rate limit |
| `jimaku.apiKeyCommand` | `""` | Shell command that prints the key. Use instead of `apiKey` |
| `jimaku.apiBaseUrl` | `"https://jimaku.cc"` | API base URL |
| `jimaku.languagePreference` | `"ja"` | Preferred language: `ja`, `en`, or `none` |
| `jimaku.maxEntryResults` | `10` | Maximum search results |
| `jimaku.autoOpenWhenPrimarySubtitleMissing` | `false` | Pause and open the Jimaku modal when a local video has no Japanese subtitle track |
### TsukiHime
@@ -531,18 +559,20 @@ 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).
| Key | Default | What it does |
| ----------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------- |
| `jellyfin.enabled` | `false` | Enable Jellyfin |
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner |
| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup (also needs `startupWarmups.jellyfinRemoteSession`) |
| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect |
| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers |
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding |
| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding |
| Key | Default | What it does |
| -------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `jellyfin.enabled` | `false` | Enable Jellyfin |
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner |
| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup (also needs `startupWarmups.jellyfinRemoteSession`) |
| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect |
| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers |
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
| `jellyfin.directPlayPreferred` | `true` | Try direct play before 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
@@ -606,8 +636,8 @@ Settings for mpv instances that SubMiner starts, and for the bundled mpv plugin.
| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file |
| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds |
| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
| `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt |
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown |
| `mpv.aniskipEnabled` | `true` | Detect intros and outros (file chapters, then AniSkip) and show a skip prompt |
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro or outro while it plays |
### YouTube playback settings
+27 -8
View File
@@ -50,11 +50,15 @@ Deleting a session or session group refreshes the Overview totals, charts, calen
Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel.
Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
Seasons, movies, and OVAs of one anime share a card. SubMiner follows AniList's sequel, prequel, parent, side-story, summary, and compilation links, including through entries you have not watched, so two films can meet at a TV series you never played. Spin-offs and alternative versions keep their own cards. A shared card is named after the anime's first TV series, shows the cover of the earliest part you have, and opens to a list of its parts in release order. Relations come from AniList in the background and refresh weekly, so a newly linked show can take a minute to join its card.
If a part lands on the wrong card, open it and choose **Move to Another Anime…** (the target must be linked to AniList) or **Show On Its Own**. **Put Back Where AniList Has It** undoes either. This only changes how the library is listed; duplicate entries for the same season still need a merge.
Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand.
The same show can end up on several cards when release names disagree. To fix that:
- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Merge: click **Select** (the grid then lists every entry on its own), tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry.
- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction.
- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**.
@@ -64,7 +68,17 @@ The same show can end up on several cards when release names disagree. To fix th
### Trends
Charts for watch time, cards, words, and sessions per day or month, running totals, efficiency (words per minute, cards per hour), and viewing patterns by weekday and hour. Each chart has its own date range and grouping.
Pick a date range (or set **Custom** dates), group by day, week, or month, and the whole page follows. Your choices are remembered.
- **Summary**: totals for the range, compared with the period just before it.
- **Activity**: watch time, cards, words, and finished episodes. Click a bar to open that period's sessions.
- **Learning**: new words per 1,000 words seen, and how common those new words are. Conjugations of a word count once, and names are left out.
- **Efficiency**: words per minute, cards per hour, and lookups per 100 words. Daily views use a rolling 7 days, and gaps mean too little data to rate.
- **Running total**: one chart with a switcher for each metric, climbing from zero at the start of the range.
- **Patterns**: a day and hour heatmap of when you watch.
- **Titles**: a timeline of what you watched when, and a sortable summary table. Click a title, or use the filter box, to narrow the page to it. **↗** opens the title.
An episode counts as finished once, on the last day you watched it.
![Stats Trends](/screenshots/stats-trends.png)
@@ -76,10 +90,15 @@ Session history. Expand a session for its pace, lines, known-word rate, lookups,
### Vocabulary
Unique words and kanji you have seen, new words per day, frequency rank tables with Hide Known and Hide Kana filters, and a kanji breakdown. Click a word to see every line it appeared in.
Words are counted as dictionary words, so a word's conjugations count once. Names are left out unless you turn off **Hide names**.
- **Exclusions** hides words from every vocabulary view. You can restore them from the same dialog.
- **Duplicates** cleans up lines repeated by karaoke openings and animated signs (see [Repeated lines](#repeated-lines)).
- **Summary**: words seen, how many are in Anki, new words this week, and kanji seen.
- **Known Words by Frequency**: how much of each frequency band you already know.
- **Vocabulary Growth**: your running total of words seen.
- **Words**: one table for every word you have seen. **Worth mining** lists common words you haven't mined, most seen first. **All words**, **Across titles**, and **Newest** are the other views. Sort by any column, or filter by known words, names, kana, and part of speech. Searching looks through everything, including conjugated forms and readings. Click a word for its forms, where it appeared, and example lines you can mine from. **Hide** excludes a word.
- **Kanji**: every kanji you have seen, shaded by how often. Dashed kanji are not in any word you know.
**Exclusions** at the bottom of the page lists hidden words so you can restore them. **Clean up duplicates** removes lines repeated by karaoke openings and animated signs (see [Repeated lines](#repeated-lines)).
![Stats Vocabulary](/screenshots/stats-vocabulary.png)
@@ -89,7 +108,7 @@ Searches the primary subtitle lines and titles in your history. **Search by head
## Mining from the dashboard
Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available:
Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available. Lines from a stream, such as Jellyfin or YouTube, have no file to cut clips from, so they say so instead of offering mining. Lines you can mine are listed first. The word panel counts how many of a word's lines this affects, and the word table marks words with only streamed lines as **Stream only**.
- **Mine Word**: looks up the word with the selected dictionary backend (Yomitan or Hachidori), plus sentence, audio, and image. The history line you picked is the card's sentence, even while mpv plays another line. Hachidori uses its own Anki template, dictionary aliases, and frequency data.
- **Mine Sentence**: a sentence card with `IsSentenceCard` set, for Lapis and Kiku note types.
@@ -103,7 +122,7 @@ Dashboard cards also get the `SubMiner::Stats` tag. With the Anki proxy off, Sub
Karaoke openings and animated signs repeat the same text once per frame. SubMiner collapses these as it records, so one lyric is stored once. Stats recorded before that can hold hundreds of copies and skew Top Repeated Words.
To clean them, use **Duplicates** in the Vocabulary tab: pick a time window, **Scan** to preview, then **Clean Up**. Or from the terminal:
To clean them, use **Clean up duplicates** in the Vocabulary tab: pick a time window, **Scan** to preview, then **Clean Up**. Or from the terminal:
```bash
subminer stats cleanup --duplicate-lines --dry-run --lookback-days 30
+5 -4
View File
@@ -12,7 +12,7 @@ Getting started takes three steps:
## 1. Install requirements
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot.
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner.
| Dependency | Needed for | Platforms |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
@@ -124,7 +124,7 @@ mpv --version
ffmpeg -version
```
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. Otherwise, use the FFmpeg download in first-run setup. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
<details>
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
@@ -262,8 +262,9 @@ Setup walks you through:
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
3. **FFmpeg** (optional). If `ffmpeg` and `ffprobe` are on your `PATH` and run, there is nothing to do. Otherwise **Download FFmpeg** saves a static build to `tools/ffmpeg/` next to your config file. SubMiner and the `subminer` command use it only when FFmpeg is missing from `PATH`, so a system install always takes priority.
4. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
5. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
+18 -8
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.
## 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. With mpv 0.42 or newer, the playlist lists the queued episodes by title; 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
The launcher can browse your libraries and play an item without a Jellyfin client:
@@ -42,14 +50,16 @@ 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.
| Key | What it does |
| -------------------------- | ---------------------------------------------------------------------- |
| `enabled` | Turns the integration on. Set for you when you sign in. |
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
| `remoteControlEnabled` | Lets SubMiner act as a cast target. |
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. |
| Key | What it does |
| ----------------------------- | ---------------------------------------------------------------------- |
| `enabled` | Turns the integration on. Set for you when you sign in. |
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
| `remoteControlEnabled` | Lets SubMiner act as a cast target. |
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
| `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.
+22 -7
View File
@@ -37,17 +37,32 @@ The file is saved next to the video (or to a temp directory for streams) and loa
You can also open the modal with `subminer app --open-jimaku`, or change the shortcut with `shortcuts.openJimaku`.
### Open automatically when a video has no Japanese subtitles
Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to `true` to skip the shortcut. When a local video loads without a subtitle track in `youtube.primarySubLanguages` (Japanese by default), SubMiner pauses playback about a second after the video loads and opens the Jimaku modal, so you can pick a subtitle before watching. Playback stays paused while the modal is open and resumes when it closes, whether or not you picked a subtitle. On a cold start it resumes once subtitle processing is ready, as usual, and a pause you made yourself before the modal opened is kept.
A single unlabeled sidecar file (such as `episode.srt` next to the video) counts as a Japanese track, matching how SubMiner auto-selects local subtitles. An embedded track with no language tag does not, so the modal still opens for it. Audio files, streams, YouTube, and Jellyfin playback are not checked.
```jsonc
{
"jimaku": {
"autoOpenWhenPrimarySubtitleMissing": true,
},
}
```
The file name parser understands `S01E03`, `1x03`, `E03`, `EP03`, and `Title - 03 -` patterns, and reads the season from a parent folder such as `Season 2`. It ignores bracket tags like `[SubGroup]` and year tags like `(2024)`.
## Options
| Key | What it does |
| --------------------------- | ------------------------------------------------------------------- |
| `jimaku.apiKey` | API key in plain text. |
| `jimaku.apiKeyCommand` | Shell command that prints the API key. |
| `jimaku.languagePreference` | Sorts files tagged with this language first: `ja`, `en`, or `none`. |
| `jimaku.maxEntryResults` | Maximum entries per search. |
| `jimaku.apiBaseUrl` | API address. Change only for a mirror. |
| Key | What it does |
| ------------------------------------------- | -------------------------------------------------------------------- |
| `jimaku.apiKey` | API key in plain text. |
| `jimaku.apiKeyCommand` | Shell command that prints the API key. |
| `jimaku.languagePreference` | Sorts files tagged with this language first: `ja`, `en`, or `none`. |
| `jimaku.maxEntryResults` | Maximum entries per search. |
| `jimaku.apiBaseUrl` | API address. Change only for a mirror. |
| `jimaku.autoOpenWhenPrimarySubtitleMissing` | Pauses and opens the modal when a local video has no Japanese track. |
See [Configuration](/configuration#jimaku) for defaults.
+1 -1
View File
@@ -145,7 +145,7 @@ subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a cu
subminer sync --ui # open the sync window
```
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--push` and `--pull` do not delete anything on the receiving side.
Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. The one setting it carries is a library title's anime card choice (**Move to Another Anime…**), where the most recent change wins. `--push` and `--pull` do not delete anything on the receiving side.
Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes.
+2 -2
View File
@@ -47,7 +47,7 @@ Most plugin keys are chords: press `y`, then the second key.
`v` replaces mpv's own subtitle visibility toggle.
The skip-intro key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
The intro/outro skip key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration).
The `y-y` menu lists Start overlay, Stop overlay, Toggle overlay, Open options, Restart overlay, Check status, and Stats. Press an item's number to run it. Stats only reminds you to press `` ` `` in the overlay.
@@ -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.
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-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
-11
View File
@@ -83,17 +83,6 @@ Anki must be running and logged in to AnkiWeb. Cards mined from the stats dashbo
Templates can use `{show}`, `{season}`, `{episode}`, and `{ep}` (`S01E07`, or `E07` when there is no season). When a placeholder has no value, the tag stops before that `::` level, so a movie gets `show::<title>`. The parsing is a guess from the name: a title ending in a number, like `Mob Psycho 100`, reads that number as the episode.
## Example: open Jimaku when a file has no Japanese subtitles
[`assets/plugins/auto-jimaku`](https://github.com/ksyasuda/SubMiner/tree/main/assets/plugins/auto-jimaku) opens the Jimaku search a few seconds after a file starts if none of its subtitle tracks is Japanese. A track counts as Japanese when its language code is in `languages`, or its title contains "Japanese" or 日本語.
| Setting | Default | What it does |
| ----------- | --------------------- | --------------------------------------------------------------- |
| `action` | `"openJimaku"` | Built-in action to run, e.g. `openTsukihime` |
| `languages` | `["ja", "jp", "jpn"]` | Track language codes that count as Japanese |
| `delayMs` | `3000` | Wait this long after the file starts, so external subs load |
| `streams` | `false` | Also check `http(s)` streams, which Jimaku usually can't search |
## Write a plugin
A plugin folder needs a `plugin.json`:
+44 -25
View File
@@ -128,59 +128,62 @@
"toggleLookup": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 0 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for toggling lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"closeLookup": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 1 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for closing lookup. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"toggleKeyboardOnlyMode": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 3 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for toggling keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"mineCard": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 2 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for mining the active card. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"quitMpv": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 6 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for quitting mpv. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"previousAudio": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for previous Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"nextAudio": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 5 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for next Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"playCurrentAudio": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 4 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for playing the current Yomitan audio. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"toggleMpvPause": {
"kind": "button", // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
"buttonIndex": 9 // Raw button index captured for this discrete controller action.
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor for toggling mpv play/pause. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"holdSecondarySub": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that shows the secondary subtitle only while held. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"previousEntry": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that selects the previous word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"nextEntry": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"toggleCharacterNavigation": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"previousSubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that jumps to the previous subtitle line, like Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"nextSubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that jumps to the next subtitle line, like Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"replaySubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that replays the current subtitle line, then pauses, like Ctrl+Shift+H. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"playNextSubtitle": {
"kind": "none" // Discrete binding input source kind. When kind is "axis", set both axisIndex and direction. Values: none | button | axis
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.
}, // Controller binding descriptor that plays the next subtitle line, then pauses, like Ctrl+Shift+L. Works with or without keyboard-only mode. Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.
"leftStickHorizontal": {
"kind": "axis", // Analog binding input source kind. Values: none | axis
"axisIndex": 0, // Raw axis index captured for this analog controller action.
@@ -191,11 +194,6 @@
"axisIndex": 1, // Raw axis index captured for this analog controller action.
"dpadFallback": "vertical" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
}, // Axis binding descriptor used for primary popup scrolling. Use Alt+C learn mode or set a raw axis descriptor manually.
"rightStickHorizontal": {
"kind": "axis", // Analog binding input source kind. Values: none | axis
"axisIndex": 3, // Raw axis index captured for this analog controller action.
"dpadFallback": "none" // Optional D-pad fallback used when this analog controller action should also read D-pad input. Values: none | horizontal | vertical
}, // Axis binding descriptor reserved for alternate right-stick mappings. Use Alt+C learn mode or set a raw axis descriptor manually.
"rightStickVertical": {
"kind": "axis", // Analog binding input source kind. Values: none | axis
"axisIndex": 4, // Raw axis index captured for this analog controller action.
@@ -854,6 +852,22 @@
} // CSS declaration object applied to the subtitle sidebar. Includes color, background-color, and all font properties.
}, // Parsed-subtitle sidebar cue list styling, behavior, and toggle key.
// ==========================================
// Subtitle Filters
// Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
// Applies to the overlay, sidebar, mined sentences and stats.
// Hot-reload: filter changes apply to the current subtitle file immediately.
// ==========================================
"subtitleFilter": {
"presets": {
"parentheses": false, // Remove text in () and (), such as speaker names, readings and notes. A line wrapped entirely in parentheses, usually inner thoughts, is kept. Values: true | false
"brackets": false, // Remove text in [], [], 【】 and 〔〕, such as sound effects and music cues. Values: true | false
"speakerPrefix": false, // Remove a short name followed by a colon at the start of a line, as in 山田:元気? Values: true | false
"musicSymbols": false // Remove ♪, ♫ and ♬. A line left with only symbols such as ~ is removed. Values: true | false
}, // Built-in filters. Each removes its matches and is off by default.
"customRules": [] // Your own regex rules, applied in order after the presets. Each rule is { name, pattern, replacement, enabled }; patterns use the gmu flags, so ^ and $ match per line. Leave replacement empty to remove the match.
}, // Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.
// ==========================================
// Shared AI Provider
// Canonical OpenAI-compatible provider transport settings shared by Anki and YouTube subtitle fixing.
@@ -976,7 +990,8 @@
"apiKey": "", // Jimaku API key. Optional but recommended for higher rate limits. Get one for free at https://jimaku.cc.
"apiKeyCommand": "", // Shell command that prints the Jimaku API key to stdout. Used instead of apiKey to avoid storing the key in plain text.
"languagePreference": "ja", // Preferred language used in Jimaku search. Values: ja | en | none
"maxEntryResults": 10 // Maximum Jimaku search results returned.
"maxEntryResults": 10, // Maximum Jimaku search results returned.
"autoOpenWhenPrimarySubtitleMissing": false // Pause playback and open the Jimaku modal when a local video has no subtitle track in youtube.primarySubLanguages (Japanese by default). Values: true | false
}, // Jimaku API configuration and defaults.
// ==========================================
@@ -1065,8 +1080,8 @@
"autoStartSubMiner": true, // Start SubMiner in the background when SubMiner-managed mpv loads a file. Values: true | false
"pauseUntilOverlayReady": true, // Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness. Values: true | false
"subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
"aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays.
}, // SubMiner-managed mpv launch and bundled plugin options.
// ==========================================
@@ -1096,7 +1111,11 @@
"mp3",
"aac"
], // 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.
// ==========================================
+1
View File
@@ -62,6 +62,7 @@ Built into the overlay, not configurable:
| Input | Action |
| ------------------------- | -------------------------------------------------- |
| `V` | Cycle primary subtitle bar: hidden, visible, hover |
| `C` (keyboard-only mode) | Move by word or by character |
| Right-click | Pause or resume (outside the subtitle area) |
| Right-click + drag | Move the subtitles |
| Drop files on the overlay | Replace the mpv playlist |
+15
View File
@@ -51,6 +51,17 @@ When `connect ENOENT /tmp/subminer-socket` follows a cast in the app log, SubMin
- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process).
- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors).
- macOS: grant Accessibility permission. See [macOS](#macos).
- Windows: leave the affected mpv window open for at least five seconds, then collect the daily
app log from the directory above. No debug setting is required: a stalled overlay logs
`Windows overlay is not visible after startup or tracking loss` with its PID, native window
handle, tracking state, geometry, opacity, and renderer readiness. The `reason` distinguishes
a missing mpv window, an unready renderer, a hidden window, and a transparent window.
This warning waits until mpv has answered on its IPC socket, so a requested overlay with no
mpv running stays quiet. PID lookup failures and native ownership or transparency errors also
appear at `warn`, and a PID lookup failure is the only trace if mpv never answers.
Repeated visibility/native-operation warnings are limited to one every 30 seconds; recovery
is recorded too. These logs diagnose attachment and readiness, but cannot prove that pixels
were drawn correctly by the graphics driver.
## Overlay is on the wrong monitor or position
@@ -179,6 +190,10 @@ Another app or your desktop already uses `Alt+Shift+Y` (Yomitan settings). Free
Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused.
## An mpv key does nothing over the overlay
Keys from `input.conf` reach mpv through the overlay only in some cases (see [automatic mpv bindings](/shortcuts#automatic-mpv-bindings)). Run with `--log-level debug` and press the key: an `Overlay kept an mpv-bound key` line names the reason. To make a key work everywhere, add it to [`keybindings`](/configuration#keybindings) instead.
## Update checks
**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`.
+9 -2
View File
@@ -160,11 +160,13 @@ On Wayland, the tray icon only appears if your panel provides a StatusNotifier (
You can drive the overlay with a gamepad.
1. Set `controller.enabled` to `true` in your config.
2. Connect a controller. SubMiner uses the first one it sees.
2. Connect a controller and press a button. SubMiner uses the first one it sees and announces it through [`ankiConnect.behavior.notificationType`](/configuration#ankiconnect).
3. Press `Y` on the controller to turn on keyboard-only mode. Most controller actions only work in this mode.
4. Move between words with the left stick, press `A` to look one up, and `X` to mine it.
Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want. Set **Button Style** to Xbox, Nintendo or PlayStation so buttons are named as printed on your controller; it is saved per controller. Changes apply right away. When two actions share an input, both fire, so their rows show a ⚠ warning naming the other action; this includes a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action. The window only sees a controller after you press one of its buttons; until then it shows the bindings of the controller in use as a preview, and editing stays locked. With several controllers connected, it selects the one you pressed last. `Alt+Shift+C` shows raw input values for unusual pads.
Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want, or hold one button and press another to make a combo such as `L1` + D-pad right. Set **Button Style** to Xbox, Nintendo or PlayStation so buttons are named as printed on your controller; it is saved per controller. Changes apply right away. When two actions share an input, both fire, so their rows show a ⚠ warning naming the other action; this includes a button on the D-pad while a **(D-pad)** row under **Navigation** is still on, and a stick direction used by a stick action. The window only sees a controller after you press one of its buttons; until then it shows the bindings of the controller in use as a preview, and editing stays locked. With several controllers connected, it selects the one you pressed last. `Alt+Shift+C` shows raw input values for unusual pads.
A combo fires each time you press its second button while the first is down, so holding `L1` and pressing right twice runs it twice. While a combo's hold button is down, other buttons only run combos that use it, and its press no longer drives a **(D-pad)** or stick row. A hold button can keep its own action: that action then runs when you let go, unless you pressed another bound button during the hold. The exception is **Show Secondary Subtitle (Hold)**, which can't wait for release, so its row warns if it shares a hold button.
| Button | Action |
| --------------------- | -------------------------------------- |
@@ -184,6 +186,7 @@ Press `Alt+C` to choose a controller and remap buttons. Click an action's **Lear
| Unbound by default | Previous / next subtitle line |
| Unbound by default | Replay the current line, then pause |
| Unbound by default | Play the next line, then pause |
| Unbound by default | Move by word or by character |
The secondary subtitle hold works with or without keyboard-only mode. Assign it with **Learn** on the **Show Secondary Subtitle (Hold)** row in `Alt+C`. While held, the secondary subtitle shows as if its mode were `visible`; releasing the button returns it to your chosen mode.
@@ -191,10 +194,14 @@ The **Subtitles** rows in `Alt+C` do the same as the keyboard shortcuts: **Previ
**Previous Entry** and **Next Entry** move one word entry at a time in the open popup, and Mine Card then mines the selected entry. They send Yomitan's default `Alt+Up` / `Alt+Down` entry shortcuts, so they stop working if you rebind those in Yomitan's keyboard settings. If you assign them to the D-pad, click **Clear** on the **Popup Scroll (D-pad)** row too, or the D-pad will also scroll the popup.
When the subtitle is split in the wrong place, a word can start in the middle of a box (in もっとハ|キ|ハキしなくちゃ, ハキハキ starts at the last character of the first box) and moving by word never reaches it. In keyboard-only mode, press `C` on the keyboard, or the **Toggle Character Navigation** button (unbound by default, under **Navigation** in `Alt+C`), to move one character at a time: the box turns orange and covers one character, and a lookup searches from that character, so Yomitan finds the longest word starting there. Press it again to go back to moving by word. It stays on until you switch it back, even after leaving keyboard-only mode.
The media timing review and duplicate card (field grouping) dialogs have their own controller layouts, which you can change in the **Review media timing** and **Duplicate card (field grouping)** groups of `Alt+C`; see [Review media timing](/anki-integration#with-a-controller) and [Field grouping](/anki-integration#field-grouping-with-a-controller).
On controllers that report the W3C standard layout, the default quit button lands on `L2` instead of `Select`, and the default pause button on `Start` instead of `L3`. The default right-stick popup jump does nothing on these controllers; click **Learn** on **Popup Jump (Stick)** and move the right stick up or down to set it. Remap anything else with `Alt+C`, which names buttons according to the layout your controller reports. All options are in [Configuration](/configuration#controller-support).
On macOS, a controller only reaches the app in front. When mpv is in front, a controller button brings the overlay to the front and then runs that button's action. With more than one controller connected, that first press only brings the overlay to the front; press the button again to run its action. Stick movements only work once the overlay is in front. Buttons pressed while another app is in front are left alone.
## Development profiles
`--dev` and `--debug` use a separate `SubMiner-dev` profile. They do not read or modify dictionaries and configuration from the installed app unless `SUBMINER_USE_PRODUCTION_PROFILE=1` is explicitly set. See [Development](/development#run-locally).
+2 -2
View File
@@ -227,9 +227,9 @@ The mpv plugin accepts these script messages:
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, and `subminer-aniskip-refresh` reloads intro 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.
## Related pages
+3 -3
View File
@@ -3,7 +3,7 @@
# Architecture Map
Status: active
Last verified: 2026-05-23
Last verified: 2026-11-01
Owner: Kyle Yasuda
Read when: runtime ownership, composition boundaries, or layering questions
@@ -30,14 +30,14 @@ Update checks and startup launcher migration share a serialized update-state sto
- `src/main/` owns composition, runtime setup, IPC wiring, and app lifecycle adapters.
- `src/main/boot/` owns boot-phase assembly seams so `src/main.ts` can stay focused on lifecycle coordination and startup-path selection.
- `src/main/runtime/linux-overlay-mode-runtime.ts` owns Linux fullscreen mode state and window replacement. App cleanup cancels pending replacements; `main.ts` supplies window creation and subtitle refresh hooks.
- `src/main/runtime/linux-overlay-mode-runtime.ts` owns Linux fullscreen mode state and window replacement. App cleanup cancels pending replacements; the overlay assembly supplies window creation and subtitle refresh hooks.
- `src/core/services/` owns focused runtime services plus pure or side-effect-bounded logic.
- `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative.
- Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments.
- `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps.
- `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry.
- `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes.
- `src/core/services/plugins/` owns user plugins: discovery from `<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). `main.ts` supplies the host's deps, attaches each new mpv client so plugin listeners survive client replacement, starts plugins from the app-ready path after logging is configured, and unloads them first in the `will-quit` cleanup, 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.
- `src/renderer/` owns overlay rendering and input behavior.
- `src/config/` owns config definitions, defaults, loading, and resolution.
- `src/types/` owns shared cross-runtime contracts via domain entrypoints; `src/types.ts` stays a compatibility barrel.
+28 -6
View File
@@ -3,7 +3,7 @@
# Domain Ownership
Status: active
Last verified: 2026-10-31
Last verified: 2026-11-01
Owner: Kyle Yasuda
Read when: you need to find the owner module for a behavior or test surface
@@ -23,19 +23,38 @@ Read when: you need to find the owner module for a behavior or test surface
- App startup: app-ready sequence, headless known-word refresh, overlay startup prerequisites and
overlay runtime bootstrap: `src/main/assemblies/startup.ts`
- Overlay/window state: `src/core/services/overlay-*`, `src/main/overlay-*.ts`
Overlay windows, visibility, Linux fullscreen handling, and the overlay-window IPC handlers
(modal open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
Overlay windows, visibility, geometry and pointer interaction, Linux fullscreen handling, mpv
subtitle suppression while the overlay shows, and the overlay-window IPC handlers (modal
open/close, pointer interaction, content measurement): `src/main/assemblies/overlay.ts`
Overlay-hosted modal openers: `src/main/assemblies/overlay-modals.ts`
Windows window tracking: `src/window-trackers/windows-tracker.ts` queries the target mpv IPC
socket for its PID through `mpv-process-id.ts`, then `win32.ts` matches native windows by PID.
Visible matches are revalidated every 10 seconds; a PID expires after 30 seconds without a
successful IPC response. Missing windows retry at one-second intervals. Custom executable
names remain supported because matching uses the IPC PID.
`src/core/services/overlay-visibility-diagnostics.ts` watches requested Windows overlays:
after five seconds hidden or transparent it logs a warn-level snapshot, repeating at most
every 30 seconds. Intentional hiding, minimization and having no mpv answer on the socket
yet suppress these warnings; an identified mpv whose window never matches does not. PID lookup
failures and native ownership/transparency failures also log at warn, including recovery.
- MPV runtime and protocol: `src/core/services/mpv*.ts`
mpv client creation, mpv event wiring, AniSkip, subtitle prefetch, and subtitle sidebar state: `src/main/assemblies/playback.ts`
mpv client creation, mpv event wiring, AniSkip, the autoplay-ready gate that releases mpv's
startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state:
`src/main/assemblies/playback.ts`
- Keyboard input outside the renderer (overlay, global and numeric shortcuts, session bindings):
`src/main/assemblies/shortcuts.ts`
- Session actions (the dispatcher behind shortcuts, controller buttons, CLI commands and plugin
actions), the secondary-subtitle mode cycle, and the overlay renderer's mpv commands:
`src/main/assemblies/session-actions.ts`
- System tray: `src/main/assemblies/tray.ts`
- Yomitan/Hachidori extension loading, parser runtime deps, and dictionary settings windows:
`src/main/assemblies/yomitan.ts`
Windows executable lookup and detached process creation are shared in `src/main/runtime/mpv-process.ts`. The Windows launcher and Jellyfin handlers retain their own playback and connection workflows.
- Subtitle/token pipeline: `src/core/services/subtitle-*.ts`, `src/core/services/tokenizer*`, `src/core/services/tokenizer/`, `src/subsync/`
JLPT and frequency annotation lookups: `src/main/jlpt-runtime.ts`, `src/main/frequency-dictionary-runtime.ts`, assembled by `src/main/assemblies/dictionaries.ts`
Annotation toggles (a cycled runtime option over its config value): `src/main/runtime/annotation-options.ts`
Whisper subtitle generation runtime, modal and IPC: `src/main/assemblies/subtitle-generation.ts`
Subtitle text filters (`subtitleFilter`): `src/shared/subtitle-text-filter.ts`. Primary text is filtered at its two entry points, live `sub-text` in `mpv-protocol.ts` and parsed cues in `playback.ts`, so every consumer sees the same text and live/cue matching still works. A config change re-reads `sub-text` and re-parses the active track (the prefetch controller's parse key).
- First-run setup: `src/main/runtime/first-run-setup-*.ts`, assembled by `src/main/assemblies/first-run-setup.ts`
- Anki workflow: `src/anki-integration/`, `src/core/services/anki-jimaku*.ts`
Card mining handlers, the pending lookup context, field grouping, and media timing review wiring:
@@ -45,16 +64,19 @@ Read when: you need to find the owner module for a behavior or test surface
the stats overlay window options, and the `--stats` command are assembled by `src/main/assemblies/stats.ts`
Includes stats storage/query schema such as `imm_videos`, `imm_media_art`, and `imm_youtube_videos` for per-video and YouTube-specific library metadata.
Library-entry identity aliases and merge recommendations are persisted alongside this schema; the stats HTTP and SPA layers only expose and present those domain decisions.
Franchise grouping is a view over `imm_anime`, never a merge: `query-library-groups.ts` groups library rows by union-find over the AniList relation cache (`imm_anilist_media` + `imm_anilist_relations`, written by `anilist-relation-cache.ts`; pure graph and walk in `anilist/franchise-graph.ts`, where `FRANCHISE_RELATION_TYPES` is the joining set). `franchise-relation-refresher.ts` walks from owned AniList ids (bounded depth and fetches per run, 7-day staleness, shared AniList rate limiter) when the grouped library is read, after cover art links an id, and after manual AniList or group changes; a failed fetch leaves cached rows untouched. `imm_anime.group_override` (NULL = AniList, 0 = on its own, positive = join the franchise containing that AniList id) is the only user state; `/api/stats/anime/groups` and `PUT /api/stats/anime/:id/group` expose it.
`delete-maintenance-scheduler.ts` coalesces and serializes stats deletes; the expensive work runs in `delete-maintenance-worker-thread.ts` while the tracker queues playback writes. Each batch uses one transaction, lexical update, rollup refresh, and incremental lifetime subtraction (`planLifetimeRemovals`/`applyLifetimeRemovals` in `lifetime.ts`). Merges, moves, AniList reassignments, and `stats cleanup -l` use `repairLifetimeSummariesFromMedia` (recompute from the per-video media ledger). The full lifetime rebuild survives only as the empty-table bootstrap; anywhere else it would collapse lifetime totals to the session retention window.
- Immersion sync: `src/core/services/stats-sync/`, bound by `src/main/sync-cli.ts`. The sync window and auto-sync scheduler live in `src/main/assemblies/sync.ts`.
`imm_anime.group_override` merges last-writer-wins on `group_override_updated_at` (clears carry a timestamp too); its values are AniList ids, so no id remapping. The AniList relation cache is not merged: each machine rebuilds it, and stale or partial remote cache rows would otherwise outlive the 7-day refresh.
`snapshot-transfer.ts` selects compressed rsync or scp. `transfer-cache.ts` atomically retains the last successfully received snapshot per hashed peer/database identity under the config directory's `sync-transfer-cache/`. Cache copies seed isolated transfer directories; rsync verifies reconstructed files before the existing merge engine runs. The `--make-temp` / `--remove-temp` helpers accept an internal `--transfer-cache` key, with a fallback for older peers that do not recognize it.
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`
- AniList tracking + character dictionary: `src/core/services/anilist/`, `src/main/runtime/composers/anilist-*` (called by `src/main/assemblies/anilist.ts`), `src/main/character-dictionary-runtime.ts`, `src/main/character-dictionary-runtime/`, assembled by `src/main/assemblies/character-dictionary.ts`. Every consumer maps a parsed title + season to an AniList entry through `anilist/season-resolver.ts` (sequel-chain walk; see its header for what counts as a season). Changing what it returns needs a `MEDIA_RESOLUTION_CACHE_VERSION` bump in `character-dictionary-runtime/cache.ts`, or old matches keep being served from `anilist-resolution-cache.json`.
- 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-*`,
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.
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
`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), `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/`
- Window trackers: `src/window-trackers/`
- Stats HTTP app: `src/core/services/stats-server.ts`, with route groups and shared route support
in `src/core/services/stats-server/`
+32 -10
View File
@@ -12,20 +12,42 @@ Trend charts now consume one chart-oriented backend payload from `/api/stats/tre
- collapse multiple network round-trips into one request
- keep heavy chart shaping close to tracker/query logic
## Date Ranges And Buckets
- A range resolves to calendar days (`resolveTrendWindow`). Rollups are selected by day span, never by "last N rows", so sparse activity cannot pull older days into a range. Custom ranges are `{ startDay, endDay }` from `range=custom&fromDay&toDay`.
- `all` spans the recorded data, not today.
- Day and week buckets read daily rollups. Month buckets read monthly rollups for months wholly in range, because the `minimal` and `deep-history` retention presets prune daily rollups first, and daily rollups for a partly covered month. Weeks start on Monday.
- `buckets` is the one axis for `activity`, `progress`, and `ratios`, index for index. Charts use it to map a clicked bar back to its days.
- Each `progress` point is the total at the end of its period, and the chart adds the zero starting point.
## Data Sources
- rollup-backed:
- activity charts
- cumulative watch/cards/tokens/sessions trends
- per-anime watch/cards/tokens/episodes series
- activity charts and running totals
- `titleTimeline`: sparse per-title minutes for active days only, because a dense title x day payload grew to several MB
- session-metric-backed:
- lookup trends
- lookup rate trends
- watch-time by day-of-week/hour
- lookups and lookup rate
- `watchTimeByDayHour`, attributed to the hour each session started
- rollup word counts and session metrics share one session query per request (`getTrendSessionRows`), so the per-session display-word count runs once instead of once per rollup query
- `imm_videos.watched`-backed:
- finished episodes count each watched video once, on the last day it has a rollup, since the flag has no timestamp
- vocabulary-backed:
- new-words trend reads permanent daily lexical rollups
- rollup rows count only vocabulary-visible tokens and normalize mixed legacy timestamp units
- a persisted rollup version invalidates stale materializations and triggers an atomic background rebuild
- `getNewWordFirstSeenRows` folds `imm_words` rows into dictionary words first, because the table is unique on (headword, word, reading) and stores each conjugation separately
- the aggregate scans every word, so it is cached per connection until `total_changes()` or `PRAGMA data_version` moves
- Trends new-word metrics exclude names; the Vocabulary tab offers both
- `imm_lexical_daily_rollups` is no longer read for new-word counts (it counts surface forms). Its version state still gates the `vocabulary_visible` backfill.
## Vocabulary Word List
`/api/stats/vocabulary/words` (`query-vocabulary-words.ts`) folds `imm_words` into dictionary words on the server and filters, sorts, and pages there, because a client-side list can only hold a slice of the table. The fold is cached per connection until a write, the same way as the new-word aggregate. `titles` is computed for the returned rows; sorting or filtering by it needs every word's count (about 900ms), so that map tolerates five minutes of staleness. Names are detected with `isProperNounPos2`, since merged tokens store tags like `固有名詞|一般`.
## Rates
Rates are `null` when the underlying data is under 30 active minutes or 2,000 words, and charts draw that as a gap. Daily views rate a trailing 7 calendar days, volume-weighted, which is why the query loads days before the range. Week and month views rate each bucket.
## Title Filter
`title` narrows totals, charts, and patterns. `librarySummary` and `titleTimeline` stay complete so the page can switch titles. New words have no per-title record, so `learning` and `summary.current.newWords` are `null` while filtered.
## Metric Semantics
@@ -39,6 +61,6 @@ Stats data crosses the process boundary over HTTP only. Shared JSON models live
The stats preload bridge remains limited to native window behavior such as confirmation-dialog layering. Do not add stats data request channels back to Electron IPC.
The stats UI should treat the trends payload as chart-ready data. Presentation-only work in the client is fine, but rebuilding the main trend datasets from raw sessions should stay out of the render path.
The stats UI should treat the trends payload as chart-ready data. Presentation-only work in the client is fine (including the title timeline layout), but rebuilding the main trend datasets from raw sessions should stay out of the render path.
For session detail timelines, omitting `limit` now means "return the full retained session telemetry/history". Explicit `limit` remains available for bounded callers, but the default stats UI path should not trim long sessions to the newest 200 samples.
+10 -9
View File
@@ -3,7 +3,7 @@
# Subtitle Overlay Priming
Status: active
Last verified: 2026-08-19
Last verified: 2026-11-01
Owner: Kyle Yasuda
Read when: debugging subtitle state or blank Linux/X11 overlay windows when the visible overlay is shown or recreated
@@ -19,13 +19,14 @@ subtitles do not draw.
## Entry Points
- `src/main.ts` calls `primeCurrentSubtitleForVisibleOverlay()` when manual visible-overlay show
paths run.
- `src/main.ts` calls `restoreVisibleOverlayWindowShapeForShow()` before visible-overlay show
actions on Linux, and `resetVisibleOverlayInputState()` restores a full shape instead of applying
an empty shape.
- `src/main.ts` also restores the Linux/X11 shape after applying mpv overlay bounds, so a newly
created 800x600 hidden Electron window cannot keep clipping after it is resized to mpv geometry.
- The overlay assembly (`src/main/assemblies/overlay.ts`) calls
`primeCurrentSubtitleForVisibleOverlay()` when manual visible-overlay show paths run.
- It calls `restoreVisibleOverlayWindowShapeForShow()` before visible-overlay show actions on
Linux, and `resetVisibleOverlayInputState()` restores a full shape instead of applying an empty
shape (both in `src/main/runtime/visible-overlay-interaction-runtime.ts`).
- `src/main/runtime/overlay-geometry-runtime.ts` also restores the Linux/X11 shape after applying
mpv overlay bounds, so a newly created 800x600 hidden Electron window cannot keep clipping after
it is resized to mpv geometry.
- `primeCurrentSubtitleForVisibleOverlay()` delegates to
`primeVisibleOverlaySubtitleFromMpv()` in `src/main/runtime/current-subtitle-snapshot.ts`.
- `restoreVisibleOverlayWindowShapeForShow()` delegates to `restoreLinuxOverlayWindowShape()` in
@@ -54,7 +55,7 @@ Both `onSubtitleChange` and `refreshCurrentSubtitle` pause `subtitlePrefetchServ
the matching `subtitleProcessingController` method, giving the visible overlay priority over
background prefetch work. Prefetch is not re-centered here: restarting the run per line
(`onSeek`) discarded the in-flight tokenization every time the subtitle changed, so only real
seeks restart it (see `onTimePosUpdate` in `src/main.ts`).
seeks restart it (see the time-pos handling in `src/main/assemblies/playback.ts`).
On an uncached autoplay prime the raw payload is emitted here and reported to the controller with
`notePlainSubtitleEmitted`, so the controller skips its own plain emit for that line and the
+2 -7
View File
@@ -44,10 +44,5 @@ good test looks like here.
## Known Debt
- `src/main/main-wiring.test.ts` and `src/renderer/renderer-init-order.test.ts` still
regex `main.ts` / `renderer.ts` to guard startup ordering. Replace each test with a
behavioral one as the logic moves out of `main.ts` closures.
- `src/main/runtime/overlay-geometry-runtime.ts` and
`src/main/runtime/visible-overlay-interaction-runtime.ts` value-import Electron, so they
cannot load under `bun test` and stay outside `src/main/assemblies/overlay.ts`. Inject
`screen`/`dialog` to make them testable and movable.
- `src/renderer/renderer-init-order.test.ts` still regexes `renderer.ts` to guard startup
ordering. Replace it with a behavioral test as that logic moves out of `renderer.ts`.
+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');
},
};
}
+4 -1
View File
@@ -21,7 +21,10 @@ function videoOutputArgs(display: E2eDisplay): string[] {
// gpu-next's Vulkan path (libplacebo over MoltenVK) segfaults on the first frame
// on GitHub's paravirtual macOS GPU with libplacebo 7.387. `--vo=libmpv` is mpv's
// cocoa-cb OpenGL output, which avoids it and still opens the window the overlay tracks.
if (process.platform === 'darwin') return ['--vo=libmpv'];
// Each new decoder asks that render thread for a direct-rendering image and waits with no
// timeout. cocoa-cb only answers from its main queue, which can stall on this runner, so a
// `loadfile` could freeze mpv's core and its IPC for good. `--vd-lavc-dr=no` skips the request.
if (process.platform === 'darwin') return ['--vo=libmpv', '--vd-lavc-dr=no'];
return [];
}
+3
View File
@@ -30,6 +30,8 @@ export type E2eSessionOptions = {
config?: JsonObject;
/** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */
files?: Record<string, string>;
/** Extra environment for every app launch, e.g. a Jellyfin session. */
env?: Record<string, string>;
};
export type AppTarget = {
@@ -241,6 +243,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
SUBMINER_APP_LOG: path.join(root, 'app.log'),
// Stay attached instead of re-spawning detached, so the harness owns the process.
SUBMINER_BACKGROUND_CHILD: '1',
...options.env,
},
unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'],
};
+142
View File
@@ -0,0 +1,142 @@
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 keep listing URLs.
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');
},
);
+127 -1
View File
@@ -15,7 +15,7 @@ let started: Promise<Started> | undefined;
function useSession(): Promise<Started> {
started ??= (async () => {
const session = await startE2eSession();
const session = await startE2eSession({ config: { controller: { enabled: true } } });
try {
return { session, overlay: await session.openPage(OVERLAY_PAGE) };
} catch (error) {
@@ -114,6 +114,45 @@ test(
},
);
// The other tests read the renderer over CDP, which works even if the window never appears.
// Windows keeps the overlay hidden until the tracker identifies mpv's window.
// Bun's node:test ignores the `skip` option, so this picks `test.skip` instead.
const testOnWindows = process.platform === 'win32' ? test : test.skip;
testOnWindows('visible overlay window appears over mpv', { timeout: TEST_TIMEOUT_MS }, async () => {
const { session } = await useSession();
await session.runAppCommand('--show-visible-overlay');
const mpvPid = await session.mpv.command('get_property', 'pid');
assert.equal(typeof mpvPid, 'number');
const main = await session.mainProcess();
await waitUntil(
() =>
main.evaluate<boolean>(
`(() => {
const electron = process.mainModule.require('electron');
const overlay = electron.BrowserWindow.getAllWindows().find(
(w) => w.webContents.getURL().includes(${JSON.stringify(OVERLAY_PAGE)}));
if (!overlay?.isVisible() || overlay.getOpacity() !== 1 ||
overlay.__subminerOverlayContentReady !== true) return false;
// The inspector's mainModule can be Electron's bootstrap module. Resolve app
// dependencies from the repository instead of that module's search paths.
const appRequire = process.mainModule.require('node:module').createRequire(
process.mainModule.require('node:path').resolve('package.json'));
const koffi = appRequire('koffi');
const getWindow = koffi.load('user32.dll').func(
'intptr __stdcall GetWindow(intptr hwnd, uint uCmd)');
const handle = overlay.getNativeWindowHandle();
const hwnd = handle.length >= 8 ? Number(handle.readBigUInt64LE(0)) : handle.readUInt32LE(0);
const owner = getWindow(hwnd, 4); // GW_OWNER
const win32 = appRequire(
process.mainModule.require('node:path').resolve('dist/window-trackers/win32.js'));
return win32.findMpvWindows(${JSON.stringify(mpvPid)}).matches.some(
(match) => match.hwnd === owner);
})()`,
),
{ description: 'the visible overlay to be fully revealed and owned by the target mpv window' },
);
});
test(
'seeking to another cue replaces the line and deinflects verbs to their headword',
{ timeout: TEST_TIMEOUT_MS },
@@ -273,6 +312,93 @@ test(
},
);
// macOS and Windows keep a hidden modal renderer alive, and hidden windows keep polling because
// background throttling is off. A fake pad goes to every renderer, as a real pad would.
// Linux has no such window, and under Xvfb without a window manager the overlay reports hidden,
// so requestAnimationFrame and with it the controller poll never run. Bun's node:test ignores the
// `skip` option, so this picks `test.skip` instead.
const testOutsideLinux = process.platform === 'linux' ? test.skip : test;
testOutsideLinux(
'one controller press toggles mpv pause once across every window',
{ timeout: TEST_TIMEOUT_MS },
async () => {
const { session } = await useSession();
const START_BUTTON = 9;
const targets = (await listCdpTargets(session.cdpPort)).filter((target) =>
target.url.includes('renderer/index.html'),
);
const renderers = await Promise.all(targets.map(connectCdpPage));
const everyRenderer = (expression: string) =>
Promise.all(renderers.map((renderer) => renderer.evaluate(expression)));
const nextPolls = `new Promise((done) =>
requestAnimationFrame(() => requestAnimationFrame(() => done(true))))`;
try {
await everyRenderer(`(() => {
window.__fakePadPressed = false;
Object.defineProperty(navigator, 'getGamepads', {
configurable: true,
value: () => [{
id: 'E2E Pad (STANDARD GAMEPAD)',
index: 0,
connected: true,
mapping: 'standard',
axes: [0, 0, 0, 0],
buttons: Array.from({ length: 17 }, (_, index) => {
const pressed = window.__fakePadPressed && index === ${START_BUTTON};
return { value: pressed ? 1 : 0, pressed, touched: pressed };
}),
}],
});
return true;
})()`);
await everyRenderer(nextPolls);
await session.mpv.command('set_property', 'pause', true);
await everyRenderer('window.__fakePadPressed = true');
await everyRenderer(nextPolls);
await everyRenderer('window.__fakePadPressed = false');
await everyRenderer(nextPolls);
// Long enough for a second `cycle pause` to reach mpv and cancel the first.
await new Promise((done) => setTimeout(done, 300));
assert.equal(await session.mpv.command('get_property', 'pause'), false);
} finally {
await everyRenderer('delete navigator.getGamepads');
renderers.forEach((renderer) => renderer.close());
await session.mpv.command('set_property', 'pause', true);
}
},
);
test(
'controller combos survive the real save path and can be rebound to one button',
{ timeout: TEST_TIMEOUT_MS },
async () => {
const { overlay } = await useSession();
const L1 = { kind: 'button', buttonIndex: 4 };
const DPAD_LEFT = { kind: 'button', buttonIndex: 14 };
const DPAD_RIGHT = { kind: 'button', buttonIndex: 15 };
const save = (bindings: Record<string, unknown>) =>
overlay.evaluate<Record<string, unknown>>(
`(async () => {
await window.electronAPI.saveControllerConfig(${JSON.stringify({ bindings })});
return (await window.electronAPI.getControllerConfig()).bindings;
})()`,
);
await save({ previousEntry: { ...DPAD_LEFT, hold: L1 } });
const bothCombos = await save({ nextEntry: { ...DPAD_RIGHT, hold: L1 } });
assert.deepEqual(bothCombos.previousEntry, { ...DPAD_LEFT, hold: L1 });
assert.deepEqual(bothCombos.nextEntry, { ...DPAD_RIGHT, hold: L1 });
const rebound = await save({ previousEntry: DPAD_LEFT, nextEntry: { kind: 'none' } });
assert.deepEqual(rebound.previousEntry, DPAD_LEFT);
assert.deepEqual(rebound.nextEntry, { kind: 'none' });
await save({ previousEntry: { kind: 'none' } });
},
);
// Runs last: it leaves the lookup popup open over the overlay.
test(
'holding Shift over a word opens the Yomitan popup with its dictionary entry',
+7
View File
@@ -1,6 +1,11 @@
import path from 'node:path';
import packageJson from '../package.json';
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
import { getDefaultConfigDir } from '../src/shared/setup-state.js';
import {
appendManagedFfmpegToPath,
getManagedFfmpegDir,
} from '../src/core/services/managed-ffmpeg.js';
import {
loadLauncherJellyfinConfig,
loadLauncherLoggingConfig,
@@ -65,6 +70,8 @@ function ensureAppPath(context: LauncherCommandContext): string {
async function main(): Promise<void> {
const scriptPath = process.argv[1] || 'subminer';
const scriptName = path.basename(scriptPath);
// Same PATH rule as the app: dependency checks and spawned tools see a setup-page FFmpeg.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(getDefaultConfigDir()));
const launcherConfig = loadLauncherYoutubeSubgenConfig();
const launcherMpvConfig = loadLauncherMpvConfig();
const launcherLoggingConfig = loadLauncherLoggingConfig();
+3 -1
View File
@@ -543,8 +543,10 @@ test('launchAppBackgroundDetached starts background child directly', async () =>
launchAppBackgroundDetached(appPath, 'info');
// The shell creates each file before writing to it, so wait for content, not existence.
const hasContent = (file: string) => fs.existsSync(file) && fs.statSync(file).size > 0;
const deadline = Date.now() + 1000;
while ((!fs.existsSync(argsPath) || !fs.existsSync(envPath)) && Date.now() < deadline) {
while ((!hasContent(argsPath) || !hasContent(envPath)) && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 20));
}
+3 -1
View File
@@ -25,7 +25,9 @@ export const IMMERSION_DB_FIXTURE_DDL = `
tmdb_type TEXT,
metadata_json TEXT,
CREATED_DATE TEXT,
LAST_UPDATE_DATE TEXT
LAST_UPDATE_DATE TEXT,
group_override INTEGER,
group_override_updated_at TEXT
);
CREATE UNIQUE INDEX idx_anime_namespace_title ON imm_anime((media_kind = 'youtube'), normalized_title_key);
CREATE TABLE imm_videos(
+5 -4
View File
@@ -2,7 +2,7 @@
"name": "subminer",
"productName": "SubMiner",
"desktopName": "SubMiner.desktop",
"version": "0.21.1",
"version": "0.22.1-beta.2",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5",
"main": "dist/main-entry.js",
@@ -185,6 +185,10 @@
{
"from": "dist/scripts/get-mpv-window-macos",
"to": "scripts/get-mpv-window-macos"
},
{
"from": "dist/scripts/macos-controller-watch",
"to": "scripts/macos-controller-watch"
}
],
"files": [
@@ -283,8 +287,5 @@
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all"
},
"patchedDependencies": {
"@discordjs/rest@2.6.1": "patches/@discordjs%2Frest@2.6.1.patch"
}
}
+40 -71
View File
@@ -1,88 +1,57 @@
> This is a prerelease build for testing. Stable changelog and docs-site updates remain pending until the final stable release.
<!-- prerelease-version: 0.20.1-beta.2; since: v0.20.1-beta.1 -->
<!-- prerelease-version: 0.22.1-beta.2; since: v0.22.1-beta.1 -->
## Changes since v0.20.1-beta.1
## Changes since v0.22.1-beta.1
- Upgraded the desktop runtime to Electron 43.7.7.
- SubMiner now refuses to start on an unsupported Electron runtime, or after an Electron major or minor downgrade, so your Yomitan profile data stays safe; patch downgrades are still allowed.
- Automatic character-dictionary updates now stop if a Yomitan profile that had dictionaries suddenly reports none.
- Development launches now use a separate `SubMiner-dev` profile unless you explicitly ask for the production profile.
- Sentence mining (single and multi-line) no longer counts each card twice in session and lifetime stats.
- Deleting sessions now updates word and kanji "first seen" and "last seen" dates correctly, and retention pruning keeps historical discovery dates and counts.
- Words hidden by the vocabulary filter are no longer counted in the new-words charts, so the charts now match the vocabulary summary.
- A one-time background repair on next launch fixes stale "last seen" dates and existing chart mismatches.
- Overview totals, charts, the activity calendar, and the vocabulary summary now refresh after you delete sessions, and a failed refresh keeps the dashboard visible with a retry option.
- Subtitle generation now works during Windows YouTube playback and loads the generated subtitles into the playing video.
- On Windows, moving on to a video queued from the YouTube browser window no longer drops the rest of mpv's queue.
- The stats docs now cover the automatic Overview refresh after deletions and how discovery dates are kept through retention pruning.
- Later seasons now land on the right AniList entry even when the sequel chain includes split-season halves, specials, or movies (for example Mushoku Tensei S3, Re:ZERO S4, and Attack on Titan S4).
- Entries whose title names the season ("Season 3", "III", "第3期") are now preferred over counting sequels.
- Episodes in the second half of a split season now update that half's AniList entry at the correct episode number.
- Character dictionary AniList matches cached by older versions are re-resolved once.
- Added outro skipping: the AniSkip key now also skips endings, with its own prompt and chapter markers.
- Intro and outro detection now reads the file's own chapters first and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
- AniSkip lookups now send the episode length, so skip times match your TV or Blu-ray cut.
- AniSkip rate limits, server errors, and network failures are no longer remembered as "no intro" until restart; the lookup is retried on the next load.
- The Jimaku modal fills in the series name again for Jellyfin episodes whose name contains a "/", and the AniList fallback guess is fixed for the same case.
- The stats Library now shows each anime once, with its linked seasons, movies, and OVAs grouped into one card that lists the parts in release order.
- A title's page now has options to move it to another anime, show it on its own, or restore AniList's grouping, and `subminer sync` keeps the most recent choice.
- mpv keys from `input.conf` are no longer sent to a Yomitan popup that has already closed.
- mpv keys are no longer dropped while the overlay reloads mpv's bindings after it regains focus.
- With `--log-level debug`, the log now says why the overlay kept an mpv-bound key instead of forwarding it.
- First-run setup now shows whether FFmpeg and FFprobe are usable, and a **Download FFmpeg** button saves a verified build that SubMiner and the `subminer` command use when no system FFmpeg is found.
## Highlights
### Added
- **YouTube Browser Window**:
- Open it with `subminer youtube` (or `subminer yt`), or pick **Browse YouTube** from the tray. It stays logged in across restarts.
- Clicking a video plays it in mpv. Middle-click, Shift-click, Ctrl-click, or the right-click menu adds it to mpv's playlist.
- Queued videos get the same Japanese subtitle setup when they start.
- Closing the window quits SubMiner if you started it with `subminer youtube`. If a video is still playing, SubMiner waits until mpv closes.
- **Whisper Subtitles for YouTube**:
- Set `youtube.subtitleSource` to `whisper` to make subtitles with Whisper instead of downloading YouTube's captions.
- The video stays paused while Whisper works, and progress shows in the subtitle generation modal. You can close the modal to keep watching, or cancel.
- The subtitle generation modal (`Ctrl+Shift+G`) now works on YouTube videos, including on Windows.
- **Mouse and Scroll Wheel Bindings**:
- You can now use scroll wheel keys (`WHEEL_UP`, `WHEEL_DOWN`, `WHEEL_LEFT`, `WHEEL_RIGHT`) in `keybindings` and record them in the settings key editor.
- mpv's mouse button and wheel bindings now work while the cursor is over the overlay. This matters most on Hyprland, where these bindings did nothing before.
- When a binding conflicts, SubMiner's own bindings and right-click pause take priority over mpv's.
- **Session Help Commands**: During playback, press `Enter` or double-click a row in session help to run that command. Hovering over a row makes it the target for `Enter`.
### Changed
- **Release Assets**: Releases no longer include package-size JSON reports.
- **Intro and Outro Skipping**:
- The AniSkip key now skips endings too, with its own prompt and chapter markers.
- Intros and outros are detected from the file's own chapters first, so skipping also works for Jellyfin and other streams.
- AniSkip times now match your TV or Blu-ray cut.
- **Library Franchise Cards**: Seasons, movies, and OVAs of the same anime now share one library card, with each part's own stats listed inside. To fix the grouping, use **Move to Another Anime…**, **Show On Its Own**, or **Put Back Where AniList Has It** on a title's page.
- **FFmpeg Download in Setup**: First-run setup now shows whether FFmpeg and FFprobe are usable. If they are missing, click **Download FFmpeg** to install a verified build that SubMiner and the `subminer` command can use.
### Fixed
- **Jellyfin Subtitles**:
- The Japanese track is selected, and annotations start, as soon as it downloads. SubMiner no longer waits for the other tracks.
- Japanese and English tracks are now picked automatically on episodes with image-based subtitles (PGS, DVD, DVB).
- If one track fails to download, the other tracks are still selected.
- **Jellyfin Audio Track**: On direct-play streams, timing review previews and mined card audio now use the audio track you're playing.
- **Media Timing Review**:
- Trim handles are now thin lines centered on the clip edges.
- Original subtitle boundaries are now plain orange bars with no labels.
- The preview cursor no longer stutters on macOS with Bluetooth headphones such as AirPods.
- **Hyprland Fullscreen**: The overlay stays visible when mpv enters or leaves fullscreen. With `mpv.backend: x11`, subtitles and the sidebar stay clickable after going fullscreen.
- **mpv Key Bindings in the Overlay**: mpv key bindings, such as `9`/`0` for volume, now work while the overlay has focus, even when the overlay loaded before mpv connected.
- **YouTube Japanese Subtitles**: Some videos also list a machine-translated Japanese track. On those, Japanese subtitles no longer fail with "HTTP 429". If YouTube refuses a direct download, SubMiner retries with yt-dlp.
- **Stats Accuracy**:
- Sentence mining no longer counts each card twice in session and lifetime stats.
- Overview totals, charts, the activity calendar, and the vocabulary summary now update after you delete sessions.
- Word and kanji dates stay correct after deleting sessions. New-word charts now match the vocabulary summary.
- **Dictionary Safety**: Automatic character dictionary changes now stop if a Yomitan profile that had dictionaries suddenly reports none. SubMiner also refuses to load Yomitan data after a downgrade to an older Electron version.
- **AppImage in Sandboxes**: The AppImage now opens its window in sandboxes that mount the image themselves, such as `firejail --appimage`.
- **Ctrl+C Crash**: Stopping the terminal command that started SubMiner with Ctrl+C no longer crashes it with a "write EPIPE" error.
- **Security Updates**: Electron is updated to 43.7.7 and undici to 7.29.1, which fixes known security advisories.
- **AniList Seasons**: Later seasons now match the right AniList entry when the series has split-season halves, specials, or movies. Episodes in the second half of a split season now update the right entry.
- **AniSkip**: Rate limits, server errors, and network failures are no longer remembered as "no intro" until restart. SubMiner retries them on the next load.
- **Jimaku**: The modal fills in the series name again for Jellyfin episodes whose name contains a "/".
- **Windows Overlay**:
- The overlay now finds mpv more reliably, without relying on PowerShell lookups.
- You can now configure the IPC socket in `mpv.conf`.
- The overlay no longer stays attached to an unrelated window after mpv's process ID is reused.
- Stalled overlays now log diagnostic warnings without debug logging enabled.
- **mpv Keys in the Overlay**: Keys bound in `input.conf` are no longer sent to a Yomitan popup that has already closed. They also no longer get dropped while the overlay reloads mpv's bindings after it regains focus.
### Docs
- **Docs Site Rewrite**: Pages are shorter and easier to scan. The configuration reference now has a short explanation and a table of keys and defaults for each config block. Pages that no longer matched current behavior are fixed.
- **Arch Linux Install**: The MeCab install command now uses the AUR package `mecab-git`. The README now matches the installation guide.
- **Stats**: The docs now cover the Overview refreshing after you delete sessions, and how first-seen dates are kept when old sessions are cleaned up.
- **Windows Overlay Troubleshooting**: New guide to collecting and reading overlay attachment and readiness warnings without debug logging.
## What's Changed
- fix(storage): protect Yomitan profiles across Electron runtime changes by @ksyasuda in #211
- fix(jellyfin): select subtitles faster and survive failed track downloads by @ksyasuda in #270
- fix(jellyfin): use the current audio track for media generation by @ksyasuda in #271
- feat(youtube): add YouTube browser window and Whisper subtitle source by @ksyasuda in #273
- fix(overlay): thin centered trim handles and label-free subtitle boundaries in timing review by @ksyasuda in #274
- feat(overlay): run session help commands with Enter or double-click by @ksyasuda in #275
- fix(overlay): keep overlay mapped during Hyprland/Sway fullscreen by @ksyasuda in #276
- fix(linux): skip AppImage mount keepalive on sandbox squashfs mounts by @ksyasuda in #277
- fix(overlay): reload imported mpv keys after mpv connects by @ksyasuda in #278
- feat(overlay): forward mpv mouse button and wheel bindings by @ksyasuda in #279
- fix(stats): count mined cards once and keep lexical stats exact after deletes by @ksyasuda in #280
- fix(youtube): keep mpv queue when advancing to a queued video on Windows by @ksyasuda in #281
- fix(subtitles): allow Whisper generation during Windows YouTube stream playback by @ksyasuda in #282
- fix(overlay): identify Windows mpv windows through IPC PID by @ksyasuda in #330
- fix(overlay): keep forwarding mpv keys after a Yomitan popup closes by @ksyasuda in #332
- feat(setup): download FFmpeg from first-run setup when none is usable by @ksyasuda in #333
- feat(aniskip): detect intros and outros from file chapters and AniSkip v2 by @ksyasuda in #334
- fix(anilist): resolve later seasons past split-cour halves and specials by @ksyasuda in #335
- feat(stats): group library seasons, movies and OVAs into franchise cards by @ksyasuda in #336
- fix(jimaku): keep the series name for stream titles containing slashes by @ksyasuda in #337
## Installation
+61 -7
View File
@@ -1,19 +1,73 @@
## Highlights
### Added
- **Plugins**:
- JavaScript plugins load from `<config dir>/plugins/<id>/` and are enabled under `plugins` in the config.
- Plugins can react to mpv events and mined cards, call AnkiConnect, run programs, and show results in an overlay panel or window.
- Three examples are included: `ai-explain` for line explanations, `anki-sync` for AnkiWeb syncing, and `episode-tags` for tagging cards by show and episode.
- **Subtitle Filters**: Remove parenthesized text, sound descriptions, speaker names, music notes, or custom regex matches from primary subtitles. Configure them in Settings under Behavior → Subtitle Filters.
- **Controller Dialog Layouts**: The media timing review and duplicate card dialogs can now be fully operated by controller and show button hints. Remap both layouts per controller in `Alt+C`.
- **Controller Customization**:
- `Alt+C` actions can be combos: click **Learn**, hold one button, and press another.
- New unbound actions cover subtitle navigation, holding to show the secondary subtitle, Yomitan entry selection, and character navigation.
- **Button Style** offers Xbox, Nintendo, or PlayStation names and symbols, saved per controller.
- `Alt+C` now warns when two actions share an input.
- **Keyboard-Only Mode**: Press `C` to move and look up by character, reaching words split by subtitle tokenization. **Pause Video In Keyboard-Only Mode** can also pause when the mode turns on and resume when it turns off.
- **Jimaku Auto-Open**: Set `jimaku.autoOpenWhenPrimarySubtitleMissing` to pause and open Jimaku when a local video has no Japanese subtitle track. Playback resumes when the modal closes.
### Changed
- **Stats Session View**: The expanded session view in the stats dashboard has been redesigned. It shows stat tiles for pace, lines, known-word rate, lookups, and paused time, plus a reading density chart of known and unknown words with lookup and card-mined markers.
- **Stats Trends**: Rebuilt with period comparisons, Learning charts, a heatmap, a title timeline, and a single running-total chart. Week grouping, custom ranges, a page-wide title filter, and click-through to sessions and library pages are also new.
- **Stats Vocabulary**:
- Rebuilt around one searchable, sortable word table with Worth mining, All words, Across titles, and Newest views.
- Added known words by frequency band, a vocabulary growth chart, and a full kanji view.
- New word counts now count dictionary words, so a word's conjugations count once and totals are lower than before.
- Words and lines from streams now say they can't be mined, instead of showing Unavailable buttons.
- **Controller Behavior**: **Toggle MPV Pause** now works outside keyboard-only mode. Controller connected and disabled messages now follow your regular notification setting instead of using a separate overlay pill.
- **Keyboard-Only Mode Exit**: Turning the mode off now also closes the dictionary popup.
- **Hachidori**: The bundled dictionary reader is updated to 0.4.0, adding every pitch accent in each popup entry, pitch drawn on the headword reading, per-kanji furigana, and Yomitan-style definition tags.
### Fixed
- **Subtitle Delay**: Retiming subtitles in mpv (z/x or sub-step) now carries through SubMiner. Mined card audio, images, and timestamps match the retimed line, and so do the subtitle sidebar, subtitle navigation, and replay.
- **Subtitle Sidebar**: mpv keys and mouse buttons, such as volume keys and double-click fullscreen, work again while the sidebar is open.
- **Controller Settings (`Alt+C`)**:
- Remaps now apply right away, without restarting SubMiner.
- Editing stays locked until you press a button, so the window can't edit a controller it can't see.
- With several controllers connected, it selects and listens to the one you just pressed.
- **Learn**, **Clear**, and **Reset** are reachable again, D-pad **Learn** no longer errors, and button names are correct on standard-layout pads.
- **Controller Input**: One press no longer runs its action twice on macOS and Windows. On macOS, buttons now work while mpv is in front.
- **Dictionary Popup**: Controller and keyboard lookups pause and resume playback reliably, and moving between words right after closing the popup no longer reopens it.
- **Anki Sentence Audio**: `ankiConnect.fields.audio` now defaults to `SentenceAudio`, so generated audio no longer overwrites Yomitan's word audio. If you relied on the old default, set it to `ExpressionAudio`.
- **AniList**: Progress sync now adds an exactly matched or pinned show to your Watching or Completed list when it isn't on your list yet. Completed, Paused, Dropped, and Rewatching entries are never changed.
- **Stats Dashboard**:
- Overview, media, library, trends, vocabulary, and sentence search load several times faster on large databases.
- Trends totals, episode counts, rate charts, axis labels, and date handling in time zones ahead of UTC are corrected.
- Word lists now total every form of a word and show the dictionary form's reading.
- Names no longer slip past Hide Names, and totals stay correct after vocabulary cleanup.
- **Playback**: Reloading the current file in mpv no longer leaves playback paused, and the "Overlay loading" message no longer gets stuck when moving to the next playlist file.
- **AppImage**: "Service Crash" notifications on quit no longer appear on Ubuntu 26.04 and newer.
### Docs
- **README**: Refreshed the anime screenshots using the current build.
- **Keyboard and Controller Reference**: Keyboard shortcuts now list the keyboard-only `C` key, and the configuration reference points to Controller support for default button actions.
## What's Changed
- fix(overlay): forward mpv input while subtitle sidebar is open by @ksyasuda in #300
- fix(subtitles): follow mpv sub-delay in mining, sidebar, and navigation by @ksyasuda in #302
- feat(stats): redesign expanded session view with density chart by @ksyasuda in #304
- feat(plugins): add JavaScript plugin system with overlay panel by @ksyasuda in #303
- fix(anilist): add missing list entry on confident match by @dandascan in #305
- Controller: hold to show the secondary subtitle, dictionary entry navigation, standard button names by @YashaNoos in #312
- Controller: layouts for the media timing review and duplicate card dialogs by @YashaNoos in #313
- Controller: subtitle line actions, Button Style, keyboard-only mode pause, Alt+C fixes by @YashaNoos in #316
- fix(plugin): keep loading OSD off on warm playlist advance by @ksyasuda in #317
- feat(subtitles): add regex subtitle filters with built-in presets by @ksyasuda in #318
- feat(jimaku): auto-open modal when a video has no Japanese subtitle by @dandascan in #319
- fix(controller): pick up macOS presses while mpv is in front by @ksyasuda in #321
- perf(stats): speed up dashboard queries on large databases by @ksyasuda in #322
- fix(mpv): resume playback after a same-file reload that skips the path clear by @ksyasuda in #323
- fix(controller): keep popup pause and press handling reliable by @ksyasuda in #324
- feat(stats): overhaul the Trends tab by @ksyasuda in #325
- Controller: character navigation in keyboard-only mode, plain Xbox face names by @YashaNoos in #326
- feat(controller): add hold + press combos to main bindings by @ksyasuda in #328
## New Contributors
- @dandascan made their first contribution in #305
- @YashaNoos made their first contribution in #312
## Installation
-13
View File
@@ -1,13 +0,0 @@
diff --git a/package.json b/package.json
index 02d2d8809a98c5d32b889fceba11458660f1fa6a..72cd7004d92809689daaeec1cd8a274e1cabdff5 100644
--- a/package.json
+++ b/package.json
@@ -77,7 +77,7 @@
"discord-api-types": "^0.38.40",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
- "undici": "6.24.1",
+ "undici": "6.27.0",
"@discordjs/collection": "^2.1.1",
"@discordjs/util": "^1.2.0"
},
+11 -1
View File
@@ -210,8 +210,17 @@ function M.create(ctx)
})
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()
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()
end
if state.pending_reload_media_identity ~= nil then
@@ -322,6 +331,7 @@ function M.create(ctx)
state.pending_reload_reason = nil
state.app_managed_playback_pending = false
state.app_managed_playback_active = false
state.app_managed_playlist_paths = {}
end
local function register_lifecycle_hooks()
+9
View File
@@ -27,6 +27,15 @@ function M.create(ctx)
state.skip_managed_subtitle_rearm_once = true
state.app_managed_playback_pending = true
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
end)
mp.register_script_message("subminer-menu", function()
ui.show_menu()
end)
+1
View File
@@ -34,6 +34,7 @@ function M.new()
pending_reload_reason = nil,
app_managed_playback_pending = false,
app_managed_playback_active = false,
app_managed_playlist_paths = {},
auto_start_retry_generation = 0,
session_binding_generation = 0,
session_binding_names = {},
+4 -1
View File
@@ -108,6 +108,9 @@ function extractBuild() {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-yomitan-'));
try {
if (process.platform === 'win32') {
// Call .NET directly instead of Expand-Archive: under a pwsh CI step, PSModulePath
// makes Windows PowerShell load PowerShell 7's Archive module, whose
// ExtractToDirectory overload does not exist on .NET Framework.
run(
'powershell.exe',
[
@@ -116,7 +119,7 @@ function extractBuild() {
'-ExecutionPolicy',
'Bypass',
'-Command',
`Expand-Archive -LiteralPath '${escapePowerShellString(zipPath)}' -DestinationPath '${escapePowerShellString(tempDir)}' -Force`,
`$ErrorActionPreference = 'Stop'; Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapePowerShellString(zipPath)}', '${escapePowerShellString(tempDir)}')`,
],
repoRoot,
);
+56
View File
@@ -8,6 +8,9 @@ const http = require('node:http');
const root = path.resolve(__dirname, '..');
const parser = require(path.join(root, 'dist/core/services/tokenizer/yomitan-parser-runtime.js'));
const { writeStoredZip } = require(path.join(root, 'dist/shared/stored-zip.js'));
const { HACHIDORI_POPUP_OPEN_SELECTOR } = require(
path.join(root, 'dist/renderer/yomitan-popup.js'),
);
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-hachidori-parser-'));
protocol.registerSchemesAsPrivileged([
@@ -43,6 +46,58 @@ function fixture(name, title, bankName, entries, frequencyMode = 'rank-based') {
return zipPath;
}
// The renderer's popup auto-pause and key routing read this marker because the
// reader's shadow root is closed. Drives the real reader with real input, since
// stubbed DOM tests cannot notice an upstream merge that changes what it exposes.
async function assertPopupOpenMarkerFollowsPane(targetSession) {
const server = http.createServer((_request, response) => {
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.end(
'<!doctype html><p id="word" style="font-size:48px;margin:300px 0 0 100px">食べた</p>',
);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const page = new BrowserWindow({
width: 900,
height: 600,
show: true,
webPreferences: { session: targetSession, contextIsolation: true, nodeIntegration: false },
});
try {
await page.loadURL(`http://127.0.0.1:${server.address().port}/`);
const { webContents } = page;
const word = await webContents.executeJavaScript(
`(() => { const { x, y, height } = document.getElementById('word').getBoundingClientRect(); return { x, y, height }; })()`,
);
const repeatUntilMarker = async (expected, act) => {
const query = `document.querySelector(${JSON.stringify(HACHIDORI_POPUP_OPEN_SELECTOR)}) !== null`;
for (let attempt = 0; attempt < 100; attempt += 1) {
// Content scripts load asynchronously, so keep acting until the reader reacts.
act(attempt);
await new Promise((resolve) => setTimeout(resolve, 100));
if ((await webContents.executeJavaScript(query)) === expected) return;
}
assert.fail(`Hachidori popup-open marker never became ${expected}`);
};
page.focus();
webContents.focus();
await repeatUntilMarker(true, (attempt) =>
webContents.sendInputEvent({
type: 'mouseMove',
x: Math.round(word.x + 24) + (attempt % 2),
y: Math.round(word.y + word.height / 2),
}),
);
await repeatUntilMarker(false, () => {
webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
webContents.sendInputEvent({ type: 'keyUp', keyCode: 'Escape' });
});
} finally {
page.destroy();
await new Promise((resolve) => server.close(resolve));
}
}
app
.whenReady()
.then(async () => {
@@ -211,6 +266,7 @@ app
assert.deepEqual(unmatched, []);
assert.equal(await parser.getYomitanCurrentAnkiDeckName(deps, logger), 'Test Mining');
assert.equal((await targetSession.extensions.getAllExtensions()).length, 1);
await assertPopupOpenMarkerFollowsPane(targetSession);
assert.equal(
await parser.syncYomitanDefaultAnkiServer('http://127.0.0.1:8765', deps, logger),
true,
+22 -19
View File
@@ -4,6 +4,8 @@ const path = require('node:path');
const LINUX_FFMPEG_LIBRARY = 'libffmpeg.so';
const MACOS_WINDOW_HELPER = 'get-mpv-window-macos';
const MACOS_CONTROLLER_HELPER = 'macos-controller-watch';
const MACOS_HELPERS = [MACOS_WINDOW_HELPER, MACOS_CONTROLLER_HELPER];
const DEFAULT_MACOS_APP_BUNDLE = 'SubMiner.app';
function resolveMacOSAppBundlePath(context) {
@@ -52,7 +54,7 @@ async function stageLinuxAppImageSharedLibrary(
return true;
}
async function verifyMacOSWindowHelper(
async function verifyMacOSHelpers(
context,
deps = {
access: (filePath, mode) => fs.access(filePath, mode),
@@ -60,27 +62,28 @@ async function verifyMacOSWindowHelper(
) {
if (context.electronPlatformName !== 'darwin') return false;
const appBundlePath = resolveMacOSAppBundlePath(context);
const helperPath = path.join(
appBundlePath,
const scriptsDir = path.join(
resolveMacOSAppBundlePath(context),
'Contents',
'Resources',
'scripts',
MACOS_WINDOW_HELPER,
);
try {
await deps.access(helperPath, fsSync.constants.X_OK);
} catch (error) {
if (error && typeof error === 'object' && error.code === 'ENOENT') {
throw new Error(
`macOS packaging requires ${MACOS_WINDOW_HELPER} at ${helperPath}. Run bun run build:assets on macOS with swiftc available before packaging.`,
);
for (const helperName of MACOS_HELPERS) {
const helperPath = path.join(scriptsDir, helperName);
try {
await deps.access(helperPath, fsSync.constants.X_OK);
} catch (error) {
if (error && typeof error === 'object' && error.code === 'ENOENT') {
throw new Error(
`macOS packaging requires ${helperName} at ${helperPath}. Run bun run build:assets on macOS with swiftc available before packaging.`,
);
}
if (error && typeof error === 'object' && error.code === 'EACCES') {
throw new Error(`macOS helper is not executable: ${helperPath}`);
}
throw error;
}
if (error && typeof error === 'object' && error.code === 'EACCES') {
throw new Error(`macOS window helper is not executable: ${helperPath}`);
}
throw error;
}
return true;
@@ -103,17 +106,17 @@ async function stageBundledBunRuntime(context, deps = {}) {
async function afterPack(context, deps = {}) {
await stageLinuxAppImageSharedLibrary(context);
await verifyMacOSWindowHelper(context);
await verifyMacOSHelpers(context);
await stageBundledBunRuntime(context, deps);
await (deps.auditPackage ?? require('./package-audit.cjs').auditPackage)(context);
}
module.exports = {
LINUX_FFMPEG_LIBRARY,
MACOS_WINDOW_HELPER,
MACOS_HELPERS,
resolveMacOSAppBundlePath,
stageBundledBunRuntime,
stageLinuxAppImageSharedLibrary,
verifyMacOSWindowHelper,
verifyMacOSHelpers,
default: afterPack,
};
+19 -21
View File
@@ -6,13 +6,13 @@ import test from 'node:test';
const {
LINUX_FFMPEG_LIBRARY,
MACOS_WINDOW_HELPER,
MACOS_HELPERS,
default: afterPack,
stageLinuxAppImageSharedLibrary,
verifyMacOSWindowHelper,
verifyMacOSHelpers,
} = require('./electron-builder-after-pack.cjs') as {
LINUX_FFMPEG_LIBRARY: string;
MACOS_WINDOW_HELPER: string;
MACOS_HELPERS: string[];
default: (
context: {
appOutDir: string;
@@ -34,7 +34,7 @@ const {
appOutDir: string;
electronPlatformName: string;
}) => Promise<boolean>;
verifyMacOSWindowHelper: (context: {
verifyMacOSHelpers: (context: {
appOutDir: string;
electronPlatformName: string;
}) => Promise<boolean>;
@@ -88,24 +88,19 @@ test('stageLinuxAppImageSharedLibrary skips non-Linux packaging contexts', async
}
});
test('verifyMacOSWindowHelper accepts packaged macOS helper binary', async () => {
test('verifyMacOSHelpers accepts packaged macOS helper binaries', async () => {
const workspace = createWorkspace('subminer-after-pack-macos-helper');
const appOutDir = path.join(workspace, 'SubMiner-darwin-arm64');
const helperPath = path.join(
appOutDir,
'SubMiner.app',
'Contents',
'Resources',
'scripts',
MACOS_WINDOW_HELPER,
);
const scriptsDir = path.join(appOutDir, 'SubMiner.app', 'Contents', 'Resources', 'scripts');
fs.mkdirSync(path.dirname(helperPath), { recursive: true });
fs.writeFileSync(helperPath, 'compiled helper', 'utf8');
fs.chmodSync(helperPath, 0o755);
fs.mkdirSync(scriptsDir, { recursive: true });
for (const helperName of MACOS_HELPERS) {
fs.writeFileSync(path.join(scriptsDir, helperName), 'compiled helper', 'utf8');
fs.chmodSync(path.join(scriptsDir, helperName), 0o755);
}
try {
const verified = await verifyMacOSWindowHelper({
const verified = await verifyMacOSHelpers({
appOutDir,
electronPlatformName: 'darwin',
});
@@ -116,19 +111,22 @@ test('verifyMacOSWindowHelper accepts packaged macOS helper binary', async () =>
}
});
test('verifyMacOSWindowHelper throws when macOS helper binary is missing', async () => {
test('verifyMacOSHelpers throws when a macOS helper binary is missing', async () => {
const workspace = createWorkspace('subminer-after-pack-macos-helper-missing');
const appOutDir = path.join(workspace, 'SubMiner-darwin-arm64');
const scriptsDir = path.join(appOutDir, 'SubMiner.app', 'Contents', 'Resources', 'scripts');
fs.mkdirSync(path.join(appOutDir, 'SubMiner.app', 'Contents', 'Resources'), { recursive: true });
fs.mkdirSync(scriptsDir, { recursive: true });
fs.writeFileSync(path.join(scriptsDir, 'get-mpv-window-macos'), 'compiled helper', 'utf8');
fs.chmodSync(path.join(scriptsDir, 'get-mpv-window-macos'), 0o755);
try {
await assert.rejects(
verifyMacOSWindowHelper({
verifyMacOSHelpers({
appOutDir,
electronPlatformName: 'darwin',
}),
/macOS packaging requires get-mpv-window-macos/,
/macOS packaging requires macos-controller-watch/,
);
} finally {
fs.rmSync(workspace, { recursive: true, force: true });
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env swift
//
// macos-controller-watch.swift
// SubMiner - Report controller button presses on macOS while SubMiner is in the background
//
// macOS only delivers GameController input to the frontmost app, so the overlay sees no
// presses while mpv is in front. This helper opts in to background events and prints one
// line per press so SubMiner can focus the overlay and replay the press there.
//
// Usage: macos-controller-watch (long-running; exits when stdin closes)
// Output: "press <index> <connected pads>" per button press, using the W3C standard gamepad
// button indices. SubMiner only replays a press when one pad is connected: nothing identifies
// a pad to both GameController and Chromium, so with several it could hit the wrong one.
//
import Cocoa
import Foundation
import GameController
private func emit(_ line: String) {
FileHandle.standardOutput.write(Data((line + "\n").utf8))
}
/// Standard gamepad mapping (https://w3c.github.io/gamepad/#remapping), matching the
/// indices Chromium reports for the same pad.
private func standardButtons(_ pad: GCExtendedGamepad) -> [(Int, GCControllerButtonInput?)] {
return [
(0, pad.buttonA),
(1, pad.buttonB),
(2, pad.buttonX),
(3, pad.buttonY),
(4, pad.leftShoulder),
(5, pad.rightShoulder),
(6, pad.leftTrigger),
(7, pad.rightTrigger),
(8, pad.buttonOptions),
(9, pad.buttonMenu),
(10, pad.leftThumbstickButton),
(11, pad.rightThumbstickButton),
(12, pad.dpad.up),
(13, pad.dpad.down),
(14, pad.dpad.left),
(15, pad.dpad.right),
(16, pad.buttonHome),
]
}
private func connectedPadCount() -> Int {
return GCController.controllers().filter { $0.extendedGamepad != nil }.count
}
private func watch(_ controller: GCController) {
guard let pad = controller.extendedGamepad else { return }
for (index, button) in standardButtons(pad) {
button?.pressedChangedHandler = { _, _, pressed in
if pressed {
emit("press \(index) \(connectedPadCount())")
}
}
}
}
// Exit with SubMiner: it holds our stdin open for as long as it runs.
private func exitWhenStdinCloses() {
Thread.detachNewThread {
while !FileHandle.standardInput.availableData.isEmpty {}
exit(0)
}
}
let app = NSApplication.shared
app.setActivationPolicy(.prohibited)
GCController.shouldMonitorBackgroundEvents = true
NotificationCenter.default.addObserver(
forName: .GCControllerDidConnect,
object: nil,
queue: .main
) { notification in
if let controller = notification.object as? GCController {
watch(controller)
}
}
GCController.controllers().forEach(watch)
exitWhenStdinCloses()
app.run()
+21 -21
View File
@@ -14,9 +14,8 @@ const settingsOutputDir = path.join(repoRoot, 'dist', 'settings');
const syncUiSourceDir = path.join(repoRoot, 'src', 'syncui');
const syncUiOutputDir = path.join(repoRoot, 'dist', 'syncui');
const scriptsOutputDir = path.join(repoRoot, 'dist', 'scripts');
const macosHelperSourcePath = path.join(scriptDir, 'get-mpv-window-macos.swift');
const macosHelperBinaryPath = path.join(scriptsOutputDir, 'get-mpv-window-macos');
const macosHelperSourceCopyPath = path.join(scriptsOutputDir, 'get-mpv-window-macos.swift');
// Swift helpers compiled on macOS and shipped in Resources/scripts.
const MACOS_HELPERS = ['get-mpv-window-macos', 'macos-controller-watch'];
function ensureDir(dirPath) {
fs.mkdirSync(dirPath, { recursive: true });
@@ -45,9 +44,10 @@ function copySyncUiAssets() {
copyAssets(syncUiSourceDir, syncUiOutputDir, 'syncui');
}
function fallbackToMacosSource() {
copyFile(macosHelperSourcePath, macosHelperSourceCopyPath);
process.stdout.write(`Staged macOS helper source fallback: ${macosHelperSourceCopyPath}\n`);
function fallbackToMacosSource(helperName) {
const sourceCopyPath = path.join(scriptsOutputDir, `${helperName}.swift`);
copyFile(path.join(scriptDir, `${helperName}.swift`), sourceCopyPath);
process.stdout.write(`Staged macOS helper source fallback: ${sourceCopyPath}\n`);
}
// Pin the minimum macOS to the app's own floor (Electron's `minos`). Without an
@@ -64,34 +64,34 @@ function shouldSkipMacosHelperBuild() {
return process.env.SUBMINER_SKIP_MACOS_HELPER_BUILD === '1';
}
function buildMacosHelper() {
function buildMacosHelper(helperName) {
if (shouldSkipMacosHelperBuild()) {
process.stdout.write('Skipping macOS helper build (SUBMINER_SKIP_MACOS_HELPER_BUILD=1)\n');
fallbackToMacosSource();
fallbackToMacosSource(helperName);
return;
}
if (process.platform !== 'darwin') {
process.stdout.write('Skipping macOS helper build (not on macOS)\n');
fallbackToMacosSource();
fallbackToMacosSource(helperName);
return;
}
ensureDir(scriptsOutputDir);
const sourcePath = path.join(scriptDir, `${helperName}.swift`);
const binaryPath = path.join(scriptsOutputDir, helperName);
try {
execFileSync(
'swiftc',
['-O', '-target', macosHelperTarget(), macosHelperSourcePath, '-o', macosHelperBinaryPath],
{
stdio: 'inherit',
},
);
fs.chmodSync(macosHelperBinaryPath, 0o755);
process.stdout.write(`Built macOS helper: ${macosHelperBinaryPath}\n`);
execFileSync('swiftc', ['-O', '-target', macosHelperTarget(), sourcePath, '-o', binaryPath], {
stdio: 'inherit',
});
fs.chmodSync(binaryPath, 0o755);
process.stdout.write(`Built macOS helper: ${binaryPath}\n`);
} catch (error) {
process.stdout.write('Failed to compile macOS helper; using source fallback.\n');
fallbackToMacosSource();
process.stdout.write(`Failed to compile macOS helper ${helperName}; using source fallback.\n`);
// A binary from an earlier build would otherwise pass the after-pack check and ship stale.
fs.rmSync(binaryPath, { force: true });
fallbackToMacosSource(helperName);
if (error instanceof Error) {
process.stderr.write(`${error.message}\n`);
}
@@ -117,7 +117,7 @@ function main() {
copyRendererAssets();
copySettingsAssets();
copySyncUiAssets();
buildMacosHelper();
MACOS_HELPERS.forEach(buildMacosHelper);
stageIntegrationKeys();
}
+59
View File
@@ -1042,6 +1042,65 @@ do
)
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 recorded, err = run_plugin_scenario({
process_list = "",
+53 -1
View File
@@ -1297,7 +1297,6 @@ test('parses controller settings with logical bindings and tuning knobs', () =>
"toggleMpvPause": "leftStickPress",
"leftStickHorizontal": "rightStickX",
"leftStickVertical": "rightStickY",
"rightStickHorizontal": "leftStickX",
"rightStickVertical": "leftStickY"
}
}
@@ -1383,6 +1382,59 @@ test('parses descriptor-based controller bindings', () => {
});
});
test('parses a hold input on discrete controller bindings and rejects an invalid one', () => {
const dir = makeTempDir();
fs.writeFileSync(
path.join(dir, 'config.jsonc'),
`{
"controller": {
"bindings": {
"nextAudio": {
"kind": "button",
"buttonIndex": 15,
"hold": { "kind": "button", "buttonIndex": 4 }
},
"nextEntry": {
"kind": "axis",
"axisIndex": 0,
"direction": "positive",
"hold": { "kind": "axis", "axisIndex": 2, "direction": "positive" }
},
"mineCard": {
"kind": "button",
"buttonIndex": 12,
"hold": { "kind": "button" }
}
}
}
}`,
'utf-8',
);
const service = new ConfigService(dir);
const config = service.getConfig();
assert.deepEqual(config.controller.bindings.nextAudio, {
kind: 'button',
buttonIndex: 15,
hold: { kind: 'button', buttonIndex: 4 },
});
assert.deepEqual(config.controller.bindings.nextEntry, {
kind: 'axis',
axisIndex: 0,
direction: 'positive',
hold: { kind: 'axis', axisIndex: 2, direction: 'positive' },
});
// A broken hold must not silently become a plain press of button 12.
assert.deepEqual(
config.controller.bindings.mineCard,
DEFAULT_CONFIG.controller.bindings.mineCard,
);
assert.ok(
service.getWarnings().some((warning) => warning.path === 'controller.bindings.mineCard'),
);
});
test('parses controller profiles as per-gamepad binding overrides', () => {
const dir = makeTempDir();
fs.writeFileSync(
+2 -1
View File
@@ -52,7 +52,7 @@ const {
discordPresence,
ai,
} = INTEGRATIONS_DEFAULT_CONFIG;
const { subtitleStyle, subtitleSidebar } = SUBTITLE_DEFAULT_CONFIG;
const { subtitleStyle, subtitleSidebar, subtitleFilter } = SUBTITLE_DEFAULT_CONFIG;
const { immersionTracking } = IMMERSION_DEFAULT_CONFIG;
const { stats } = STATS_DEFAULT_CONFIG;
@@ -78,6 +78,7 @@ export const DEFAULT_CONFIG: ResolvedConfig = {
plugins,
subtitleStyle,
subtitleSidebar,
subtitleFilter,
auto_start_overlay,
jimaku,
tsukihime,
+1 -1
View File
@@ -85,13 +85,13 @@ export const CORE_DEFAULT_CONFIG: Pick<
holdSecondarySub: { kind: 'none' },
previousEntry: { kind: 'none' },
nextEntry: { kind: 'none' },
toggleCharacterNavigation: { kind: 'none' },
previousSubtitle: { kind: 'none' },
nextSubtitle: { kind: 'none' },
replaySubtitle: { kind: 'none' },
playNextSubtitle: { kind: 'none' },
leftStickHorizontal: { kind: 'axis', axisIndex: 0, dpadFallback: 'horizontal' },
leftStickVertical: { kind: 'axis', axisIndex: 1, dpadFallback: 'vertical' },
rightStickHorizontal: { kind: 'axis', axisIndex: 3, dpadFallback: 'none' },
rightStickVertical: { kind: 'axis', axisIndex: 4, dpadFallback: 'none' },
},
reviewBindings: getDefaultControllerReviewBindings(),
@@ -108,6 +108,7 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
apiKeyCommand: '',
languagePreference: 'ja',
maxEntryResults: 10,
autoOpenWhenPrimarySubtitleMissing: false,
},
tsukihime: {
apiBaseUrl: 'https://api.tsukihime.org/v1',
@@ -159,6 +160,10 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
directPlayPreferred: true,
directPlayContainers: ['mkv', 'mp4', 'webm', 'mov', 'flac', 'mp3', 'aac'],
transcodeVideoCodec: 'h264',
episodePlaylist: {
enabled: true,
maxEpisodes: 5,
},
},
discordPresence: {
enabled: true,
+13 -1
View File
@@ -1,6 +1,9 @@
import { ResolvedConfig } from '../../types/config';
export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle' | 'subtitleSidebar'> = {
export const SUBTITLE_DEFAULT_CONFIG: Pick<
ResolvedConfig,
'subtitleStyle' | 'subtitleSidebar' | 'subtitleFilter'
> = {
subtitleStyle: {
primaryDefaultMode: 'visible',
css: {},
@@ -94,4 +97,13 @@ export const SUBTITLE_DEFAULT_CONFIG: Pick<ResolvedConfig, 'subtitleStyle' | 'su
activeLineBackgroundColor: 'rgba(138, 173, 244, 0.22)',
hoverLineBackgroundColor: 'rgba(54, 58, 79, 0.84)',
},
subtitleFilter: {
presets: {
parentheses: false,
brackets: false,
speakerPrefix: false,
musicSymbols: false,
},
customRules: [],
},
};
+14 -6
View File
@@ -82,6 +82,12 @@ export function buildCoreConfigOptionRegistry(
description:
'Controller binding descriptor that selects the next word entry in the open Yomitan popup. Mine Card mines the selected entry.',
},
{
id: 'toggleCharacterNavigation',
defaultValue: defaultConfig.controller.bindings.toggleCharacterNavigation,
description:
'Controller binding descriptor that switches keyboard-only mode between moving by word and moving by character, like C. A lookup on a character searches from that character, which reaches words the subtitle split cuts in two.',
},
{
id: 'previousSubtitle',
defaultValue: defaultConfig.controller.bindings.previousSubtitle,
@@ -119,11 +125,6 @@ export function buildCoreConfigOptionRegistry(
defaultValue: defaultConfig.controller.bindings.leftStickVertical,
description: 'Axis binding descriptor used for primary popup scrolling.',
},
{
id: 'rightStickHorizontal',
defaultValue: defaultConfig.controller.bindings.rightStickHorizontal,
description: 'Axis binding descriptor reserved for alternate right-stick mappings.',
},
{
id: 'rightStickVertical',
defaultValue: defaultConfig.controller.bindings.rightStickVertical,
@@ -466,7 +467,7 @@ export function buildCoreConfigOptionRegistry(
path: `controller.bindings.${binding.id}`,
kind: 'object' as const,
defaultValue: binding.defaultValue,
description: `${binding.description} Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required.`,
description: `${binding.description} Use Alt+C learn mode or set a raw button/axis descriptor manually. If kind is "axis", direction is required. Alt+C can also learn a combo, saved as an optional "hold" input.`,
},
{
path: `controller.bindings.${binding.id}.kind`,
@@ -499,6 +500,13 @@ export function buildCoreConfigOptionRegistry(
description:
'Axis direction captured for this discrete controller action. Required when kind is "axis".',
},
{
path: `controller.bindings.${binding.id}.hold`,
kind: 'object' as const,
defaultValue: undefined,
description:
'Optional button or axis input, in the same form, that must be held down while pressing this one.',
},
]),
...axisBindings.flatMap((binding) => [
{
+24 -2
View File
@@ -467,6 +467,13 @@ export function buildIntegrationConfigOptionRegistry(
defaultValue: defaultConfig.jimaku.maxEntryResults,
description: 'Maximum Jimaku search results returned.',
},
{
path: 'jimaku.autoOpenWhenPrimarySubtitleMissing',
kind: 'boolean',
defaultValue: defaultConfig.jimaku.autoOpenWhenPrimarySubtitleMissing,
description:
'Pause playback and open the Jimaku modal when a local video has no subtitle track in youtube.primarySubLanguages (Japanese by default).',
},
{
path: 'tsukihime.apiBaseUrl',
kind: 'string',
@@ -609,13 +616,14 @@ export function buildIntegrationConfigOptionRegistry(
path: 'mpv.aniskipEnabled',
kind: 'boolean',
defaultValue: defaultConfig.mpv.aniskipEnabled,
description: 'Enable AniSkip intro detection, chapter markers, and the skip-intro key.',
description:
'Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key.',
},
{
path: 'mpv.aniskipButtonKey',
kind: 'string',
defaultValue: defaultConfig.mpv.aniskipButtonKey,
description: 'mpv key used to skip the detected intro while the skip prompt is visible.',
description: 'mpv key that skips the detected intro or outro while it plays.',
},
{
path: 'jellyfin.enabled',
@@ -696,6 +704,20 @@ export function buildIntegrationConfigOptionRegistry(
defaultValue: defaultConfig.jellyfin.transcodeVideoCodec,
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',
kind: 'boolean',
@@ -1,6 +1,10 @@
import { ResolvedConfig } from '../../types/config';
import { ConfigOptionRegistryEntry } from './shared';
import { SUBTITLE_GENERATION_MODELS } from '../../shared/subtitle-generation-model-catalog';
import {
SUBTITLE_FILTER_PRESET_IDS,
SUBTITLE_FILTER_PRESETS,
} from '../../shared/subtitle-text-filter';
export function buildSubtitleConfigOptionRegistry(
defaultConfig: ResolvedConfig,
@@ -340,5 +344,24 @@ export function buildSubtitleConfigOptionRegistry(
defaultValue: defaultConfig.subtitleSidebar.hoverLineBackgroundColor,
description: 'Background color for hovered subtitle cues.',
},
{
path: 'subtitleFilter.presets',
kind: 'object',
defaultValue: defaultConfig.subtitleFilter.presets,
description: 'Built-in filters. Each removes its matches and is off by default.',
},
...SUBTITLE_FILTER_PRESET_IDS.map((id) => ({
path: `subtitleFilter.presets.${id}`,
kind: 'boolean' as const,
defaultValue: defaultConfig.subtitleFilter.presets[id],
description: SUBTITLE_FILTER_PRESETS[id].description,
})),
{
path: 'subtitleFilter.customRules',
kind: 'array',
defaultValue: defaultConfig.subtitleFilter.customRules,
description:
'Your own regex rules, applied in order after the presets. Each rule is { name, pattern, replacement, enabled }; patterns use the gmu flags, so ^ and $ match per line. Leave replacement empty to remove the match.',
},
];
}
@@ -153,6 +153,15 @@ const SUBTITLE_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
notes: ['Hot-reload: subtitle sidebar changes apply live without restarting SubMiner.'],
key: 'subtitleSidebar',
},
{
title: 'Subtitle Filters',
description: [
'Remove unwanted text from primary subtitles, such as speaker names, readings and sound descriptions.',
'Applies to the overlay, sidebar, mined sentences and stats.',
],
notes: ['Hot-reload: filter changes apply to the current subtitle file immediately.'],
key: 'subtitleFilter',
},
];
const INTEGRATION_TEMPLATE_SECTIONS: ConfigTemplateSection[] = [
+9 -3
View File
@@ -8,6 +8,7 @@ const HOT_RELOAD_ROOTS = [
'shortcuts',
'subtitleSidebar',
'subtitleSelection',
'subtitleFilter',
] as const;
const HOT_RELOAD_EXACT_OR_PREFIX_PATHS = [
@@ -61,9 +62,14 @@ export function getConfigHotReloadField(path: string): string | null {
// These consumers read the current config when the next operation starts.
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;
}
+2
View File
@@ -7,12 +7,14 @@ import { applyIntegrationConfig } from './resolve/integrations';
import { applyPluginsConfig } from './resolve/plugins';
import { applyStatsConfig } from './resolve/stats';
import { applySubtitleDomainConfig } from './resolve/subtitle-domains';
import { applySubtitleFilterConfig } from './resolve/subtitle-filter';
import { applyTopLevelConfig } from './resolve/top-level';
const APPLY_RESOLVE_STEPS = [
applyTopLevelConfig,
applyCoreDomainConfig,
applySubtitleDomainConfig,
applySubtitleFilterConfig,
applyIntegrationConfig,
applyImmersionTrackingConfig,
applyStatsConfig,
+4 -32
View File
@@ -1,6 +1,5 @@
import type {
ControllerAxisBinding,
ControllerAxisDirection,
ControllerButtonBinding,
ControllerButtonIndicesConfig,
ControllerDpadFallback,
@@ -11,6 +10,7 @@ import type {
import {
isControllerFaceButtonLabels,
isControllerScreenAction,
parseControllerDiscreteBinding,
parseControllerReviewBinding,
type ControllerScreenBindings,
type ControllerScreenDefinition,
@@ -70,7 +70,6 @@ const CONTROLLER_BUTTON_INDEX_KEY_BY_BINDING: Record<
const CONTROLLER_AXIS_FALLBACK_BY_SLOT = {
leftStickHorizontal: 'horizontal',
leftStickVertical: 'vertical',
rightStickHorizontal: 'none',
rightStickVertical: 'none',
} as const satisfies Record<string, ControllerDpadFallback>;
@@ -101,6 +100,7 @@ const CONTROLLER_DISCRETE_BINDING_KEYS = [
'holdSecondarySub',
'previousEntry',
'nextEntry',
'toggleCharacterNavigation',
'previousSubtitle',
'nextSubtitle',
'replaySubtitle',
@@ -110,7 +110,6 @@ const CONTROLLER_DISCRETE_BINDING_KEYS = [
const CONTROLLER_AXIS_BINDING_KEYS = [
'leftStickHorizontal',
'leftStickVertical',
'rightStickHorizontal',
'rightStickVertical',
] as const;
@@ -119,10 +118,6 @@ const RESERVED_CONTROLLER_PROFILE_IDS = new Set(['__proto__', 'constructor', 'pr
type ControllerBindingsTarget = Required<ResolvedControllerBindingsConfig>;
type ControllerButtonIndicesTarget = Required<ControllerButtonIndicesConfig>;
function isControllerAxisDirection(value: unknown): value is ControllerAxisDirection {
return value === 'negative' || value === 'positive';
}
function isControllerDpadFallback(value: unknown): value is ControllerDpadFallback {
return value === 'none' || value === 'horizontal' || value === 'vertical';
}
@@ -151,29 +146,6 @@ function resolveLegacyAxisBinding(
};
}
function parseDiscreteBindingObject(value: unknown): ResolvedControllerDiscreteBinding | null {
if (!isObject(value) || typeof value.kind !== 'string') return null;
if (value.kind === 'none') {
return { kind: 'none' };
}
if (value.kind === 'button') {
return typeof value.buttonIndex === 'number' &&
Number.isInteger(value.buttonIndex) &&
value.buttonIndex >= 0
? { kind: 'button', buttonIndex: value.buttonIndex }
: null;
}
if (value.kind === 'axis') {
return typeof value.axisIndex === 'number' &&
Number.isInteger(value.axisIndex) &&
value.axisIndex >= 0 &&
isControllerAxisDirection(value.direction)
? { kind: 'axis', axisIndex: value.axisIndex, direction: value.direction }
: null;
}
return null;
}
function parseAxisBindingObject(
value: unknown,
slot: keyof typeof CONTROLLER_AXIS_FALLBACK_BY_SLOT,
@@ -241,7 +213,7 @@ function applyControllerBindings(
);
continue;
}
const parsedObject = parseDiscreteBindingObject(bindingValue);
const parsedObject = parseControllerDiscreteBinding(bindingValue);
if (parsedObject) {
target[key] = parsedObject;
} else if (bindingValue !== undefined) {
@@ -249,7 +221,7 @@ function applyControllerBindings(
`${pathPrefix}.${key}`,
bindingValue,
target[key],
"Expected legacy controller button name or binding object with kind 'none', 'button', or 'axis'.",
"Expected legacy controller button name or binding object with kind 'none', 'button', or 'axis', and an optional button or axis 'hold'.",
);
}
}
+15
View File
@@ -57,3 +57,18 @@ test('resolveConfig warns for invalid mpv launch mode', () => {
message: "Expected one of: 'normal', 'maximized', 'fullscreen'.",
});
});
test('resolveConfig parses the Jimaku auto-open toggle and warns on non-boolean values', () => {
const enabled = resolveConfig({ jimaku: { autoOpenWhenPrimarySubtitleMissing: true } });
assert.equal(enabled.resolved.jimaku.autoOpenWhenPrimarySubtitleMissing, true);
assert.deepEqual(enabled.warnings, []);
const invalid = resolveConfig({
jimaku: { autoOpenWhenPrimarySubtitleMissing: 'sometimes' as never },
});
assert.equal(invalid.resolved.jimaku.autoOpenWhenPrimarySubtitleMissing, false);
assert.deepEqual(
invalid.warnings.map((warning) => warning.path),
['jimaku.autoOpenWhenPrimarySubtitleMissing'],
);
});
+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)) {
const seenRecentServers = new Set<string>();
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'),
);
});
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);
});
+12
View File
@@ -90,6 +90,18 @@ export function applySubtitleDomainConfig(context: ResolveContext): void {
'Expected positive number.',
);
}
const autoOpen = asBoolean(src.jimaku.autoOpenWhenPrimarySubtitleMissing);
if (autoOpen !== undefined) {
resolved.jimaku.autoOpenWhenPrimarySubtitleMissing = autoOpen;
} else if (src.jimaku.autoOpenWhenPrimarySubtitleMissing !== undefined) {
warn(
'jimaku.autoOpenWhenPrimarySubtitleMissing',
src.jimaku.autoOpenWhenPrimarySubtitleMissing,
resolved.jimaku.autoOpenWhenPrimarySubtitleMissing,
'Expected boolean.',
);
}
}
const currentTsukihimeSource = isObject(src.tsukihime) ? src.tsukihime : null;
@@ -0,0 +1,50 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { resolveConfig } from '../resolve';
test('subtitleFilter resolves presets and fills custom rule defaults', () => {
const { resolved, warnings } = resolveConfig({
subtitleFilter: {
presets: { parentheses: true },
customRules: [
{ pattern: '\\n' },
{ name: 'tag', pattern: '<i>', replacement: '', enabled: false },
],
},
});
assert.deepEqual(warnings, []);
assert.equal(resolved.subtitleFilter.presets.parentheses, true);
assert.equal(resolved.subtitleFilter.presets.brackets, false);
assert.deepEqual(resolved.subtitleFilter.customRules, [
{ name: '', pattern: '\\n', replacement: '', enabled: true },
{ name: 'tag', pattern: '<i>', replacement: '', enabled: false },
]);
});
test('subtitleFilter keeps empty and invalid patterns, warns on invalid, drops malformed rules', () => {
const { resolved, warnings } = resolveConfig({
subtitleFilter: {
presets: { brackets: 'yes' as unknown as boolean },
customRules: [
{ name: 'broken', pattern: '(' },
{ name: 'placeholder', pattern: '' },
{ name: 'no pattern' },
'oops' as never,
],
},
});
assert.deepEqual(
resolved.subtitleFilter.customRules.map((rule) => rule.name),
['broken', 'placeholder'],
);
assert.equal(resolved.subtitleFilter.presets.brackets, false);
assert.deepEqual(
warnings.map((warning) => warning.path),
[
'subtitleFilter.presets.brackets',
'subtitleFilter.customRules[0].pattern',
'subtitleFilter.customRules[2]',
'subtitleFilter.customRules[3]',
],
);
});
Loaded 100 of 351 files, more files were not shown because too many files have changed in this diff. Show more