Compare commits

..
Author SHA1 Message Date
sudacode 361f9dde4f fix(aniskip): reuse a cached lookup only for the episode length it used 2026-11-22 16:29:41 -08:00
sudacode 2bf8e09ddb fix(aniskip): retry chapter detection after a failed chapter-list read
A failed read left resolution marked as started, so streams never got skip
windows until a refresh or file change. It is now retried on the next
duration change or same-media reload; a successful empty list stays final.
2026-11-22 15:22:31 -08:00
sudacode 3e51d76d6b fix(aniskip): address review findings on chapter writes, lookups and request spacing
- Never rewrite chapter-list after a failed read, or after the media changed
  while the read was pending (also for marker removal).
- Install file-chapter windows before the AniSkip lookup so their prompt and
  skip key work at once; AniSkip windows are merged in without resetting
  prompts already shown.
- A lookup superseded by a refresh or media change no longer writes the cache.
- A same-media reload retries a lookup that failed transiently.
- Serialize AniSkip request slots so late timers cannot release a burst.
2026-11-22 14:32:41 -08:00
sudacode 5a332e39c5 feat(aniskip): detect intros and outros from file chapters and AniSkip v2
- Read mpv's chapter-list first and classify the file's own opening and
  ending (names incl. Japanese, else song-length heuristics, ported from
  Telly); ask AniSkip only for what the chapters lack. Chapter detection
  also runs for remote streams; AniSkip stays local-only.
- Query AniSkip v2 with episodeLength from mpv's duration and parse both
  op and ed. Requests are spaced at least 1 s apart.
- The skip key now skips whichever of the intro or outro is playing, with
  an outro prompt and AniSkip Outro Start/End chapter markers.
- Fix transient AniSkip/MAL failures (non-404 errors, network, timeouts)
  being cached as a definite miss; only 404s and unmatched titles are cached.
