Compare commits

..
30 changed files with 857 additions and 1088 deletions

No files matched your search

+1 -1
View File
@@ -121,7 +121,7 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to
| mpv | Required | The video player SubMiner draws over | | mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage | | fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup | | Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
| ffmpeg | Recommended | Audio clips and screenshots on cards | | ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) |
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting | | MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway | | xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
| yt-dlp | Optional | YouTube playback | | yt-dlp | Optional | YouTube playback |
-7
View File
@@ -1,7 +0,0 @@
type: added
area: aniskip
- Added outro skipping: the AniSkip key now also skips the ending, with its own prompt and chapter markers.
- Intro and outro detection now reads the file's own chapters first (named OP/ED chapters, or song-length chapters near the start and end) and only asks AniSkip for what is missing, so it also works for Jellyfin and other streams.
- AniSkip lookups now send the episode length so the times match your TV or Blu-ray cut.
- Fixed AniSkip rate limits, server errors, and network failures being remembered as "no intro" until restart; they are now retried on the next load.
+4
View File
@@ -0,0 +1,4 @@
type: added
area: setup
- First-run setup now shows whether FFmpeg and FFprobe are usable. When they are missing from `PATH`, **Download FFmpeg** saves a verified static build next to your config, and SubMiner and the `subminer` command use it whenever no system FFmpeg is found.
+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 "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 "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. "subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false "aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays. "aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
}, // SubMiner-managed mpv launch and bundled plugin options. }, // SubMiner-managed mpv launch and bundled plugin options.
// ========================================== // ==========================================
+4 -11
View File
@@ -1,6 +1,6 @@
# AniSkip integration # AniSkip integration
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. SubMiner looks up opening timestamps on [AniSkip](https://aniskip.com) so you can skip an anime's intro with one key.
## Setup ## Setup
@@ -23,24 +23,17 @@ python3 -m pip install --user guessit
## Usage ## Usage
Once a file's duration is known, SubMiner looks for the opening and ending in the file's chapters: 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.
- 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. 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 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. 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 ## Triggering from mpv
| Command | What it does | | Command | What it does |
| ----------------------------------------- | ------------------------------------------------------- | | ----------------------------------------- | ------------------------------------------------------- |
| `script-message subminer-skip-intro` | Skip to the end of the intro or outro that is playing | | `script-message subminer-skip-intro` | Skip to the end of the intro |
| `script-message subminer-aniskip-refresh` | Look up the current file again, ignoring cached results | | `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. Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show.
+1 -1
View File
@@ -8,7 +8,7 @@ For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on t
1. Install [Anki](https://apps.ankiweb.net/). 1. Install [Anki](https://apps.ankiweb.net/).
2. Install AnkiConnect (add-on code `2055492159`). 2. Install AnkiConnect (add-on code `2055492159`).
3. Install FFmpeg and make sure it is on your `PATH`. SubMiner uses it for audio and images. 3. Install FFmpeg and make sure it is on your `PATH`, or download it from first-run setup. SubMiner uses it for audio and images.
4. Keep Anki running while you mine. 4. Keep Anki running while you mine.
If you changed AnkiConnect's port, set `ankiConnect.url` to match. If you changed AnkiConnect's port, set `ankiConnect.url` to match.
+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/`. - 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/`. - 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/`.
- 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. - 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.
## Component diagram ## 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.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.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.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path |
| `mpv.aniskipEnabled` | `true` | Detect intros and outros (file chapters, then AniSkip) and show a skip prompt | | `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt |
| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro or outro while it plays | | `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown |
### YouTube playback settings ### YouTube playback settings
+5 -4
View File
@@ -12,7 +12,7 @@ Getting started takes three steps:
## 1. Install requirements ## 1. Install requirements
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner.
| Dependency | Needed for | Platforms | | Dependency | Needed for | Platforms |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ | | ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
@@ -124,7 +124,7 @@ mpv --version
ffmpeg -version ffmpeg -version
``` ```
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`). ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. Otherwise, use the FFmpeg download in first-run setup. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
<details> <details>
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary> <summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
@@ -262,8 +262,9 @@ Setup walks you through:
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows). 1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser. 2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`. 3. **FFmpeg** (optional). If `ffmpeg` and `ffprobe` are on your `PATH` and run, there is nothing to do. Otherwise **Download FFmpeg** saves a static build to `tools/ffmpeg/` next to your config file. SubMiner and the `subminer` command use it only when FFmpeg is missing from `PATH`, so a system install always takes priority.
4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached. 4. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
5. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`. **Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
+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. `v` replaces mpv's own subtitle visibility toggle.
The intro/outro skip key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration). The skip-intro 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. 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 "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 "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. "subminerBinaryPath": "", // Optional SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path.
"aniskipEnabled": true, // Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key. Values: true | false "aniskipEnabled": true, // Enable AniSkip intro detection, chapter markers, and the skip-intro key. Values: true | false
"aniskipButtonKey": "TAB" // mpv key that skips the detected intro or outro while it plays. "aniskipButtonKey": "TAB" // mpv key used to skip the detected intro while the skip prompt is visible.
}, // SubMiner-managed mpv launch and bundled plugin options. }, // SubMiner-managed mpv launch and bundled plugin options.
// ========================================== // ==========================================
+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. 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 or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata. While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro, and `subminer-aniskip-refresh` reloads intro data, for example after your script changes title or episode metadata.
## Related pages ## Related pages
+7
View File
@@ -1,6 +1,11 @@
import path from 'node:path'; import path from 'node:path';
import packageJson from '../package.json'; import packageJson from '../package.json';
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js'; import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
import { getDefaultConfigDir } from '../src/shared/setup-state.js';
import {
appendManagedFfmpegToPath,
getManagedFfmpegDir,
} from '../src/core/services/managed-ffmpeg.js';
import { import {
loadLauncherJellyfinConfig, loadLauncherJellyfinConfig,
loadLauncherLoggingConfig, loadLauncherLoggingConfig,
@@ -65,6 +70,8 @@ function ensureAppPath(context: LauncherCommandContext): string {
async function main(): Promise<void> { async function main(): Promise<void> {
const scriptPath = process.argv[1] || 'subminer'; const scriptPath = process.argv[1] || 'subminer';
const scriptName = path.basename(scriptPath); const scriptName = path.basename(scriptPath);
// Same PATH rule as the app: dependency checks and spawned tools see a setup-page FFmpeg.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(getDefaultConfigDir()));
const launcherConfig = loadLauncherYoutubeSubgenConfig(); const launcherConfig = loadLauncherYoutubeSubgenConfig();
const launcherMpvConfig = loadLauncherMpvConfig(); const launcherMpvConfig = loadLauncherMpvConfig();
const launcherLoggingConfig = loadLauncherLoggingConfig(); const launcherLoggingConfig = loadLauncherLoggingConfig();
@@ -616,14 +616,13 @@ export function buildIntegrationConfigOptionRegistry(
path: 'mpv.aniskipEnabled', path: 'mpv.aniskipEnabled',
kind: 'boolean', kind: 'boolean',
defaultValue: defaultConfig.mpv.aniskipEnabled, defaultValue: defaultConfig.mpv.aniskipEnabled,
description: description: 'Enable AniSkip intro detection, chapter markers, and the skip-intro key.',
'Enable intro and outro detection (file chapters, then AniSkip), chapter markers, and the skip key.',
}, },
{ {
path: 'mpv.aniskipButtonKey', path: 'mpv.aniskipButtonKey',
kind: 'string', kind: 'string',
defaultValue: defaultConfig.mpv.aniskipButtonKey, defaultValue: defaultConfig.mpv.aniskipButtonKey,
description: 'mpv key that skips the detected intro or outro while it plays.', description: 'mpv key used to skip the detected intro while the skip prompt is visible.',
}, },
{ {
path: 'jellyfin.enabled', path: 'jellyfin.enabled',
+154
View File
@@ -0,0 +1,154 @@
import assert from 'node:assert/strict';
import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from './managed-ffmpeg';
async function withTempDirs(run: (dirs: { system: string; managed: string }) => Promise<void>) {
const root = await mkdtemp(path.join(tmpdir(), 'managed-ffmpeg-'));
const dirs = { system: path.join(root, 'bin'), managed: getManagedFfmpegDir(root) };
await mkdir(dirs.system, { recursive: true });
await mkdir(dirs.managed, { recursive: true });
try {
await run(dirs);
} finally {
await rm(root, { recursive: true, force: true });
}
}
async function writeExecutable(directory: string, name: string): Promise<void> {
const filePath = path.join(directory, name);
await writeFile(filePath, '#!/bin/sh\n');
await chmod(filePath, 0o755);
}
const passVersionCheck = async () => undefined;
test('managed FFmpeg is appended to PATH once, behind system entries, only when downloaded', async () => {
await withTempDirs(async ({ system, managed }) => {
const env: NodeJS.ProcessEnv = { Path: system };
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
await writeExecutable(managed, 'ffmpeg');
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), true);
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
// Writes the existing key (Windows spells it Path) instead of adding a second one.
assert.deepEqual(env, { Path: [system, managed].join(path.delimiter) });
});
});
test('detectFfmpeg prefers system tools and fills gaps from the managed copy', async () => {
await withTempDirs(async ({ system, managed }) => {
const env = { PATH: [system, managed].join(path.delimiter) };
const detect = () =>
detectFfmpeg({
managedDir: managed,
env,
platform: 'linux',
arch: 'x64',
runVersionCheck: passVersionCheck,
});
assert.deepEqual(await detect(), {
kind: 'missing',
missing: ['ffmpeg', 'ffprobe'],
downloadable: true,
});
await writeExecutable(system, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
assert.deepEqual(await detect(), {
kind: 'ready',
source: 'managed',
ffmpegPath: path.join(system, 'ffmpeg'),
ffprobePath: path.join(managed, 'ffprobe'),
});
await writeExecutable(system, 'ffprobe');
const status = await detect();
assert.equal(status.kind === 'ready' ? status.source : status.kind, 'system');
});
});
test('detectFfmpeg reports a tool that is found but fails to run', async () => {
await withTempDirs(async ({ managed }) => {
await writeExecutable(managed, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
const status = await detectFfmpeg({
managedDir: managed,
env: { PATH: managed },
platform: 'freebsd',
arch: 'x64',
runVersionCheck: async () => {
throw new Error('Killed: 9');
},
});
assert.deepEqual(status, {
kind: 'broken',
path: path.join(managed, 'ffmpeg'),
message: 'Killed: 9',
managed: true,
downloadable: false,
});
});
});
test('detectFfmpeg reports a broken system tool before offering a download for its companion', async () => {
await withTempDirs(async ({ system, managed }) => {
await writeExecutable(system, 'ffmpeg');
const detect = (runVersionCheck: (executablePath: string) => Promise<void>) =>
detectFfmpeg({
managedDir: managed,
env: { PATH: system },
platform: 'linux',
arch: 'x64',
runVersionCheck,
});
// A download would only add ffprobe; the broken system ffmpeg would still shadow it.
assert.deepEqual(
await detect(async () => {
throw new Error('exit 127');
}),
{
kind: 'broken',
path: path.join(system, 'ffmpeg'),
message: 'exit 127',
managed: false,
downloadable: true,
},
);
assert.deepEqual(await detect(passVersionCheck), {
kind: 'missing',
missing: ['ffprobe'],
downloadable: true,
});
});
});
test('installManagedFfmpeg rejects unsupported platforms and never publishes a failed download', async () => {
await withTempDirs(async ({ managed }) => {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'freebsd', arch: 'x64' }),
/no FFmpeg download for freebsd-x64/,
);
const originalFetch = globalThis.fetch;
globalThis.fetch = Object.assign(async () => new Response('not ffmpeg'), originalFetch);
try {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'linux', arch: 'x64' }),
/FFmpeg failed integrity verification/,
);
} finally {
globalThis.fetch = originalFetch;
}
assert.deepEqual(await readdir(managed), []);
});
});
+222
View File
@@ -0,0 +1,222 @@
import { execFile } from 'node:child_process';
import { createReadStream, createWriteStream, existsSync } from 'node:fs';
import { chmod, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { createGunzip } from 'node:zlib';
import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
import { findOnPath } from './subtitle-generation-tools';
/**
* SubMiner can download its own FFmpeg when none is usable on PATH. The copy lives in
* `<configDir>/tools/ffmpeg` and is appended to PATH at startup, so a system FFmpeg always
* wins and every bare `ffmpeg`/`ffprobe` spawn picks up the download otherwise.
*/
export type FfmpegTool = 'ffmpeg' | 'ffprobe';
const FFMPEG_TOOLS: readonly FfmpegTool[] = ['ffmpeg', 'ffprobe'];
/** Pinned ffmpeg-static release: single gzipped static binaries per platform. */
const MANAGED_FFMPEG_RELEASE_URL =
'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1';
type ManagedAsset = { size: number; sha256: string };
const MANAGED_FFMPEG_ASSETS = {
'linux-x64': {
ffmpeg: {
size: 29354986,
sha256: 'bfe8a8fc511530457b528c48d77b5737527b504a3797a9bc4866aeca69c2dffa',
},
ffprobe: {
size: 29276839,
sha256: '25d9b6ccb05e3d9de9e04e31e2506d8dd7f9f0418981965ac6df12e8d3afd067',
},
},
'linux-arm64': {
ffmpeg: {
size: 25568691,
sha256: '754a678672298bc68156adff58aa7385a592c2b30b1d0ae8750c45c915c4bac0',
},
ffprobe: {
size: 25493573,
sha256: '2ab6aba60ee84412dff9188720703376cb4e7aaf7e0b5e43aa8249f2acae5bf8',
},
},
'darwin-x64': {
ffmpeg: {
size: 25296431,
sha256: '929b375c1182d956c51f7ac25e0b2b0411fb01f6f407aa15c9758efeb4242106',
},
ffprobe: {
size: 25239438,
sha256: 'd4da574d6e2e197bd259b47d69cf262df9e312af24ad960444f6d806d3d4c186',
},
},
'darwin-arm64': {
ffmpeg: {
size: 19246198,
sha256: '8923876afa8db5585022d7860ec7e589af192f441c56793971276d450ed3bbfa',
},
ffprobe: {
size: 19207077,
sha256: 'd986a8ec7b030899fe66a8a288ed809a3543338705a3ce178cfb85869c5d80be',
},
},
'win32-x64': {
ffmpeg: {
size: 29581307,
sha256: '8883a3dffbd0a16cf4ef95206ea05283f78908dbfb118f73c83f4951dcc06d77',
},
ffprobe: {
size: 29521644,
sha256: 'f309e6223ad89d2fe54bccd420a7709b66fd27540674e92309578ed491a43c8d',
},
},
} as const satisfies Record<string, Record<FfmpegTool, ManagedAsset>>;
type ManagedFfmpegTarget = keyof typeof MANAGED_FFMPEG_ASSETS;
function getManagedFfmpegTarget(
platform: NodeJS.Platform,
arch: string,
): ManagedFfmpegTarget | null {
// Windows on ARM runs the x64 build through emulation; there is no native arm64 build.
const key = platform === 'win32' && arch === 'arm64' ? 'win32-x64' : `${platform}-${arch}`;
return key in MANAGED_FFMPEG_ASSETS ? (key as ManagedFfmpegTarget) : null;
}
export function getManagedFfmpegDir(configDir: string): string {
return path.join(configDir, 'tools', 'ffmpeg');
}
function managedBinaryPath(
managedDir: string,
tool: FfmpegTool,
platform: NodeJS.Platform,
): string {
return path.join(managedDir, platform === 'win32' ? `${tool}.exe` : tool);
}
function pathKey(env: NodeJS.ProcessEnv): string {
return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';
}
/**
* Appends the managed FFmpeg directory to `env`'s PATH when a download exists there.
* Appending keeps a system FFmpeg in front. Returns whether PATH changed.
*/
export function appendManagedFfmpegToPath(
env: NodeJS.ProcessEnv,
managedDir: string,
platform: NodeJS.Platform = process.platform,
): boolean {
if (!existsSync(managedBinaryPath(managedDir, 'ffmpeg', platform))) return false;
const key = pathKey(env);
const entries = (env[key] ?? '').split(path.delimiter).filter(Boolean);
if (entries.some((entry) => path.resolve(entry) === path.resolve(managedDir))) return false;
env[key] = [...entries, managedDir].join(path.delimiter);
return true;
}
export type FfmpegSetupStatus =
| { kind: 'ready'; source: 'system' | 'managed'; ffmpegPath: string; ffprobePath: string }
| { kind: 'missing'; missing: FfmpegTool[]; downloadable: boolean }
/** Found on PATH but `-version` failed. Only a broken managed copy is fixed by downloading. */
| { kind: 'broken'; path: string; message: string; managed: boolean; downloadable: boolean };
export type RunVersionCheck = (executablePath: string) => Promise<void>;
const runVersionCheckDefault: RunVersionCheck = (executablePath) =>
new Promise((resolve, reject) => {
// Generous timeout: Windows Defender scans a fresh 80 MB exe on first launch.
execFile(executablePath, ['-version'], { timeout: 15_000 }, (error) =>
error ? reject(error) : resolve(),
);
});
/** Whether SubMiner can run FFmpeg and FFprobe from the current PATH, and where they come from. */
export async function detectFfmpeg(options: {
managedDir: string;
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
arch?: string;
runVersionCheck?: RunVersionCheck;
}): Promise<FfmpegSetupStatus> {
const env = options.env ?? process.env;
const platform = options.platform ?? process.platform;
const runVersionCheck = options.runVersionCheck ?? runVersionCheckDefault;
const downloadable = getManagedFfmpegTarget(platform, options.arch ?? process.arch) !== null;
const isManaged = (filePath: string) =>
path.resolve(path.dirname(filePath)) === path.resolve(options.managedDir);
const found = await Promise.all(FFMPEG_TOOLS.map((tool) => findOnPath([tool], env)));
// Check what was found before reporting gaps: a broken system tool shadows any download.
for (const executablePath of found.filter(Boolean)) {
try {
await runVersionCheck(executablePath);
} catch (error) {
return {
kind: 'broken',
path: executablePath,
message: error instanceof Error ? error.message : String(error),
managed: isManaged(executablePath),
downloadable,
};
}
}
const missing = FFMPEG_TOOLS.filter((_, index) => !found[index]);
if (missing.length > 0) return { kind: 'missing', missing, downloadable };
const [ffmpegPath, ffprobePath] = found as [string, string];
return {
kind: 'ready',
source: isManaged(ffmpegPath) || isManaged(ffprobePath) ? 'managed' : 'system',
ffmpegPath,
ffprobePath,
};
}
/**
* Downloads, verifies, and unpacks FFmpeg and FFprobe into `managedDir`, replacing any
* earlier download. Callers append `managedDir` to PATH afterwards.
*/
export async function installManagedFfmpeg(options: {
managedDir: string;
platform?: NodeJS.Platform;
arch?: string;
}): Promise<void> {
const platform = options.platform ?? process.platform;
const arch = options.arch ?? process.arch;
const target = getManagedFfmpegTarget(platform, arch);
if (!target) {
throw new Error(
`SubMiner has no FFmpeg download for ${platform}-${arch}. Install FFmpeg yourself.`,
);
}
await mkdir(options.managedDir, { recursive: true });
const staging = await mkdtemp(path.join(options.managedDir, '.install-'));
try {
const unpacked: Array<[string, string]> = [];
for (const tool of FFMPEG_TOOLS) {
const asset = MANAGED_FFMPEG_ASSETS[target][tool];
const archivePath = path.join(staging, `${tool}.gz`);
await downloadSubtitleGenerationArtifact({
url: `${MANAGED_FFMPEG_RELEASE_URL}/${tool}-${target}.gz`,
size: asset.size,
sha256: asset.sha256,
destination: archivePath,
label: tool === 'ffmpeg' ? 'FFmpeg' : 'FFprobe',
});
const binaryPath = managedBinaryPath(staging, tool, platform);
await pipeline(createReadStream(archivePath), createGunzip(), createWriteStream(binaryPath));
await chmod(binaryPath, 0o755);
unpacked.push([binaryPath, managedBinaryPath(options.managedDir, tool, platform)]);
}
// Publish only after both tools verified, so a failed download never leaves half a pair.
for (const [from, to] of unpacked) await rename(from, to);
} finally {
await rm(staging, { recursive: true, force: true });
}
}
@@ -18,12 +18,12 @@ export async function downloadSubtitleGenerationArtifact(input: {
const temporaryDirectory = await mkdtemp( const temporaryDirectory = await mkdtemp(
path.join(path.dirname(input.destination), '.download-'), path.join(path.dirname(input.destination), '.download-'),
); );
const temporaryPath = path.join(temporaryDirectory, 'model.bin'); const temporaryPath = path.join(temporaryDirectory, 'artifact.bin');
input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` }); input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` });
try { try {
const response = await fetch(input.url, { signal: input.signal }); const response = await fetch(input.url, { signal: input.signal });
if (!response.ok || !response.body) { if (!response.ok || !response.body) {
throw new Error(`Model download failed: HTTP ${response.status}`); throw new Error(`${input.label} download failed: HTTP ${response.status}`);
} }
const file = await open(temporaryPath, 'wx'); const file = await open(temporaryPath, 'wx');
const reader = response.body.getReader(); const reader = response.body.getReader();
@@ -36,7 +36,8 @@ export async function downloadSubtitleGenerationArtifact(input: {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
if (done) break; if (done) break;
received += value.byteLength; received += value.byteLength;
if (received > input.size) throw new Error('Downloaded model exceeds expected size.'); if (received > input.size)
throw new Error(`Downloaded ${input.label} exceeds expected size.`);
digest.update(value); digest.update(value);
await file.writeFile(value); await file.writeFile(value);
const percent = Math.min(99, Math.floor((received / input.size) * 100)); const percent = Math.min(99, Math.floor((received / input.size) * 100));
@@ -50,7 +51,9 @@ export async function downloadSubtitleGenerationArtifact(input: {
} }
} }
if (received !== input.size || digest.digest('hex') !== input.sha256) { if (received !== input.size || digest.digest('hex') !== input.sha256) {
throw new Error('Downloaded model failed integrity verification. Try downloading again.'); throw new Error(
`Downloaded ${input.label} failed integrity verification. Try downloading again.`,
);
} }
await file.sync(); await file.sync();
} finally { } finally {
@@ -46,7 +46,11 @@ function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
return [name, ...extensions.map((extension) => `${name}${extension}`)]; return [name, ...extensions.map((extension) => `${name}${extension}`)];
} }
async function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv): Promise<string> { /** First executable on `env.PATH` matching any of `names` (PATHEXT-aware on Windows), or ''. */
export async function findOnPath(
names: readonly string[],
env: NodeJS.ProcessEnv,
): Promise<string> {
const directories = (env.PATH ?? '') const directories = (env.PATH ?? '')
.split(path.delimiter) .split(path.delimiter)
.map((entry) => entry.trim()) .map((entry) => entry.trim())
+4
View File
@@ -155,6 +155,7 @@ import { createSyncAssembly } from './main/assemblies/sync';
import { createYoutubeAssembly } from './main/assemblies/youtube'; import { createYoutubeAssembly } from './main/assemblies/youtube';
import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals'; import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals';
import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup'; import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup';
import { appendManagedFfmpegToPath, getManagedFfmpegDir } from './core/services/managed-ffmpeg';
import { createOverlayAssembly } from './main/assemblies/overlay'; import { createOverlayAssembly } from './main/assemblies/overlay';
import { createYomitanAssembly } from './main/assemblies/yomitan'; import { createYomitanAssembly } from './main/assemblies/yomitan';
import { createStatsAssembly } from './main/assemblies/stats'; import { createStatsAssembly } from './main/assemblies/stats';
@@ -428,6 +429,8 @@ const {
appState, appState,
appLifecycleApp, appLifecycleApp,
} = bootServices; } = bootServices;
// Before any ffmpeg/ffprobe spawn: a system FFmpeg stays first, the setup-page download fills in.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(CONFIG_DIR));
// Backend changes take effect on restart; windows and parser must share one session. // Backend changes take effect on restart; windows and parser must share one session.
const activeDictionaryBackend = configService.getConfig().dictionaryBackend; const activeDictionaryBackend = configService.getConfig().dictionaryBackend;
const yomitan = createYomitanAssembly({ const yomitan = createYomitanAssembly({
@@ -688,6 +691,7 @@ const firstRunSetup = createFirstRunSetupAssembly({
ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(), ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(),
getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(), getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(),
createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(), createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(),
waitForLoginShellPath: () => loginShellPathReady,
getAppPath: (name) => app.getPath(name), getAppPath: (name) => app.getPath(name),
trashItem: (targetPath) => shell.trashItem(targetPath), trashItem: (targetPath) => shell.trashItem(targetPath),
writeShortcutLink: (shortcutPath, operation, details) => writeShortcutLink: (shortcutPath, operation, details) =>
@@ -30,6 +30,7 @@ function makeDeps(configDir: string): FirstRunSetupAssemblyDeps {
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'), ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'), getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'), createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'),
waitForLoginShellPath: lazy('waitForLoginShellPath'),
getAppPath: lazy('getAppPath'), getAppPath: lazy('getAppPath'),
trashItem: lazy('trashItem'), trashItem: lazy('trashItem'),
writeShortcutLink: lazy('writeShortcutLink'), writeShortcutLink: lazy('writeShortcutLink'),
+32
View File
@@ -1,6 +1,12 @@
import os from 'node:os'; import os from 'node:os';
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron'; import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
import type { ConfigService } from '../../config/service'; import type { ConfigService } from '../../config/service';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from '../../core/services/managed-ffmpeg';
import { getYomitanDictionaryInfo } from '../../core/services'; import { getYomitanDictionaryInfo } from '../../core/services';
import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime'; import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime';
import type { Logger } from '../../logger'; import type { Logger } from '../../logger';
@@ -62,6 +68,8 @@ export interface FirstRunSetupAssemblyDeps {
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps; getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
/** Resolves the launcher options after the login-shell PATH is applied. */ /** Resolves the launcher options after the login-shell PATH is applied. */
createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>; createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>;
/** Resolves once the macOS login-shell PATH is merged, so FFmpeg detection sees it. */
waitForLoginShellPath: () => Promise<void>;
getAppPath: (name: 'appData' | 'desktop') => string; getAppPath: (name: 'appData' | 'desktop') => string;
trashItem: (targetPath: string) => Promise<void>; trashItem: (targetPath: string) => Promise<void>;
writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink']; writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink'];
@@ -83,6 +91,23 @@ export type FirstRunSetupAssembly = ReturnType<typeof createFirstRunSetupAssembl
export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) { export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
const { appState, configService, logger } = deps; const { appState, configService, logger } = deps;
let firstRunSetupMessage: string | null = null; let firstRunSetupMessage: string | null = null;
const managedFfmpegDir = getManagedFfmpegDir(deps.configDir);
// Shared by repeat clicks so a second press never starts a parallel download.
let ffmpegInstall: Promise<string> | null = null;
const installFfmpeg = (): Promise<string> =>
(ffmpegInstall ??= installManagedFfmpeg({ managedDir: managedFfmpegDir })
.then(() => {
appendManagedFfmpegToPath(process.env, managedFfmpegDir);
logger.info(`[ffmpeg] Downloaded FFmpeg to ${managedFfmpegDir}`);
return 'FFmpeg downloaded. SubMiner uses it whenever FFmpeg is not on PATH.';
})
.catch((error: unknown) => {
logger.error('[ffmpeg] FFmpeg download failed', error);
return `FFmpeg download failed: ${error instanceof Error ? error.message : String(error)}`;
})
.finally(() => {
ffmpegInstall = null;
}));
const resolveWindowsMpvShortcutRuntimePaths = () => const resolveWindowsMpvShortcutRuntimePaths = () =>
resolveWindowsMpvShortcutPaths({ resolveWindowsMpvShortcutPaths({
appDataDir: deps.getAppPath('appData'), appDataDir: deps.getAppPath('appData'),
@@ -232,6 +257,9 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath), mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath),
windowsMpvShortcuts: snapshot.windowsMpvShortcuts, windowsMpvShortcuts: snapshot.windowsMpvShortcuts,
commandLineLauncher: snapshot.commandLineLauncher, commandLineLauncher: snapshot.commandLineLauncher,
ffmpeg: await deps
.waitForLoginShellPath()
.then(() => detectFfmpeg({ managedDir: managedFfmpegDir })),
message: firstRunSetupMessage, message: firstRunSetupMessage,
}; };
}, },
@@ -304,6 +332,10 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
firstRunSetupMessage = snapshot.message; firstRunSetupMessage = snapshot.message;
return; return;
} }
if (submission.action === 'install-ffmpeg') {
firstRunSetupMessage = await installFfmpeg();
return;
}
if (submission.action === 'open-yomitan-settings') { if (submission.action === 'open-yomitan-settings') {
firstRunSetupMessage = deps.openDictionarySettings() firstRunSetupMessage = deps.openDictionarySettings()
? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.` ? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.`
+1 -3
View File
@@ -1118,8 +1118,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
aniskipEnabled: configService.getConfig().mpv.aniskipEnabled, aniskipEnabled: configService.getConfig().mpv.aniskipEnabled,
aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey, aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey,
}), }),
resolveMetadataForFile: (mediaPath, episodeLength) => resolveMetadataForFile: (mediaPath) => resolveAniSkipMetadataForFile(mediaPath),
resolveAniSkipMetadataForFile(mediaPath, { episodeLength }),
sendMpvCommand: (command) => { sendMpvCommand: (command) => {
appState.mpvClient?.send({ command }); appState.mpvClient?.send({ command });
}, },
@@ -1164,7 +1163,6 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
}); });
client.on('connection-change', aniSkipRuntime.handleConnectionChange); client.on('connection-change', aniSkipRuntime.handleConnectionChange);
client.on('media-path-change', aniSkipRuntime.handleMediaPathChange); client.on('media-path-change', aniSkipRuntime.handleMediaPathChange);
client.on('duration-change', aniSkipRuntime.handleDurationChange);
client.on('time-pos-change', aniSkipRuntime.handleTimePosChange); client.on('time-pos-change', aniSkipRuntime.handleTimePosChange);
client.on('client-message', aniSkipRuntime.handleClientMessage); client.on('client-message', aniSkipRuntime.handleClientMessage);
deps.getPluginHost().attachMpvClient(client); deps.getPluginHost().attachMpvClient(client);
-116
View File
@@ -1,116 +0,0 @@
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
@@ -1,124 +0,0 @@
/** 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)),
};
}
+35 -121
View File
@@ -3,21 +3,17 @@ import assert from 'node:assert/strict';
import { import {
inferAniSkipMetadataForFile, inferAniSkipMetadataForFile,
parseAniSkipGuessitJson, parseAniSkipGuessitJson,
parseAniSkipPayload,
resolveAniSkipMetadataForFile, resolveAniSkipMetadataForFile,
} from './aniskip-metadata'; } from './aniskip-metadata';
const LOOKUP = { episodeLength: 1440 }; function makeMockResponse(payload: unknown): Response {
return {
function makeMockResponse(payload: unknown, status = 200): Response { ok: true,
return new Response(JSON.stringify(payload), { status: 200,
status, json: async () => payload,
headers: { 'Content-Type': 'application/json' }, } as Response;
});
} }
const MAL_MY_SHOW = { categories: [{ items: [{ id: '1234', name: 'My Show' }] }] };
function normalizeFetchInput(input: string | URL | Request): string { function normalizeFetchInput(input: string | URL | Request): string {
if (typeof input === 'string') return input; if (typeof input === 'string') return input;
if (input instanceof URL) return input.toString(); if (input instanceof URL) return input.toString();
@@ -50,8 +46,8 @@ test('parseAniSkipGuessitJson extracts title season and episode', () => {
episode: 7, episode: 7,
source: 'guessit', source: 'guessit',
malId: null, malId: null,
intro: null, introStart: null,
outro: null, introEnd: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}); });
}); });
@@ -72,8 +68,8 @@ test('parseAniSkipGuessitJson prefers series over episode title', () => {
episode: 10, episode: 10,
source: 'guessit', source: 'guessit',
malId: null, malId: null,
intro: null, introStart: null,
outro: null, introEnd: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}); });
}); });
@@ -115,58 +111,10 @@ test('inferAniSkipMetadataForFile handles release-group filename with trailing q
assert.equal(parsed.source, 'fallback'); assert.equal(parsed.source, 'fallback');
}); });
test('parseAniSkipPayload reads op and ed from a v2 response', () => { test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async () => {
// 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( await withMockFetch(
async (input) => { async (input) => {
const url = normalizeFetchInput(input); const url = normalizeFetchInput(input);
requested.push(url);
if (url.includes('myanimelist.net/search/prefix.json')) { if (url.includes('myanimelist.net/search/prefix.json')) {
return makeMockResponse({ return makeMockResponse({
categories: [ categories: [
@@ -179,82 +127,48 @@ test('resolveAniSkipMetadataForFile queries AniSkip v2 with the episode length',
], ],
}); });
} }
if (url.includes('api.aniskip.com/v2/skip-times/1234/7')) { if (url.includes('api.aniskip.com/v1/skip-times/1234/7')) {
return makeMockResponse({ return makeMockResponse({
found: true, found: true,
results: [ results: [{ skip_type: 'op', interval: { start_time: 12.5, end_time: 54.2 } }],
{ skipType: 'op', interval: { startTime: 12.5, endTime: 54.2 } },
{ skipType: 'ed', interval: { startTime: 1300, endTime: 1390 } },
],
}); });
} }
throw new Error(`unexpected url: ${url}`); throw new Error(`unexpected url: ${url}`);
}, },
async () => { 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.malId, 1234);
assert.deepEqual(resolved.intro, { start: 12.5, end: 54.2 }); assert.equal(resolved.introStart, 12.5);
assert.deepEqual(resolved.outro, { start: 1300, end: 1390 }); assert.equal(resolved.introEnd, 54.2);
assert.equal(resolved.lookupStatus, 'ready'); assert.equal(resolved.lookupStatus, 'ready');
assert.equal(resolved.title, 'Anime My Show'); 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 treats an AniSkip 404 as a definite miss', async () => { test('resolveAniSkipMetadataForFile accepts intro payload starting at zero', async () => {
await withMockFetch( await withMockFetch(
async (input) => { async (input) => {
const url = normalizeFetchInput(input); const url = normalizeFetchInput(input);
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW); if (url.includes('myanimelist.net/search/prefix.json')) {
return makeMockResponse( return makeMockResponse({
{ found: false, results: [], message: 'No skip times found', statusCode: 404 }, categories: [{ items: [{ id: '1234', name: 'My Show' }] }],
404, });
);
},
async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E02.mkv', LOOKUP);
assert.equal(resolved.malId, 1234);
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);
},
);
} }
if (url.includes('api.aniskip.com/v1/skip-times/1234/1')) {
await withMockFetch( return makeMockResponse({
async () => makeMockResponse({}, 429), found: true,
results: [{ skip_type: 'op', interval: { start_time: 0, end_time: 89.5 } }],
});
}
throw new Error(`unexpected url: ${url}`);
},
async () => { async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP); const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E01.mkv');
assert.equal(resolved.lookupStatus, 'lookup_failed', 'MAL rate limit'); assert.equal(resolved.malId, 1234);
assert.equal(resolved.introStart, 0);
assert.equal(resolved.introEnd, 89.5);
assert.equal(resolved.lookupStatus, 'ready');
}, },
); );
}); });
@@ -263,7 +177,7 @@ test('resolveAniSkipMetadataForFile emits missing_mal_id when MAL search misses'
await withMockFetch( await withMockFetch(
async () => makeMockResponse({ categories: [] }), async () => makeMockResponse({ categories: [] }),
async () => { async () => {
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv', LOOKUP); const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv');
assert.equal(resolved.malId, null); assert.equal(resolved.malId, null);
assert.equal(resolved.lookupStatus, 'missing_mal_id'); assert.equal(resolved.lookupStatus, 'missing_mal_id');
}, },
+82 -96
View File
@@ -1,7 +1,6 @@
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import type { SkipInterval } from './aniskip-chapters';
export type AniSkipLookupStatus = export type AniSkipLookupStatus =
| 'ready' | 'ready'
@@ -16,16 +15,11 @@ export interface AniSkipMetadata {
episode: number | null; episode: number | null;
source: 'guessit' | 'fallback'; source: 'guessit' | 'fallback';
malId: number | null; malId: number | null;
intro: SkipInterval | null; introStart: number | null;
outro: SkipInterval | null; introEnd: number | null;
lookupStatus?: AniSkipLookupStatus; 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 { interface InferAniSkipDeps {
commandExists: (name: string) => boolean; commandExists: (name: string) => boolean;
runGuessit: (mediaPath: string) => string | null; runGuessit: (mediaPath: string) => string | null;
@@ -45,12 +39,12 @@ interface MalSearchResponse {
} }
interface AniSkipIntervalPayload { interface AniSkipIntervalPayload {
startTime?: unknown; start_time?: unknown;
endTime?: unknown; end_time?: unknown;
} }
interface AniSkipSkipItemPayload { interface AniSkipSkipItemPayload {
skipType?: unknown; skip_type?: unknown;
interval?: unknown; interval?: unknown;
} }
@@ -67,12 +61,9 @@ const ROMAN_SEASON_ALIASES: Record<number, readonly string[]> = {
}; };
const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword='; const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword=';
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v2/skip-times/'; const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v1/skip-times/';
const ANISKIP_USER_AGENT = 'SubMiner/ani-skip'; const ANISKIP_USER_AGENT = 'SubMiner/ani-skip';
const ANISKIP_FETCH_TIMEOUT_MS = 8000; 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([ const MAL_MATCH_STOPWORDS = new Set([
'the', 'the',
'this', 'this',
@@ -270,71 +261,49 @@ function toMalSearchItems(payload: unknown): MalSearchResult[] {
return items; return items;
} }
function parseInterval(raw: unknown): SkipInterval | null { function parseAniSkipPayload(payload: unknown): { start: number; end: number } | null {
if (typeof raw !== 'object' || raw === null) return null; const parsed = payload as AniSkipPayloadResponse;
const interval = raw as AniSkipIntervalPayload; const results = Array.isArray(parsed?.results) ? parsed.results : null;
const start = toNonNegativeNumber(interval.startTime); if (!results) return null;
const end = toPositiveNumber(interval.endTime);
return start !== null && end !== null && end > start ? { start, end } : 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) { for (const rawResult of results) {
const result = rawResult as AniSkipSkipItemPayload; const result = rawResult as AniSkipSkipItemPayload;
if (result.skipType === 'op' && !intro) intro = parseInterval(result.interval); if (
if (result.skipType === 'ed' && !outro) outro = parseInterval(result.interval); result.skip_type !== 'op' ||
typeof result.interval !== 'object' ||
result.interval === null
) {
continue;
} }
return { intro, outro }; 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;
} }
/** async function fetchJson<T>(url: string): Promise<T | null> {
* 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, { const response = await fetch(url, {
headers: { headers: {
'User-Agent': ANISKIP_USER_AGENT, 'User-Agent': ANISKIP_USER_AGENT,
}, },
signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS), signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS),
}); });
if (response.status === 404) return null; if (!response.ok) return null;
if (!response.ok) { try {
throw new Error(`HTTP ${response.status} from ${new URL(url).host}`); return (await response.json()) as T;
} catch {
return null;
} }
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> { async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> {
const lookup = season && season > 1 ? `${title} Season ${season}` : title; const lookup = season && season > 1 ? `${title} Season ${season}` : title;
const payload = await fetchJson(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`); const payload = await fetchJson<unknown>(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
const items = toMalSearchItems(payload); const items = toMalSearchItems(payload);
if (!items.length) return null; if (!items.length) return null;
@@ -357,17 +326,16 @@ async function resolveMalIdFromTitle(title: string, season: number | null): Prom
return bestMalId; return bestMalId;
} }
async function fetchAniSkipIntervals( async function fetchAniSkipPayload(
malId: number, malId: number,
episode: number, episode: number,
episodeLength: number, ): Promise<{ start: number; end: number } | null> {
): Promise<{ intro: SkipInterval | null; outro: SkipInterval | null }> { const payload = await fetchJson<unknown>(
await waitForAniSkipRequestSlot(); `${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed`,
const length = Math.round(episodeLength * 1000) / 1000;
const payload = await fetchJson(
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed&episodeLength=${length}`,
); );
return parseAniSkipPayload(payload); const parsed = payload as AniSkipPayloadResponse;
if (!parsed || parsed.found !== true) return null;
return parseAniSkipPayload(parsed);
} }
function detectEpisodeFromName(baseName: string): number | null { function detectEpisodeFromName(baseName: string): number | null {
@@ -488,8 +456,8 @@ export function parseAniSkipGuessitJson(stdout: string, mediaPath: string): AniS
episode: episodeFromDirect ?? episodeFromList, episode: episodeFromDirect ?? episodeFromList,
source: 'guessit', source: 'guessit',
malId: null, malId: null,
intro: null, introStart: null,
outro: null, introEnd: null,
lookupStatus: 'lookup_failed', lookupStatus: 'lookup_failed',
}; };
} catch { } catch {
@@ -533,20 +501,13 @@ export function inferAniSkipMetadataForFile(
episode: detectEpisodeFromName(baseName), episode: detectEpisodeFromName(baseName),
source: 'fallback', source: 'fallback',
malId: null, malId: null,
intro: null, introStart: null,
outro: null, introEnd: null,
lookupStatus: 'lookup_failed', 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); const inferred = inferAniSkipMetadataForFile(mediaPath);
if (!inferred.title) { if (!inferred.title) {
return { ...inferred, lookupStatus: 'lookup_failed' }; return { ...inferred, lookupStatus: 'lookup_failed' };
@@ -555,25 +516,50 @@ export async function resolveAniSkipMetadataForFile(
try { try {
const malId = await resolveMalIdFromTitle(inferred.title, inferred.season); const malId = await resolveMalIdFromTitle(inferred.title, inferred.season);
if (!malId) { if (!malId) {
return { ...inferred, lookupStatus: 'missing_mal_id' }; return {
} ...inferred,
if (!inferred.episode) { malId: null,
return { ...inferred, malId, lookupStatus: 'missing_episode' }; introStart: null,
introEnd: null,
lookupStatus: 'missing_mal_id',
};
} }
const { intro, outro } = await fetchAniSkipIntervals( if (!inferred.episode) {
malId,
inferred.episode,
options.episodeLength,
);
return { return {
...inferred, ...inferred,
malId, malId,
intro, introStart: null,
outro, introEnd: null,
lookupStatus: intro || outro ? 'ready' : 'missing_payload', 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,
introStart: payload.start,
introEnd: payload.end,
lookupStatus: 'ready',
}; };
} catch { } catch {
return { ...inferred, lookupStatus: 'lookup_failed' }; return {
...inferred,
malId: inferred.malId,
introStart: inferred.introStart,
introEnd: inferred.introEnd,
lookupStatus: 'lookup_failed',
};
} }
} }
+30 -310
View File
@@ -10,22 +10,19 @@ function readyMetadata(overrides: Partial<AniSkipMetadata> = {}): AniSkipMetadat
episode: 1, episode: 1,
source: 'fallback', source: 'fallback',
malId: 1234, malId: 1234,
intro: { start: 10, end: 95.5 }, introStart: 10,
outro: null, introEnd: 95.5,
lookupStatus: 'ready', lookupStatus: 'ready',
...overrides, ...overrides,
}; };
} }
const NO_SKIP_TIMES = { intro: null, outro: null } as const;
function createHarness(options?: { function createHarness(options?: {
enabled?: boolean; enabled?: boolean;
buttonKey?: string; buttonKey?: string;
metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>); metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>);
chapterList?: unknown; chapterList?: unknown;
playbackFeedback?: boolean; playbackFeedback?: boolean;
duration?: number | null;
}) { }) {
const state = { const state = {
enabled: options?.enabled ?? true, enabled: options?.enabled ?? true,
@@ -34,14 +31,9 @@ function createHarness(options?: {
osd: [] as string[], osd: [] as string[],
feedback: [] as string[], feedback: [] as string[],
resolveCalls: [] as string[], resolveCalls: [] as string[],
episodeLengths: [] as number[],
connected: true, connected: true,
duration: options?.duration === undefined ? 1440 : options.duration,
timePos: 0, timePos: 0,
chapterList: options?.chapterList ?? [], chapterList: options?.chapterList ?? [],
chapterListFails: false,
// When set, chapter-list reads wait for it before answering.
chapterGate: null as Promise<void> | null,
}; };
const deps = { const deps = {
@@ -49,9 +41,8 @@ function createHarness(options?: {
aniskipEnabled: state.enabled, aniskipEnabled: state.enabled,
aniskipButtonKey: state.buttonKey, aniskipButtonKey: state.buttonKey,
}), }),
resolveMetadataForFile: async (mediaPath, episodeLength) => { resolveMetadataForFile: async (mediaPath) => {
state.resolveCalls.push(mediaPath); state.resolveCalls.push(mediaPath);
state.episodeLengths.push(episodeLength);
const metadata = options?.metadata; const metadata = options?.metadata;
if (typeof metadata === 'function') return metadata(); if (typeof metadata === 'function') return metadata();
return metadata ?? readyMetadata(); return metadata ?? readyMetadata();
@@ -60,15 +51,7 @@ function createHarness(options?: {
state.commands.push(command); state.commands.push(command);
}, },
requestMpvProperty: async (name) => { requestMpvProperty: async (name) => {
if (name === 'chapter-list') { if (name === 'chapter-list') return state.chapterList;
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; return null;
}, },
isMpvConnected: () => state.connected, isMpvConnected: () => state.connected,
@@ -101,10 +84,6 @@ async function flushAsync(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0)); 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', () => { test('isRemoteMediaPath detects URLs but not local paths', () => {
assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true); assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true);
assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true); assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true);
@@ -122,7 +101,6 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
await flushAsync(); await flushAsync();
assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']); assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']);
assert.deepEqual(state.episodeLengths, [1440]);
const chapterCommands = chapterListCommands(state.commands); const chapterCommands = chapterListCommands(state.commands);
assert.equal(chapterCommands.length, 1); assert.equal(chapterCommands.length, 1);
const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>; const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>;
@@ -131,10 +109,7 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
{ time: 10, title: 'AniSkip Intro Start' }, { time: 10, title: 'AniSkip Intro Start' },
{ time: 95.5, title: 'AniSkip Intro End' }, { time: 95.5, title: 'AniSkip Intro End' },
]); ]);
assert.deepEqual(runtime.getSkipWindows(), { assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
intro: { start: 10, end: 95.5, source: 'aniskip' },
outro: null,
});
}); });
test('remote media paths and disabled config never resolve', async () => { test('remote media paths and disabled config never resolve', async () => {
@@ -156,18 +131,21 @@ test('skip intro seeks to intro end only inside the intro window', async () => {
state.timePos = 200; state.timePos = 200;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Skip only during intro or outro']); assert.deepEqual(state.osd, ['Skip intro only during intro']);
state.timePos = 30; state.timePos = 30;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Skip only during intro or outro', 'Skipped intro']); assert.deepEqual(state.osd, ['Skip intro only during intro', 'Skipped intro']);
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 95.5]]); const seek = state.commands.find(
(command) => command[0] === 'set_property' && command[1] === 'time-pos',
);
assert.deepEqual(seek, ['set_property', 'time-pos', 95.5]);
}); });
test('skip intro reports unavailable when no window was found', () => { test('skip intro reports unavailable when no window was found', () => {
const { runtime, state } = createHarness(); const { runtime, state } = createHarness();
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.osd, ['Intro/outro skip unavailable']); assert.deepEqual(state.osd, ['Intro skip unavailable']);
}); });
test('time-pos prompt shows once near intro start', async () => { test('time-pos prompt shows once near intro start', async () => {
@@ -180,7 +158,7 @@ test('time-pos prompt shows once near intro start', async () => {
runtime.handleTimePosChange({ time: 10.5 }); runtime.handleTimePosChange({ time: 10.5 });
runtime.handleTimePosChange({ time: 11 }); runtime.handleTimePosChange({ time: 11 });
assert.deepEqual(state.osd, ['You can skip the intro by pressing TAB']); assert.deepEqual(state.osd, ['You can skip by pressing TAB']);
}); });
test('prompt and skip messages use playback feedback when configured', async () => { test('prompt and skip messages use playback feedback when configured', async () => {
@@ -192,7 +170,7 @@ test('prompt and skip messages use playback feedback when configured', async ()
state.timePos = 30; state.timePos = 30;
runtime.handleClientMessage({ args: ['subminer-skip-intro'] }); runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
assert.deepEqual(state.feedback, ['You can skip the intro by pressing TAB', 'Skipped intro']); assert.deepEqual(state.feedback, ['You can skip by pressing TAB', 'Skipped intro']);
assert.deepEqual(state.osd, []); assert.deepEqual(state.osd, []);
}); });
@@ -262,13 +240,18 @@ test('aniskip refresh forces a fresh lookup for the current media', async () =>
assert.equal(state.resolveCalls.length, 2); assert.equal(state.resolveCalls.length, 2);
}); });
test('definite misses are cached and not looked up again for the same file', async () => { test('media without an intro window is cached and never re-resolved on reload of another file', async () => {
const { runtime, state } = createHarness({ const { runtime, state } = createHarness({
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }), metadata: readyMetadata({
malId: 1234,
introStart: null,
introEnd: null,
lookupStatus: 'missing_payload',
}),
}); });
runtime.handleMediaPathChange({ path: '/media/show.mkv' }); runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync(); await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES); assert.equal(runtime.getIntroWindow(), null);
assert.equal(chapterListCommands(state.commands).length, 0); assert.equal(chapterListCommands(state.commands).length, 0);
runtime.handleMediaPathChange({ path: '/media/other.mkv' }); runtime.handleMediaPathChange({ path: '/media/other.mkv' });
@@ -278,117 +261,25 @@ test('definite misses are cached and not looked up again for the same file', asy
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']); assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']);
}); });
test('transient lookup failures are not cached and retry on the next media load', async () => { test('transient lookup failures are retried on the next media load', async () => {
let calls = 0; let failures = 0;
const { runtime, state } = createHarness({ const { runtime, state } = createHarness({
metadata: async () => { metadata: async () => {
calls += 1; failures += 1;
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {}); return readyMetadata(
failures === 1 ? { introStart: null, introEnd: null, lookupStatus: 'lookup_failed' } : {},
);
}, },
}); });
runtime.handleMediaPathChange({ path: '/media/show.mkv' }); runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync(); await flushAsync();
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES); assert.equal(runtime.getIntroWindow(), null);
runtime.handleMediaPathChange({ path: '' }); runtime.handleMediaPathChange({ path: '' });
runtime.handleMediaPathChange({ path: '/media/show.mkv' }); runtime.handleMediaPathChange({ path: '/media/show.mkv' });
await flushAsync(); await flushAsync();
assert.equal(state.resolveCalls.length, 2); assert.equal(state.resolveCalls.length, 2);
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' }); assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
});
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', () => { test('disconnect clears bindings so reconnect rebinds the skip key', () => {
@@ -401,174 +292,3 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => {
['keybind', 'TAB', 'script-message subminer-skip-intro'], ['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]);
});
+123 -277
View File
@@ -1,16 +1,11 @@
import type { AniSkipMetadata } from './aniskip-metadata'; 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_SKIP_INTRO_MESSAGE = 'subminer-skip-intro';
export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh'; export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh';
const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB'; const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB';
const LEGACY_ANISKIP_BUTTON_KEY = 'y-k'; const LEGACY_ANISKIP_BUTTON_KEY = 'y-k';
const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
const SKIP_WINDOW_EPSILON_SECONDS = 0.35; const SKIP_WINDOW_EPSILON_SECONDS = 0.35;
const PROMPT_WINDOW_SECONDS = 3; const PROMPT_WINDOW_SECONDS = 3;
const PROMPT_OSD_DURATION_MS = 3000; const PROMPT_OSD_DURATION_MS = 3000;
@@ -21,7 +16,7 @@ export interface AniSkipRuntimeConfig {
export interface AniSkipRuntimeDeps { export interface AniSkipRuntimeDeps {
getAniSkipConfig: () => AniSkipRuntimeConfig; getAniSkipConfig: () => AniSkipRuntimeConfig;
resolveMetadataForFile: (mediaPath: string, episodeLength: number) => Promise<AniSkipMetadata>; resolveMetadataForFile: (mediaPath: string) => Promise<AniSkipMetadata>;
sendMpvCommand: (command: unknown[]) => void; sendMpvCommand: (command: unknown[]) => void;
requestMpvProperty: (name: string) => Promise<unknown>; requestMpvProperty: (name: string) => Promise<unknown>;
isMpvConnected: () => boolean; isMpvConnected: () => boolean;
@@ -33,65 +28,26 @@ export interface AniSkipRuntimeDeps {
logDebug: (message: string) => void; logDebug: (message: string) => void;
} }
export type SkipWindowKind = 'intro' | 'outro'; export interface AniSkipIntroWindow {
start: number;
export interface AniSkipWindow extends SkipInterval { end: number;
/** `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; malId: number | null;
} }
type MpvChapter = { time?: unknown; title?: unknown }; 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 { export function isRemoteMediaPath(mediaPath: string): boolean {
return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim()); 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) { export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
let requestGeneration = 0; let requestGeneration = 0;
let currentMediaPath = ''; let currentMediaPath = '';
let currentDuration: number | null = null; let introWindow: AniSkipIntroWindow | null = null;
// True once resolution for the current media has started (or finished). let promptShown = false;
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 boundButtonKey: string | null = null;
let legacyFallbackBound = false; let legacyFallbackBound = false;
// AniSkip results per media path, with the episode length they were fetched const introWindowCache = new Map<string, AniSkipIntroWindow | null>();
// for (v2 picks times by length). Only definitive answers are stored.
const lookupCache = new Map<string, { duration: number; result: AniSkipLookupResult }>();
function resolveButtonKey(): string { function resolveButtonKey(): string {
const key = deps.getAniSkipConfig().aniskipButtonKey.trim(); const key = deps.getAniSkipConfig().aniskipButtonKey.trim();
@@ -137,39 +93,22 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
} }
} }
async function readChapterList(): Promise<MpvChapter[] | null> { async function setIntroChapters(introStart: number, introEnd: number): Promise<void> {
let existing: MpvChapter[] = [];
try { try {
const chapterList = await deps.requestMpvProperty('chapter-list'); const chapterList = await deps.requestMpvProperty('chapter-list');
return Array.isArray(chapterList) ? (chapterList as MpvChapter[]) : []; if (Array.isArray(chapterList)) {
existing = chapterList as MpvChapter[];
}
} catch { } catch {
// chapter-list may be unavailable mid-load // chapter-list may be unavailable mid-load; fall back to AniSkip chapters only
return null;
} }
} const chapters = existing.filter(
(chapter) =>
/** True while the given request generation still owns the given media. */ typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
function ownsPlayback(generation: number, mediaPath: string): boolean { );
return generation === requestGeneration && mediaPath === currentMediaPath; chapters.push({ time: introStart, title: 'AniSkip Intro Start' });
} chapters.push({ time: introEnd, title: 'AniSkip Intro End' });
/** 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) => { chapters.sort((a, b) => {
const aTime = typeof a.time === 'number' ? a.time : 0; const aTime = typeof a.time === 'number' ? a.time : 0;
const bTime = typeof b.time === 'number' ? b.time : 0; const bTime = typeof b.time === 'number' ? b.time : 0;
@@ -178,13 +117,21 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
deps.sendMpvCommand(['set_property', 'chapter-list', chapters]); deps.sendMpvCommand(['set_property', 'chapter-list', chapters]);
} }
async function removeSkipChapters(): Promise<void> { async function removeIntroChapters(): Promise<void> {
if (!deps.isMpvConnected()) return; if (!deps.isMpvConnected()) return;
const generation = requestGeneration; let existing: MpvChapter[] = [];
const mediaPath = currentMediaPath; try {
const existing = await readChapterList(); const chapterList = await deps.requestMpvProperty('chapter-list');
if (!existing || !ownsPlayback(generation, mediaPath)) return; if (Array.isArray(chapterList)) {
const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter)); existing = chapterList as MpvChapter[];
}
} catch {
return;
}
const filtered = existing.filter(
(chapter) =>
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
);
if (filtered.length !== existing.length) { if (filtered.length !== existing.length) {
deps.sendMpvCommand(['set_property', 'chapter-list', filtered]); deps.sendMpvCommand(['set_property', 'chapter-list', filtered]);
} }
@@ -192,162 +139,81 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
function clearState(): void { function clearState(): void {
requestGeneration += 1; requestGeneration += 1;
resolutionStarted = false; introWindow = null;
retryResolution = false; promptShown = false;
windows = { intro: null, outro: null };
promptShown.intro = false;
promptShown.outro = false;
} }
function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void { async function applyIntroWindow(window: AniSkipIntroWindow): Promise<void> {
introWindow = window;
promptShown = false;
await setIntroChapters(window.start, window.end);
deps.logInfo( deps.logInfo(
`AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${ `AniSkip intro window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (MAL ${
window.source window.malId ?? '-'
}, MAL ${malId ?? '-'})`, })`,
); );
} }
/** Installs the file-chapter windows, resetting the prompts. */ async function resolveForMedia(mediaPath: string, options?: { force?: boolean }): Promise<void> {
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);
}
}
/**
* 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);
}
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, duration);
} catch (error) {
deps.logWarn('AniSkip metadata lookup failed', error);
return null;
}
const result: AniSkipLookupResult = {
intro: metadata.intro,
outro: metadata.outro,
malId: metadata.malId,
};
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;
}
async function resolveForMedia(mediaPath: string, duration: number): Promise<void> {
if (!deps.getAniSkipConfig().aniskipEnabled) return; if (!deps.getAniSkipConfig().aniskipEnabled) return;
const generation = requestGeneration; if (!mediaPath || isRemoteMediaPath(mediaPath)) {
const isStale = () => generation !== requestGeneration || mediaPath !== currentMediaPath; deps.logDebug('AniSkip lookup skipped: no local media path');
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; return;
} }
const lookup = await lookUpAniSkip(mediaPath, duration, generation); if (options?.force) {
if (isStale()) return; introWindowCache.delete(mediaPath);
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; const generation = requestGeneration;
void deps const cached = introWindowCache.get(mediaPath);
.requestMpvProperty('duration') if (cached !== undefined) {
.then((value) => { if (cached) {
if (generation !== requestGeneration || !isUsableDuration(value)) return; await applyIntroWindow(cached);
currentDuration ??= value; }
maybeStartResolution(); return;
}) }
.catch(() => {
// duration is unavailable until the file is loaded; duration-change will follow let metadata: AniSkipMetadata;
}); try {
metadata = await deps.resolveMetadataForFile(mediaPath);
} catch (error) {
deps.logWarn('AniSkip metadata lookup failed', error);
return;
}
if (generation !== requestGeneration || mediaPath !== currentMediaPath) {
return;
} }
function getActiveWindow(now: number): SkipWindowKind | null {
for (const kind of ['intro', 'outro'] as const) {
const window = windows[kind];
if ( if (
window && metadata.lookupStatus !== 'ready' ||
now >= window.start - SKIP_WINDOW_EPSILON_SECONDS && metadata.introStart === null ||
now <= window.end + SKIP_WINDOW_EPSILON_SECONDS metadata.introEnd === null ||
metadata.introEnd <= metadata.introStart
) { ) {
return kind; // 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(
return null; `AniSkip: no intro window for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
);
return;
} }
function skipNow(): void { const window: AniSkipIntroWindow = {
start: metadata.introStart,
end: metadata.introEnd,
malId: metadata.malId,
};
introWindowCache.set(mediaPath, window);
await applyIntroWindow(window);
}
function skipIntroNow(): void {
if (!deps.getAniSkipConfig().aniskipEnabled) return; if (!deps.getAniSkipConfig().aniskipEnabled) return;
if (!windows.intro && !windows.outro) { if (!introWindow) {
showPlaybackFeedback('Intro/outro skip unavailable'); showPlaybackFeedback('Intro skip unavailable');
return; return;
} }
const now = deps.getCurrentTimePos(); const now = deps.getCurrentTimePos();
@@ -355,56 +221,40 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
showPlaybackFeedback('Skip unavailable'); showPlaybackFeedback('Skip unavailable');
return; return;
} }
const kind = getActiveWindow(now); if (
const window = kind ? windows[kind] : null; now < introWindow.start - SKIP_WINDOW_EPSILON_SECONDS ||
if (!kind || !window) { now > introWindow.end + SKIP_WINDOW_EPSILON_SECONDS
showPlaybackFeedback('Skip only during intro or outro'); ) {
showPlaybackFeedback('Skip intro only during intro');
return; return;
} }
deps.sendMpvCommand(['set_property', 'time-pos', window.end]); deps.sendMpvCommand(['set_property', 'time-pos', introWindow.end]);
showPlaybackFeedback(`Skipped ${KIND_LABEL[kind].word}`); showPlaybackFeedback('Skipped intro');
} }
function handleTimePosChange({ time }: { time: number }): void { function handleTimePosChange({ time }: { time: number }): void {
if (!introWindow || promptShown) return;
if (!deps.getAniSkipConfig().aniskipEnabled) return; if (!deps.getAniSkipConfig().aniskipEnabled) return;
for (const kind of ['intro', 'outro'] as const) { const promptWindowEnd = Math.min(introWindow.start + PROMPT_WINDOW_SECONDS, introWindow.end);
const window = windows[kind]; if (time >= introWindow.start && time < promptWindowEnd) {
if (!window || promptShown[kind]) continue; promptShown = true;
const promptWindowEnd = Math.min(window.start + PROMPT_WINDOW_SECONDS, window.end); showPlaybackFeedback(`You can skip by pressing ${resolveButtonKey()}`);
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 { function handleMediaPathChange({ path }: { path: string }): void {
const nextPath = typeof path === 'string' ? path : ''; const nextPath = typeof path === 'string' ? path : '';
if (nextPath === currentMediaPath && resolutionStarted) { if (nextPath === currentMediaPath && introWindow) {
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. // Same-media reload: mpv rebuilt the chapter list, so re-apply markers.
void setSkipChapters().catch(() => {}); void setIntroChapters(introWindow.start, introWindow.end).catch(() => {});
return; return;
} }
currentMediaPath = nextPath; currentMediaPath = nextPath;
currentDuration = null;
clearState(); clearState();
if (!nextPath || !deps.getAniSkipConfig().aniskipEnabled) return; if (!nextPath) return;
requestCurrentDuration(); void resolveForMedia(nextPath).catch((error) => {
deps.logWarn('AniSkip media resolution failed', error);
});
} }
function handleConnectionChange({ connected }: { connected: boolean }): void { function handleConnectionChange({ connected }: { connected: boolean }): void {
@@ -413,7 +263,6 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
legacyFallbackBound = false; legacyFallbackBound = false;
clearState(); clearState();
currentMediaPath = ''; currentMediaPath = '';
currentDuration = null;
return; return;
} }
bindSkipKeys(); bindSkipKeys();
@@ -422,46 +271,43 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
function handleClientMessage({ args }: { args: string[] }): void { function handleClientMessage({ args }: { args: string[] }): void {
const messageName = args[0]; const messageName = args[0];
if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) { if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) {
skipNow(); skipIntroNow();
return; return;
} }
if (messageName === ANISKIP_REFRESH_MESSAGE) { if (messageName === ANISKIP_REFRESH_MESSAGE) {
if (!currentMediaPath) return; const mediaPath = currentMediaPath;
lookupCache.delete(currentMediaPath); if (!mediaPath) return;
clearState(); clearState();
void removeSkipChapters().catch(() => {}); void removeIntroChapters().catch(() => {});
if (currentDuration === null) { void resolveForMedia(mediaPath, { force: true }).catch((error) => {
requestCurrentDuration(); deps.logWarn('AniSkip refresh failed', error);
return; });
}
maybeStartResolution();
} }
} }
function applyConfigChange(): void { function applyConfigChange(): void {
bindSkipKeys(); bindSkipKeys();
if (!deps.getAniSkipConfig().aniskipEnabled) { const enabled = deps.getAniSkipConfig().aniskipEnabled;
if (!enabled) {
clearState(); clearState();
void removeSkipChapters().catch(() => {}); void removeIntroChapters().catch(() => {});
return; return;
} }
if (!currentMediaPath || resolutionStarted) return; if (!introWindow && currentMediaPath) {
if (currentDuration === null) { void resolveForMedia(currentMediaPath).catch((error) => {
requestCurrentDuration(); deps.logWarn('AniSkip media resolution failed', error);
return; });
} }
maybeStartResolution();
} }
return { return {
handleConnectionChange, handleConnectionChange,
handleMediaPathChange, handleMediaPathChange,
handleDurationChange,
handleTimePosChange, handleTimePosChange,
handleClientMessage, handleClientMessage,
applyConfigChange, applyConfigChange,
skipNow, skipIntroNow,
getSkipWindows: (): AniSkipWindows => windows, getIntroWindow: () => introWindow,
}; };
} }
@@ -7,6 +7,14 @@ import {
parseFirstRunSetupSubmissionUrl, parseFirstRunSetupSubmissionUrl,
} from './first-run-setup-window'; } from './first-run-setup-window';
import type { CommandLineLauncherSnapshot } from './command-line-launcher'; import type { CommandLineLauncherSnapshot } from './command-line-launcher';
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
const READY_FFMPEG: FfmpegSetupStatus = {
kind: 'ready',
source: 'system',
ffmpegPath: '/usr/bin/ffmpeg',
ffprobePath: '/usr/bin/ffprobe',
};
function createCommandLineLauncherSnapshot( function createCommandLineLauncherSnapshot(
overrides: Partial<CommandLineLauncherSnapshot> = {}, overrides: Partial<CommandLineLauncherSnapshot> = {},
@@ -52,6 +60,7 @@ test('buildFirstRunSetupHtml shows legacy mpv plugin removal action with confirm
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -90,6 +99,7 @@ test('buildFirstRunSetupHtml marks an invalid configured mpv path as invalid', (
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -117,6 +127,7 @@ test('buildFirstRunSetupHtml explains the config blocker when setup is missing c
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -146,6 +157,7 @@ test('buildFirstRunSetupHtml explains external yomitan mode and keeps finish ena
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -221,6 +233,7 @@ test('buildFirstRunSetupHtml reports a broken included runtime in the optional l
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'failed', status: 'failed',
@@ -275,6 +288,7 @@ test('buildFirstRunSetupHtml labels a missing launcher without error-message wor
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'ready', status: 'ready',
@@ -310,6 +324,7 @@ test('buildFirstRunSetupHtml disables launcher install when no target is install
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
launcher: { launcher: {
status: 'not_installable', status: 'not_installable',
@@ -403,6 +418,7 @@ test('opening first-run setup shows and focuses window after content loads', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -469,6 +485,7 @@ test('opening first-run setup skips rendering if window is destroyed after snaps
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}; };
@@ -538,6 +555,7 @@ test('first-run setup action can skip rerender after launching another window',
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -620,6 +638,7 @@ test('closing incomplete first-run setup quits app outside background mode', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -692,6 +711,7 @@ test('closing completed first-run setup quits app when completion policy allows
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -747,6 +767,7 @@ test('Hachidori setup names the active dictionary backend', () => {
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -775,3 +796,55 @@ test('setup parses link and unlink actions without losing the host address', ()
{ action: 'unlink-hachidori-host' }, { action: 'unlink-hachidori-host' },
); );
}); });
test('FFmpeg card offers a download only when one would be used', () => {
const render = (ffmpeg: FfmpegSetupStatus) =>
buildFirstRunSetupHtml({
configReady: true,
dictionaryCount: 1,
canFinish: true,
externalYomitanConfigured: false,
pluginStatus: 'installed',
pluginInstallPathSummary: null,
mpvExecutablePath: '',
mpvExecutablePathStatus: 'blank',
windowsMpvShortcuts: {
supported: false,
startMenuEnabled: false,
desktopEnabled: false,
startMenuInstalled: false,
desktopInstalled: false,
status: 'optional',
},
ffmpeg,
commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null,
});
const system = render(READY_FFMPEG);
assert.match(system, /Found on your system\. Nothing to do\./);
assert.match(system, /\/usr\/bin\/ffprobe/);
assert.doesNotMatch(system, /action=install-ffmpeg/);
const missing = render({ kind: 'missing', missing: ['ffprobe'], downloadable: true });
assert.match(missing, /Not found on PATH: ffprobe\./);
assert.match(missing, /action=install-ffmpeg/);
const unsupported = render({ kind: 'missing', missing: ['ffmpeg'], downloadable: false });
assert.match(unsupported, /No download is available for this platform/);
assert.doesNotMatch(unsupported, /action=install-ffmpeg/);
const broken = {
kind: 'broken',
path: '/x/ffmpeg',
message: 'exit 127',
downloadable: true,
} as const;
assert.doesNotMatch(render({ ...broken, managed: false }), /action=install-ffmpeg/);
assert.match(render({ ...broken, managed: true }), /Download FFmpeg again/);
assert.deepEqual(
parseFirstRunSetupSubmissionUrl('subminer://first-run-setup?action=install-ffmpeg'),
{ action: 'install-ffmpeg' },
);
});
@@ -1,3 +1,4 @@
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
import type { HachidoriHostStatus } from '../../shared/hachidori-sharing'; import type { HachidoriHostStatus } from '../../shared/hachidori-sharing';
import type { DictionaryBackend } from '../../types/config'; import type { DictionaryBackend } from '../../types/config';
import { getFirstRunSetupCompletionMessage } from './first-run-setup-service'; import { getFirstRunSetupCompletionMessage } from './first-run-setup-service';
@@ -34,6 +35,7 @@ export type FirstRunSetupSubmission =
| 'remove-legacy-plugin' | 'remove-legacy-plugin'
| 'install-bun' | 'install-bun'
| 'install-command-line-launcher' | 'install-command-line-launcher'
| 'install-ffmpeg'
| 'open-yomitan-settings' | 'open-yomitan-settings'
| 'open-config-settings' | 'open-config-settings'
| 'refresh' | 'refresh'
@@ -63,6 +65,7 @@ export interface FirstRunSetupHtmlModel {
status: 'installed' | 'optional' | 'skipped' | 'failed'; status: 'installed' | 'optional' | 'skipped' | 'failed';
}; };
commandLineLauncher: CommandLineLauncherSnapshot; commandLineLauncher: CommandLineLauncherSnapshot;
ffmpeg: FfmpegSetupStatus;
message: string | null; message: string | null;
} }
@@ -154,6 +157,56 @@ function renderCommandLineLauncherSection(
</section>`; </section>`;
} }
function renderFfmpegCard(ffmpeg: FfmpegSetupStatus): string {
const lines: string[] = [];
let badge: string;
let showDownload = false;
if (ffmpeg.kind === 'ready') {
lines.push(
ffmpeg.source === 'system'
? 'Found on your system. Nothing to do.'
: 'Using the copy SubMiner downloaded. Nothing to do.',
`FFmpeg: ${ffmpeg.ffmpegPath}`,
`FFprobe: ${ffmpeg.ffprobePath}`,
);
badge = renderStatusBadge(ffmpeg.source === 'system' ? 'Detected' : 'Downloaded', 'ready');
} else if (ffmpeg.kind === 'missing') {
lines.push(`Not found on PATH: ${ffmpeg.missing.join(', ')}.`);
lines.push(
ffmpeg.downloadable
? 'Download a copy for SubMiner (under 60 MB), or install FFmpeg yourself and refresh.'
: 'No download is available for this platform. Install FFmpeg, then refresh.',
);
badge = renderStatusBadge('Missing', 'warn');
showDownload = ffmpeg.downloadable;
} else {
lines.push(`${ffmpeg.path} failed to run: ${ffmpeg.message}`);
lines.push(
ffmpeg.managed
? 'Download it again to repair the copy SubMiner downloaded.'
: 'Repair or remove that FFmpeg install, then refresh.',
);
badge = renderStatusBadge('Not working', 'danger');
showDownload = ffmpeg.managed && ffmpeg.downloadable;
}
// The button relabels itself because the page only re-renders once the download finishes.
const downloadButton = showDownload
? `<div class="inline-actions"><button onclick="this.disabled = true; this.textContent = 'Downloading FFmpeg...'; window.location.href='subminer://first-run-setup?action=install-ffmpeg'">${ffmpeg.kind === 'broken' ? 'Download FFmpeg again' : 'Download FFmpeg'}</button></div>`
: '';
return `
<div class="card block">
<div class="card-head">
<div>
<strong>FFmpeg</strong>
<div class="meta">Used for card audio and screenshots, and subtitle generation.</div>
${lines.map((line) => `<div class="meta">${escapeHtml(line)}</div>`).join('')}
</div>
${badge}
</div>
${downloadButton}
</div>`;
}
export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string { export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? []; const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? [];
const finishButtonLabel = const finishButtonLabel =
@@ -535,6 +588,7 @@ export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)} ${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)}
</div> </div>
${hostCard} ${hostCard}
${renderFfmpegCard(model.ffmpeg)}
${mpvExecutablePathCard} ${mpvExecutablePathCard}
${windowsShortcutCard} ${windowsShortcutCard}
${renderCommandLineLauncherSection(model.commandLineLauncher)} ${renderCommandLineLauncherSection(model.commandLineLauncher)}
@@ -566,6 +620,7 @@ export function parseFirstRunSetupSubmissionUrl(rawUrl: string): FirstRunSetupSu
action !== 'configure-windows-mpv-shortcuts' && action !== 'configure-windows-mpv-shortcuts' &&
action !== 'install-bun' && action !== 'install-bun' &&
action !== 'install-command-line-launcher' && action !== 'install-command-line-launcher' &&
action !== 'install-ffmpeg' &&
action !== 'open-yomitan-settings' && action !== 'open-yomitan-settings' &&
action !== 'open-config-settings' && action !== 'open-config-settings' &&
action !== 'refresh' && action !== 'refresh' &&