2026-11-22 02:21:17 -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
50 changed files with 2351 additions and 654 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
+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.
+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.
@@ -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.
+2 -2
View File
@@ -1080,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.
// ==========================================
+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.
+1 -1
View File
@@ -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
+2 -2
View File
@@ -634,8 +634,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
+1 -1
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.
+2 -2
View File
@@ -1080,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.
// ==========================================
+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`.
+1 -1
View File
@@ -229,7 +229,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
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.
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
+10
View File
@@ -27,6 +27,16 @@ Read when: you need to find the owner module for a behavior or test surface
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, the autoplay-ready gate that releases mpv's
startup pause, managed local subtitle selection, subtitle prefetch, and subtitle sidebar state:
+39
View File
@@ -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 },
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "subminer",
"productName": "SubMiner",
"desktopName": "SubMiner.desktop",
"version": "0.22.0",
"version": "0.22.1-beta.1",
"description": "All-in-one sentence mining overlay with AnkiConnect and dictionary integration",
"packageManager": "bun@1.3.5",
"main": "dist/main-entry.js",
+8 -75
View File
@@ -1,88 +1,21 @@
> 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 -->
## Changes since v0.20.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.
<!-- prerelease-version: 0.22.1-beta.1 -->
## 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.
### 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.
- **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.
### 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**: Added a guide to collecting and interpreting 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
## Installation
@@ -616,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',
+10
View File
@@ -40,10 +40,14 @@ import {
parseSessionActionDispatchRequest,
parseSubtitlePosition,
parseSubsyncManualRunRequest,
parseUnforwardedMpvKeyReport,
parseYoutubePickerResolveRequest,
} from '../../shared/ipc/validators';
import { createLogger } from '../../logger';
import { applyOverlayClickThrough } from './overlay-click-through';
const overlayInputLogger = createLogger('overlay:input');
const { ipcMain } = electron;
export interface IpcServiceDeps {
@@ -640,6 +644,12 @@ export function registerIpcHandlers(deps: IpcServiceDeps, ipc: IpcMainRegistrar
},
);
// Shows, at --log-level debug, why an mpv input.conf key never reached mpv.
ipc.on(IPC_CHANNELS.command.reportUnforwardedMpvKey, (_event: unknown, payload: unknown) => {
const report = parseUnforwardedMpvKeyReport(payload);
if (report) overlayInputLogger.debug('Overlay kept an mpv-bound key', report);
});
ipc.on(IPC_CHANNELS.command.recordYomitanLookup, (_event: unknown, payload: unknown) => {
try {
deps.recordSubtitleMiningContext?.(parseSubtitleMiningContext(payload));
@@ -0,0 +1,176 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createOverlayVisibilityDiagnostics,
readOverlayVisibilitySnapshot,
type OverlayVisibilitySnapshot,
} from './overlay-visibility-diagnostics';
type SnapshotArgs = Parameters<typeof readOverlayVisibilitySnapshot>[0];
function snapshotFor(
options: {
tracking?: boolean;
targetPid?: number | null;
minimized?: boolean;
window?: Record<string, unknown>;
noTracker?: boolean;
} & Pick<SnapshotArgs, 'modalActive' | 'suspendVisibleOverlay'> & {
visibleOverlayVisible?: boolean;
} = {},
) {
const tracker = {
isTracking: () => options.tracking ?? false,
getGeometry: () => null,
isTargetWindowFocused: () => false,
isTargetWindowMinimized: () => options.minimized ?? false,
getDiagnosticState: () => ({ targetPid: options.targetPid ?? null, socketPath: '/tmp/mpv' }),
};
return readOverlayVisibilitySnapshot({
mainWindow: {
isDestroyed: () => false,
isVisible: () => false,
getOpacity: () => 0,
...options.window,
} as unknown as SnapshotArgs['mainWindow'],
windowTracker: options.noTracker ? null : (tracker as unknown as SnapshotArgs['windowTracker']),
visibleOverlayVisible: options.visibleOverlayVisible ?? true,
modalActive: options.modalActive,
suspendVisibleOverlay: options.suspendVisibleOverlay,
});
}
function harness() {
let now = 0;
let callback: (() => void) | null = null;
let delay = 0;
const warnings: Array<{ message: string; details: Record<string, unknown> }> = [];
let snapshot: OverlayVisibilitySnapshot | null = {
expectedVisible: true,
visible: false,
opacity: 0,
contentReady: false,
tracking: false,
targetPid: 4242,
pidLookupPending: false,
};
const diagnostics = createOverlayVisibilityDiagnostics({
now: () => now,
warn: (message, details) => warnings.push({ message, details }),
schedule: (fn, ms) => {
callback = fn;
delay = ms;
return { unref() {} } as ReturnType<typeof setTimeout>;
},
cancel: () => {
callback = null;
},
});
const update = () => diagnostics.update(() => snapshot);
return {
warnings,
update,
setSnapshot: (value: typeof snapshot) => {
snapshot = value;
},
tick: () => {
assert.ok(callback, 'watchdog must be scheduled');
now += delay;
callback();
},
scheduled: () => callback !== null,
};
}
test('visibility watchdog warns without more events and rate limits repeated polls', () => {
const h = harness();
h.update();
assert.equal(h.warnings.length, 0);
for (let i = 0; i < 100; i += 1) h.update();
h.tick();
assert.equal(h.warnings.length, 1);
assert.equal(h.warnings[0]?.details.reason, 'mpv-window-not-tracked');
assert.equal(h.warnings[0]?.details.targetPid, 4242);
assert.equal(h.warnings[0]?.details.elapsedMs, 5_000);
for (let i = 0; i < 100; i += 1) h.update();
assert.equal(h.warnings.length, 1);
h.tick();
assert.equal(h.warnings[1]?.details.elapsedMs, 35_000);
});
test('visibility watchdog distinguishes renderer readiness, hidden windows and opacity', () => {
for (const [contentReady, visible, opacity, reason] of [
[false, false, 0, 'renderer-not-ready'],
[true, false, 0, 'window-hidden'],
[true, true, 0, 'window-transparent'],
] as const) {
const h = harness();
h.setSnapshot({ expectedVisible: true, tracking: true, contentReady, visible, opacity });
h.update();
h.tick();
assert.equal(h.warnings[0]?.details.reason, reason);
}
});
test('visibility watchdog reports recovery only after warning and stops', () => {
const h = harness();
h.update();
h.tick();
h.setSnapshot({
expectedVisible: true,
visible: true,
opacity: 1,
contentReady: true,
tracking: true,
});
h.tick();
assert.match(h.warnings[1]!.message, /recovered/);
assert.equal(h.scheduled(), false);
h.update();
assert.equal(h.warnings.length, 2);
});
test('visibility watchdog stays quiet after fast startup, intentional hide or window destruction', () => {
for (const snapshot of [
{ expectedVisible: true, visible: true, opacity: 1, contentReady: true, tracking: true },
{ expectedVisible: false, visible: false, opacity: 0, contentReady: false, tracking: false },
null,
]) {
const h = harness();
h.update();
h.setSnapshot(snapshot);
h.tick();
assert.deepEqual(h.warnings, []);
assert.equal(h.scheduled(), false);
}
});
test('overlay snapshot expects visibility only once an mpv has been identified', () => {
// Requested before any mpv exists: auto_start_overlay, tray or --show-visible-overlay.
assert.equal(snapshotFor()?.expectedVisible, false);
assert.equal(snapshotFor({ noTracker: true })?.expectedVisible, false);
// mpv answered on the socket but its window never matched, so tracking never started.
assert.equal(snapshotFor({ targetPid: 4242 })?.expectedVisible, true);
// A tracker with no target socket matches windows without ever learning a PID.
assert.equal(snapshotFor({ tracking: true })?.expectedVisible, true);
});
test('overlay snapshot does not expect an intentionally hidden overlay', () => {
const identified = { targetPid: 4242, tracking: true };
assert.equal(snapshotFor(identified)?.expectedVisible, true);
assert.equal(snapshotFor({ ...identified, modalActive: true })?.expectedVisible, false);
assert.equal(snapshotFor({ ...identified, suspendVisibleOverlay: true })?.expectedVisible, false);
assert.equal(snapshotFor({ ...identified, minimized: true })?.expectedVisible, false);
assert.equal(
snapshotFor({ ...identified, visibleOverlayVisible: false })?.expectedVisible,
false,
);
});
test('overlay snapshot carries tracker state, defaults opacity and ends with the window', () => {
const snapshot = snapshotFor({ targetPid: 4242, window: { getOpacity: undefined } });
assert.equal(snapshot?.targetPid, 4242);
assert.equal(snapshot?.socketPath, '/tmp/mpv');
assert.equal(snapshot?.opacity, 1);
assert.equal(snapshotFor({ window: { isDestroyed: () => true } }), null);
});
@@ -0,0 +1,153 @@
import type { BrowserWindow } from 'electron';
import type { BaseWindowTracker } from '../../window-trackers';
import { createLogger } from '../../logger';
import {
OVERLAY_WINDOW_CONTENT_READY_FLAG,
OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG,
} from './overlay-window-flags';
const log = createLogger('overlay:visibility');
export type OverlayVisibilitySnapshot = {
expectedVisible: boolean;
visible: boolean;
opacity: number;
contentReady: boolean;
tracking: boolean;
[key: string]: unknown;
};
// One watchdog per window, independent of further visibility events: a renderer
// that never becomes ready must still leave evidence at the default warn level.
export function createOverlayVisibilityDiagnostics(deps: {
warn: (message: string, details: Record<string, unknown>) => void;
now: () => number;
schedule: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancel: (timer: ReturnType<typeof setTimeout>) => void;
}) {
let timer: ReturnType<typeof setTimeout> | null = null;
let readSnapshot: () => OverlayVisibilitySnapshot | null = () => null;
let stalledAtMs: number | null = null;
let warned = false;
let lastWarningAtMs = 0;
const check = () => {
if (timer !== null) deps.cancel(timer);
timer = null;
const snapshot = readSnapshot();
if (!snapshot?.expectedVisible) {
stalledAtMs = null;
warned = false;
return;
}
if (snapshot.visible && snapshot.opacity > 0 && snapshot.contentReady) {
if (warned) {
deps.warn('Windows overlay visibility recovered', {
...snapshot,
elapsedMs: deps.now() - stalledAtMs!,
});
}
stalledAtMs = null;
warned = false;
return;
}
stalledAtMs ??= deps.now();
const elapsedMs = deps.now() - stalledAtMs;
if (elapsedMs >= 5_000 && (!warned || deps.now() - lastWarningAtMs >= 30_000)) {
const reason = !snapshot.tracking
? 'mpv-window-not-tracked'
: !snapshot.contentReady
? 'renderer-not-ready'
: !snapshot.visible
? 'window-hidden'
: 'window-transparent';
deps.warn('Windows overlay is not visible after startup or tracking loss', {
...snapshot,
reason,
elapsedMs,
});
warned = true;
lastWarningAtMs = deps.now();
}
timer = deps.schedule(
check,
warned ? 30_000 - (deps.now() - lastWarningAtMs) : 5_000 - elapsedMs,
);
timer.unref?.();
};
return {
update(reader: () => OverlayVisibilitySnapshot | null) {
readSnapshot = reader;
// Frequent polls must not postpone a warning or bypass its rate limit.
check();
},
};
}
const diagnosticsByWindow = new WeakMap<
BrowserWindow,
ReturnType<typeof createOverlayVisibilityDiagnostics>
>();
type OverlayVisibilityWatchArgs = {
mainWindow: BrowserWindow;
windowTracker: BaseWindowTracker | null;
visibleOverlayVisible: boolean;
modalActive?: boolean;
suspendVisibleOverlay?: boolean;
};
export function readOverlayVisibilitySnapshot(
args: OverlayVisibilityWatchArgs,
): OverlayVisibilitySnapshot | null {
const window = args.mainWindow;
if (window.isDestroyed()) return null;
const tracker = args.windowTracker as
| (BaseWindowTracker & {
getDiagnosticState?: () => { targetPid?: number | null } & Record<string, unknown>;
})
| null;
const trackerState = tracker?.getDiagnosticState?.();
const flags = window as unknown as Record<string, unknown>;
const minimized = tracker?.isTargetWindowMinimized?.() ?? false;
const tracking = tracker?.isTracking() ?? false;
// The overlay may be requested with no mpv to attach to (auto_start_overlay, tray,
// --show-visible-overlay), so it only counts as stalled once an mpv has answered on the
// socket. That still covers an mpv whose window never matches, which never starts tracking.
const mpvIdentified = tracking || (trackerState?.targetPid ?? null) !== null;
return {
...trackerState,
expectedVisible:
args.visibleOverlayVisible &&
mpvIdentified &&
!args.modalActive &&
!args.suspendVisibleOverlay &&
!minimized,
visible: window.isVisible(),
opacity: window.getOpacity?.() ?? 1,
contentReady: flags[OVERLAY_WINDOW_CONTENT_READY_FLAG] === true,
documentLoaded: flags[OVERLAY_WINDOW_DOCUMENT_LOADED_FLAG] === true,
rendererLoading: window.webContents?.isLoading?.() ?? null,
tracking,
trackerInitialized: tracker !== null,
geometry: tracker?.getGeometry() ?? null,
focused: tracker?.isTargetWindowFocused?.() ?? false,
minimized,
};
}
export function watchWindowsOverlayVisibility(args: OverlayVisibilityWatchArgs): void {
const window = args.mainWindow;
let diagnostics = diagnosticsByWindow.get(window);
if (!diagnostics) {
diagnostics = createOverlayVisibilityDiagnostics({
warn: (message, details) => log.warn(message, details),
now: Date.now,
schedule: setTimeout,
cancel: clearTimeout,
});
diagnosticsByWindow.set(window, diagnostics);
}
diagnostics.update(() => readOverlayVisibilitySnapshot(args));
}
@@ -589,6 +589,34 @@ runScenarios([
},
]);
test('only a live Windows overlay reads visibility diagnostics', () => {
const diagnosticReads = (platform: Platform, overrides: Partial<VisibilityArgs> = {}): number => {
let reads = 0;
createHarness({ platform, tracker: tracked() }).run({
windowTracker: {
isTracking: () => true,
getGeometry: () => GEOMETRY,
getDiagnosticState: () => {
reads += 1;
return { targetPid: 4242 };
},
} as unknown as VisibilityArgs['windowTracker'],
...overrides,
});
return reads;
};
assert.equal(diagnosticReads('windows'), 1);
assert.equal(diagnosticReads('linux'), 0);
assert.equal(diagnosticReads('macos'), 0);
assert.equal(
diagnosticReads('windows', {
mainWindow: { isDestroyed: () => true } as unknown as VisibilityArgs['mainWindow'],
}),
0,
);
});
test('Windows visible overlay restores opacity and rebinds after the deferred reveal delay', async () => {
const h = createHarness({ platform: 'windows', tracker: tracked() });
assertOutcome(h.run(), { opacity: 0, zOrderSyncs: 1 });
+11 -1
View File
@@ -3,6 +3,7 @@ import { BaseWindowTracker } from '../../window-trackers';
import { WindowGeometry } from '../../types';
import { applyOverlayClickThrough } from './overlay-click-through';
import { OVERLAY_WINDOW_CONTENT_READY_FLAG } from './overlay-window-flags';
import { watchWindowsOverlayVisibility } from './overlay-visibility-diagnostics';
const WINDOWS_OVERLAY_REVEAL_DELAY_MS = 48;
const pendingWindowsOverlayRevealTimeoutByWindow = new WeakMap<
@@ -65,7 +66,7 @@ function isOverlayWindowContentReady(window: BrowserWindow): boolean {
);
}
export function updateVisibleOverlayVisibility(args: {
function applyVisibleOverlayVisibility(args: {
visibleOverlayVisible: boolean;
modalActive?: boolean;
forceMousePassthrough?: boolean;
@@ -453,6 +454,15 @@ export function updateVisibleOverlayVisibility(args: {
args.syncOverlayShortcuts();
}
export function updateVisibleOverlayVisibility(
args: Parameters<typeof applyVisibleOverlayVisibility>[0],
): void {
applyVisibleOverlayVisibility(args);
if (args.isWindowsPlatform && args.mainWindow && !args.mainWindow.isDestroyed()) {
watchWindowsOverlayVisibility({ ...args, mainWindow: args.mainWindow });
}
}
export function setVisibleOverlayVisible(options: {
visible: boolean;
setVisibleOverlayVisibleState: (visible: boolean) => void;
+3 -1
View File
@@ -1118,7 +1118,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
aniskipEnabled: configService.getConfig().mpv.aniskipEnabled,
aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey,
}),
resolveMetadataForFile: (mediaPath) => resolveAniSkipMetadataForFile(mediaPath),
resolveMetadataForFile: (mediaPath, episodeLength) =>
resolveAniSkipMetadataForFile(mediaPath, { episodeLength }),
sendMpvCommand: (command) => {
appState.mpvClient?.send({ command });
},
@@ -1163,6 +1164,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
});
client.on('connection-change', aniSkipRuntime.handleConnectionChange);
client.on('media-path-change', aniSkipRuntime.handleMediaPathChange);
client.on('duration-change', aniSkipRuntime.handleDurationChange);
client.on('time-pos-change', aniSkipRuntime.handleTimePosChange);
client.on('client-message', aniSkipRuntime.handleClientMessage);
deps.getPluginHost().attachMpvClient(client);
+116
View File
@@ -0,0 +1,116 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { classifyChapterSkipIntervals } from './aniskip-chapters';
const DURATION = 1440;
function chapters(...entries: Array<[number, string]>) {
return entries.map(([time, title]) => ({ time, title }));
}
test('finds named openings and endings case-insensitively', () => {
const result = classifyChapterSkipIntervals(
chapters([0, 'Prologue'], [95, 'OPENING'], [185, 'Part A'], [1310, 'Ending'], [1400, 'Next']),
DURATION,
);
assert.deepEqual(result, {
intro: { start: 95, end: 185 },
outro: { start: 1310, end: 1400 },
});
});
test('matches short OP/ED titles but not words that merely start with them', () => {
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Op'], [90, 'Episode'], [1350, 'ED']), DURATION),
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
);
assert.deepEqual(
classifyChapterSkipIntervals(
chapters([0, 'OP "Song Title"'], [90, 'Episode'], [1350, 'ED "Song Title"']),
DURATION,
),
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Operation'], [500, 'Editing']), DURATION),
{ intro: null, outro: null },
);
});
test('recognises Japanese chapter names', () => {
assert.deepEqual(
classifyChapterSkipIntervals(
chapters([0, 'アバン'], [60, 'オープニング'], [150, '本編'], [1330, 'エンディング']),
DURATION,
),
{ intro: { start: 60, end: 150 }, outro: { start: 1330, end: 1440 } },
);
});
test('accepts outro and credits names, with bare "Credits" only in the second half', () => {
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Outro']), DURATION).outro,
{ start: 1350, end: 1440 },
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Closing Credits']), DURATION)
.outro,
{ start: 1350, end: 1440 },
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Credits'], [90, 'Episode']), DURATION).outro,
null,
);
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Credits']), DURATION).outro,
{ start: 1350, end: 1440 },
);
});
test('falls back to song-length heuristics when the file has at least three chapters', () => {
const result = classifyChapterSkipIntervals(
chapters(
[0, 'Chapter 1'],
[60, 'Chapter 2'], // 60 s long, in the first 30%
[120, 'Chapter 3'], // 88 s long, nearest 90 s
[208, 'Chapter 4'],
[1100, 'Chapter 5'], // starts after 70% but 230 s long
[1330, 'Chapter 6'], // first song-length chapter after 70%
[1420, 'Chapter 7'],
),
DURATION,
);
assert.deepEqual(result, {
intro: { start: 120, end: 208 },
outro: { start: 1330, end: 1420 },
});
});
test('skips heuristics for files with fewer than three chapters', () => {
assert.deepEqual(
classifyChapterSkipIntervals(chapters([0, 'Chapter 1'], [1350, 'Chapter 2']), DURATION),
{ intro: null, outro: null },
);
});
test("ignores SubMiner's own AniSkip marker chapters", () => {
const result = classifyChapterSkipIntervals(
chapters(
[0, 'Episode'],
[10, 'AniSkip Intro Start'],
[100, 'AniSkip Intro End'],
[1330, 'AniSkip Outro Start'],
[1420, 'AniSkip Outro End'],
),
DURATION,
);
assert.deepEqual(result, { intro: null, outro: null });
});
test('returns nothing without a usable duration or chapter list', () => {
assert.deepEqual(classifyChapterSkipIntervals(chapters([0, 'Opening'], [90, 'A']), 0), {
intro: null,
outro: null,
});
assert.deepEqual(classifyChapterSkipIntervals(null, DURATION), { intro: null, outro: null });
});
+124
View File
@@ -0,0 +1,124 @@
/** A skippable time range in seconds. */
export interface SkipInterval {
start: number;
end: number;
}
export interface ChapterSkipIntervals {
intro: SkipInterval | null;
outro: SkipInterval | null;
}
/** Prefix of the marker chapters SubMiner writes; never treated as the file's own chapters. */
export const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
interface Chapter {
title: string;
start: number;
end: number;
}
const MIN_HEURISTIC_CHAPTERS = 3;
const MIN_SONG_SECONDS = 55;
const MAX_SONG_SECONDS = 150;
const TYPICAL_OPENING_SECONDS = 90;
function isSongLength(chapter: Chapter): boolean {
const length = chapter.end - chapter.start;
return length >= MIN_SONG_SECONDS && length <= MAX_SONG_SECONDS;
}
/**
* Turns mpv's `chapter-list` (entries with `time` and `title`) into sorted
* chapters with an end time (the next chapter's start, or the duration),
* dropping SubMiner's own AniSkip marker chapters.
*/
function toChapters(chapterList: unknown, duration: number): Chapter[] {
if (!Array.isArray(chapterList)) return [];
const starts: Array<{ title: string; start: number }> = [];
for (const entry of chapterList) {
if (typeof entry !== 'object' || entry === null) continue;
const { time, title } = entry as { time?: unknown; title?: unknown };
if (typeof time !== 'number' || !Number.isFinite(time) || time < 0 || time >= duration) {
continue;
}
const text = typeof title === 'string' ? title : '';
if (text.startsWith(ANISKIP_CHAPTER_PREFIX)) continue;
starts.push({ title: text, start: time });
}
starts.sort((a, b) => a.start - b.start);
return starts.map((chapter, index) => ({
...chapter,
end: starts[index + 1]?.start ?? duration,
}));
}
function isNamedOpening(chapter: Chapter): boolean {
const title = chapter.title.trim().toLowerCase();
return (
title.includes('opening') ||
title === 'op' ||
title.startsWith('op ') ||
chapter.title.includes('オープニング')
);
}
function isNamedEnding(chapter: Chapter, duration: number): boolean {
const title = chapter.title.trim().toLowerCase();
return (
title.includes('ending') ||
title === 'ed' ||
title === 'outro' ||
title === 'end credits' ||
title === 'closing credits' ||
(title === 'credits' && chapter.start > duration * 0.5) ||
title.startsWith('ed ') ||
chapter.title.includes('エンディング')
);
}
function findOpening(chapters: Chapter[], duration: number): Chapter | null {
const named = chapters.find(isNamedOpening);
if (named) return named;
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
let best: Chapter | null = null;
for (const chapter of chapters) {
if (chapter.start >= duration * 0.3 || !isSongLength(chapter)) continue;
const distance = Math.abs(chapter.end - chapter.start - TYPICAL_OPENING_SECONDS);
if (!best || distance < Math.abs(best.end - best.start - TYPICAL_OPENING_SECONDS)) {
best = chapter;
}
}
return best;
}
function findEnding(chapters: Chapter[], duration: number): Chapter | null {
const named = chapters.find((chapter) => isNamedEnding(chapter, duration));
if (named) return named;
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
return (
chapters.find((chapter) => chapter.start > duration * 0.7 && isSongLength(chapter)) ?? null
);
}
function toInterval(chapter: Chapter | null): SkipInterval | null {
return chapter && chapter.end > chapter.start ? { start: chapter.start, end: chapter.end } : null;
}
/**
* Finds the opening and ending in a file's own chapters: by name first
* ("Opening", "OP", "ED", "Credits", オープニング, ...), else by length and
* position when the file has at least three chapters. Rules follow Telly's
* `media.rs` opening()/ending().
*/
export function classifyChapterSkipIntervals(
chapterList: unknown,
duration: number,
): ChapterSkipIntervals {
if (!Number.isFinite(duration) || duration <= 0) return { intro: null, outro: null };
const chapters = toChapters(chapterList, duration);
return {
intro: toInterval(findOpening(chapters, duration)),
outro: toInterval(findEnding(chapters, duration)),
};
}
+120 -34
View File
@@ -3,17 +3,21 @@ import assert from 'node:assert/strict';
import {
inferAniSkipMetadataForFile,
parseAniSkipGuessitJson,
parseAniSkipPayload,
resolveAniSkipMetadataForFile,
} from './aniskip-metadata';
function makeMockResponse(payload: unknown): Response {
return {
ok: true,
status: 200,
json: async () => payload,
} as Response;
const LOOKUP = { episodeLength: 1440 };
function makeMockResponse(payload: unknown, status = 200): Response {
return new Response(JSON.stringify(payload), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
const MAL_MY_SHOW = { categories: [{ items: [{ id: '1234', name: 'My Show' }] }] };
function normalizeFetchInput(input: string | URL | Request): string {
if (typeof input === 'string') return input;
if (input instanceof URL) return input.toString();
@@ -46,8 +50,8 @@ test('parseAniSkipGuessitJson extracts title season and episode', () => {
episode: 7,
source: 'guessit',
malId: null,
introStart: null,
introEnd: null,
intro: null,
outro: null,
lookupStatus: 'lookup_failed',
});
});
@@ -68,8 +72,8 @@ test('parseAniSkipGuessitJson prefers series over episode title', () => {
episode: 10,
source: 'guessit',
malId: null,
introStart: null,
introEnd: null,
intro: null,
outro: null,
lookupStatus: 'lookup_failed',
});
});
@@ -111,10 +115,58 @@ test('inferAniSkipMetadataForFile handles release-group filename with trailing q
assert.equal(parsed.source, 'fallback');
});
test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async () => {
test('parseAniSkipPayload reads op and ed from a v2 response', () => {
// Shape captured from api.aniskip.com/v2 on 2026-11-22.
const parsed = parseAniSkipPayload({
found: true,
results: [
{
interval: { startTime: 310.571, endTime: 400.571 },
skipType: 'op',
skipId: 'd4f34b6d-0547-4438-ac93-b25b577eddd5',
episodeLength: 1443.984,
},
{
interval: { startTime: 1396.006, endTime: 1434 },
skipType: 'ed',
skipId: '5751c57a-2bcd-4dd9-be93-58e6af0f8c81',
episodeLength: 1434.985,
},
],
message: 'Successfully found skip times',
statusCode: 200,
});
assert.deepEqual(parsed, {
intro: { start: 310.571, end: 400.571 },
outro: { start: 1396.006, end: 1434 },
});
});
test('parseAniSkipPayload ignores invalid intervals and not-found responses', () => {
assert.deepEqual(
parseAniSkipPayload({
found: true,
results: [
{ skipType: 'op', interval: { startTime: 50, endTime: 20 } },
{ skipType: 'op', interval: { startTime: 0, endTime: 89.5 } },
{ skipType: 'recap', interval: { startTime: 0, endTime: 30 } },
],
}),
{ intro: { start: 0, end: 89.5 }, outro: null },
);
assert.deepEqual(parseAniSkipPayload({ found: false, results: [] }), {
intro: null,
outro: null,
});
assert.deepEqual(parseAniSkipPayload(null), { intro: null, outro: null });
});
test('resolveAniSkipMetadataForFile queries AniSkip v2 with the episode length', async () => {
const requested: string[] = [];
await withMockFetch(
async (input) => {
const url = normalizeFetchInput(input);
requested.push(url);
if (url.includes('myanimelist.net/search/prefix.json')) {
return makeMockResponse({
categories: [
@@ -127,48 +179,82 @@ test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async ()
],
});
}
if (url.includes('api.aniskip.com/v1/skip-times/1234/7')) {
if (url.includes('api.aniskip.com/v2/skip-times/1234/7')) {
return makeMockResponse({
found: true,
results: [{ skip_type: 'op', interval: { start_time: 12.5, end_time: 54.2 } }],
results: [
{ skipType: 'op', interval: { startTime: 12.5, endTime: 54.2 } },
{ skipType: 'ed', interval: { startTime: 1300, endTime: 1390 } },
],
});
}
throw new Error(`unexpected url: ${url}`);
},
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv');
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv', {
episodeLength: 1423.4567,
});
assert.equal(resolved.malId, 1234);
assert.equal(resolved.introStart, 12.5);
assert.equal(resolved.introEnd, 54.2);
assert.deepEqual(resolved.intro, { start: 12.5, end: 54.2 });
assert.deepEqual(resolved.outro, { start: 1300, end: 1390 });
assert.equal(resolved.lookupStatus, 'ready');
assert.equal(resolved.title, 'Anime My Show');
},
);
assert.equal(
requested[1],
'https://api.aniskip.com/v2/skip-times/1234/7?types=op&types=ed&episodeLength=1423.457',
);
});
test('resolveAniSkipMetadataForFile accepts intro payload starting at zero', async () => {
test('resolveAniSkipMetadataForFile treats an AniSkip 404 as a definite miss', async () => {
await withMockFetch(
async (input) => {
const url = normalizeFetchInput(input);
if (url.includes('myanimelist.net/search/prefix.json')) {
return makeMockResponse({
categories: [{ items: [{ id: '1234', name: 'My Show' }] }],
});
}
if (url.includes('api.aniskip.com/v1/skip-times/1234/1')) {
return makeMockResponse({
found: true,
results: [{ skip_type: 'op', interval: { start_time: 0, end_time: 89.5 } }],
});
}
throw new Error(`unexpected url: ${url}`);
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
return makeMockResponse(
{ found: false, results: [], message: 'No skip times found', statusCode: 404 },
404,
);
},
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E01.mkv');
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E02.mkv', LOOKUP);
assert.equal(resolved.malId, 1234);
assert.equal(resolved.introStart, 0);
assert.equal(resolved.introEnd, 89.5);
assert.equal(resolved.lookupStatus, 'ready');
assert.equal(resolved.lookupStatus, 'missing_payload');
},
);
});
test('resolveAniSkipMetadataForFile reports transient failures as lookup_failed', async () => {
const failures: Array<[string, () => Promise<Response>]> = [
['AniSkip rate limit', async () => makeMockResponse({ statusCode: 429 }, 429)],
['AniSkip server error', async () => makeMockResponse({ statusCode: 503 }, 503)],
[
'network error',
async () => {
throw new TypeError('fetch failed');
},
],
];
for (const [label, failAniSkip] of failures) {
await withMockFetch(
async (input) => {
const url = normalizeFetchInput(input);
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
return failAniSkip();
},
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
assert.equal(resolved.lookupStatus, 'lookup_failed', label);
},
);
}
await withMockFetch(
async () => makeMockResponse({}, 429),
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
assert.equal(resolved.lookupStatus, 'lookup_failed', 'MAL rate limit');
},
);
});
@@ -177,7 +263,7 @@ test('resolveAniSkipMetadataForFile emits missing_mal_id when MAL search misses'
await withMockFetch(
async () => makeMockResponse({ categories: [] }),
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv');
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv', LOOKUP);
assert.equal(resolved.malId, null);
assert.equal(resolved.lookupStatus, 'missing_mal_id');
},
+98 -84
View File
@@ -1,6 +1,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import type { SkipInterval } from './aniskip-chapters';
export type AniSkipLookupStatus =
| 'ready'
@@ -15,11 +16,16 @@ export interface AniSkipMetadata {
episode: number | null;
source: 'guessit' | 'fallback';
malId: number | null;
introStart: number | null;
introEnd: number | null;
intro: SkipInterval | null;
outro: SkipInterval | null;
lookupStatus?: AniSkipLookupStatus;
}
export interface AniSkipLookupOptions {
/** Length of the playing file in seconds; AniSkip v2 uses it to pick times marked on the same cut. */
episodeLength: number;
}
interface InferAniSkipDeps {
commandExists: (name: string) => boolean;
runGuessit: (mediaPath: string) => string | null;
@@ -39,12 +45,12 @@ interface MalSearchResponse {
}
interface AniSkipIntervalPayload {
start_time?: unknown;
end_time?: unknown;
startTime?: unknown;
endTime?: unknown;
}
interface AniSkipSkipItemPayload {
skip_type?: unknown;
skipType?: unknown;
interval?: unknown;
}
@@ -61,9 +67,12 @@ const ROMAN_SEASON_ALIASES: Record<number, readonly string[]> = {
};
const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword=';
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v1/skip-times/';
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v2/skip-times/';
const ANISKIP_USER_AGENT = 'SubMiner/ani-skip';
const ANISKIP_FETCH_TIMEOUT_MS = 8000;
// AniSkip allows 120 requests a minute; one lookup per file load stays far below that,
// but a gap keeps fast playlist skipping from bursting.
const ANISKIP_MIN_REQUEST_GAP_MS = 1000;
const MAL_MATCH_STOPWORDS = new Set([
'the',
'this',
@@ -261,49 +270,71 @@ function toMalSearchItems(payload: unknown): MalSearchResult[] {
return items;
}
function parseAniSkipPayload(payload: unknown): { start: number; end: number } | null {
const parsed = payload as AniSkipPayloadResponse;
const results = Array.isArray(parsed?.results) ? parsed.results : null;
if (!results) return null;
for (const rawResult of results) {
const result = rawResult as AniSkipSkipItemPayload;
if (
result.skip_type !== 'op' ||
typeof result.interval !== 'object' ||
result.interval === null
) {
continue;
}
const interval = result.interval as AniSkipIntervalPayload;
const start = toNonNegativeNumber(interval?.start_time);
const end = toPositiveNumber(interval?.end_time);
if (start !== null && end !== null && end > start) {
return { start, end };
}
}
return null;
function parseInterval(raw: unknown): SkipInterval | null {
if (typeof raw !== 'object' || raw === null) return null;
const interval = raw as AniSkipIntervalPayload;
const start = toNonNegativeNumber(interval.startTime);
const end = toPositiveNumber(interval.endTime);
return start !== null && end !== null && end > start ? { start, end } : null;
}
async function fetchJson<T>(url: string): Promise<T | null> {
/** Reads the first valid opening (`op`) and ending (`ed`) from an AniSkip v2 response. */
export function parseAniSkipPayload(payload: unknown): {
intro: SkipInterval | null;
outro: SkipInterval | null;
} {
const parsed = payload as AniSkipPayloadResponse | null;
const results = parsed?.found === true && Array.isArray(parsed.results) ? parsed.results : [];
let intro: SkipInterval | null = null;
let outro: SkipInterval | null = null;
for (const rawResult of results) {
const result = rawResult as AniSkipSkipItemPayload;
if (result.skipType === 'op' && !intro) intro = parseInterval(result.interval);
if (result.skipType === 'ed' && !outro) outro = parseInterval(result.interval);
}
return { intro, outro };
}
/**
* Fetches JSON. A 404 is a definite "nothing here" and returns null; any other
* failure (non-OK status, network error, timeout, bad JSON) throws so callers
* report a retryable lookup failure instead of caching a miss.
*/
async function fetchJson(url: string): Promise<unknown> {
const response = await fetch(url, {
headers: {
'User-Agent': ANISKIP_USER_AGENT,
},
signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS),
});
if (!response.ok) return null;
try {
return (await response.json()) as T;
} catch {
return null;
if (response.status === 404) return null;
if (!response.ok) {
throw new Error(`HTTP ${response.status} from ${new URL(url).host}`);
}
return await response.json();
}
let lastAniSkipRequestAt = 0;
let aniSkipRequestQueue: Promise<void> = Promise.resolve();
/**
* Resolves when the caller may send its AniSkip request. Callers are released
* one at a time, each at least ANISKIP_MIN_REQUEST_GAP_MS after the previous
* release, so timers that fire late cannot release a burst.
*/
function waitForAniSkipRequestSlot(): Promise<void> {
const slot = aniSkipRequestQueue.then(async () => {
const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now();
if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
lastAniSkipRequestAt = Date.now();
});
aniSkipRequestQueue = slot;
return slot;
}
async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> {
const lookup = season && season > 1 ? `${title} Season ${season}` : title;
const payload = await fetchJson<unknown>(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
const payload = await fetchJson(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
const items = toMalSearchItems(payload);
if (!items.length) return null;
@@ -326,16 +357,17 @@ async function resolveMalIdFromTitle(title: string, season: number | null): Prom
return bestMalId;
}
async function fetchAniSkipPayload(
async function fetchAniSkipIntervals(
malId: number,
episode: number,
): Promise<{ start: number; end: number } | null> {
const payload = await fetchJson<unknown>(
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed`,
episodeLength: number,
): Promise<{ intro: SkipInterval | null; outro: SkipInterval | null }> {
await waitForAniSkipRequestSlot();
const length = Math.round(episodeLength * 1000) / 1000;
const payload = await fetchJson(
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed&episodeLength=${length}`,
);
const parsed = payload as AniSkipPayloadResponse;
if (!parsed || parsed.found !== true) return null;
return parseAniSkipPayload(parsed);
return parseAniSkipPayload(payload);
}
function detectEpisodeFromName(baseName: string): number | null {
@@ -456,8 +488,8 @@ export function parseAniSkipGuessitJson(stdout: string, mediaPath: string): AniS
episode: episodeFromDirect ?? episodeFromList,
source: 'guessit',
malId: null,
introStart: null,
introEnd: null,
intro: null,
outro: null,
lookupStatus: 'lookup_failed',
};
} catch {
@@ -501,13 +533,20 @@ export function inferAniSkipMetadataForFile(
episode: detectEpisodeFromName(baseName),
source: 'fallback',
malId: null,
introStart: null,
introEnd: null,
intro: null,
outro: null,
lookupStatus: 'lookup_failed',
};
}
export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<AniSkipMetadata> {
/**
* Resolves a local file's MAL id and AniSkip opening/ending. Statuses other
* than `lookup_failed` are definite answers that callers may cache.
*/
export async function resolveAniSkipMetadataForFile(
mediaPath: string,
options: AniSkipLookupOptions,
): Promise<AniSkipMetadata> {
const inferred = inferAniSkipMetadataForFile(mediaPath);
if (!inferred.title) {
return { ...inferred, lookupStatus: 'lookup_failed' };
@@ -516,50 +555,25 @@ export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<
try {
const malId = await resolveMalIdFromTitle(inferred.title, inferred.season);
if (!malId) {
return {
...inferred,
malId: null,
introStart: null,
introEnd: null,
lookupStatus: 'missing_mal_id',
};
return { ...inferred, lookupStatus: 'missing_mal_id' };
}
if (!inferred.episode) {
return {
...inferred,
malId,
introStart: null,
introEnd: null,
lookupStatus: 'missing_episode',
};
}
const payload = await fetchAniSkipPayload(malId, inferred.episode);
if (!payload) {
return {
...inferred,
malId,
introStart: null,
introEnd: null,
lookupStatus: 'missing_payload',
};
return { ...inferred, malId, lookupStatus: 'missing_episode' };
}
const { intro, outro } = await fetchAniSkipIntervals(
malId,
inferred.episode,
options.episodeLength,
);
return {
...inferred,
malId,
introStart: payload.start,
introEnd: payload.end,
lookupStatus: 'ready',
intro,
outro,
lookupStatus: intro || outro ? 'ready' : 'missing_payload',
};
} catch {
return {
...inferred,
malId: inferred.malId,
introStart: inferred.introStart,
introEnd: inferred.introEnd,
lookupStatus: 'lookup_failed',
};
return { ...inferred, lookupStatus: 'lookup_failed' };
}
}
+310 -30
View File
@@ -10,19 +10,22 @@ function readyMetadata(overrides: Partial<AniSkipMetadata> = {}): AniSkipMetadat
episode: 1,
source: 'fallback',
malId: 1234,
introStart: 10,
introEnd: 95.5,
intro: { start: 10, end: 95.5 },
outro: null,
lookupStatus: 'ready',
...overrides,
};
}
const NO_SKIP_TIMES = { intro: null, outro: null } as const;
function createHarness(options?: {
enabled?: boolean;
buttonKey?: string;
metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>);
chapterList?: unknown;
playbackFeedback?: boolean;
duration?: number | null;
}) {
const state = {
enabled: options?.enabled ?? true,
@@ -31,9 +34,14 @@ function createHarness(options?: {
osd: [] as string[],
feedback: [] as string[],
resolveCalls: [] as string[],
episodeLengths: [] as number[],
connected: true,
duration: options?.duration === undefined ? 1440 : options.duration,
timePos: 0,
chapterList: options?.chapterList ?? [],
chapterListFails: false,
// When set, chapter-list reads wait for it before answering.
chapterGate: null as Promise<void> | null,
};
const deps = {
@@ -41,8 +49,9 @@ function createHarness(options?: {
aniskipEnabled: state.enabled,
aniskipButtonKey: state.buttonKey,
}),
resolveMetadataForFile: async (mediaPath) => {
resolveMetadataForFile: async (mediaPath, episodeLength) => {
state.resolveCalls.push(mediaPath);
state.episodeLengths.push(episodeLength);
const metadata = options?.metadata;
if (typeof metadata === 'function') return metadata();
return metadata ?? readyMetadata();
@@ -51,7 +60,15 @@ function createHarness(options?: {
state.commands.push(command);
},
requestMpvProperty: async (name) => {
if (name === 'chapter-list') return state.chapterList;
if (name === 'chapter-list') {
if (state.chapterGate) await state.chapterGate;
if (state.chapterListFails) throw new Error('property unavailable');
return state.chapterList;
}
if (name === 'duration') {
if (state.duration === null) throw new Error('property unavailable');
return state.duration;
}
return null;
},
isMpvConnected: () => state.connected,
@@ -84,6 +101,10 @@ async function flushAsync(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
function seekCommands(commands: unknown[][]): unknown[][] {
return commands.filter((command) => command[0] === 'set_property' && command[1] === 'time-pos');
}
test('isRemoteMediaPath detects URLs but not local paths', () => {
assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true);
assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true);
@@ -101,6 +122,7 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
await flushAsync();
assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']);
assert.deepEqual(state.episodeLengths, [1440]);
const chapterCommands = chapterListCommands(state.commands);
assert.equal(chapterCommands.length, 1);
const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>;
@@ -109,7 +131,10 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
{ time: 10, title: 'AniSkip Intro Start' },
{ time: 95.5, title: 'AniSkip Intro End' },
]);
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 10, end: 95.5, source: 'aniskip' },
outro: null,
});
});
test('remote media paths and disabled config never resolve', async () => {
@@ -131,21 +156,18 @@ test('skip intro seeks to intro end only inside the intro window', async () => {
state.timePos = 200;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Skip intro only during intro']);
assert.deepEqual(state.osd, ['Skip only during intro or outro']);
state.timePos = 30;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Skip intro only during intro', 'Skipped intro']);
const seek = state.commands.find(
(command) => command[0] === 'set_property' && command[1] === 'time-pos',
);
assert.deepEqual(seek, ['set_property', 'time-pos', 95.5]);
assert.deepEqual(state.osd, ['Skip only during intro or outro', 'Skipped intro']);
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 95.5]]);
});
test('skip intro reports unavailable when no window was found', () => {
const { runtime, state } = createHarness();
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Intro skip unavailable']);
assert.deepEqual(state.osd, ['Intro/outro skip unavailable']);
});
test('time-pos prompt shows once near intro start', async () => {
@@ -158,7 +180,7 @@ test('time-pos prompt shows once near intro start', async () => {
runtime.handleTimePosChange({ time: 10.5 });
runtime.handleTimePosChange({ time: 11 });
assert.deepEqual(state.osd, ['You can skip by pressing TAB']);
assert.deepEqual(state.osd, ['You can skip the intro by pressing TAB']);
});
test('prompt and skip messages use playback feedback when configured', async () => {
@@ -170,7 +192,7 @@ test('prompt and skip messages use playback feedback when configured', async ()
state.timePos = 30;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.feedback, ['You can skip by pressing TAB', 'Skipped intro']);
assert.deepEqual(state.feedback, ['You can skip the intro by pressing TAB', 'Skipped intro']);
assert.deepEqual(state.osd, []);
});
@@ -240,18 +262,13 @@ test('aniskip refresh forces a fresh lookup for the current media', async () =>
assert.equal(state.resolveCalls.length, 2);
});
test('media without an intro window is cached and never re-resolved on reload of another file', async () => {
test('definite misses are cached and not looked up again for the same file', async () => {
const { runtime, state } = createHarness({
metadata: readyMetadata({
malId: 1234,
introStart: null,
introEnd: null,
lookupStatus: 'missing_payload',
}),
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(runtime.getIntroWindow(), null);
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
assert.equal(chapterListCommands(state.commands).length, 0);
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
@@ -261,25 +278,117 @@ test('media without an intro window is cached and never re-resolved on reload of
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']);
});
test('transient lookup failures are retried on the next media load', async () => {
let failures = 0;
test('transient lookup failures are not cached and retry on the next media load', async () => {
let calls = 0;
const { runtime, state } = createHarness({
metadata: async () => {
failures += 1;
return readyMetadata(
failures === 1 ? { introStart: null, introEnd: null, lookupStatus: 'lookup_failed' } : {},
);
calls += 1;
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
},
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(runtime.getIntroWindow(), null);
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
runtime.handleMediaPathChange({ path: '' });
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(state.resolveCalls.length, 2);
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
});
test('resolution waits for a known duration before reading chapters or AniSkip', async () => {
const { runtime, state } = createHarness({ duration: null });
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, []);
runtime.handleDurationChange({ duration: 1425.2 });
await flushAsync();
assert.deepEqual(state.episodeLengths, [1425.2]);
});
test('file chapters with both an opening and an ending skip the AniSkip lookup', async () => {
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Prologue' },
{ time: 120, title: 'Opening' },
{ time: 210, title: 'Part A' },
{ time: 1300, title: 'Ending' },
{ time: 1390, title: 'Preview' },
],
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, []);
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 120, end: 210, source: 'chapters' },
outro: { start: 1300, end: 1390, source: 'chapters' },
});
// The file already has chapter boundaries there, so no AniSkip markers are added.
assert.equal(chapterListCommands(state.commands).length, 0);
});
test('AniSkip fills in the window the file chapters lack', async () => {
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Opening' },
{ time: 90, title: 'Episode' },
],
metadata: readyMetadata({
intro: { start: 3, end: 93 },
outro: { start: 1330, end: 1420 },
}),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(state.resolveCalls.length, 1);
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 0, end: 90, source: 'chapters' },
outro: { start: 1330, end: 1420, source: 'aniskip' },
});
assert.deepEqual(chapterListCommands(state.commands)[0]![2], [
{ time: 0, title: 'Opening' },
{ time: 90, title: 'Episode' },
{ time: 1330, title: 'AniSkip Outro Start' },
{ time: 1420, title: 'AniSkip Outro End' },
]);
});
test('remote streams use file chapters without an AniSkip lookup', async () => {
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Intro' },
{ time: 30, title: 'OP' },
{ time: 120, title: 'Episode' },
],
});
runtime.handleMediaPathChange({ path: 'https://jellyfin.example/Videos/1/stream.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, []);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 30, end: 120, source: 'chapters' });
});
test('skip key skips the outro inside its window and prompts at its start', async () => {
const { runtime, state } = createHarness({
metadata: readyMetadata({ outro: { start: 1330, end: 1420 } }),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleTimePosChange({ time: 1331 });
runtime.handleTimePosChange({ time: 1332 });
assert.deepEqual(state.osd, ['You can skip the outro by pressing TAB']);
state.timePos = 1329.8;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
state.timePos = 1425;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 1420]]);
assert.deepEqual(state.osd.slice(1), ['Skipped outro', 'Skip only during intro or outro']);
});
test('disconnect clears bindings so reconnect rebinds the skip key', () => {
@@ -292,3 +401,174 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => {
['keybind', 'TAB', 'script-message subminer-skip-intro'],
]);
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
test('a failed chapter-list read leaves the file chapters untouched', async () => {
const harness = createHarness({
chapterList: [{ time: 0, title: 'Prologue' }],
metadata: async () => {
harness.state.chapterListFails = true;
return readyMetadata();
},
});
harness.runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(harness.runtime.getSkipWindows().intro?.source, 'aniskip');
assert.equal(chapterListCommands(harness.state.commands).length, 0);
});
test('markers are not written into a file that replaced the one being read', async () => {
const gate = deferred<void>();
let calls = 0;
const harness = createHarness({
metadata: async () => {
calls += 1;
if (calls === 1) {
harness.state.chapterGate = gate.promise;
return readyMetadata();
}
return readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' });
},
});
harness.runtime.handleMediaPathChange({ path: '/media/a.mkv' });
await flushAsync();
// The marker write for a.mkv is waiting on its chapter-list read.
harness.runtime.handleMediaPathChange({ path: '/media/b.mkv' });
harness.state.chapterGate = null;
gate.resolve();
await flushAsync();
await flushAsync();
assert.deepEqual(harness.state.resolveCalls, ['/media/a.mkv', '/media/b.mkv']);
assert.equal(chapterListCommands(harness.state.commands).length, 0);
});
test('a file-chapter intro is usable while the AniSkip lookup is still running', async () => {
const lookup = deferred<AniSkipMetadata>();
const { runtime, state } = createHarness({
chapterList: [
{ time: 0, title: 'Opening' },
{ time: 90, title: 'Episode' },
],
metadata: () => lookup.promise,
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 0, end: 90, source: 'chapters' },
outro: null,
});
runtime.handleTimePosChange({ time: 1 });
assert.equal(state.osd.length, 1);
lookup.resolve(
readyMetadata({ intro: { start: 3, end: 93 }, outro: { start: 1330, end: 1420 } }),
);
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), {
intro: { start: 0, end: 90, source: 'chapters' },
outro: { start: 1330, end: 1420, source: 'aniskip' },
});
// The intro prompt already shown is not shown again.
runtime.handleTimePosChange({ time: 1.5 });
assert.equal(state.osd.length, 1);
});
test('a lookup superseded by a refresh does not overwrite the cache', async () => {
const first = deferred<AniSkipMetadata>();
let calls = 0;
const { runtime, state } = createHarness({
metadata: () => {
calls += 1;
return calls === 1 ? first.promise : Promise.resolve(readyMetadata());
},
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleClientMessage({ args: ['subminer-aniskip-refresh'] });
await flushAsync();
first.resolve(readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }));
await flushAsync();
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
await flushAsync();
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/show.mkv', '/media/other.mkv']);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
});
test('a same-media reload retries a transient lookup failure', async () => {
let calls = 0;
const { runtime, state } = createHarness({
metadata: async () => {
calls += 1;
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
},
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
assert.equal(state.resolveCalls.length, 2);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
});
test('a failed chapter-list read is retried on the next duration change or reload', async () => {
const stream = 'https://jellyfin.example/Videos/1/stream.mkv';
const chapters = [
{ time: 0, title: 'OP' },
{ time: 90, title: 'Episode' },
];
for (const retry of ['duration', 'reload'] as const) {
const { runtime, state } = createHarness({ chapterList: chapters });
state.chapterListFails = true;
runtime.handleMediaPathChange({ path: stream });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
state.chapterListFails = false;
if (retry === 'duration') runtime.handleDurationChange({ duration: 1440 });
else runtime.handleMediaPathChange({ path: stream });
await flushAsync();
assert.deepEqual(runtime.getSkipWindows().intro, { start: 0, end: 90, source: 'chapters' });
}
});
test('a successful empty chapter list is not read again on a duration change', async () => {
const { runtime, state } = createHarness({
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
});
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleDurationChange({ duration: 1441 });
await flushAsync();
assert.equal(state.resolveCalls.length, 1);
});
test('a cached lookup is reused only for the episode length it was fetched for', async () => {
const { runtime, state } = createHarness();
// A failing chapter read keeps resolution retrying on each duration change.
state.chapterListFails = true;
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync();
runtime.handleDurationChange({ duration: 1440 });
await flushAsync();
assert.deepEqual(state.episodeLengths, [1440]);
runtime.handleDurationChange({ duration: 1500 });
await flushAsync();
assert.deepEqual(state.episodeLengths, [1440, 1500]);
});
+276 -122
View File
@@ -1,11 +1,16 @@
import type { AniSkipMetadata } from './aniskip-metadata';
import {
ANISKIP_CHAPTER_PREFIX,
classifyChapterSkipIntervals,
type SkipInterval,
} from './aniskip-chapters';
/** mpv script-message that skips whichever of the intro or outro is playing. */
export const ANISKIP_SKIP_INTRO_MESSAGE = 'subminer-skip-intro';
export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh';
const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB';
const LEGACY_ANISKIP_BUTTON_KEY = 'y-k';
const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
const SKIP_WINDOW_EPSILON_SECONDS = 0.35;
const PROMPT_WINDOW_SECONDS = 3;
const PROMPT_OSD_DURATION_MS = 3000;
@@ -16,7 +21,7 @@ export interface AniSkipRuntimeConfig {
export interface AniSkipRuntimeDeps {
getAniSkipConfig: () => AniSkipRuntimeConfig;
resolveMetadataForFile: (mediaPath: string) => Promise<AniSkipMetadata>;
resolveMetadataForFile: (mediaPath: string, episodeLength: number) => Promise<AniSkipMetadata>;
sendMpvCommand: (command: unknown[]) => void;
requestMpvProperty: (name: string) => Promise<unknown>;
isMpvConnected: () => boolean;
@@ -28,26 +33,65 @@ export interface AniSkipRuntimeDeps {
logDebug: (message: string) => void;
}
export interface AniSkipIntroWindow {
start: number;
end: number;
export type SkipWindowKind = 'intro' | 'outro';
export interface AniSkipWindow extends SkipInterval {
/** `chapters` = the file's own chapters; `aniskip` = the AniSkip database. */
source: 'chapters' | 'aniskip';
}
export interface AniSkipWindows {
intro: AniSkipWindow | null;
outro: AniSkipWindow | null;
}
interface AniSkipLookupResult {
intro: SkipInterval | null;
outro: SkipInterval | null;
malId: number | null;
}
type MpvChapter = { time?: unknown; title?: unknown };
const KIND_LABEL: Record<SkipWindowKind, { chapter: string; word: string }> = {
intro: { chapter: 'Intro', word: 'intro' },
outro: { chapter: 'Outro', word: 'outro' },
};
export function isRemoteMediaPath(mediaPath: string): boolean {
return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim());
}
function isAniSkipChapter(chapter: MpvChapter): boolean {
return typeof chapter?.title === 'string' && chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX);
}
function isUsableDuration(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value > 0;
}
/**
* Finds the intro and outro for each loaded file (file chapters first, then
* AniSkip for whatever the chapters lack), marks them as chapters, prompts when
* one starts, and skips the active one when the skip key is pressed.
*/
export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
let requestGeneration = 0;
let currentMediaPath = '';
let introWindow: AniSkipIntroWindow | null = null;
let promptShown = false;
let currentDuration: number | null = null;
// True once resolution for the current media has started (or finished).
let resolutionStarted = false;
// True when resolution for the current media hit a retryable failure (the
// chapter-list read or the AniSkip lookup), so a reload or duration change
// runs it again.
let retryResolution = false;
let windows: AniSkipWindows = { intro: null, outro: null };
const promptShown: Record<SkipWindowKind, boolean> = { intro: false, outro: false };
let boundButtonKey: string | null = null;
let legacyFallbackBound = false;
const introWindowCache = new Map<string, AniSkipIntroWindow | null>();
// AniSkip results per media path, with the episode length they were fetched
// for (v2 picks times by length). Only definitive answers are stored.
const lookupCache = new Map<string, { duration: number; result: AniSkipLookupResult }>();
function resolveButtonKey(): string {
const key = deps.getAniSkipConfig().aniskipButtonKey.trim();
@@ -93,22 +137,39 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
}
}
async function setIntroChapters(introStart: number, introEnd: number): Promise<void> {
let existing: MpvChapter[] = [];
async function readChapterList(): Promise<MpvChapter[] | null> {
try {
const chapterList = await deps.requestMpvProperty('chapter-list');
if (Array.isArray(chapterList)) {
existing = chapterList as MpvChapter[];
}
return Array.isArray(chapterList) ? (chapterList as MpvChapter[]) : [];
} catch {
// chapter-list may be unavailable mid-load; fall back to AniSkip chapters only
// chapter-list may be unavailable mid-load
return null;
}
const chapters = existing.filter(
(chapter) =>
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
);
chapters.push({ time: introStart, title: 'AniSkip Intro Start' });
chapters.push({ time: introEnd, title: 'AniSkip Intro End' });
}
/** True while the given request generation still owns the given media. */
function ownsPlayback(generation: number, mediaPath: string): boolean {
return generation === requestGeneration && mediaPath === currentMediaPath;
}
/** Replaces SubMiner's marker chapters with ones for the AniSkip-sourced windows. */
async function setSkipChapters(): Promise<void> {
const generation = requestGeneration;
const mediaPath = currentMediaPath;
const markers: MpvChapter[] = [];
for (const kind of ['intro', 'outro'] as const) {
const window = windows[kind];
if (window?.source !== 'aniskip') continue;
const label = KIND_LABEL[kind].chapter;
markers.push({ time: window.start, title: `${ANISKIP_CHAPTER_PREFIX}${label} Start` });
markers.push({ time: window.end, title: `${ANISKIP_CHAPTER_PREFIX}${label} End` });
}
if (markers.length === 0) return;
const existing = await readChapterList();
// A failed read must not wipe the file's chapters, and a read that finished
// after the media changed must not write into the next file.
if (!existing || !ownsPlayback(generation, mediaPath)) return;
const chapters = existing.filter((chapter) => !isAniSkipChapter(chapter)).concat(markers);
chapters.sort((a, b) => {
const aTime = typeof a.time === 'number' ? a.time : 0;
const bTime = typeof b.time === 'number' ? b.time : 0;
@@ -117,21 +178,13 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
deps.sendMpvCommand(['set_property', 'chapter-list', chapters]);
}
async function removeIntroChapters(): Promise<void> {
async function removeSkipChapters(): Promise<void> {
if (!deps.isMpvConnected()) return;
let existing: MpvChapter[] = [];
try {
const chapterList = await deps.requestMpvProperty('chapter-list');
if (Array.isArray(chapterList)) {
existing = chapterList as MpvChapter[];
}
} catch {
return;
}
const filtered = existing.filter(
(chapter) =>
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
);
const generation = requestGeneration;
const mediaPath = currentMediaPath;
const existing = await readChapterList();
if (!existing || !ownsPlayback(generation, mediaPath)) return;
const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter));
if (filtered.length !== existing.length) {
deps.sendMpvCommand(['set_property', 'chapter-list', filtered]);
}
@@ -139,81 +192,162 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
function clearState(): void {
requestGeneration += 1;
introWindow = null;
promptShown = false;
resolutionStarted = false;
retryResolution = false;
windows = { intro: null, outro: null };
promptShown.intro = false;
promptShown.outro = false;
}
async function applyIntroWindow(window: AniSkipIntroWindow): Promise<void> {
introWindow = window;
promptShown = false;
await setIntroChapters(window.start, window.end);
function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void {
deps.logInfo(
`AniSkip intro window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (MAL ${
window.malId ?? '-'
})`,
`AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${
window.source
}, MAL ${malId ?? '-'})`,
);
}
async function resolveForMedia(mediaPath: string, options?: { force?: boolean }): Promise<void> {
if (!deps.getAniSkipConfig().aniskipEnabled) return;
if (!mediaPath || isRemoteMediaPath(mediaPath)) {
deps.logDebug('AniSkip lookup skipped: no local media path');
return;
/** Installs the file-chapter windows, resetting the prompts. */
function applyChapterWindows(next: AniSkipWindows): void {
windows = next;
promptShown.intro = false;
promptShown.outro = false;
for (const kind of ['intro', 'outro'] as const) {
const window = next[kind];
if (window) logWindow(kind, window, null);
}
}
if (options?.force) {
introWindowCache.delete(mediaPath);
/**
* Fills the windows the chapters lacked from AniSkip, leaving the chapter
* windows (and whether their prompt was shown) untouched.
*/
async function mergeAniSkipWindows(lookup: AniSkipLookupResult): Promise<void> {
const added: SkipWindowKind[] = [];
for (const kind of ['intro', 'outro'] as const) {
const interval = lookup[kind];
if (windows[kind] || !interval) continue;
windows = { ...windows, [kind]: { ...interval, source: 'aniskip' } };
promptShown[kind] = false;
added.push(kind);
}
const generation = requestGeneration;
const cached = introWindowCache.get(mediaPath);
if (cached !== undefined) {
if (cached) {
await applyIntroWindow(cached);
}
return;
if (added.length === 0) return;
for (const kind of added) {
const window = windows[kind];
if (window) logWindow(kind, window, lookup.malId);
}
await setSkipChapters();
}
/**
* Looks up AniSkip, using the cache for definitive answers fetched at the same
* episode length. Null means a retryable failure.
*/
async function lookUpAniSkip(
mediaPath: string,
duration: number,
generation: number,
): Promise<AniSkipLookupResult | null> {
const cached = lookupCache.get(mediaPath);
if (cached?.duration === duration) return cached.result;
let metadata: AniSkipMetadata;
try {
metadata = await deps.resolveMetadataForFile(mediaPath);
metadata = await deps.resolveMetadataForFile(mediaPath, duration);
} catch (error) {
deps.logWarn('AniSkip metadata lookup failed', error);
return;
return null;
}
if (generation !== requestGeneration || mediaPath !== currentMediaPath) {
return;
}
if (
metadata.lookupStatus !== 'ready' ||
metadata.introStart === null ||
metadata.introEnd === null ||
metadata.introEnd <= metadata.introStart
) {
// Only definitive "no skip window exists" results are cached; transient
// lookup failures stay retryable on the next load or refresh.
if (metadata.lookupStatus !== 'lookup_failed') {
introWindowCache.set(mediaPath, null);
}
deps.logInfo(
`AniSkip: no intro window for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
);
return;
}
const window: AniSkipIntroWindow = {
start: metadata.introStart,
end: metadata.introEnd,
const result: AniSkipLookupResult = {
intro: metadata.intro,
outro: metadata.outro,
malId: metadata.malId,
};
introWindowCache.set(mediaPath, window);
await applyIntroWindow(window);
if (metadata.lookupStatus === 'lookup_failed') {
deps.logInfo(`AniSkip lookup failed for "${metadata.title}"; will retry on next load`);
return null;
}
// Every other status is definitive (a 404 or an unmatched title), so cache it,
// unless a refresh or media change superseded this lookup while it ran.
if (generation === requestGeneration) lookupCache.set(mediaPath, { duration, result });
if (metadata.lookupStatus !== 'ready') {
deps.logInfo(
`AniSkip: no skip times for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
);
}
return result;
}
function skipIntroNow(): void {
async function resolveForMedia(mediaPath: string, duration: number): Promise<void> {
if (!deps.getAniSkipConfig().aniskipEnabled) return;
if (!introWindow) {
showPlaybackFeedback('Intro skip unavailable');
const generation = requestGeneration;
const isStale = () => generation !== requestGeneration || mediaPath !== currentMediaPath;
const chapterList = await readChapterList();
if (isStale()) return;
// A failed read is retried later; a successful empty list is a final answer.
if (chapterList === null) retryResolution = true;
const fromChapters = classifyChapterSkipIntervals(chapterList ?? [], duration);
const next: AniSkipWindows = {
intro: fromChapters.intro ? { ...fromChapters.intro, source: 'chapters' } : null,
outro: fromChapters.outro ? { ...fromChapters.outro, source: 'chapters' } : null,
};
// Chapter windows work right away; AniSkip only fills what they lack.
applyChapterWindows(next);
if (next.intro && next.outro) return;
if (isRemoteMediaPath(mediaPath)) {
deps.logDebug('AniSkip lookup skipped for remote media; using file chapters only');
return;
}
const lookup = await lookUpAniSkip(mediaPath, duration, generation);
if (isStale()) return;
if (lookup === null) retryResolution = true;
if (lookup) await mergeAniSkipWindows(lookup);
}
/** Starts resolution once the current media has both a path and a known duration. */
function maybeStartResolution(): void {
if (resolutionStarted || !currentMediaPath || currentDuration === null) return;
if (!deps.getAniSkipConfig().aniskipEnabled) return;
resolutionStarted = true;
void resolveForMedia(currentMediaPath, currentDuration).catch((error) => {
deps.logWarn('AniSkip media resolution failed', error);
});
}
function requestCurrentDuration(): void {
const generation = requestGeneration;
void deps
.requestMpvProperty('duration')
.then((value) => {
if (generation !== requestGeneration || !isUsableDuration(value)) return;
currentDuration ??= value;
maybeStartResolution();
})
.catch(() => {
// duration is unavailable until the file is loaded; duration-change will follow
});
}
function getActiveWindow(now: number): SkipWindowKind | null {
for (const kind of ['intro', 'outro'] as const) {
const window = windows[kind];
if (
window &&
now >= window.start - SKIP_WINDOW_EPSILON_SECONDS &&
now <= window.end + SKIP_WINDOW_EPSILON_SECONDS
) {
return kind;
}
}
return null;
}
function skipNow(): void {
if (!deps.getAniSkipConfig().aniskipEnabled) return;
if (!windows.intro && !windows.outro) {
showPlaybackFeedback('Intro/outro skip unavailable');
return;
}
const now = deps.getCurrentTimePos();
@@ -221,40 +355,56 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
showPlaybackFeedback('Skip unavailable');
return;
}
if (
now < introWindow.start - SKIP_WINDOW_EPSILON_SECONDS ||
now > introWindow.end + SKIP_WINDOW_EPSILON_SECONDS
) {
showPlaybackFeedback('Skip intro only during intro');
const kind = getActiveWindow(now);
const window = kind ? windows[kind] : null;
if (!kind || !window) {
showPlaybackFeedback('Skip only during intro or outro');
return;
}
deps.sendMpvCommand(['set_property', 'time-pos', introWindow.end]);
showPlaybackFeedback('Skipped intro');
deps.sendMpvCommand(['set_property', 'time-pos', window.end]);
showPlaybackFeedback(`Skipped ${KIND_LABEL[kind].word}`);
}
function handleTimePosChange({ time }: { time: number }): void {
if (!introWindow || promptShown) return;
if (!deps.getAniSkipConfig().aniskipEnabled) return;
const promptWindowEnd = Math.min(introWindow.start + PROMPT_WINDOW_SECONDS, introWindow.end);
if (time >= introWindow.start && time < promptWindowEnd) {
promptShown = true;
showPlaybackFeedback(`You can skip by pressing ${resolveButtonKey()}`);
for (const kind of ['intro', 'outro'] as const) {
const window = windows[kind];
if (!window || promptShown[kind]) continue;
const promptWindowEnd = Math.min(window.start + PROMPT_WINDOW_SECONDS, window.end);
if (time >= window.start && time < promptWindowEnd) {
promptShown[kind] = true;
showPlaybackFeedback(
`You can skip the ${KIND_LABEL[kind].word} by pressing ${resolveButtonKey()}`,
);
}
}
}
function handleDurationChange({ duration }: { duration: number }): void {
if (!isUsableDuration(duration) || !currentMediaPath) return;
currentDuration = duration;
if (retryResolution) clearState();
maybeStartResolution();
}
function handleMediaPathChange({ path }: { path: string }): void {
const nextPath = typeof path === 'string' ? path : '';
if (nextPath === currentMediaPath && introWindow) {
if (nextPath === currentMediaPath && resolutionStarted) {
if (retryResolution) {
// The last resolution failed transiently; a reload is the retry.
clearState();
maybeStartResolution();
return;
}
// Same-media reload: mpv rebuilt the chapter list, so re-apply markers.
void setIntroChapters(introWindow.start, introWindow.end).catch(() => {});
void setSkipChapters().catch(() => {});
return;
}
currentMediaPath = nextPath;
currentDuration = null;
clearState();
if (!nextPath) return;
void resolveForMedia(nextPath).catch((error) => {
deps.logWarn('AniSkip media resolution failed', error);
});
if (!nextPath || !deps.getAniSkipConfig().aniskipEnabled) return;
requestCurrentDuration();
}
function handleConnectionChange({ connected }: { connected: boolean }): void {
@@ -263,6 +413,7 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
legacyFallbackBound = false;
clearState();
currentMediaPath = '';
currentDuration = null;
return;
}
bindSkipKeys();
@@ -271,43 +422,46 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
function handleClientMessage({ args }: { args: string[] }): void {
const messageName = args[0];
if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) {
skipIntroNow();
skipNow();
return;
}
if (messageName === ANISKIP_REFRESH_MESSAGE) {
const mediaPath = currentMediaPath;
if (!mediaPath) return;
if (!currentMediaPath) return;
lookupCache.delete(currentMediaPath);
clearState();
void removeIntroChapters().catch(() => {});
void resolveForMedia(mediaPath, { force: true }).catch((error) => {
deps.logWarn('AniSkip refresh failed', error);
});
void removeSkipChapters().catch(() => {});
if (currentDuration === null) {
requestCurrentDuration();
return;
}
maybeStartResolution();
}
}
function applyConfigChange(): void {
bindSkipKeys();
const enabled = deps.getAniSkipConfig().aniskipEnabled;
if (!enabled) {
if (!deps.getAniSkipConfig().aniskipEnabled) {
clearState();
void removeIntroChapters().catch(() => {});
void removeSkipChapters().catch(() => {});
return;
}
if (!introWindow && currentMediaPath) {
void resolveForMedia(currentMediaPath).catch((error) => {
deps.logWarn('AniSkip media resolution failed', error);
});
if (!currentMediaPath || resolutionStarted) return;
if (currentDuration === null) {
requestCurrentDuration();
return;
}
maybeStartResolution();
}
return {
handleConnectionChange,
handleMediaPathChange,
handleDurationChange,
handleTimePosChange,
handleClientMessage,
applyConfigChange,
skipIntroNow,
getIntroWindow: () => introWindow,
skipNow,
getSkipWindows: (): AniSkipWindows => windows,
};
}
+5
View File
@@ -19,6 +19,7 @@
import { clipboard, contextBridge, ipcRenderer, IpcRendererEvent, webUtils } from 'electron';
import { resolveOverlayLayerFromArgv } from './preload-args';
import { createIpcListenerFactories } from './preload-ipc-listeners';
import type { UnforwardedMpvKeyReport } from './types/session-bindings';
import {
DICTIONARY_EXTERNAL_LINK_CHANNEL,
parseDictionaryExternalUrl,
@@ -329,6 +330,10 @@ const electronAPI: ElectronAPI = {
ipcRenderer.send(IPC_CHANNELS.command.recordYomitanLookup, context ?? null);
},
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => {
ipcRenderer.send(IPC_CHANNELS.command.reportUnforwardedMpvKey, report);
},
getSubtitlePosition: (): Promise<SubtitlePosition | null> =>
ipcRenderer.invoke(IPC_CHANNELS.request.getSubtitlePosition),
saveSubtitlePosition: (position: SubtitlePosition) => {
+26
View File
@@ -150,6 +150,7 @@ function installKeyboardTestGlobals() {
let markActiveVideoWatchedCalls = 0;
let statsToggleOverlayCalls = 0;
const openedModalNotifications: string[] = [];
const unforwardedMpvKeys: Array<{ key: string; reason: string }> = [];
let selectionClearCount = 0;
let selectionAddCount = 0;
let mutationRecordsTaken = 0;
@@ -252,6 +253,9 @@ function installKeyboardTestGlobals() {
sendMpvCommand: (command: Array<string | number>) => {
mpvCommands.push(command);
},
reportUnforwardedMpvKey: (report: { key: string; reason: string }) => {
unforwardedMpvKeys.push(report);
},
dispatchSessionAction: async (actionId: string, payload?: unknown) => {
sessionActions.push({ actionId, payload });
},
@@ -518,6 +522,7 @@ function installKeyboardTestGlobals() {
markActiveVideoWatchedCalls: () => markActiveVideoWatchedCalls,
statsToggleOverlayCalls: () => statsToggleOverlayCalls,
openedModalNotifications,
unforwardedMpvKeys,
getPlaybackPaused: async () => playbackPausedResponse,
setPlaybackPausedResponse: (value: boolean | null) => {
playbackPausedResponse = value;
@@ -2570,6 +2575,27 @@ test('discovered mpv keys only run after SubMiner controls and stay out of sessi
}
});
test('imported mpv keys forward once the popup closes, even if the cached popup flag lags', async () => {
const { handlers, testGlobals, ctx } = createKeyboardHandlerHarness();
try {
testGlobals.setGetMpvInputBindings(async () => ({ keys: ['r'], blockedKeys: [] }));
await handlers.setupMpvInputForwarding();
await wait(0);
testGlobals.setPopupVisible(true);
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
assert.deepEqual(testGlobals.mpvCommands, []);
assert.deepEqual(testGlobals.unforwardedMpvKeys, [{ key: 'r', reason: 'lookup-popup' }]);
// #331: the popup closed, but a late popup event left the cached flag set.
testGlobals.setPopupVisible(false);
ctx.state.yomitanPopupVisible = true;
testGlobals.dispatchKeydown({ key: 'r', code: 'KeyR' });
assert.deepEqual(testGlobals.mpvCommands, [['keydown', 'r']]);
} finally {
testGlobals.restore();
}
});
test('stalled mpv discovery does not delay configured overlay controls', async () => {
const { handlers, testGlobals } = createKeyboardHandlerHarness();
try {
+26 -8
View File
@@ -1,4 +1,5 @@
import type { CompiledSessionBinding, PrimarySubMode, ShortcutsConfig } from '../../types';
import type { MpvKeyForwardBlock } from '../../types/session-bindings';
import type { RendererContext } from '../context';
import { createMpvInputForwarding } from './mpv-input-forwarding';
import { MPV_MOUSE_BUTTON_BY_BUTTON, wheelEventToMpvWheel } from '../../shared/mpv-input-bindings';
@@ -141,14 +142,24 @@ export function createKeyboardHandlers(
// Imported mpv bindings only run when no SubMiner UI could be the input's target.
// The subtitle sidebar is a side panel over playback, so only input inside it (a
// `.modal` target) stays with SubMiner.
// Why imported mpv input must stay in the overlay right now, or null when it may forward.
// SubMiner's own keybindings never pass through here.
function getMpvForwardBlock(target: EventTarget | null): MpvKeyForwardBlock | null {
if (!keyboardConfigLoaded) return 'config-loading';
if (ctx.state.playlistBrowserModalOpen || ctx.state.youtubePickerModalOpen) return 'modal';
if (isLookupPopupOpen(ctx.state, document)) return 'lookup-popup';
if (isInteractiveTarget(target)) return 'interactive-target';
return null;
}
function canForwardToMpv(target: EventTarget | null): boolean {
return (
keyboardConfigLoaded &&
!ctx.state.playlistBrowserModalOpen &&
!ctx.state.youtubePickerModalOpen &&
!isLookupPopupOpen(ctx.state, document) &&
!isInteractiveTarget(target)
);
return getMpvForwardBlock(target) === null;
}
// Debug breadcrumb for "my mpv key does nothing": the main process logs it at debug level.
function reportUnforwardedMpvKey(e: KeyboardEvent, reason: MpvKeyForwardBlock): void {
const report = importedMpvBindings.unforwardedReport(e, reason);
if (report) window.electronAPI.reportUnforwardedMpvKey(report);
}
// Scrolling over subtitles still reaches mpv; only scrollable overlay UI keeps the wheel.
@@ -1403,6 +1414,7 @@ export function createKeyboardHandlers(
if (isLookupPopupOpen(ctx.state, document)) {
if (handleYomitanPopupKeybind(e)) {
reportUnforwardedMpvKey(e, 'lookup-popup');
e.preventDefault();
return;
}
@@ -1469,7 +1481,13 @@ export function createKeyboardHandlers(
e.preventDefault();
return;
}
if (canForwardToMpv(e.target)) importedMpvBindings.keydown(e);
const forwardBlock = getMpvForwardBlock(e.target);
if (forwardBlock) {
reportUnforwardedMpvKey(e, forwardBlock);
} else if (!importedMpvBindings.keydown(e)) {
// Reports only while nothing is imported; an unbound key is not worth a line.
reportUnforwardedMpvKey(e, 'no-imported-bindings');
}
});
document.addEventListener('mousedown', (e: MouseEvent) => {
@@ -175,3 +175,50 @@ test('focus loss releases held keys and failed refresh clears stale bindings', a
await forwarding.refresh();
assert.equal(forwarding.keydown(keyEvent()), false);
});
test('a reload keeps forwarding the current keys until it settles', async () => {
let resolveReload: (snapshot: MpvInputBindingsSnapshot) => void = () => {};
let loads = 0;
const forwarding = createMpvInputForwarding({
load: () => {
loads += 1;
if (loads === 1) return Promise.resolve({ keys: ['r'], blockedKeys: [] });
return new Promise((resolve) => {
resolveReload = resolve;
});
},
send: () => {},
});
await forwarding.refresh();
const reload = forwarding.refresh();
assert.equal(forwarding.keydown(keyEvent()), true);
forwarding.keyup(keyEvent());
resolveReload({ keys: ['t'], blockedKeys: [] });
await reload;
assert.equal(forwarding.keydown(keyEvent()), false);
assert.equal(forwarding.keydown(keyEvent({ key: 't', code: 'KeyT' })), true);
});
test('unforwarded reports name keys mpv binds, or any key while nothing is imported', async () => {
let snapshot: MpvInputBindingsSnapshot = { keys: [], blockedKeys: [] };
const forwarding = createMpvInputForwarding({ load: async () => snapshot, send: () => {} });
await forwarding.refresh();
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'lookup-popup'), {
key: 'r',
reason: 'no-imported-bindings',
});
assert.equal(
forwarding.unforwardedReport(keyEvent({ key: 'Shift', code: 'ShiftLeft' }), 'lookup-popup'),
null,
);
snapshot = { keys: ['r', 't'], blockedKeys: [{ code: 'KeyT', modifiers: [] }] };
await forwarding.refresh();
assert.deepEqual(forwarding.unforwardedReport(keyEvent(), 'interactive-target'), {
key: 'r',
reason: 'interactive-target',
});
assert.equal(forwarding.unforwardedReport(keyEvent(), 'no-imported-bindings'), null);
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 't', code: 'KeyT' }), 'modal'), null);
assert.equal(forwarding.unforwardedReport(keyEvent({ key: 'z', code: 'KeyZ' }), 'modal'), null);
});
+44 -10
View File
@@ -4,7 +4,13 @@ import {
normalizeMpvInputKey,
wheelEventToMpvWheel,
} from '../../shared/mpv-input-bindings';
import type { MpvInputBindingsSnapshot } from '../../types/session-bindings';
import type {
MpvInputBindingsSnapshot,
MpvKeyForwardBlock,
UnforwardedMpvKeyReport,
} from '../../types/session-bindings';
const MODIFIER_ONLY_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph']);
type ModifierState = Pick<KeyboardEvent, 'ctrlKey' | 'altKey' | 'shiftKey' | 'metaKey'>;
type ForwardedKeyEvent = Parameters<typeof keyboardEventToMpvKey>[0] &
@@ -31,25 +37,26 @@ export function createMpvInputForwarding(deps: {
heldKeys.clear();
}
// Every window focus refreshes, so the current list keeps forwarding until the reload
// settles; a key pressed mid-reload would otherwise be dropped.
function refresh(): Promise<void> {
if (disposed) return Promise.resolve();
generation += 1;
keys.clear();
blockedKeys = [];
releaseAll();
if (pending) return pending;
pending = (async () => {
let requestedGeneration: number;
do {
requestedGeneration = generation;
let snapshot: MpvInputBindingsSnapshot | null = null;
try {
const snapshot = await deps.load();
if (!disposed && requestedGeneration === generation) {
keys = new Set(snapshot.keys);
blockedKeys = snapshot.blockedKeys;
}
snapshot = await deps.load();
} catch {
// Discovery is optional. Keep the existing overlay controls available.
// Discovery is optional: SubMiner's own bindings keep working without it.
}
if (!disposed && requestedGeneration === generation) {
keys = new Set(snapshot?.keys ?? []);
blockedKeys = snapshot?.blockedKeys ?? [];
}
} while (!disposed && requestedGeneration !== generation);
})().finally(() => {
@@ -98,6 +105,23 @@ export function createMpvInputForwarding(deps: {
return true;
}
/**
* The debug report for a key the overlay kept from mpv, or null when mpv does not bind
* it. With nothing imported yet, every nameable key is reported as such.
*/
function unforwardedReport(
event: ForwardedKeyEvent,
reason: MpvKeyForwardBlock,
): UnforwardedMpvKeyReport | null {
if (disposed || event.repeat || MODIFIER_ONLY_KEYS.has(event.key)) return null;
const key = keyboardEventToMpvKey(event);
if (!key) return null;
if (keys.size === 0) return { key, reason: 'no-imported-bindings' };
if (reason === 'no-imported-bindings') return null;
if (isBlocked(event.code, event) || !keys.has(key)) return null;
return { key, reason };
}
function keyup(event: Pick<KeyboardEvent, 'code' | 'preventDefault'>): void {
const key = heldKeys.get(event.code);
if (!key) return;
@@ -154,5 +178,15 @@ export function createMpvInputForwarding(deps: {
releaseAll();
}
return { refresh, keydown, keyup, wheel, mousedown, mouseup, releaseAll, dispose };
return {
refresh,
keydown,
keyup,
wheel,
mousedown,
mouseup,
releaseAll,
dispose,
unforwardedReport,
};
}
+4 -2
View File
@@ -125,11 +125,13 @@ export function isHachidoriPopupOpen(root: ParentNode | null | undefined = docum
* (the shown event and the host's visible marker) also covers a plain press.
*/
export function isLookupPopupOpen(
state: { yomitanPopupVisible: boolean; hachidoriReaderSeen: boolean },
state: { hachidoriReaderSeen: boolean },
root: ParentNode | null | undefined = document,
): boolean {
if (state.hachidoriReaderSeen) return isHachidoriPopupOpen(root);
return state.yomitanPopupVisible || isYomitanPopupVisible(root);
// The fork marks the host before it fires the shown event, so the DOM is authoritative.
// The cached yomitanPopupVisible flag can lag a close (#331) and would keep stealing keys.
return isYomitanPopupVisible(root);
}
export function isYomitanPopupVisible(root: ParentNode | null | undefined = document): boolean {
+1
View File
@@ -27,6 +27,7 @@ export const IPC_CHANNELS = {
setIgnoreMouseEvents: 'set-ignore-mouse-events',
overlayModalClosed: 'overlay:modal-closed',
recordYomitanLookup: 'record-yomitan-lookup',
reportUnforwardedMpvKey: 'overlay:unforwarded-mpv-key',
youtubePickerResolve: 'youtube:picker-resolve',
toggleDevTools: 'toggle-dev-tools',
saveSubtitlePosition: 'save-subtitle-position',
+11 -1
View File
@@ -4,7 +4,7 @@ import test from 'node:test';
import { DEFAULT_CONFIG, DEFAULT_KEYBINDINGS } from '../../config/definitions';
import { compileSessionBindings } from '../../core/services/session-bindings';
import { resolveConfiguredShortcuts } from '../../core/utils/shortcut-config';
import { parseSessionActionDispatchRequest } from './validators';
import { parseSessionActionDispatchRequest, parseUnforwardedMpvKeyReport } from './validators';
// Regression guard: SESSION_ACTION_IDS in validators.ts is a hand-maintained mirror of the
// SessionActionId union. If a new shortcut-backed action is added to the union/defaults but not to
@@ -36,3 +36,13 @@ test('every default session-action binding is accepted by parseSessionActionDisp
);
}
});
test('unforwarded mpv key reports accept known reasons only', () => {
assert.deepEqual(parseUnforwardedMpvKeyReport({ key: 'LEFT', reason: 'lookup-popup' }), {
key: 'LEFT',
reason: 'lookup-popup',
});
assert.equal(parseUnforwardedMpvKeyReport({ key: 'LEFT', reason: 'toString' }), null);
assert.equal(parseUnforwardedMpvKeyReport({ key: '', reason: 'modal' }), null);
assert.equal(parseUnforwardedMpvKeyReport(null), null);
});
+26 -1
View File
@@ -14,7 +14,12 @@ import type {
SubsyncManualRunRequest,
} from '../../types/runtime';
import type { RuntimeOptionId, RuntimeOptionValue } from '../../types/runtime-options';
import type { SessionActionId, SessionActionPayload } from '../../types/session-bindings';
import type {
MpvKeyForwardBlock,
SessionActionId,
SessionActionPayload,
UnforwardedMpvKeyReport,
} from '../../types/session-bindings';
import type { SubtitlePosition } from '../../types/subtitle';
import { OVERLAY_HOSTED_MODALS, type OverlayHostedModal } from './contracts';
import { isControllerFaceButtonLabels, parseControllerDiscreteBinding } from '../controller-review';
@@ -365,6 +370,26 @@ export function parseMpvCommand(value: unknown): Array<string | number> | null {
: null;
}
// A Record so a new MpvKeyForwardBlock member fails typecheck until it is listed here.
const MPV_KEY_FORWARD_BLOCKS: Record<MpvKeyForwardBlock, true> = {
'config-loading': true,
modal: true,
'lookup-popup': true,
'interactive-target': true,
'no-imported-bindings': true,
};
function isMpvKeyForwardBlock(value: unknown): value is MpvKeyForwardBlock {
return typeof value === 'string' && Object.hasOwn(MPV_KEY_FORWARD_BLOCKS, value);
}
export function parseUnforwardedMpvKeyReport(value: unknown): UnforwardedMpvKeyReport | null {
if (!isObject(value)) return null;
const { key, reason } = value;
if (typeof key !== 'string' || key.length === 0 || key.length > 64) return null;
return isMpvKeyForwardBlock(reason) ? { key, reason } : null;
}
export function parseOptionalForwardingOptions(value: unknown): {
forward?: boolean;
} {
+3 -1
View File
@@ -1,4 +1,4 @@
import type { MpvInputBindingsSnapshot } from './session-bindings';
import type { MpvInputBindingsSnapshot, UnforwardedMpvKeyReport } from './session-bindings';
import type {
KikuFieldGroupingChoice,
KikuFieldGroupingRequestData,
@@ -600,6 +600,8 @@ export interface ElectronAPI {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward?: boolean }) => void;
reportOverlayInteractive: (interactive: boolean) => void;
recordYomitanLookup: (context?: SubtitleMiningContext | null) => void;
/** Debug-only: the overlay kept a key that mpv binds. */
reportUnforwardedMpvKey: (report: UnforwardedMpvKeyReport) => void;
getSubtitlePosition: () => Promise<SubtitlePosition | null>;
saveSubtitlePosition: (position: SubtitlePosition) => void;
sendMpvCommand: (command: (string | number)[]) => void;
+14
View File
@@ -13,6 +13,20 @@ export interface MpvInputBindingsSnapshot {
blockedKeys: SessionKeySpec[];
}
/** Why the overlay kept a key that mpv binds instead of forwarding it. */
export type MpvKeyForwardBlock =
| 'config-loading'
| 'modal'
| 'lookup-popup'
| 'interactive-target'
| 'no-imported-bindings';
/** Debug report the overlay sends when it does not forward an mpv-bound key. */
export interface UnforwardedMpvKeyReport {
key: string;
reason: MpvKeyForwardBlock;
}
export interface SessionBindingWarning {
kind: 'unsupported' | 'conflict' | 'deprecated-config';
path: string;
@@ -0,0 +1,93 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { queryMpvProcessId } from './mpv-process-id';
// Runs a stand-in mpv IPC server that hands each request line to `onRequest`.
async function withFakeMpv(
onRequest: (socket: net.Socket, request: string) => void,
run: (socketPath: string) => Promise<void>,
): Promise<void> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mpv-pid-'));
const socketPath =
process.platform === 'win32'
? path.win32.join(String.raw`\\.\pipe`, path.basename(dir))
: path.join(dir, 'mpv.sock');
const server = net.createServer((socket) => {
socket.once('data', (data) => onRequest(socket, data.toString()));
});
try {
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(socketPath, resolve);
});
await run(socketPath);
} finally {
await new Promise((resolve) => server.close(resolve));
fs.rmSync(dir, { recursive: true, force: true });
}
}
test('queryMpvProcessId asks mpv for pid and returns the answer', async () => {
let request = '';
await withFakeMpv(
(socket, line) => {
request = line;
socket.write('{"data":4242,"request_id":1,"error":"success"}\n');
},
async (socketPath) => {
assert.equal(await queryMpvProcessId(socketPath), 4242);
},
);
assert.deepEqual(JSON.parse(request), { command: ['get_property', 'pid'], request_id: 1 });
});
test('queryMpvProcessId skips events and malformed lines, across split chunks', async () => {
await withFakeMpv(
(socket) => {
socket.write('{"event":"idle"}\nnot json\n{"data":42');
setTimeout(() => socket.write('42,"request_id":1,"error":"success"}\n'), 10);
},
async (socketPath) => {
assert.equal(await queryMpvProcessId(socketPath), 4242);
},
);
});
test('queryMpvProcessId rejects when mpv refuses the property', async () => {
await withFakeMpv(
(socket) => socket.write('{"request_id":1,"error":"property unavailable"}\n'),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath), /no process ID/);
},
);
});
test('queryMpvProcessId rejects when nothing is listening', async () => {
const missing =
process.platform === 'win32'
? path.win32.join(String.raw`\\.\pipe`, `mpv-pid-missing-${process.pid}`)
: path.join(os.tmpdir(), `mpv-pid-missing-${process.pid}.sock`);
await assert.rejects(queryMpvProcessId(missing));
});
test('queryMpvProcessId rejects when mpv hangs up or never answers', async () => {
await withFakeMpv(
(socket) => socket.end(),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath), /closed before mpv answered/);
},
);
const held: net.Socket[] = [];
await withFakeMpv(
(socket) => held.push(socket),
async (socketPath) => {
await assert.rejects(queryMpvProcessId(socketPath, 20), /no answer within 20ms/);
held.forEach((socket) => socket.destroy());
},
);
});
+67
View File
@@ -0,0 +1,67 @@
import net from 'node:net';
const PID_REQUEST_ID = 1;
const PID_QUERY_TIMEOUT_MS = 5_000;
// This runs inside a socket callback, where a parse error would be an uncaught exception.
function parseIpcLine(line: string): unknown {
try {
return JSON.parse(line);
} catch {
return null;
}
}
// Asks the mpv listening on `socketPath` for its process ID over a short-lived IPC connection.
export function queryMpvProcessId(
socketPath: string,
timeoutMs = PID_QUERY_TIMEOUT_MS,
): Promise<number> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(socketPath);
let buffered = '';
const fail = (message: string): void => {
socket.destroy();
reject(new Error(message));
};
socket.setEncoding('utf8');
socket.setTimeout(timeoutMs, () => fail(`no answer within ${timeoutMs}ms`));
socket.once('error', (error) => fail(error.message));
socket.once('close', () => fail('connection closed before mpv answered'));
socket.once('connect', () => {
socket.write(
`${JSON.stringify({ command: ['get_property', 'pid'], request_id: PID_REQUEST_ID })}\n`,
);
});
socket.on('data', (chunk: string) => {
buffered += chunk;
const lines = buffered.split('\n');
buffered = lines.pop() ?? '';
// mpv also streams events on this connection, so skip to the line answering the request.
for (const line of lines) {
const message = parseIpcLine(line);
if (
typeof message !== 'object' ||
message === null ||
!('request_id' in message) ||
message.request_id !== PID_REQUEST_ID
) {
continue;
}
const pid = 'data' in message ? message.data : undefined;
if (typeof pid === 'number') {
socket.destroy();
resolve(pid);
} else {
fail(`mpv returned no process ID: ${line}`);
}
return;
}
});
});
}
@@ -1,72 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
filterMpvPollResultBySocketPath,
matchesMpvSocketPathInCommandLine,
} from './mpv-socket-match';
import type { MpvPollResult } from './win32';
function createPollResult(commandLines: Array<string | null>): MpvPollResult {
return {
matches: commandLines.map((commandLine, index) => ({
hwnd: index + 1,
bounds: { x: index * 10, y: 0, width: 1280, height: 720 },
area: 1280 * 720,
isForeground: index === 0,
commandLine,
})),
focusState: true,
windowState: 'visible',
};
}
test('matchesMpvSocketPathInCommandLine accepts equals and space-delimited socket flags', () => {
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video.mkv',
'\\\\.\\pipe\\subminer-a',
),
true,
);
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server "\\\\.\\pipe\\subminer-b" video.mkv',
'\\\\.\\pipe\\subminer-b',
),
true,
);
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video.mkv',
'\\\\.\\pipe\\subminer-b',
),
false,
);
});
test('filterMpvPollResultBySocketPath keeps only matches for the requested socket path', () => {
const result = filterMpvPollResultBySocketPath(
createPollResult([
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-a video-a.mkv',
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-b video-b.mkv',
null,
]),
'\\\\.\\pipe\\subminer-b',
);
assert.deepEqual(
result.matches.map((match) => match.hwnd),
[2],
);
assert.equal(result.windowState, 'visible');
});
test('matchesMpvSocketPathInCommandLine rejects socket-path prefix matches', () => {
assert.equal(
matchesMpvSocketPathInCommandLine(
'mpv.exe --input-ipc-server=\\\\.\\pipe\\subminer-10 video.mkv',
'\\\\.\\pipe\\subminer-1',
),
false,
);
});
-41
View File
@@ -1,41 +0,0 @@
import type { MpvPollResult } from './win32';
function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function matchesMpvSocketPathInCommandLine(
commandLine: string,
targetSocketPath: string,
): boolean {
if (!commandLine || !targetSocketPath) {
return false;
}
const escapedSocketPath = escapeRegex(targetSocketPath);
return new RegExp(
`(?:^|\\s)--input-ipc-server(?:=|\\s+)(?:"${escapedSocketPath}"|${escapedSocketPath})(?=\\s|$)`,
'i',
).test(commandLine);
}
export function filterMpvPollResultBySocketPath(
result: MpvPollResult,
targetSocketPath?: string | null,
): MpvPollResult {
if (!targetSocketPath) {
return result;
}
const matches = result.matches.filter(
(match) =>
typeof match.commandLine === 'string' &&
matchesMpvSocketPathInCommandLine(match.commandLine, targetSocketPath),
);
return {
matches,
focusState: matches.some((match) => match.isForeground),
windowState: matches.length > 0 ? 'visible' : 'not-found',
};
}
+7 -109
View File
@@ -1,6 +1,4 @@
import { execFile } from 'node:child_process';
import koffi from 'koffi';
import { matchesMpvSocketPathInCommandLine } from './mpv-socket-match';
const user32 = koffi.load('user32.dll');
const dwmapi = koffi.load('dwmapi.dll');
@@ -129,7 +127,6 @@ export interface MpvWindowMatch {
bounds: WindowBounds;
area: number;
isForeground: boolean;
commandLine?: string | null;
}
export interface MpvPollResult {
@@ -200,102 +197,9 @@ function pruneExpiredProcessNames(nowMs: number): void {
}
}
type ProcessCommandLineCacheEntry =
| { state: 'resolved'; commandLine: string; expiresAtMs: number; refreshInFlight: boolean }
| { state: 'pending' }
| { state: 'failed'; retryAtMs: number; backoffMs: number };
const COMMAND_LINE_RETRY_INITIAL_BACKOFF_MS = 2_000;
const COMMAND_LINE_RETRY_MAX_BACKOFF_MS = 30_000;
// A process command line never changes, so a resolved entry only has to expire to survive
// Windows PID reuse (a dead mpv's PID handed to a new instance, whose stale socket path would
// otherwise match the wrong window forever). Longer than the process-name TTL because each
// refresh costs a PowerShell spawn, and the cached value keeps being served while the refresh
// runs, so expiry never interrupts window matching.
const COMMAND_LINE_CACHE_TTL_MS = 60_000;
const processCommandLineCache = new Map<number, ProcessCommandLineCacheEntry>();
function queryProcessCommandLine(
pid: number,
onResult: (commandLine: string | null) => void,
): void {
execFile(
'powershell.exe',
[
'-NoProfile',
'-NonInteractive',
'-ExecutionPolicy',
'Bypass',
'-Command',
`$process = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; if ($process -and $process.CommandLine) { [Console]::Out.Write($process.CommandLine) }`,
],
{
encoding: 'utf8',
windowsHide: true,
timeout: 1500,
},
(error, stdout) => {
const output = error ? '' : stdout.trim();
onResult(output.length > 0 ? output : null);
},
);
}
// Resolves a process command line via a background PowerShell lookup. Returns null until the
// first lookup completes; the caller's next poll picks up the cached result. Failures are
// negative-cached with exponential backoff: the synchronous version of this lookup could
// block the main thread for its full 1.5s timeout on every 250ms poll, which (combined with
// the forward:true mouse hook) stalled mouse input system-wide.
function getProcessCommandLineByPid(pid: number): string | null {
const entry = processCommandLineCache.get(pid);
const nowMs = Date.now();
if (entry?.state === 'resolved') {
if (nowMs >= entry.expiresAtMs && !entry.refreshInFlight) {
entry.refreshInFlight = true;
queryProcessCommandLine(pid, (commandLine) => {
processCommandLineCache.set(pid, {
state: 'resolved',
// A failed refresh is usually a transient query error rather than a dead process
// (a gone process owns no window, so it is never looked up again). Keep the last
// known command line and re-check after the next TTL.
commandLine: commandLine ?? entry.commandLine,
expiresAtMs: Date.now() + COMMAND_LINE_CACHE_TTL_MS,
refreshInFlight: false,
});
});
}
return entry.commandLine;
}
if (entry?.state === 'pending') return null;
if (entry?.state === 'failed' && nowMs < entry.retryAtMs) return null;
const nextBackoffMs =
entry?.state === 'failed'
? Math.min(entry.backoffMs * 2, COMMAND_LINE_RETRY_MAX_BACKOFF_MS)
: COMMAND_LINE_RETRY_INITIAL_BACKOFF_MS;
processCommandLineCache.set(pid, { state: 'pending' });
queryProcessCommandLine(pid, (commandLine) => {
if (commandLine !== null) {
processCommandLineCache.set(pid, {
state: 'resolved',
commandLine,
expiresAtMs: Date.now() + COMMAND_LINE_CACHE_TTL_MS,
refreshInFlight: false,
});
} else {
processCommandLineCache.set(pid, {
state: 'failed',
retryAtMs: Date.now() + nextBackoffMs,
backoffMs: nextBackoffMs,
});
}
});
return null;
}
export function findMpvWindows(targetSocketPath?: string | null): MpvPollResult {
// With a target PID only that process's windows match, whatever its executable is named.
// Without one, any process named mpv matches.
export function findMpvWindows(targetPid?: number | null): MpvPollResult {
const foregroundHwnd = GetForegroundWindow();
const matches: MpvWindowMatch[] = [];
let hasMinimized = false;
@@ -310,15 +214,10 @@ export function findMpvWindows(targetSocketPath?: string | null): MpvPollResult
const pidValue = pid[0]!;
if (pidValue === 0) return true;
const processName = getCachedProcessNameByPid(pidValue);
if (!processName || processName.toLowerCase() !== 'mpv') return true;
let commandLine: string | null = null;
if (targetSocketPath) {
commandLine = getProcessCommandLineByPid(pidValue);
if (!commandLine || !matchesMpvSocketPathInCommandLine(commandLine, targetSocketPath)) {
return true;
}
if (targetPid != null) {
if (pidValue !== targetPid) return true;
} else if (getCachedProcessNameByPid(pidValue)?.toLowerCase() !== 'mpv') {
return true;
}
if (IsIconic(hwnd)) {
@@ -337,7 +236,6 @@ export function findMpvWindows(targetSocketPath?: string | null): MpvPollResult
bounds,
area: bounds.width * bounds.height,
isForeground,
commandLine,
});
return true;
+73 -1
View File
@@ -1,8 +1,80 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { findWindowsMpvTargetWindowHandle } from './windows-helper';
import { createWindowsOverlayOperations, findWindowsMpvTargetWindowHandle } from './windows-helper';
import type { MpvPollResult } from './win32';
function overlayOperationsHarness() {
let nowMs = 0;
let failing = true;
const warnings: Array<{ message: string; operation: unknown }> = [];
const nativeCall = () => {
if (failing) throw new Error('native failure');
};
const operations = createWindowsOverlayOperations({
loadWin32: () => ({
setOverlayOwner: nativeCall,
ensureOverlayTransparency: nativeCall,
bindOverlayAboveMpv: nativeCall,
clearOverlayOwner: nativeCall,
}),
warn: (message, details) => warnings.push({ message, operation: details.operation }),
now: () => nowMs,
});
return {
operations,
warnings,
setNow: (value: number) => {
nowMs = value;
},
setFailing: (value: boolean) => {
failing = value;
},
};
}
for (const [operation, call] of [
['set-owner', (ops) => ops.setOwner(1, 2)],
['transparency', (ops) => ops.ensureTransparency(1)],
['bind-above-mpv', (ops) => ops.bindAboveMpv(1, 2)],
['clear-owner', (ops) => ops.clearOwner(1)],
] as const satisfies ReadonlyArray<
readonly [string, (ops: ReturnType<typeof createWindowsOverlayOperations>) => boolean]
>) {
test(`${operation} reports failure, rate limits warnings and records recovery`, () => {
const h = overlayOperationsHarness();
const failed = { message: 'Windows native overlay operation failed', operation };
assert.equal(call(h.operations), false);
assert.deepEqual(h.warnings, [failed]);
h.setNow(29_999);
assert.equal(call(h.operations), false);
assert.deepEqual(h.warnings, [failed]);
h.setNow(30_000);
assert.equal(call(h.operations), false);
assert.deepEqual(h.warnings, [failed, failed]);
h.setFailing(false);
const recovered = { message: 'Windows native overlay operation recovered', operation };
assert.equal(call(h.operations), true);
assert.deepEqual(h.warnings, [failed, failed, recovered]);
assert.equal(call(h.operations), true);
assert.equal(h.warnings.length, 3);
});
}
test('native overlay operations rate limit independently', () => {
const h = overlayOperationsHarness();
h.operations.setOwner(1, 2);
h.operations.clearOwner(1);
assert.deepEqual(
h.warnings.map((warning) => warning.operation),
['set-owner', 'clear-owner'],
);
});
test('findWindowsMpvTargetWindowHandle prefers the focused mpv window', () => {
const result: MpvPollResult = {
matches: [
+74 -38
View File
@@ -17,11 +17,85 @@
*/
import type { MpvPollResult } from './win32';
import { createLogger } from '../logger';
const log = createLogger('overlay:windows');
type OverlayWin32 = Pick<
typeof import('./win32'),
'setOverlayOwner' | 'ensureOverlayTransparency' | 'bindOverlayAboveMpv' | 'clearOverlayOwner'
>;
// These run on every visibility update, so each operation warns at most every 30 seconds
// while it keeps failing, and once more when it recovers.
export function createWindowsOverlayOperations(deps: {
loadWin32: () => OverlayWin32;
warn: (message: string, details: Record<string, unknown>) => void;
now: () => number;
}) {
const failures = new Map<string, number>();
const run = (
operation: string,
handles: { overlayHwnd: number; mpvHwnd?: number },
action: (win32: OverlayWin32) => void,
): boolean => {
try {
action(deps.loadWin32());
if (failures.delete(operation)) {
deps.warn('Windows native overlay operation recovered', { operation, ...handles });
}
return true;
} catch (error) {
const lastWarning = failures.get(operation);
if (lastWarning === undefined || deps.now() - lastWarning >= 30_000) {
deps.warn('Windows native overlay operation failed', {
operation,
...handles,
error: error instanceof Error ? error.message : String(error),
});
failures.set(operation, deps.now());
}
return false;
}
};
return {
setOwner: (overlayHwnd: number, mpvHwnd: number): boolean =>
run('set-owner', { overlayHwnd, mpvHwnd }, (win32) => {
win32.setOverlayOwner(overlayHwnd, mpvHwnd);
}),
ensureTransparency: (overlayHwnd: number): boolean =>
run('transparency', { overlayHwnd }, (win32) => {
win32.ensureOverlayTransparency(overlayHwnd);
}),
bindAboveMpv: (overlayHwnd: number, mpvHwnd: number): boolean =>
run('bind-above-mpv', { overlayHwnd, mpvHwnd }, (win32) => {
win32.bindOverlayAboveMpv(overlayHwnd, mpvHwnd);
win32.ensureOverlayTransparency(overlayHwnd);
}),
clearOwner: (overlayHwnd: number): boolean =>
run('clear-owner', { overlayHwnd }, (win32) => {
win32.clearOverlayOwner(overlayHwnd);
}),
};
}
function loadWin32(): typeof import('./win32') {
return require('./win32') as typeof import('./win32');
}
const overlayOperations = createWindowsOverlayOperations({
loadWin32,
warn: (message, details) => log.warn(message, details),
now: Date.now,
});
export const setWindowsOverlayOwner = overlayOperations.setOwner;
export const ensureWindowsOverlayTransparency = overlayOperations.ensureTransparency;
export const bindWindowsOverlayAboveMpv = overlayOperations.bindAboveMpv;
export const clearWindowsOverlayOwner = overlayOperations.clearOwner;
export function findWindowsMpvTargetWindowHandle(result?: MpvPollResult): number | null {
const poll = result ?? loadWin32().findMpvWindows();
const focused = poll.matches.find((match) => match.isForeground);
@@ -31,44 +105,6 @@ export function findWindowsMpvTargetWindowHandle(result?: MpvPollResult): number
return best?.hwnd ?? null;
}
export function setWindowsOverlayOwner(overlayHwnd: number, mpvHwnd: number): boolean {
try {
loadWin32().setOverlayOwner(overlayHwnd, mpvHwnd);
return true;
} catch {
return false;
}
}
export function ensureWindowsOverlayTransparency(overlayHwnd: number): boolean {
try {
loadWin32().ensureOverlayTransparency(overlayHwnd);
return true;
} catch {
return false;
}
}
export function bindWindowsOverlayAboveMpv(overlayHwnd: number, mpvHwnd: number): boolean {
try {
const win32 = loadWin32();
win32.bindOverlayAboveMpv(overlayHwnd, mpvHwnd);
win32.ensureOverlayTransparency(overlayHwnd);
return true;
} catch {
return false;
}
}
export function clearWindowsOverlayOwner(overlayHwnd: number): boolean {
try {
loadWin32().clearOverlayOwner(overlayHwnd);
return true;
} catch {
return false;
}
}
export function getWindowsForegroundProcessName(): string | null {
try {
return loadWin32().getForegroundProcessName();
+186
View File
@@ -265,3 +265,189 @@ test('WindowsWindowTracker keeps tracking through repeated transient minimized r
assert.equal(tracker.isTargetWindowMinimized(), false);
assert.deepEqual(tracker.getGeometry(), { x: 10, y: 20, width: 1280, height: 720 });
});
const SOCKET_PATH = String.raw`\\.\pipe\subminer-socket`;
const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
function pollOnce(tracker: WindowsWindowTracker): void {
(tracker as unknown as { pollGeometry: () => void }).pollGeometry();
}
test('WindowsWindowTracker follows the process that answers on the target socket', async () => {
const queriedSockets: string[] = [];
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
queryMpvProcessId: async (socketPath) => {
queriedSockets.push(socketPath);
return 4242;
},
pollMpvWindows: (targetPid) => {
polledPids.push(targetPid);
return mpvVisible();
},
});
pollOnce(tracker);
assert.equal(tracker.isTracking(), false);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
assert.deepEqual(queriedSockets, [SOCKET_PATH]);
assert.deepEqual(polledPids, [4242]);
});
test('WindowsWindowTracker keeps polling while a process lookup is pending', async () => {
let queries = 0;
let answer: (pid: number) => void = () => {};
let now = 1_000;
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: () => {
queries += 1;
return new Promise((resolve) => {
answer = resolve;
});
},
pollMpvWindows: () => mpvVisible(),
});
for (let poll = 0; poll < 120; poll += 1) {
pollOnce(tracker);
now += 250;
}
assert.equal(tracker.isTracking(), false);
assert.equal(queries, 1);
answer(4242);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
});
test('WindowsWindowTracker retries a failed lookup at a limited rate', async () => {
let queries = 0;
let now = 1_000;
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => {
queries += 1;
if (queries === 1) throw new Error('connect ENOENT');
return 4242;
},
pollMpvWindows: () => mpvVisible(),
});
pollOnce(tracker);
await flushPromises();
now += 250;
pollOnce(tracker);
await flushPromises();
assert.equal(queries, 1);
now += 1_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(queries, 2);
assert.equal(tracker.isTracking(), true);
});
test('WindowsWindowTracker moves to the new process when mpv restarts on the same socket', async () => {
let currentPid = 1111;
let now = 1_000;
let queries = 0;
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => {
queries += 1;
return currentPid;
},
// Only the live process still owns a window.
pollMpvWindows: (targetPid) => {
polledPids.push(targetPid);
return targetPid === currentPid ? mpvVisible() : mpvNotFound;
},
});
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
currentPid = 2222;
now += 2_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
assert.deepEqual(tracker.getGeometry(), { x: 0, y: 0, width: 1280, height: 720 });
assert.equal(polledPids.at(-1), 2222);
assert.equal(queries, 2);
});
test('WindowsWindowTracker revalidates a PID even while its window remains visible', async () => {
let currentPid = 1111;
let now = 0;
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => currentPid,
// Simulates PID reuse: the old PID still has a visible, unrelated window.
pollMpvWindows: (pid) => {
polledPids.push(pid);
return mpvVisible();
},
});
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
currentPid = 2222;
now = 10_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(polledPids.at(-1), 2222);
});
test('WindowsWindowTracker expires an unvalidated PID and recovers after IPC returns', async () => {
let available = true;
let now = 0;
const polledPids: Array<number | null> = [];
const tracker = new WindowsWindowTracker(SOCKET_PATH, {
now: () => now,
queryMpvProcessId: async () => {
if (!available) throw new Error('IPC unavailable');
return 4242;
},
pollMpvWindows: (pid) => {
polledPids.push(pid);
return mpvVisible();
},
trackingLossGraceMs: 0,
maxConsecutiveMisses: 1,
});
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
available = false;
now = 10_000;
pollOnce(tracker);
await flushPromises();
assert.equal(tracker.isTracking(), true);
polledPids.length = 0;
now = 30_000;
pollOnce(tracker);
await flushPromises();
assert.equal(tracker.isTracking(), false);
assert.deepEqual(polledPids, []);
available = true;
now += 1_000;
pollOnce(tracker);
await flushPromises();
pollOnce(tracker);
assert.equal(tracker.isTracking(), true);
assert.equal(polledPids.at(-1), 4242);
});
+97 -7
View File
@@ -19,27 +19,35 @@
import { BaseWindowTracker } from './base-tracker';
import type { WindowGeometry } from '../types';
import type { MpvPollResult } from './win32';
import { queryMpvProcessId } from './mpv-process-id';
import { createLogger } from '../logger';
const log = createLogger('tracker').child('windows');
const MPV_PID_LOOKUP_INTERVAL_MS = 1_000;
const MPV_PID_REVALIDATE_INTERVAL_MS = 10_000;
const MPV_PID_MAX_AGE_MS = 30_000;
const NO_MPV_WINDOW: MpvPollResult = { matches: [], focusState: false, windowState: 'not-found' };
type WindowsTrackerDeps = {
pollMpvWindows?: () => MpvPollResult;
pollMpvWindows?: (targetPid: number | null) => MpvPollResult;
queryMpvProcessId?: (socketPath: string) => Promise<number>;
maxConsecutiveMisses?: number;
trackingLossGraceMs?: number;
minimizedTrackingLossGraceMs?: number;
now?: () => number;
};
function defaultPollMpvWindows(_targetMpvSocketPath?: string | null): MpvPollResult {
function defaultPollMpvWindows(targetPid: number | null): MpvPollResult {
const win32 = require('./win32') as typeof import('./win32');
return win32.findMpvWindows(_targetMpvSocketPath);
return win32.findMpvWindows(targetPid);
}
export class WindowsWindowTracker extends BaseWindowTracker {
private pollInterval: ReturnType<typeof setInterval> | null = null;
private pollInFlight = false;
private readonly pollMpvWindows: () => MpvPollResult;
private readonly pollMpvWindows: (targetPid: number | null) => MpvPollResult;
private readonly queryMpvProcessId: (socketPath: string) => Promise<number>;
private readonly maxConsecutiveMisses: number;
private readonly trackingLossGraceMs: number;
private readonly minimizedTrackingLossGraceMs: number;
@@ -51,12 +59,17 @@ export class WindowsWindowTracker extends BaseWindowTracker {
private targetWindowMinimized = false;
private readonly targetMpvSocketPath: string | null;
private currentTargetWindowHwnd: number | null = null;
private targetMpvPid: number | null = null;
private pidLookupInFlight = false;
private lastPidLookupAtMs: number | null = null;
private lastPidConfirmedAtMs: number | null = null;
private pidLookupFailureLogged = false;
constructor(_targetMpvSocketPath?: string, deps: WindowsTrackerDeps = {}) {
super();
this.targetMpvSocketPath = _targetMpvSocketPath?.trim() || null;
this.pollMpvWindows =
deps.pollMpvWindows ?? (() => defaultPollMpvWindows(this.targetMpvSocketPath));
this.pollMpvWindows = deps.pollMpvWindows ?? defaultPollMpvWindows;
this.queryMpvProcessId = deps.queryMpvProcessId ?? queryMpvProcessId;
this.maxConsecutiveMisses = Math.max(1, Math.floor(deps.maxConsecutiveMisses ?? 2));
this.trackingLossGraceMs = Math.max(0, Math.floor(deps.trackingLossGraceMs ?? 1_500));
this.minimizedTrackingLossGraceMs = Math.max(
@@ -86,6 +99,16 @@ export class WindowsWindowTracker extends BaseWindowTracker {
return this.currentTargetWindowHwnd;
}
getDiagnosticState() {
return {
socketPath: this.targetMpvSocketPath,
targetPid: this.targetMpvPid,
targetHwnd: this.currentTargetWindowHwnd,
pidLookupPending: this.pidLookupInFlight,
pidAgeMs: this.lastPidConfirmedAtMs === null ? null : this.now() - this.lastPidConfirmedAtMs,
};
}
private maybeLogPollError(error: Error): void {
const now = Date.now();
const fingerprint = error.message;
@@ -142,12 +165,79 @@ export class WindowsWindowTracker extends BaseWindowTracker {
};
}
// Asks the mpv on the target socket which process it is. Runs in the background so a slow
// answer never stalls the poll, which shares the main thread with the mouse hook.
private refreshTargetMpvPid(socketPath: string, intervalMs = MPV_PID_LOOKUP_INTERVAL_MS): void {
const nowMs = this.now();
if (
this.pidLookupInFlight ||
(this.lastPidLookupAtMs !== null && nowMs - this.lastPidLookupAtMs < intervalMs)
) {
return;
}
this.pidLookupInFlight = true;
this.lastPidLookupAtMs = nowMs;
this.queryMpvProcessId(socketPath)
.then(
(pid) => {
this.targetMpvPid = pid;
this.lastPidConfirmedAtMs = this.now();
if (this.pidLookupFailureLogged) {
log.warn('Windows mpv PID lookup recovered', this.getDiagnosticState());
}
this.pidLookupFailureLogged = false;
},
(error: unknown) => {
// The overlay stays hidden until mpv is identified, so leave a trace of why it isn't.
if (this.pidLookupFailureLogged) return;
this.pidLookupFailureLogged = true;
log.warn('Windows mpv PID lookup failed; overlay attachment may be unavailable', {
...this.getDiagnosticState(),
error: error instanceof Error ? error.message : String(error),
});
},
)
.finally(() => {
this.pidLookupInFlight = false;
});
}
private pollTargetWindows(): MpvPollResult {
const socketPath = this.targetMpvSocketPath;
if (!socketPath) return this.pollMpvWindows(null);
// Windows can reuse a PID for an unrelated visible window. A cached match must
// remain tied to the process answering on our socket, even while it is visible.
if (
this.lastPidConfirmedAtMs !== null &&
this.now() - this.lastPidConfirmedAtMs >= MPV_PID_MAX_AGE_MS
) {
this.targetMpvPid = null;
}
if (this.targetMpvPid === null) {
this.refreshTargetMpvPid(socketPath);
return NO_MPV_WINDOW;
}
const result = this.pollMpvWindows(this.targetMpvPid);
// A new mpv may have taken over the socket after the known process exited.
this.refreshTargetMpvPid(
socketPath,
result.windowState === 'not-found'
? MPV_PID_LOOKUP_INTERVAL_MS
: MPV_PID_REVALIDATE_INTERVAL_MS,
);
return result;
}
private pollGeometry(): void {
if (this.pollInFlight) return;
this.pollInFlight = true;
try {
const result = this.pollMpvWindows();
const result = this.pollTargetWindows();
const best = this.selectBestMatch(result);
if (best) {