diff --git a/.github/workflows/docs-pages.yml b/.github/workflows/docs-pages.yml index e95f137d..477fa1d8 100644 --- a/.github/workflows/docs-pages.yml +++ b/.github/workflows/docs-pages.yml @@ -2,6 +2,11 @@ name: Docs Pages on: workflow_dispatch: + inputs: + rebuild_archives: + description: 'Stable tags to rebuild in R2 (comma-separated, or "all"); archives are otherwise built once' + required: false + default: '' push: branches: - main @@ -10,6 +15,8 @@ on: paths: - 'docs-site/**' - 'scripts/docs-versioning.ts' + - 'scripts/docs-versioned-assets.ts' + - 'scripts/docs-archive-store.ts' - 'scripts/build-versioned-docs.ts' - '.github/workflows/docs-pages.yml' - 'package.json' @@ -54,20 +61,21 @@ jobs: bun install --frozen-lockfile cd docs-site && bun install --frozen-lockfile - - name: Cache versioned docs archives - if: steps.tag_guard.outputs.stable_tag != 'false' - uses: actions/cache@v4 - with: - path: .tmp/docs-versioned-archive-cache - key: docs-versioned-archives-${{ runner.os }}-${{ hashFiles('docs-site/.vitepress/**', 'docs-site/public/assets/fonts/**', 'docs-site/package.json', 'docs-site/bun.lock', 'scripts/build-versioned-docs.ts', 'scripts/docs-versioning.ts') }} - - name: Test docs if: steps.tag_guard.outputs.stable_tag != 'false' run: bun run docs:test + # Builds only archives missing from R2 (plus any requested rebuilds), then the + # root and /main/ builds that make up the Pages deployment. - name: Build versioned docs if: steps.tag_guard.outputs.stable_tag != 'false' - run: bun run docs:build:versioned + env: + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + DOCS_ARCHIVE_R2_ACCESS_KEY_ID: ${{ secrets.DOCS_ARCHIVE_R2_ACCESS_KEY_ID }} + DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY: ${{ secrets.DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY }} + DOCS_ARCHIVE_R2_BUCKET: ${{ vars.DOCS_ARCHIVE_R2_BUCKET }} + REBUILD_ARCHIVES: ${{ inputs.rebuild_archives }} + run: bun run scripts/build-versioned-docs.ts --require-archives "--rebuild-archives=${REBUILD_ARCHIVES}" - name: Deploy docs to Cloudflare Pages if: steps.tag_guard.outputs.stable_tag != 'false' @@ -75,4 +83,6 @@ jobs: with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - command: pages deploy .tmp/docs-versioned-site --project-name "${{ vars.CLOUDFLARE_PAGES_PROJECT_NAME }}" --branch main + # Run from docs-site so Wrangler bundles docs-site/functions (the /v/* archive server). + workingDirectory: docs-site + command: pages deploy ../.tmp/docs-versioned-site --project-name "${{ vars.CLOUDFLARE_PAGES_PROJECT_NAME }}" --branch main diff --git a/changes/docs-site-simplify.md b/changes/docs-site-simplify.md new file mode 100644 index 00000000..542271e8 --- /dev/null +++ b/changes/docs-site-simplify.md @@ -0,0 +1,6 @@ +type: docs +area: docs + +- Rewrote the docs site to be shorter and easier to scan: pages lead with setup and use, reference material lives in compact tables, and internal detail was cut from user pages. +- The configuration reference now has a short explanation and a key/default table for each config block. +- Fixed docs that no longer matched current behavior. diff --git a/docs-site/.vitepress/config.ts b/docs-site/.vitepress/config.ts index acace595..42795fd1 100644 --- a/docs-site/.vitepress/config.ts +++ b/docs-site/.vitepress/config.ts @@ -1,6 +1,6 @@ import { spawnSync } from 'node:child_process'; -import { existsSync, readFileSync, statSync } from 'node:fs'; -import { extname, join, posix, resolve, sep } from 'node:path'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; import type { DefaultTheme, HeadConfig, TransformContext, UserConfig } from 'vitepress'; const DOCS_HOSTNAME = 'https://docs.subminer.moe'; @@ -14,12 +14,6 @@ const PLAUSIBLE_INIT_SCRIPT = [ type DocsChannel = 'stable-root' | 'stable-archive' | 'main'; -type VersionManifest = { - latestStable: string; - channels: Array<{ label: string; path: string }>; - versions: Array<{ version: string; path: string }>; -}; - function optionalEnv(value: string | undefined): string | undefined { return value && value !== 'undefined' ? value : undefined; } @@ -32,17 +26,6 @@ const docsSourceDir = optionalEnv(process.env.SUBMINER_DOCS_SOURCE_DIR) ?? proce const repoDocsDir = optionalEnv(process.env.SUBMINER_DOCS_REPO_DIR) ?? process.cwd(); const channel = normalizeChannel(optionalEnv(process.env.SUBMINER_DOCS_CHANNEL)); const docsVersion = optionalEnv(process.env.SUBMINER_DOCS_VERSION); -const latestStable = optionalEnv(process.env.SUBMINER_DOCS_LATEST_STABLE) ?? 'v0.18.0'; -const versionManifest = parseVersionManifest(process.env.SUBMINER_DOCS_VERSION_MANIFEST); -const versionLinkOrigin = - optionalEnv(process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN) ?? 'production'; - -function getLocalArchiveDir(): string { - return resolve( - optionalEnv(process.env.SUBMINER_DOCS_LOCAL_ARCHIVE_DIR) ?? - join(docsSourceDir, '..', '.tmp/docs-versioned-site'), - ); -} function normalizeBase(value: string): string { if (!value || value === '/') return '/'; @@ -54,21 +37,6 @@ function normalizeChannel(value: string | undefined): DocsChannel { return 'stable-root'; } -function parseVersionManifest(value: string | undefined): VersionManifest { - if (!value || value === 'undefined') { - return { - latestStable, - channels: [ - { label: 'Latest stable', path: '/' }, - { label: 'main', path: '/main/' }, - ], - versions: [{ version: latestStable, path: `/v/${latestStable.replace(/^v/, '')}/` }], - }; - } - - return JSON.parse(value) as VersionManifest; -} - function withDocsBase(path: string): string { if (/^[a-z]+:\/\//i.test(path)) return path; const normalizedPath = path.startsWith('/') ? path : `/${path}`; @@ -164,137 +132,16 @@ function filterSidebar(items: DefaultTheme.SidebarItem[]): DefaultTheme.SidebarI .filter((item): item is DefaultTheme.SidebarItem => Boolean(item)); } -function versionSwitchLink(path: string): string { - if (/^[a-z]+:\/\//i.test(path)) return path; - const normalizedPath = path.startsWith('/') ? path : `/${path}`; - if (versionLinkOrigin === 'local') return localVersionSwitchLink(normalizedPath); - return `${DOCS_HOSTNAME}${normalizedPath}`; -} - -function localVersionSwitchLink(path: string): string { - if (base === '/') return path; - - const basePath = base.replace(/\/$/, ''); - const targetPath = path === '/' ? '/' : path.replace(/\/$/, ''); - const relativePath = posix.relative(basePath, targetPath) || '.'; - - return path.endsWith('/') ? `${relativePath}/` : relativePath; -} - -function shouldHandleLocalVersionRoute(pathname: string): boolean { - if (base !== '/' || channel !== 'stable-root') return false; - return /^\/main(?:\/|$)/.test(pathname) || /^\/v\/[^/]+(?:\/|$)/.test(pathname); -} - -function contentTypeForPath(path: string): string { - switch (extname(path)) { - case '.css': - return 'text/css; charset=utf-8'; - case '.gif': - return 'image/gif'; - case '.ico': - return 'image/x-icon'; - case '.jpg': - case '.jpeg': - return 'image/jpeg'; - case '.js': - case '.mjs': - return 'text/javascript; charset=utf-8'; - case '.json': - case '.jsonc': - return 'application/json; charset=utf-8'; - case '.mp4': - return 'video/mp4'; - case '.png': - return 'image/png'; - case '.svg': - return 'image/svg+xml'; - case '.ttf': - return 'font/ttf'; - case '.webm': - return 'video/webm'; - case '.woff': - return 'font/woff'; - case '.woff2': - return 'font/woff2'; - case '.xml': - return 'application/xml; charset=utf-8'; - default: - return 'text/html; charset=utf-8'; - } -} - -function isFile(path: string): boolean { - try { - return statSync(path).isFile(); - } catch { - return false; - } -} - -function archiveFileForPathname(pathname: string): string | null { - if (!shouldHandleLocalVersionRoute(pathname)) return null; - - const localArchiveDir = getLocalArchiveDir(); - const routePath = decodeURIComponent(pathname).replace(/^\/+/, ''); - const filePath = resolve(localArchiveDir, routePath); - if (filePath !== localArchiveDir && !filePath.startsWith(`${localArchiveDir}${sep}`)) { - return null; - } - - const candidates = pathname.endsWith('/') - ? [join(filePath, 'index.html')] - : extname(filePath) - ? [filePath] - : [`${filePath}.html`, join(filePath, 'index.html')]; - - return candidates.find(isFile) ?? null; -} - -function serveLocalArchiveRoute(pathname: string, response: DevServerResponse): boolean { - if ( - (optionalEnv(process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN) ?? versionLinkOrigin) !== 'local' - ) { - return false; - } - - const filePath = archiveFileForPathname(pathname); - if (!filePath) return false; - - response.statusCode = 200; - response.setHeader('Content-Type', contentTypeForPath(filePath)); - response.end(readFileSync(filePath)); - return true; -} - -type DevServerResponse = { - statusCode: number; - setHeader(name: string, value: string): void; - end(chunk?: string | Uint8Array): void; -}; - -const versionItems = [ - { - text: `Latest stable (${versionManifest.latestStable})`, - link: versionSwitchLink('/'), - target: '_self', - noIcon: true, - }, - ...versionManifest.channels - .filter((entry) => entry.label !== 'Latest stable') - .map((entry) => ({ - text: entry.label, - link: versionSwitchLink(entry.path), - target: '_self', - noIcon: true, - })), - ...versionManifest.versions.map((entry) => ({ - text: entry.version, - link: versionSwitchLink(entry.path), - target: '_self', - noIcon: true, - })), -]; +// Version navigation targets other builds (root, `/main/`, `/versions`), so it links to +// production by absolute URL: base-relative links would stay inside this build, and +// `target: '_self'` makes the VitePress router do a full page load. The list is +// deliberately static; the full release list lives on the root-only `/versions` page +// so frozen `/v//` archives never need a rebuild when a new tag ships. +const versionItems: DefaultTheme.NavItemWithLink[] = [ + { text: 'Latest stable', link: `${DOCS_HOSTNAME}/` }, + { text: 'main', link: `${DOCS_HOSTNAME}/main/` }, + { text: 'All versions', link: `${DOCS_HOSTNAME}/versions` }, +].map((item) => ({ ...item, target: '_self', noIcon: true })); function sitemapUrlToPage(url: string): string { const route = url.replace(/\.html$/, '').replace(/^\/+|\/+$/g, ''); @@ -336,7 +183,7 @@ const nav: DefaultTheme.NavItem[] = [ { text: 'Configuration', link: '/configuration' }, { text: 'Changelog', link: '/changelog' }, { text: 'Troubleshooting', link: '/troubleshooting' }, - { text: docsVersion ?? (channel === 'main' ? 'main' : latestStable), items: versionItems }, + { text: docsVersion ?? 'main', items: versionItems }, ]; const sidebar: DefaultTheme.SidebarItem[] = [ @@ -394,33 +241,6 @@ const config: UserConfig = { 'SubMiner: an MPV immersion-mining overlay with Yomitan and AnkiConnect integration.', base, ...(outDir ? { outDir } : {}), - vite: { - plugins: [ - { - name: 'subminer-docs-local-version-redirects', - configureServer(server) { - server.middlewares.use((request, response, next) => { - const requestUrl = new URL(request.url ?? '/', 'http://localhost'); - if (serveLocalArchiveRoute(requestUrl.pathname, response)) { - return; - } - - if (!shouldHandleLocalVersionRoute(requestUrl.pathname)) { - next(); - return; - } - - response.statusCode = 302; - response.setHeader( - 'Location', - `${DOCS_HOSTNAME}${requestUrl.pathname}${requestUrl.search}`, - ); - response.end(); - }); - }, - }, - ], - }, head: [ ['link', { rel: 'preconnect', href: PLAUSIBLE_PROXY_HOSTNAME }], [ diff --git a/docs-site/.vitepress/theme/components/StatusLine.vue b/docs-site/.vitepress/theme/components/StatusLine.vue index 0d523cc6..56bc77bf 100644 --- a/docs-site/.vitepress/theme/components/StatusLine.vue +++ b/docs-site/.vitepress/theme/components/StatusLine.vue @@ -1,10 +1,10 @@ @@ -40,8 +40,8 @@ const lastUpdated = computed(() => {
{{ section }} - {{ lastUpdated }} - + {{ today }} + GPL-3.0
diff --git a/docs-site/.vitepress/theme/status-line.test.ts b/docs-site/.vitepress/theme/status-line.test.ts index 61317fd4..4d33e780 100644 --- a/docs-site/.vitepress/theme/status-line.test.ts +++ b/docs-site/.vitepress/theme/status-line.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'bun:test'; -import { formatStatusLineFilePath } from './status-line'; +import { formatStatusLineDate, formatStatusLineFilePath } from './status-line'; test('status line file path formats root home as index markdown', () => { expect(formatStatusLineFilePath('/')).toBe('index.md'); @@ -10,7 +10,9 @@ test('status line file path formats version archive home without trailing slash' }); test('status line file path keeps normal docs routes as markdown files', () => { - expect(formatStatusLineFilePath('/v/0.12.0/configuration')).toBe( - 'v/0.12.0/configuration.md', - ); + expect(formatStatusLineFilePath('/v/0.12.0/configuration')).toBe('v/0.12.0/configuration.md'); +}); + +test('status line date uses the local calendar day, zero padded', () => { + expect(formatStatusLineDate(new Date(2026, 0, 5, 23, 59))).toBe('2026-01-05'); }); diff --git a/docs-site/.vitepress/theme/status-line.ts b/docs-site/.vitepress/theme/status-line.ts index e473e54c..e47bd82e 100644 --- a/docs-site/.vitepress/theme/status-line.ts +++ b/docs-site/.vitepress/theme/status-line.ts @@ -2,3 +2,10 @@ export function formatStatusLineFilePath(routePath: string): string { if (routePath === '/') return 'index.md'; return `${routePath.replace(/^\/|\/$/g, '')}.md`; } + +// Local calendar date as YYYY-MM-DD (toISOString would give the UTC date). +export function formatStatusLineDate(date: Date): string { + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${date.getFullYear()}-${month}-${day}`; +} diff --git a/docs-site/README.md b/docs-site/README.md index 687452cb..85d0061c 100644 --- a/docs-site/README.md +++ b/docs-site/README.md @@ -40,8 +40,23 @@ The public docs root is stable-only: - `/` serves the latest stable release docs. - `/main/` serves development docs from `main`. - `/v//` serves stable release archives. +- `/versions` (root build only) lists every published version. - Prerelease tags do not update the docs site. -Only `/` is indexable. `/main/` and every `/v//` page carries a self-referential canonical plus `noindex,follow`, and the generated `_headers` file repeats that as an `X-Robots-Tag`. They stay crawlable so their links still resolve, but ~30 archived copies of every page would otherwise consume the crawl budget the current docs need. Only the root build emits `sitemap.xml`, and its `` dates come from `git log` against the tracked checkout at the released tag, because the build renders from an untracked snapshot that VitePress cannot date itself. +Only `/` is indexable. `/main/` and every `/v//` page carries a self-referential canonical plus `noindex,follow`, repeated as an `X-Robots-Tag` header (by the generated `_headers` file for `/main/`, by the archive function for `/v/`). They stay crawlable so their links still resolve, but ~30 archived copies of every page would otherwise consume the crawl budget the current docs need. Only the root build emits `sitemap.xml`, and its `` dates come from `git log` against the tracked checkout at the released tag, because the build renders from an untracked snapshot that VitePress cannot date itself. Keep Cloudflare Git auto-deploy disabled. The production deploy is `.github/workflows/docs-pages.yml`, which uploads `.tmp/docs-versioned-site` with `--branch main` so tag-triggered runs update Production instead of creating preview deployments. + +### Stable archives in R2 + +`/v//` archives are not part of the Pages deployment. Each one is built once, uploaded to an R2 bucket under `v//`, and served by the Pages Function in `functions/v/[[path]].ts`. Each deploy builds only archives the bucket is missing (an archive counts as present once its `_archive.json` marker exists), plus the root and `/main/` builds. Archive nav links to `/versions` instead of listing releases, so a new tag never invalidates old archives. + +To re-render archives on purpose (theme change, docs fix), run the `Docs Pages` workflow manually with `rebuild_archives` set to comma-separated tags or `all`. + +One-time setup: + +- R2 bucket for archives; its name goes in the `DOCS_ARCHIVE_R2_BUCKET` repository variable. +- R2 API token with Object Read & Write on that bucket; its S3 credentials go in the `DOCS_ARCHIVE_R2_ACCESS_KEY_ID` and `DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY` repository secrets. +- Pages project: Settings > Bindings > R2 bucket, variable name `DOCS_ARCHIVES`, pointing at the same bucket. + +The first deploy after setup builds and uploads every stable archive; later deploys only add new tags. diff --git a/docs-site/anilist-integration.md b/docs-site/anilist-integration.md index 5b36cd75..dab55b0c 100644 --- a/docs-site/anilist-integration.md +++ b/docs-site/anilist-integration.md @@ -1,137 +1,68 @@ # AniList integration -SubMiner syncs your watch progress to [AniList](https://anilist.co). Finish an episode and it reads the title and episode number off the filename, finds the matching AniList entry, and updates your progress through the GraphQL API. A failed update retries in the background with exponential backoff. - -The same AniList data feeds [cover art](#cover-art) in the stats dashboard and the [Character Dictionary](/character-dictionary) for in-overlay name lookup. - -[AniList](https://anilist.co) is a free anime tracking site. The **access token** is a private key SubMiner keeps so it can update your list for you. You approve it once during setup, and your AniList password never touches SubMiner. +SubMiner updates your [AniList](https://anilist.co) watch progress when you finish an episode. The same connection supplies cover art for the stats dashboard and names for the [character dictionary](/character-dictionary). ## Setup -AniList integration is opt-in. To enable it: +1. Set `anilist.enabled` to `true`: -1. Set `anilist.enabled` to `true` in your config. -2. Leave `anilist.accessToken` empty and restart SubMiner (or run `--anilist-setup`). -3. Approve access in the AniList authorization page. -4. The callback returns to SubMiner via the `subminer://anilist-setup?...` protocol URL, and SubMiner stores the token automatically. + ```jsonc + { + "anilist": { + "enabled": true, + }, + } + ``` -```jsonc -{ - "anilist": { - "enabled": true, - "accessToken": "", - }, -} -``` +2. Restart SubMiner. With no token stored, it opens the AniList setup window. You can also open it from the tray (**Configure AniList**) or with `subminer app --anilist-setup`. +3. Approve access on the AniList page. SubMiner receives the token through a `subminer://` link and stores it encrypted. -The access token is encrypted at rest using Electron's `safeStorage` API. On Linux this defaults to `gnome-libsecret`; override the backend with `--password-store=` (for example `--password-store=basic_text`). +If the setup window does not render, SubMiner opens the authorization page in your browser instead. To skip the flow entirely, paste a token into `anilist.accessToken`. -If the embedded auth UI fails to render, SubMiner opens the authorize URL in your default browser and shows fallback instructions in-app. +On Linux, the token is stored with `gnome-libsecret` by default. If your keyring is unavailable, start it (gnome-keyring or KWallet) or launch SubMiner with `--password-store=basic_text`. -::: tip -You can also set `anilist.accessToken` directly in config to skip the setup flow entirely. When blank, SubMiner uses the locally stored encrypted token. -::: +## How updates work -## How tracking works +An episode counts as watched after 85% of its length and at least 10 minutes of playback. SubMiner then: -SubMiner watches playback and pushes an AniList progress update once an episode counts as watched. That means at least 85% of its duration, and at least 10 minutes either way. +1. Reads the title, season, and episode from the file name and folder. Install [guessit](https://github.com/guessit-io/guessit) for better parsing. A folder named `Season 2` is a strong season hint. +2. Finds the matching AniList entry. For season 2 and later, it follows the show's sequels. +3. Sets your progress to that episode and marks the entry Watching, or Completed on the final episode. -The update flow: +The show must already be on your Planning or Watching list. SubMiner does not add new entries, and it never lowers your progress. -1. **Title detection** - SubMiner extracts the anime title, season, and episode number from the media filename and path. Season folders such as `Season 2` are treated as a strong season signal. SubMiner tries [`guessit`](https://github.com/guessit-io/guessit) first for accurate parsing, then falls back to an internal filename parser if guessit is unavailable. -2. **AniList search** - The base title (with any `Season N` / `SN` marker stripped) is searched against the AniList GraphQL API, and SubMiner picks the best match by comparing titles (romaji, English, native, synonyms) and filtering by episode count. AniList has no notion of numbered seasons - sequels are separate entries with their own titles (`Zoku`, `Kan`, `2nd Season`), so searching ` Season 3` finds nothing. For season 2 and later, SubMiner instead walks `SEQUEL` relations from the season 1 entry, preferring the TV line, and falls back to ordering the franchise's TV entries by air date when the relation chain is incomplete. If neither locates the season, SubMiner **skips the update** rather than writing progress to the season 1 entry, and tells you to pin the right entry with a [character dictionary override](/character-dictionary#correcting-anilist-matches). -3. **Progress check** - SubMiner fetches your current list entry for the matched media. The media must already be in Planning or Watching; otherwise SubMiner shows an MPV message explaining that the update is not possible. If your recorded progress already meets or exceeds the detected episode, the update is skipped. -4. **Mutation** - A `SaveMediaListEntry` mutation sets the new progress and marks the entry as `CURRENT`, or `COMPLETED` when the watched episode is the final episode of the season (the "already at this progress" skip is bypassed for the final episode so completion still lands). +Failed updates are saved and retried in the background, up to 8 times with growing delays. The queue survives restarts. -## Update queue and retry +## Fixing a wrong match -Failed AniList updates are persisted to a retry queue on disk and retried with exponential backoff. +If a cover or title in the stats Library is wrong, open the title and use **Change AniList Entry**. -Updates are skipped if the media path cannot produce a safe, nonempty identity. Invalid entries are discarded when loading or adding to the retry queue. +If SubMiner cannot find a later season, it skips the update rather than writing progress to season 1. Pin the right entry with the character dictionary's AniList override. See [Character dictionary](/character-dictionary). -| Parameter | Value | -| ---------------- | ---------- | -| Initial backoff | 30 seconds | -| Maximum backoff | 6 hours | -| Maximum attempts | 8 | -| Queue capacity | 500 items | +## Commands -After 8 failed attempts, the update is moved to a dead-letter queue and no longer retried automatically. The queue is persisted across restarts so no updates are lost if SubMiner exits before a retry succeeds. +| Command | What it does | +| ------------------------------------ | --------------------------------------- | +| `subminer app --anilist-setup` | Open the AniList setup window | +| `subminer app --anilist-status` | Show token state and retry queue counts | +| `subminer app --anilist-logout` | Remove the stored token | +| `subminer app --anilist-retry-queue` | Retry one queued update now | -Use `--anilist-retry-queue` to manually process one ready item from the queue. +## Options -## Cover art +| Key | What it does | +| --------------------- | ------------------------------------------------------------- | +| `anilist.enabled` | Turns on progress updates. | +| `anilist.accessToken` | Token override. Leave empty to use the token stored by setup. | -SubMiner fetches cover art from AniList for display in the stats dashboard. When a new video starts playing, the cover art fetcher: - -1. Checks the local database for cached art. -2. If missing, parses the media title (guessit then fallback) and searches the AniList API. -3. Downloads the cover image from the AniList CDN and caches it locally (both URL and blob). -4. Stores AniList metadata (romaji/English titles, total episodes) alongside the cover for dashboard display. - -A no-match result is cached for 5 minutes before SubMiner retries, preventing repeated API calls for unrecognized media. - -When AniList has no match, SubMiner tries [TMDB](/configuration#tmdb) next so live-action dramas and movies get a poster and synopsis too. See [Immersion tracking](/immersion-tracking#library) for how live-action entries are grouped. - -If the automatic match is wrong, use **Change AniList Entry** on a title in the stats Library. Relinking rewrites the cached art for every episode of that title, and both the detail view and the Library grid pick up the new cover right away: the grid refetches after a relink, and cover responses carry an ETag and are revalidated on each request instead of being cached for a day. - -## Rate limiting - -All AniList API calls go through a shared rate limiter that enforces a sliding window of 20 requests per minute. The limiter also reads AniList's `X-RateLimit-Remaining` and `Retry-After` response headers and pauses requests when the server signals throttling. This applies to both episode tracking and cover art fetching. - -## Configuration reference - -```jsonc -{ - "anilist": { - "enabled": true, - "accessToken": "", - "characterDictionary": { - "maxLoaded": 3, - "profileScope": "all", - "collapsibleSections": { - "description": false, - "characterInformation": false, - "voicedBy": false, - }, - }, - }, -} -``` - -| Option | Values | Description | -| ------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------ | -| `enabled` | `true`, `false` | Enable AniList post-watch progress updates (default: `false`) | -| `accessToken` | string | Explicit AniList access token override; when blank, SubMiner uses the stored encrypted token (default: `""`) | -| `characterDictionary.maxLoaded` | number | Number of recent media snapshots kept in the merged dictionary (default: `3`) | -| `characterDictionary.refreshTtlHours` | number | Hours before a cached media snapshot is refreshed (default: `168`, clamped to 1–8760) | -| `characterDictionary.evictionPolicy` | `"delete"`, `"disable"` | What happens to snapshots evicted beyond `maxLoaded` (default: `"delete"`) | -| `characterDictionary.profileScope` | `"all"`, `"active"` | Apply dictionary to all Yomitan profiles or only the active one | -| `characterDictionary.collapsibleSections.*` | `true`, `false` | Control which dictionary entry sections start expanded | - -There is no `characterDictionary.enabled` key: character dictionary sync is enabled by `subtitleStyle.nameMatchEnabled`. See the [Character Dictionary](/character-dictionary) page for full details on the character dictionary feature, including name generation, matching, auto-sync lifecycle, and dictionary entry format. - -## CLI commands - -| Command | Description | -| ----------------------- | ------------------------------------------------------------- | -| `--anilist-setup` | Open AniList setup/auth flow helper window | -| `--anilist-status` | Print current token resolution state and retry queue counters | -| `--anilist-logout` | Clear stored AniList token from local persisted state | -| `--anilist-retry-queue` | Process one ready retry queue item immediately | +Character dictionary settings live under `anilist.characterDictionary` and are covered on the [Character dictionary](/character-dictionary) page. See [Configuration](/configuration#anilist) for defaults. ## Troubleshooting -- **Updates not triggering:** Confirm `anilist.enabled` is `true`. SubMiner requires at least 85% of the episode watched and a minimum of 10 minutes. Short episodes or partial watches will not trigger an update. -- **Update not possible:** Add the season to your AniList Planning or Watching list first. SubMiner will not create new AniList list entries automatically. -- **Wrong episode or title matched:** Detection quality is best when `guessit` is installed and on your `PATH`. Without it, SubMiner falls back to internal filename parsing which can be less accurate with unusual naming conventions. -- **Token issues:** Run `--anilist-status` to check token state. If the token is invalid or expired, run `--anilist-setup` or `--anilist-logout` and re-authenticate. -- **Updates failing repeatedly:** Run `--anilist-status` to see retry queue counters. Items that fail 8 times are moved to the dead-letter queue. Check network connectivity and AniList API status. -- **Cover art missing:** Cover art is fetched on a best-effort basis using title matching. If the filename is hard to parse, the search may return no results. The fetcher retries after 5 minutes. -- **Encryption unavailable on Linux:** If you see warnings about safeStorage, try `--password-store=basic_text` as a workaround, or start your desktop keyring (gnome-keyring, KWallet). +**No update after an episode.** Check that `anilist.enabled` is `true` and that you watched at least 85% of the episode. -## Related +**"AniList update not possible."** Add the show to your Planning or Watching list, then mark the episode watched again. -- [Character Dictionary](/character-dictionary) - AniList-powered character name dictionary for Yomitan -- [Configuration Reference](/configuration) - full config options -- [Jellyfin Integration](/jellyfin-integration) - media server integration +**Wrong show or episode.** Install guessit and make sure it is on your `PATH`. Unusual file names parse poorly without it. + +**Token errors.** Run `subminer app --anilist-status`. If the token is invalid, run `--anilist-logout`, then `--anilist-setup`. diff --git a/docs-site/aniskip-integration.md b/docs-site/aniskip-integration.md index ee5ff5dd..e02071f4 100644 --- a/docs-site/aniskip-integration.md +++ b/docs-site/aniskip-integration.md @@ -1,53 +1,39 @@ # AniSkip integration -SubMiner looks up anime intro timings from [AniSkip](https://aniskip.com) so you can jump past the OP with one key. - -Intro detection runs in the SubMiner app over the mpv IPC socket. It works whenever the overlay is connected to mpv, not only at launch, and covers every local file loaded during the session including playlist advances. +SubMiner looks up opening timestamps on [AniSkip](https://aniskip.com) so you can skip an anime's intro with one key. ## Setup -AniSkip is enabled by default. Disable it or change the skip key in your config: +AniSkip is on by default. To turn it off or change the key: ```jsonc { "mpv": { - "aniskipEnabled": true, // default: true + "aniskipEnabled": true, "aniskipButtonKey": "TAB", }, } ``` -Both settings hot-reload: changing them in your config takes effect immediately without restarting playback or mpv. - -For best title and episode detection, install [`guessit`](https://github.com/guessit-io/guessit): +Both settings apply immediately, without restarting mpv. For better title and episode detection, install [guessit](https://github.com/guessit-io/guessit): ```bash python3 -m pip install --user guessit ``` -Without `guessit`, SubMiner falls back to its own filename parser. That handles the usual release naming, but unusual formats slip past it. +## Usage -## How it works +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. -On each local file load: +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. -1. SubMiner infers the anime title, season, and episode number from the filename and path (using `guessit` if available, otherwise the built-in parser). Remote URLs are skipped entirely. -2. The title is matched against MyAnimeList to resolve a MAL id. -3. SubMiner queries the AniSkip API for an OP skip interval for that MAL id and episode. -4. If an interval is found, SubMiner adds `AniSkip Intro Start` and `AniSkip Intro End` chapter markers to the current file and binds the skip key (`mpv.aniskipButtonKey`, default `TAB`). -5. At the start of the intro, an OSD prompt appears for 3 seconds: `You can skip by pressing TAB` (reflects your configured key). Pressing the key at any point during the intro seeks to the intro end. - -When a custom key (other than `TAB` or `y-k`) is configured, the legacy `y-k` chord is also bound as a fallback skip trigger. - -Results are cached per file for the app session. Only a definitive "no intro found" is cached, so a failed lookup gets retried on the next load rather than sticking. If mpv reloads the same file, SubMiner re-applies the chapter markers without hitting the API again. +With a custom key other than `TAB` or `y-k`, `y-k` also skips. ## Triggering from mpv -AniSkip actions are also reachable from mpv script-messages: +| Command | What it does | +| ----------------------------------------- | ------------------------------------------------------- | +| `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 | -| Command | Effect | -| ------- | ------ | -| `script-message subminer-skip-intro` | Skip to the intro end immediately (same as pressing the key) | -| `script-message subminer-aniskip-refresh` | Force a fresh lookup for the current file, discarding any cached result | - -The SubMiner app handles both over the IPC socket. +Use `subminer-aniskip-refresh` after a lookup failed or matched the wrong show. diff --git a/docs-site/anki-integration.md b/docs-site/anki-integration.md index c5d8c757..d7317e69 100644 --- a/docs-site/anki-integration.md +++ b/docs-site/anki-integration.md @@ -1,59 +1,34 @@ # Anki integration -SubMiner uses the [AnkiConnect](https://ankiweb.net/shared/info/2055492159) add-on to create and update Anki cards with sentence context, audio, and screenshots. -This project is built primarily for [Kiku](https://kiku.youyoumu.my.id/) and [Lapis](https://github.com/donkuri/lapis) note types, including sentence-card and field-grouping behavior. +SubMiner talks to Anki through the [AnkiConnect](https://ankiweb.net/shared/info/2055492159) add-on. It fills new cards with the sentence, an audio clip, and a screenshot, and can create sentence cards and merge duplicate words. It is built for the [Lapis](https://github.com/donkuri/lapis), [Kiku](https://kiku.youyoumu.my.id/), and [Senren](https://github.com/BrenoAqua/Senren) note types, but works with any note type once you map its fields. -::: tip New to these terms? - -- **Anki** is the flashcard app where your study cards live. -- **AnkiConnect** is a free add-on that lets other programs (like SubMiner) talk to Anki over a local connection. SubMiner needs it installed to add or edit cards. -- A **note type** (also called a "model") is the template that defines what a card looks like - for example the Kiku or Lapis templates many Japanese learners use. -- A **field** is one labeled slot in that template, such as `Sentence`, `Expression`, or `Picture`. SubMiner fills these fields when it mines a card. - ::: +For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on this page, with its default, is listed in the [AnkiConnect config reference](/configuration#ankiconnect). ## Prerequisites 1. Install [Anki](https://apps.ankiweb.net/). -2. Install the [AnkiConnect](https://ankiweb.net/shared/info/2055492159) add-on (code: `2055492159`). -3. Keep Anki running while using SubMiner. +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. +4. Keep Anki running while you mine. -AnkiConnect listens on `http://127.0.0.1:8765` by default. If you changed the port in AnkiConnect's settings, update `ankiConnect.url` in your SubMiner config. +If you changed AnkiConnect's port, set `ankiConnect.url` to match. -AnkiConnect and Kiku/Senren settings follow the [configuration validation rules](/configuration#configuration-file): invalid values produce a warning and fall back to the option's default. Use JSON booleans such as `true`, not strings such as `"true"`, and a positive number for `ankiConnect.pollingRate`. +## How cards get filled -### Reusing SubMiner settings in Hachidori +When Yomitan or Hachidori adds a note, SubMiner fills the sentence, audio, image, and MiscInfo fields. It finds new notes in one of two ways: -When Hachidori is the selected backend, SubMiner uses its Anki settings to populate Hachidori's first Anki template on startup and when opening its settings. It sets the template's deck to `ankiConnect.deck` when one is configured, copies the configured tags into untouched defaults, then fills missing word, sentence, pronunciation-audio, and picture mappings with fields that exist in Anki. Pronunciation uses `ankiConnect.fields.wordAudio`, falling back to `fields.audio` when no word-audio field is set. +- **Proxy (default).** SubMiner runs a local AnkiConnect-compatible server. The dictionary sends notes through it, and SubMiner fills each one right after Anki accepts it. +- **Polling.** With `ankiConnect.proxy.enabled` set to `false`, SubMiner asks AnkiConnect for recently added notes every `ankiConnect.pollingRate` milliseconds. -If the note type is unset, SubMiner looks for a unique match containing its configured word and sentence fields. Enabled Lapis, Kiku, or Senren integration narrows the search; Lapis uses its configured model name. A fresh mapping also receives Hachidori's matching preset for readings, definitions, and other recognized fields. If several note types match, choose one in Hachidori Settings. If Anki is closed, open Hachidori Settings again after starting Anki to retry. +Set `ankiConnect.behavior.autoUpdateNewCards` to `false` to stop automatic filling and update cards by hand with `Ctrl/Cmd+V` instead. -The deck always follows `ankiConnect.deck`, as it does for Yomitan's mining deck, because polling mode only looks for new cards in that deck. Existing custom tags, field mappings, advanced templates, and additional templates stay intact. Apart from the deck, this fills missing settings rather than continually overwriting Hachidori choices. The Anki endpoint continues to follow SubMiner's proxy configuration. Sentence audio, image timing, translation, metadata, and duplicate field grouping remain controlled by SubMiner; pronunciation sources are configured in Hachidori. Linking an external dictionary host does not change this behavior. +`ankiConnect.deck` limits enrichment and duplicate checks to one deck. If it is empty, SubMiner uses Yomitan's mining deck when it can read it, and otherwise searches all decks. -## Auto-enrichment transport - -When you add a word via Yomitan, SubMiner detects the new card and fills in the sentence, audio, and image fields automatically. Two detection methods are available: - -**Proxy mode** (default) - SubMiner runs a small local server between Yomitan and Anki. Yomitan sends the new card to SubMiner, SubMiner fills in the media fields, and the finished card goes on to Anki. There is no polling delay. - -**Polling mode** (fallback, when the proxy is disabled) - SubMiner asks AnkiConnect every few seconds whether new cards showed up, then fills them in. Less to configure, at the cost of roughly a 3 second delay. - -Use proxy mode unless your Yomitan runs in a browser rather than the bundled instance, in which case polling is the simpler path. - -In both modes, the enrichment workflow is the same: - -1. Checks if a duplicate expression already exists (for field grouping). -2. Updates the sentence field with the current subtitle. -3. Generates and uploads audio and image media. -4. Writes metadata to the miscInfo field. - -Polling mode uses the query `"deck:<ankiConnect.deck>" added:1` to find recently added cards. If no deck is configured, it searches all decks (`added:1`). In Settings, the AnkiConnect deck dropdown auto-fills and persists Yomitan's current mining deck when available, then falls back to the decks reported by AnkiConnect; stats-dashboard mining also falls back to Yomitan's mining deck when `ankiConnect.deck` is empty. -Known-word sync scope is controlled by `ankiConnect.knownWords.decks`. - -### Proxy mode setup (Yomitan / texthooker) +### Proxy mode setup (Yomitan / texthooker) {#proxy-mode-setup-yomitan-texthooker} ```jsonc "ankiConnect": { - "url": "http://127.0.0.1:8765", // real AnkiConnect + "url": "http://127.0.0.1:8765", "proxy": { "enabled": true, "host": "127.0.0.1", @@ -63,379 +38,203 @@ Known-word sync scope is controlled by `ankiConnect.knownWords.decks`. } ``` -Then point Yomitan/clients to `http://127.0.0.1:8766` instead of `8765`. +Clients must send notes to the proxy (`http://127.0.0.1:8766` here), not to AnkiConnect directly. -When SubMiner loads the bundled Yomitan extension, it also attempts to update the **currently active Yomitan profile**'s Anki server to the active SubMiner endpoint (falling back to `profiles[0]` if the active-profile index is invalid): +- **Bundled Yomitan.** SubMiner sets the active Yomitan profile's Anki server for you. With the proxy on, it always points the profile at the proxy. With the proxy off, it sets `ankiConnect.url`, but only if the profile's server is blank or the stock `http://127.0.0.1:8765`. +- **Browser Yomitan or other clients.** Set the Anki server to the proxy URL yourself. To leave your main profile alone, create a separate Yomitan profile for SubMiner, set its Anki server (Settings, Anki) to the proxy URL, and make it active while you mine. +- **Hachidori.** SubMiner routes Hachidori to the proxy while it is active. Keep the proxy on for screenshots and sentence audio. -- proxy URL when `ankiConnect.proxy.enabled` is `true` -- direct `ankiConnect.url` when proxy mode is disabled +### Hachidori settings from SubMiner -To avoid clobbering custom setups, this auto-update only changes the profile when its current server is blank or the stock Yomitan default (`http://127.0.0.1:8765`). +With the [Hachidori backend](/usage#hachidori-setup), SubMiner fills Hachidori's first Anki template from your `ankiConnect` settings on startup and whenever you open Hachidori Settings: -For browser-based Yomitan or other external clients (for example Texthooker in a normal browser profile), set their Anki server to the same proxy URL separately: `http://127.0.0.1:8766` (or your configured `proxy.host` + `proxy.port`). +- The deck always follows `ankiConnect.deck`, because polling only looks for new cards in that deck. +- Configured tags go into untouched defaults. +- Missing word, sentence, pronunciation-audio, and picture mappings are filled with fields that exist in Anki. Pronunciation uses `fields.wordAudio`, or `fields.audio` when no word-audio field is set. +- If the note type is unset, SubMiner picks the one note type that has your word and sentence fields. Enabled Lapis, Kiku, or Senren narrows the search. A fresh mapping also gets Hachidori's matching preset for readings, definitions, and other known fields. -### Browser/Yomitan external setup (separate profile) +Apart from the deck, SubMiner only fills missing settings. Custom tags, field mappings, advanced templates, and extra templates stay as you set them. If several note types match, pick one in Hachidori Settings. If Anki was closed, start it and open Hachidori Settings again to retry. -If you want SubMiner to use proxy mode without touching your main/default Yomitan profile, create or select a separate Yomitan profile just for SubMiner and set its Anki server to the proxy URL. +Sentence audio, image timing, translation, metadata, and field grouping stay under SubMiner's control. Pronunciation sources are set in Hachidori. Linking an external dictionary host does not change any of this. -That profile isolation gives you both benefits: +### Proxy troubleshooting -- SubMiner can auto-enrich immediately via proxy. -- Your default Yomitan profile keeps its existing Anki server setting. +If cards are not getting filled: -In Yomitan, go to Settings → Profile and: +1. Check that the proxy is listening while SubMiner runs: -1. Create a profile for SubMiner (or choose one dedicated profile). -2. Open Anki settings for that profile. -3. Set server to `http://127.0.0.1:8766` (or your configured proxy URL). -4. Save and make that profile active when using SubMiner. + ```bash + ss -ltnp | grep 8766 + ``` -This is only for non-bundled, external/browser Yomitan or other clients. The bundled profile auto-update logic only targets the active profile when its server is blank or still default. +2. Check that requests pass through to Anki: -### Proxy troubleshooting (quick checks) + ```bash + curl -sS http://127.0.0.1:8766 \ + -H 'content-type: application/json' \ + -d '{"action":"version","version":2}' + ``` -If auto-enrichment appears to do nothing: - -1. Confirm proxy listener is running while SubMiner is active: - -```bash -ss -ltnp | rg 8766 -``` - -2. Confirm requests can pass through the proxy: - -```bash -curl -sS http://127.0.0.1:8766 \ - -H 'content-type: application/json' \ - -d '{"action":"version","version":2}' -``` - -3. Check the log sinks in `~/.config/SubMiner/logs/`: - -- App runtime log: `app-YYYY-MM-DD.log` -- Launcher log: `launcher-YYYY-MM-DD.log` -- mpv log: `mpv-YYYY-MM-DD.log` - -4. Check that the config JSONC parses and the logging shape is right: - -```jsonc -"logging": { - "level": "debug" -} -``` - -`"logging": "debug"` is invalid for current schema and can break reload/start behavior. +3. Read the app log (`app-YYYY-MM-DD.log`) in the logs folder. See [Troubleshooting](/troubleshooting) for where logs live. ## Field mapping -SubMiner maps its data to your Anki note fields. Configure these under `ankiConnect.fields`: +`ankiConnect.fields` maps SubMiner's data to fields on your note type. + +| Key | Receives | +| ------------------ | ------------------------------------------------------------------------- | +| `fields.word` | The mined word | +| `fields.audio` | Sentence audio cut from the video | +| `fields.wordAudio` | Read only: Yomitan's word audio, used to time animated images (see below) | +| `fields.image` | Screenshot or animated clip | +| `fields.sentence` | Subtitle text | +| `fields.miscInfo` | Text from `ankiConnect.metadata.pattern` | ```jsonc "ankiConnect": { "fields": { - "word": "Expression", // mined word / expression text - "audio": "SentenceAudio", // sentence audio clip cut from the video - "wordAudio": "ExpressionAudio", // existing Yomitan word audio, read for animation sync - "image": "Picture", // screenshot or animated clip - "sentence": "Sentence", // subtitle text - "miscInfo": "MiscInfo" // metadata (filename, timestamp) + "audio": "SentenceAudio", + "sentence": "Sentence" } } ``` -`fields.audio` receives the **sentence** audio SubMiner cuts from the video, not word audio. Yomitan writes its own dictionary audio when you mine, so point this at a separate field such as `SentenceAudio` to keep the two apart. The built-in default is still `ExpressionAudio`, which collides with Yomitan on note types that use that field for word audio. +Field names are matched case-insensitively. A mapped field that is missing from the note type is skipped. -Field names are matched against your Anki note type case-insensitively (an exact match wins, then a lowercase comparison). If a configured field does not exist on the note type, SubMiner skips it without error. +Hachidori prepares downloadable word audio before it saves a note through the proxy, so the animated image delay works on the first mine. Set a downloadable pronunciation source in Hachidori's Audio settings. Browser speech cannot be saved to Anki. Without word audio, Hachidori shows a warning and the card gets no word-audio hold. -`fields.wordAudio` selects the existing dictionary-audio field used to calculate the animated image's opening freeze. This mapping only reads audio; `fields.audio` still controls where generated sentence audio is written. See [config.example.jsonc](/config.example.jsonc) for defaults. +`fields.audio` gets sentence audio, not word audio. Yomitan writes its own dictionary audio into your note, so point `fields.audio` at a separate field such as `SentenceAudio`. The default, `ExpressionAudio`, is the field many note types use for Yomitan's word audio, so leaving it would overwrite that audio. -When Hachidori mines through SubMiner's Anki proxy, it prepares downloadable word audio before saving the note so the animation delay can be measured on the first mine. Configure a downloadable pronunciation source in Hachidori's Audio settings; browser speech cannot be saved into Anki by the SubMiner overlay. If pronunciation is unavailable, Hachidori reports a warning and the card has no word-audio hold. +`ankiConnect.tags` adds tags to every mined or updated card. Set it to `[]` to add none. -These mappings always control normal word-card enrichment, including Yomitan proxy/polling updates and manual clipboard updates. Enabling Lapis or Kiku does not replace the configured word-card sentence and audio fields with `Sentence` and `SentenceAudio`. The dedicated sentence-card and audio-card shortcuts still use those Lapis/Kiku field names. +`ankiConnect.metadata.pattern` builds the MiscInfo text. Tokens: `%f` file name, `%F` file name with extension, `%t` timestamp, `%T` timestamp with milliseconds, `<br>` line break. -Two related options live alongside `fields`: `ankiConnect.deck` (target deck; empty falls back as described above) and `ankiConnect.tags` (tags added to mined cards, default `["SubMiner"]`; set `[]` to disable tagging). The `miscInfo` content is controlled by `ankiConnect.metadata.pattern` (default `[SubMiner] %f (%t)`; tokens: `%f` filename, `%F` filename with extension, `%t` timestamp, `%T` timestamp with milliseconds, `<br>` newline). +## Media -### Minimal config +| Key | What it does | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | +| `media.generateAudio` | Cut sentence audio (MP3) from the subtitle's start and end time | +| `media.audioPadding` | Seconds added before and after the clip | +| `media.fallbackDuration` | Clip length when the subtitle has no timing | +| `media.maxMediaDuration` | Longest allowed clip, in seconds (`0` removes the cap) | +| `media.normalizeAudio` | Normalize clip loudness | +| `media.mirrorMpvVolume` | Scale the clip by mpv's current volume, so quiet playback gives quiet clips | +| `media.generateImage` | Capture an image | +| `media.imageType` | `static` for one frame, `avif` for an animated clip of the line | +| `media.imageFormat` | Static format: `jpg`, `png`, or `webp` | +| `media.imageQuality` | Static image quality | +| `media.imageMaxWidth` / `Height` | Static size limit (`0` keeps source size) | +| `media.animatedFps` | Animated clip frame rate | +| `media.animatedMaxWidth` / `Height` | Animated size limit (`0` keeps aspect ratio) | +| `media.animatedCrf` | Animated quality, `0` to `63`, lower is better | +| `media.syncAnimatedImageToWordAudio` | Hold the first frame for the length of the word audio in `fields.wordAudio`, so the motion starts with the sentence audio | +| `media.reviewTiming` | Pause and let you adjust the clip before media is made (see below) | -If you only want sentence and audio on your cards: +Animated AVIF needs an FFmpeg build with an AV1 encoder (`libaom-av1`, `libsvtav1`, or `librav1e`). -```jsonc -"ankiConnect": { - "enabled": true, - "fields": { - "sentence": "Sentence", - "audio": "SentenceAudio" - } -} -``` +Media settings apply to the next card without a restart. -## Media generation +### Review media timing -SubMiner shells out to FFmpeg for audio clips and screenshots, so FFmpeg has to be installed and on `PATH`. +With `media.reviewTiming` on, SubMiner pauses before making media for word, sentence, and audio cards and opens a review dialog. You can also toggle it for the current session with **Review Media Timing** in the runtime options palette (`Ctrl/Cmd+Shift+O`). Clipboard updates and stats-dashboard mining skip the review. -For remote streams such as Jellyfin playback, SubMiner downloads the clip's time window once into a temporary Matroska file (a stream copy, no re-encoding) and reads the timing review waveform, audio preview, audio, and image from that file instead of fetching the stream again for each step. The window covers the clip plus padding, plus the visible timeline in timing review, and grows when you reveal more of the timeline. It is deleted when a different window replaces it, after ten minutes without use, or when SubMiner exits. If the download fails, media generation reads the remote stream directly as before. +Playback stays paused while the dialog is open, even if the popup or hover that paused it goes away. When the dialog closes, playback resumes if it was playing before, or if the popup closed in the meantime. A popup that is still open keeps it paused. -### Audio +The dialog shows the clip over a speech waveform. When the waveform loads, an untouched clip end moves back to just after the last speech in the line. The Line end rail still marks the subtitle's own end. -Audio is extracted from the video file using the subtitle's start and end timestamps. Padding is opt-in; keep it at `0` when you want sentence audio to start exactly at the mined sentence. +| Action | How | +| ------------------------ | --------------------------------------------------------------------- | +| Trim | Drag either edge, or click the waveform to move the nearer edge there | +| Nudge an edge | Arrow keys on a focused edge (100 ms, `Shift` for 500 ms) | +| Slide the clip | Drag the middle | +| Show more timeline | Earlier / Later | +| Pick the screenshot | Screenshot slider or Frame buttons (static images only) | +| Add previous / next line | `P` / `N` (`Shift+P` / `Shift+N` removes) | +| Preview | `Space` | +| Confirm | `Enter` | +| Cancel | `Escape` | -```jsonc -"ankiConnect": { - "media": { - "generateAudio": true, - "normalizeAudio": true, // normalize generated clip loudness - "mirrorMpvVolume": true, // apply the current mpv volume level - "reviewTiming": false, // review and adjust timing before media generation - "audioPadding": 0, // optional seconds before and after subtitle timing - "maxMediaDuration": 30 // cap total duration in seconds - } -} -``` +The confirmed range is used as is, with no extra padding. Added lines go into the sentence field. Reset restores the original timing and removes added lines. -Output format: MP3 at 44100 Hz. If the video has multiple audio streams, SubMiner uses the active stream. Generated sentence audio is loudness-normalized to -23 LUFS by default during extraction; set `normalizeAudio` to `false` to keep raw source loudness. When subtitle timing is missing, clips fall back to `media.fallbackDuration` seconds (default `3`). Changing these settings applies to the next extraction without restarting SubMiner. +When you cancel, you can go back to editing, keep the original timing, create the card without media, or discard it. Discard deletes the Yomitan note or audio card, and skips creation for a sentence card. -`mirrorMpvVolume` is also enabled by default. Immediately before extracting each playback-overlay card's audio, SubMiner reads mpv's numeric `volume` and applies mpv's cubic software-volume curve after loudness normalization. For example, mpv volume `50` produces `0.5³ = 0.125` gain. Amplified output above mpv volume `100` is limited to a `-1 dBFS` ceiling before MP3 encoding to prevent clipping. It ignores mpv's separate `mute` state. If the volume property is missing, invalid, or unavailable, extraction continues with unity scaling; disabling this option skips the query and volume filter. Changing this setting applies to the next extraction without restarting SubMiner. YouTube cards queued for a background media-cache download retain the volume captured when the card was mined. Stats-dashboard mining does not currently have access to the active mpv property client, so it does not apply mpv volume scaling. +### Update behavior -The audio is uploaded to Anki's media folder and inserted as `[sound:audio_<timestamp>.mp3]`. +| Key | What it does | +| ----------------------------- | ---------------------------------------------------- | +| `behavior.overwriteAudio` | Replace existing audio instead of adding to it | +| `behavior.overwriteImage` | Replace the existing image instead of adding to it | +| `behavior.mediaInsertMode` | `append` or `prepend` new media when not overwriting | +| `behavior.autoUpdateNewCards` | Fill new Yomitan notes automatically | +| `behavior.highlightWord` | Bold the mined word in the sentence field | +| `behavior.notificationType` | `overlay`, `system`, `both`, or `none` | -Overlay and stats-dashboard mining use the same `media.maxMediaDuration` limit. See the [configuration example](/config.example.jsonc) for its default and how to disable the cap. +Manual clipboard updates (`Ctrl/Cmd+V`) always replace the sentence audio, whatever `overwriteAudio` says. -Set `media.reviewTiming` to `true` to pause playback and check the clip before its media is generated. It applies to word, sentence, and audio cards. +## Sentence cards (Lapis) {#sentence-cards-lapis} -Playback stays paused while the review is open, even if the dictionary popup or subtitle hover that paused it goes away. When the review closes, playback resumes if it was playing before the review or if the popup closed in the meantime. A dictionary popup that is still open keeps playback paused. - -The review opens on the subtitle range plus your configured audio padding. Subtitles usually hang around after the dialogue has stopped, so once the waveform loads, an untouched clip end pulls back to just after the last speech in the line. The Line end rail still marks the original subtitle timing, Reset puts it back, and a line whose speech runs right through its end is left alone. - -**Adjusting the clip.** Drag either edge to trim, drag the middle to slide the whole clip without changing its length, or click anywhere on the waveform to snap the nearer edge there. A focused edge also moves with the arrow keys: 100 ms per press, or 500 ms with Shift. The 100 ms buttons do the same thing. Earlier and Later each reveal two more seconds of timeline without moving the selection. - -**Choosing the screenshot.** With still images enabled, drag the screenshot slider or use the Frame buttons to choose a video frame independently of the audio. Earlier and Later reveal more time for both sliders. The image follows the audio midpoint until you pick a frame, then stays fixed while you trim audio. Reset below the image restores automatic selection; the audio Reset affects only the audio. The screenshot slider also supports arrow keys, Home, and End. - -The picker supports local video and seekable remote streams, including Jellyfin, without seeking the main player. A selected frame must load before you can confirm; if it fails, choose another frame or Reset. The picker is hidden when image generation is disabled or animated AVIF is selected. Animated images continue to use the reviewed audio range. - -**Keys.** Space previews the selection with a playhead sweeping the clip. The preview ends when the hidden player has actually played the last sample, so Bluetooth output latency does not clip the tail. Enter confirms and Escape cancels. - -**The waveform.** SubMiner reads a center channel when one carries dialogue and falls back to a mono mix otherwise, keeps only the 250 to 3500 Hz speech band, and draws each slice's loudness against the clip's own noise floor. Steady background music flattens out and dialogue stands up, which makes it much easier to tell adjacent lines apart. The mined subtitle appears as a tinted band with labeled line-start and line-end rails. If waveform analysis fails, the timing controls still work. - -The range you confirm is used exactly as-is; SubMiner does not add audio padding a second time. Static screenshots take its midpoint, and animated AVIF clips cover the whole range. - -**Pulling in adjacent lines.** Press `P` or `N`, or use the Prev and Next steppers above the sentence preview, to add the previous or next subtitle line. Repeat for as many lines as exist. Shift+`P` and Shift+`N` remove them again. The sentence preview lists every included line with the mined one highlighted, so you always see the sentence field before confirming. The clip bounds and the waveform rails follow the outermost added line, keeping the review's audio padding. - -Confirming writes the combined lines to the sentence field. Reset drops the added lines along with any timing changes. Adjacent lines come from the parsed subtitle track when one is loaded; otherwise you only get lines that already played. A clip capped by `media.maxMediaDuration` still keeps the full combined sentence even when the audio cannot stretch to cover every added line. - -**Canceling.** You can go back to editing, finish with the original timing, create the card without audio or an image, or discard it. Discard deletes an existing Yomitan or audio card, and skips creation entirely for a direct sentence card. A failed audio preview does not block confirmation or card creation. - -When word-card enrichment changes the sentence context, including an expanded timing-review selection, SubMiner regenerates `SentenceFurigana` from the final sentence. Unchanged sentences keep their existing furigana formatting. If generation fails, SubMiner clears stale furigana so compatible templates can fall back to `Sentence`. - -Clipboard updates and stats-dashboard mining never open timing review. The option is off by default and hot-reloads. **Review Media Timing** in the runtime options palette (`Ctrl/Cmd+Shift+O`) toggles it for the current session. - -If SubMiner closes the overlay while a timing review is still loading, it cancels pending setup and modal retries and restores playback if the review paused it. A new timing review can start after the overlay reopens. - -### Screenshots (static) - -A single frame is captured at the current playback position. - -```jsonc -"ankiConnect": { - "media": { - "generateImage": true, - "imageType": "static", - "imageFormat": "jpg", // "jpg", "png", or "webp" - "imageQuality": 92, // 1–100 - "imageMaxWidth": 0, // 0 = preserve source resolution - "imageMaxHeight": 0 - } -} -``` - -### Animated clips (AVIF) - -SubMiner can produce an animated AVIF spanning the subtitle duration instead of a still frame. - -```jsonc -"ankiConnect": { - "media": { - "generateImage": true, - "imageType": "avif", - "animatedFps": 10, - "animatedMaxWidth": 640, - "animatedMaxHeight": 0, // 0 = preserve aspect ratio - "animatedCrf": 35 // 0–63, lower = better quality - } -} -``` - -Animated AVIF requires an AV1 encoder (`libaom-av1`, `libsvtav1`, or `librav1e`) in your FFmpeg build. Generation timeout is 60 seconds. `media.syncAnimatedImageToWordAudio` (default `true`) prepends a frozen first frame matching the existing audio duration in `fields.wordAudio`, so the motion starts together with the sentence audio. The freeze is baked into the image when mined; changing the mapping does not repair previously generated images. - -### Behavior options - -```jsonc -"ankiConnect": { - "behavior": { - "overwriteAudio": true, // replace existing audio, or append - "overwriteImage": true, // replace existing image, or append - "mediaInsertMode": "append", // "append" or "prepend" to field content - "autoUpdateNewCards": true, // auto-update when new card detected - "highlightWord": true, // bold the mined word inside the sentence field - "notificationType": "overlay" // "overlay", "system", "both", or "none" - } -} -``` - -`both` now means overlay + system notification. `osd` and `osd-system` are legacy config-file-only values; set `notificationType` to `"osd-system"` in `config.jsonc` if you previously used `both` and want to keep mpv OSD + system notifications. The Settings window shows `osd` or `osd-system` when already configured, but only offers `overlay`, `system`, `both`, and `none` as normal choices. - -When media is available, mined-card overlay and system notifications include the same current-frame thumbnail. - -`overwriteAudio` applies to automatic card updates and duplicate-card enrichment. Manual clipboard subtitle updates (`Ctrl/Cmd+C`, then `Ctrl/Cmd+V`) always replace generated sentence audio in `ankiConnect.fields.audio`, even when `overwriteAudio` is disabled. - -## Sentence cards (Lapis) - -SubMiner can create standalone sentence cards (without a word/expression) using a separate note type. This is designed for use with [Lapis](https://github.com/donkuri/Lapis) and similar sentence-focused note types. - -::: warning Required config -Sentence card creation and audio card marking require a non-empty `ankiConnect.isLapis.sentenceCardModel` naming a note type that exists in Anki (default: `"Lapis"`). If the model is empty or missing, the `Ctrl/Cmd+S` and `Ctrl/Cmd+Shift+A` shortcuts will not create cards. -::: +`Ctrl/Cmd+S` creates a standalone sentence card from the current line, and `Ctrl/Cmd+Shift+S` then a digit combines several lines. The card uses the note type named in `ankiConnect.isLapis.sentenceCardModel`, which must exist in Anki. If it is empty, no card is created. ```jsonc "ankiConnect": { "isLapis": { "enabled": true, - "sentenceCardModel": "Lapis" // default; point at your Lapis/Kiku note type + "sentenceCardModel": "Lapis" } } ``` -Trigger with the mine sentence shortcut (`Ctrl/Cmd+S` by default). The card is created directly via AnkiConnect with the sentence, audio, and image filled in. - -The dedicated sentence-card and audio-card shortcuts use the Lapis/Kiku-compatible `Sentence` and `SentenceAudio` fields. This does not affect the configured fields used to enrich normal word cards. - -To mine multiple subtitle lines as one sentence card, use `Ctrl/Cmd+Shift+S` followed by a digit (1–9) to select how many recent lines to combine. +Sentence cards and audio cards (`Ctrl/Cmd+Shift+A`) always write to the `Sentence` and `SentenceAudio` fields. Normal word cards keep using your `ankiConnect.fields` mapping. ## Word card type (Kiku/Lapis) -Word cards get a card-type flag when SubMiner fills their sentence, whether that comes from Yomitan auto-enrichment, a manual clipboard update, or stats-dashboard word mining. By default the flag is `IsWordAndSentenceCard`; pick a different one with `ankiConnect.lapisKiku.wordCardKind`. +When `isKiku` or `isLapis` is enabled, SubMiner sets a card-type flag on word cards it fills. Choose the flag with `ankiConnect.lapisKiku.wordCardKind`: -```jsonc -"ankiConnect": { - "isKiku": { "enabled": true }, - "lapisKiku": { - "wordCardKind": "click" // word-and-sentence (default), click, sentence, audio, none - } -} -``` +| Value | Flag | +| ------------------- | ----------------------- | +| `word-and-sentence` | `IsWordAndSentenceCard` | +| `click` | `IsClickCard` | +| `sentence` | `IsSentenceCard` | +| `audio` | `IsAudioCard` | +| `none` | Leaves flags alone | -`click` marks `IsClickCard`, `sentence` marks `IsSentenceCard`, `audio` marks `IsAudioCard`, and `none` leaves the flags untouched for templates that manage them elsewhere. Whichever flag is chosen, the other card-type flags are cleared so the note never claims two card types. The setting is only read when `isKiku` or `isLapis` is enabled, and cards mined with Mine Sentence or Mine Audio keep their own flag. +The other card-type flags are cleared. Sentence cards and audio cards keep their own flag. -## Field grouping (Kiku/Senren) +## Field grouping (Kiku/Senren) {#field-grouping-kiku-senren} -When you mine the same word multiple times, SubMiner can merge the cards instead of creating duplicates. This is designed for note types that support grouped fields: [Kiku](https://github.com/youyoumu/kiku) and [Senren](https://github.com/BrenoAqua/Senren) (which calls the feature scene switching). +When you mine a word that already has a card, SubMiner can merge the new card into the old one. The sentence, audio, image, and MiscInfo from both cards are kept as grouped entries, and the template lets you switch between them. This works with [Kiku](https://github.com/youyoumu/kiku) and [Senren](https://github.com/BrenoAqua/Senren) (which calls it [scene switching](https://github.com/BrenoAqua/Senren/blob/main/docs/scene_switching.md)). -Field grouping runs when a new note is added with known duplicates. With the Hachidori backend that is the popup's **Add anyway** choice; **Overwrite** updates the existing note in place and only receives media enrichment. +Enable one of them. They write different markup to the same fields, so only one can be on. If both are enabled, Kiku is used and SubMiner logs a config warning. ```jsonc "ankiConnect": { "isKiku": { "enabled": true, - "fieldGrouping": "manual", // "auto", "manual", or "disabled" - "deleteDuplicateInAuto": true // delete new card after auto-merge + "fieldGrouping": "manual", + "deleteDuplicateInAuto": true } } ``` -For Senren note types, enable `isSenren` instead. Kiku and Senren write incompatible markup into the same fields, so only one can be enabled at a time; if both are enabled, Kiku wins and a config warning is emitted. +For Senren, use the same keys under `isSenren`. -```jsonc -"ankiConnect": { - "isSenren": { - "enabled": true, - "fieldGrouping": "auto", // "auto" (default), "manual", or "disabled" - "deleteDuplicateInAuto": true // delete new card after auto-merge - } -} -``` +| `fieldGrouping` | Behavior | +| --------------- | ------------------------------------------------------------------------------- | +| `disabled` | No duplicate check | +| `auto` | Merge into the existing card. With `deleteDuplicateInAuto`, delete the new card | +| `manual` | Show both cards, let you choose which to keep and preview the merge | -### Modes +Grouping runs when a new note is added while duplicates exist. With Hachidori, that is the popup's **Add anyway** choice. **Overwrite** updates the existing note in place and only gets media. -**Disabled** (`"disabled"`): No duplicate detection. Each card is independent. +The manual dialog cancels itself after 90 seconds. Identical entries are not deduplicated. Press `Ctrl/Cmd+G` to run the duplicate check on the last card yourself. -**Auto** (`"auto"`): When a duplicate expression is found, SubMiner merges the new card into the existing one automatically. Both cards' sentences, audio clips, and images are preserved as grouped entries. If `deleteDuplicateInAuto` is true, the new card is deleted after merging. +| Key | Action | +| ----------- | ------------------------------------- | +| `1` / `2` | Keep card 1 or card 2 | +| `Enter` | Confirm | +| `Backspace` | Back from the merge preview | +| `Esc` | Cancel and leave both cards unchanged | -**Manual** (`"manual"`): A modal appears in the overlay showing both cards. You choose which card to keep, preview the merge result, then confirm. The modal has a 90-second timeout, after which it cancels automatically. +## Config validation -### What gets merged - -| Field | Merge behavior | -| -------- | ----------------------------------------------- | -| Sentence | Both cards' sentences kept as grouped entries | -| Audio | Both cards' `[sound:...]` entries kept | -| Image | Both cards' images kept | -| MiscInfo | Both cards' source info kept as grouped entries | - -Identical values from both cards are kept as separate grouped entries; the merge does not deduplicate. - -The merge markup depends on the note type. Kiku entries are wrapped in `<span data-group-id="...">` spans ordered newest first. Senren entries follow the [scene switching](https://github.com/BrenoAqua/Senren/blob/main/docs/scene_switching.md) format: sentence, sentenceFurigana, and miscInfo entries use `group` spans when ordinal order is sufficient and numbered `groupN` spans when they need an absolute scene target. Audio and pictures are appended positionally, and the number of sentenceAudio entries drives Senren's scene count. Ungrouped legacy content is wrapped into a group span on first merge, and source `groupN` spans are rebased after the kept note's existing audio scenes. - -### Keyboard shortcuts in the modal - -| Key | Action | -| ----------- | ---------------------------------- | -| `1` / `2` | Select card 1 or card 2 to keep | -| `Enter` | Confirm selection | -| `Backspace` | Go back from the merge preview | -| `Esc` | Cancel (keep both cards unchanged) | - -## Full config example - -```jsonc -{ - "ankiConnect": { - "enabled": true, - "url": "http://127.0.0.1:8765", - "pollingRate": 3000, - "deck": "", - "tags": ["SubMiner"], - "proxy": { - "enabled": true, // default - "host": "127.0.0.1", - "port": 8766, - "upstreamUrl": "http://127.0.0.1:8765", - }, - "fields": { - "word": "Expression", - "audio": "SentenceAudio", - "image": "Picture", - "sentence": "Sentence", - "miscInfo": "MiscInfo", - }, - "media": { - "generateAudio": true, - "generateImage": true, - "imageType": "static", - "imageFormat": "jpg", - "imageQuality": 92, - "normalizeAudio": true, - "mirrorMpvVolume": true, - "audioPadding": 0, - "maxMediaDuration": 30, - }, - "behavior": { - "overwriteAudio": true, - "overwriteImage": true, - "mediaInsertMode": "append", - "autoUpdateNewCards": true, - "notificationType": "overlay", - }, - "metadata": { - "pattern": "[SubMiner] %f (%t)", - }, - "isKiku": { - "enabled": false, - "fieldGrouping": "disabled", - "deleteDuplicateInAuto": true, - }, - "isLapis": { - "enabled": false, - "sentenceCardModel": "Lapis", - }, - }, -} -``` +Invalid `ankiConnect` values produce a warning and fall back to the default. Use JSON booleans (`true`, not `"true"`) and a positive number for `pollingRate`. diff --git a/docs-site/architecture.md b/docs-site/architecture.md index 0aa87cc3..f4d9531b 100644 --- a/docs-site/architecture.md +++ b/docs-site/architecture.md @@ -1,148 +1,55 @@ # Architecture -This page is a contributor-facing architecture summary. Canonical internal architecture guidance lives in `docs/architecture/README.md` at the repo root. +A contributor-facing map of how SubMiner is put together. The canonical internal guidance, including domain ownership and layering rules, is [`docs/architecture/README.md`](https://github.com/ksyasuda/SubMiner/blob/main/docs/architecture/README.md) in the repo. -SubMiner is split into three cooperating runtimes: +SubMiner runs as three cooperating runtimes: -- Electron desktop app (`src/`) for overlay/UI/runtime orchestration. -- Launcher CLI (`launcher/`) for mpv/app command workflows. -- mpv Lua plugin (`plugin/subminer/main.lua` + module files) for player-side controls and IPC handoff. +- the Electron desktop app (`src/`): overlay, UI, and runtime orchestration +- the launcher CLI (`launcher/`): mpv and app command workflows +- the mpv Lua plugin (`plugin/subminer/`): player-side controls and handoff to the app -Within the desktop app, `src/main.ts` is a composition root that wires small runtime/domain modules plus core services. +Inside the app, `src/main.ts` is a composition root. It owns wiring and state, and delegates behavior to small runtime and domain modules that can be tested without Electron or mpv. -## Goals - -- Keep behavior stable while reducing coupling. -- Prefer small, single-purpose units that can be tested in isolation. -- Keep `main.ts` focused on wiring and state ownership, not implementation detail. -- Follow Unix-style composability: - - each service does one job - - services compose through explicit inputs/outputs - - orchestration is separate from implementation - -## Project structure +## Project layout ```text -launcher/ # Standalone CLI launcher wrapper and mpv helpers - commands/ # Command modules (doctor/config/mpv/jellyfin/playback/app passthrough/ - # dictionary/history/logs/stats/update) - config/ # Launcher config parsers + CLI parser builder - main.ts # Launcher entrypoint and command dispatch -plugin/ - subminer/ # Modular mpv plugin (main · init · bootstrap · lifecycle · process - # state · messages · hover · ui · options · environment · log - # binary · session_bindings · version) +launcher/ + main.ts # entrypoint and command dispatch + commands/ # one module per subcommand (playback, jellyfin, stats, sync, ...) + config/ # launcher config readers and CLI parser +plugin/subminer/ # mpv plugin; main.lua loads init.lua, which boots the other modules src/ - main-entry.ts # Background-mode bootstrap wrapper before loading main.js - main.ts # Entry point - delegates to runtime composers/domain modules - preload.ts # Electron preload bridge - types.ts # Shared type definitions - main/ # Main-process composition/runtime adapters - boot/ # Pre-ready boot helpers - app-lifecycle.ts # App lifecycle + app-ready runtime runner factories - character-dictionary-runtime.ts # Character-dictionary orchestration/public runtime API - cli-runtime.ts # CLI command runtime service adapters - config-validation.ts # Startup/hot-reload config error formatting and fail-fast helpers - dependencies.ts # Shared dependency builders for IPC/runtime services - ipc-runtime.ts # IPC runtime registration wrappers - overlay-runtime.ts # Overlay modal routing + active-window selection - overlay-shortcuts-runtime.ts # Overlay keyboard shortcut handling - overlay-visibility-runtime.ts # Overlay visibility + tracker-driven bounds service - frequency-dictionary-runtime.ts # Frequency dictionary runtime adapter - jlpt-runtime.ts # JLPT dictionary runtime adapter - media-runtime.ts # Media path/title/subtitle-position runtime service - startup.ts # Startup bootstrap dependency builder - startup-lifecycle.ts # Lifecycle runtime runner adapter - state.ts # Application runtime state container + reducer transitions - subsync-runtime.ts # Subsync command runtime adapter - character-dictionary-runtime/ # Character-dictionary fetch/build/cache modules + focused tests - runtime/ - composers/ # High-level composition clusters used by main.ts - domains/ # Domain barrel exports (startup/overlay/mpv/jellyfin/...) - registry.ts # Domain registry consumed by main.ts - core/ - services/ # Focused runtime services (Electron adapters + pure logic) - anilist/ # AniList token store/update queue/update helpers - immersion-tracker/ # Immersion persistence/session/metadata modules - tokenizer/ # Tokenizer stage modules (selection/enrichment/annotation) - utils/ # Pure helpers and coercion/config utilities - cli/ # CLI parsing and help output - config/ # Config defaults/definitions, loading, parse, resolution pipeline - definitions/ # Domain-specific defaults + option registries - resolve/ # Domain-specific config resolution pipeline stages - shared/ipc/ # Cross-process IPC channel constants + payload validators - renderer/ # Overlay renderer (modularized UI/runtime) - handlers/ # Keyboard/mouse/gamepad interaction modules - modals/ # Modal flows (Jimaku, Kiku, subsync, runtime options, session help, - # changelog, character dictionary, playlist browser, subtitle - # sidebar, YouTube track picker, controller config/debug/select) - positioning/ # Subtitle position controller (drag-to-reposition) - settings/ # Settings window UI (model, controls, markup) - types/ # Domain type modules (anki, config, integrations, ...) - window-trackers/ # Backend-specific tracker implementations (Hyprland, Sway, X11, macOS, Windows) - jimaku/ # Jimaku API integration helpers - subsync/ # Subtitle sync (alass/ffsubsync) helpers - anki-integration/ # AnkiConnect proxy server + note-update enrichment workflow + main-entry.ts # bootstrap wrapper that runs before main.js + main.ts # composition root + preload*.ts # preload bridges (overlay, settings, stats, sync, Jellyfin setup) + main/ # main-process runtime modules and IPC/CLI wiring + boot/ # pre-ready boot helpers + runtime/composers/ # larger runtime clusters assembled for main.ts + runtime/domains/ # domain barrels (startup, overlay, mpv, ipc, shortcuts, anilist, jellyfin, mining) + core/services/ # focused services: mpv client, overlay, tokenizer, mining, integrations, stats + core/utils/ # pure helpers + shared/ipc/ # IPC channel constants and payload validators + renderer/ # overlay renderer: subtitle rendering, input handlers, modals + config/ # definitions/ (defaults + option registries) and resolve/ (resolution pipeline) + cli/ # app CLI parsing and help output + settings/, syncui/ # settings and sync windows + window-trackers/ # Hyprland, Sway, X11, macOS, and Windows trackers + anki-integration/ # AnkiConnect proxy and note-update workflow + jimaku/, subsync/, tsukihime/ # integration helpers + types/ # shared domain types +stats/ # stats dashboard UI (Vite) +vendor/ # Yomitan fork, texthooker-ui, JLPT vocab ``` -### Service layer (`src/core/services/`) +A few ownership notes that are hard to guess from file names: -- **Overlay/window runtime:** `overlay-manager.ts`, `overlay-window.ts`, `overlay-visibility.ts`, `overlay-bridge.ts`, `overlay-runtime-init.ts`, `overlay-content-measurement.ts` -- **Shortcuts/input:** `shortcut.ts`, `overlay-shortcut.ts`, `overlay-shortcut-handler.ts`, `shortcut-fallback.ts`, `numeric-shortcut.ts` -- **MPV runtime:** `mpv.ts`, `mpv-transport.ts`, `mpv-protocol.ts`, `mpv-properties.ts`, `mpv-render-metrics.ts` -- **Mining + Anki/Jimaku runtime:** `mining.ts`, `field-grouping.ts`, `field-grouping-overlay.ts`, `anki-jimaku.ts`, `anki-jimaku-ipc.ts` -- **Subtitle/token pipeline:** `subtitle-processing-controller.ts`, `subtitle-position.ts`, `subtitle-ws.ts`, `tokenizer.ts` + `tokenizer/*` stage modules (including `parser-enrichment-worker-runtime.ts` for async MeCab enrichment and `yomitan-parser-runtime.ts`) -- **Integrations:** `jimaku.ts`, `subsync.ts`, `subsync-runner.ts`, `texthooker.ts`, `jellyfin.ts`, `jellyfin-remote.ts`, `discord-presence.ts`, `yomitan-extension-loader.ts`, `yomitan-settings.ts` -- **Anki integration (repo `src/` root, not under `core/services/`):** `src/anki-integration.ts`, `src/anki-integration/anki-connect-proxy.ts` (local proxy for push-based auto-enrichment), `src/anki-integration/note-update-workflow.ts` -- **Config/runtime controls:** `config-hot-reload.ts`, `runtime-options-ipc.ts`, `cli-command.ts`, `startup.ts` -- **Domain submodules:** `anilist/*` (token/update queue/updater), `immersion-tracker/*` (storage/session/metadata/query/reducer) +- mpv access is split into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and property modules under `src/core/services/`. +- The renderer keeps `renderer.ts` to orchestration. Keyboard, mouse, and gamepad input live in `renderer/handlers/`, and each modal flow has its own file in `renderer/modals/`. +- AniSkip intro detection runs in the app (`src/main/runtime/aniskip-runtime.ts`), which drives mpv chapters and the skip key over the mpv IPC socket. The plugin does not handle it. -### Renderer layer (`src/renderer/`) +## Component diagram -The renderer keeps `renderer.ts` focused on orchestration. UI behavior is delegated to per-concern modules. - -```text -src/renderer/ - renderer.ts # Entrypoint/orchestration only - context.ts # Shared runtime context contract - state.ts # Centralized renderer mutable state (visible overlay only) - error-recovery.ts # Global renderer error boundary + recovery actions - overlay-content-measurement.ts # Reports rendered bounds to main process - subtitle-render.ts # Primary/secondary subtitle rendering + style application - positioning.ts # Facade export for positioning controller - yomitan-popup.ts # Yomitan popup iframe detection utilities - positioning/ - controller.ts # Subtitle drag-position controller - position-state.ts # Position state helpers (yPercent) - handlers/ - keyboard.ts # Keybindings, chord handling, modal key routing - mouse.ts # Hover/drag behavior, selection + observer wiring - gamepad-controller.ts # Gamepad/controller input handling - controller-binding-capture.ts # Controller binding capture flow - modals/ - jimaku.ts # Jimaku modal flow - kiku.ts # Kiku field-grouping modal flow - runtime-options.ts # Runtime options modal flow - session-help.ts # Keyboard shortcuts/help modal flow - subsync.ts # Manual subsync modal flow - character-dictionary.ts # Character dictionary modal flow - playlist-browser.ts # Playlist browser modal flow - subtitle-sidebar.ts # Subtitle sidebar modal flow - youtube-track-picker.ts # YouTube subtitle track picker - controller-*.ts # Controller config/debug/select modals - utils/ - dom.ts # Required DOM lookups + typed handles - platform.ts # Layer/platform capability detection -``` - -### Launcher + plugin runtimes - -- `launcher/main.ts` dispatches commands through `launcher/commands/*` and shared config readers in `launcher/config/*`. It handles mpv startup, app passthrough, Jellyfin helper commands, and playback handoff. -- `plugin/subminer/main.lua` is the mpv entrypoint: it sets up the module path and loads `init.lua`, a thin shim that boots the modular Lua files: `bootstrap.lua` (startup), `lifecycle.lua` (connect/disconnect), `process.lua` (process management), `state.lua` (shared state), `messages.lua` (IPC), `hover.lua` (hover-token highlight rendering), `ui.lua` (OSD rendering), `options.lua` (config), `environment.lua` (detection), `log.lua` (logging), `binary.lua` (path resolution), `session_bindings.lua` (configurable session keybindings), `version.lua` (version metadata). AniSkip intro detection lives in the SubMiner app (`src/main/runtime/aniskip-runtime.ts`), which drives mpv chapters and the skip key over the IPC socket. - -## Flow diagram - -The main process orchestrates a single primary overlay window plus modal surfaces: `main.ts` delegates to composition modules that wire together domain services. Subtitle layers (primary + secondary bar) are rendered in the same overlay renderer process, connected through `preload.ts`. External runtimes (launcher CLI and mpv plugin) operate independently and communicate via IPC socket or CLI passthrough. +The main process drives one primary overlay window plus modal surfaces. Primary and secondary subtitle layers render in the same overlay renderer, connected to the main process through `preload.ts`. The launcher and mpv plugin run as separate processes and talk to the app through sockets or CLI passthrough. ```mermaid flowchart TB @@ -225,63 +132,39 @@ flowchart TB ## Composition pattern -Most runtime code follows a dependency-injection pattern: +Runtime code uses dependency injection: -1. Define a service interface in `src/core/services/*`. -2. Keep core logic in pure or side-effect-bounded functions. -3. Build runtime deps in `src/main/` composition modules; extract an adapter/helper only when it adds meaningful behavior or reuse. -4. Call the service from lifecycle/command wiring points. +1. Put the logic in a service under `src/core/services/`, as pure or side-effect-bounded functions. +2. Build its runtime dependencies in a `src/main/` module. Pass simple dependencies inline; extract an adapter only when it adds behavior or gets reused. +3. Call the service from lifecycle or command wiring. -The composition root (`src/main.ts`) delegates to focused modules in `src/main/` and `src/main/runtime/composers/`: +`main.ts` gets domain handlers through `createMainRuntimeRegistry()` (`src/main/runtime/registry.ts`), which exposes the barrels in `src/main/runtime/domains/`. Larger clusters, such as app-ready startup, mpv, Jellyfin, AniList tracking, shortcuts, and IPC, are assembled by composers in `src/main/runtime/composers/`. Many handlers take a `*MainDeps` object built by a `createBuild*MainDepsHandler` builder, which keeps side effects out of the unit under test. -- `startup.ts` - argv/env processing and bootstrap flow -- `app-lifecycle.ts` - Electron lifecycle event registration -- `startup-lifecycle.ts` - app-ready initialization sequence -- `state.ts` - centralized application runtime state container -- `ipc-runtime.ts` - IPC channel registration and handler wiring -- `cli-runtime.ts` - CLI command parsing and dispatch -- `overlay-runtime.ts` - overlay window selection and modal state management -- `subsync-runtime.ts` - subsync command orchestration -- `runtime/composers/anilist-tracking-composer.ts` - AniList media tracking/probe/retry wiring -- `runtime/composers/jellyfin-runtime-composer.ts` - Jellyfin config/client/playback/command/setup composition wiring -- `runtime/composers/mpv-runtime-composer.ts` - MPV event/factory/tokenizer/warmup wiring +Composers declare their inputs with `ComposerInputs<T>` and results with `ComposerOutputs<T>` from `src/main/runtime/composers/contracts.ts`. A missing dependency then fails at compile time. -Composer modules share contract conventions via `src/main/runtime/composers/contracts.ts`: +### IPC boundary -- composer input surfaces are declared with `ComposerInputs<T>` so required dependencies cannot be omitted at compile time -- composer outputs are declared with `ComposerOutputs<T>` to keep result contracts explicit and stable -- builder return payload extraction should use shared type helpers instead of inline ad-hoc inference +Channel names live in `src/shared/ipc/contracts.ts` and payload validators in `src/shared/ipc/validators.ts`. Renderer payloads are validated at the IPC entry points (`src/core/services/ipc.ts`, `src/core/services/anki-jimaku-ipc.ts`) before any domain handler runs. See [IPC + runtime contracts](/ipc-contracts) for the full rules. -This keeps side effects explicit and makes behavior easy to unit-test with fakes. +### Runtime state ownership -Additional conventions in the current code: +Some domains, such as AniList token, queue, and media-guess state, use reducer-style transitions: -- `main.ts` uses `createMainRuntimeRegistry()` (`src/main/runtime/registry.ts`) to access domain handlers (`startup`, `overlay`, `mpv`, `ipc`, `shortcuts`, `anilist`, `jellyfin`, `mining`) without importing every runtime module directly. -- Domain barrels in `src/main/runtime/domains/*` re-export runtime handlers + main-deps builders, while composers in `src/main/runtime/composers/*` assemble larger runtime clusters. -- Many runtime handlers accept `*MainDeps` objects generated by `createBuild*MainDepsHandler` builders to isolate side effects and keep units testable. - -### IPC contract + validation boundary - -- Central channel constants live in `src/shared/ipc/contracts.ts` and are consumed by both main (`ipcMain`) and renderer preload (`ipcRenderer`) wiring. -- Runtime payload parsers/type guards live in `src/shared/ipc/validators.ts`. -- Rule: renderer-supplied payloads must be validated at IPC entry points (`src/core/services/ipc.ts`, `src/core/services/anki-jimaku-ipc.ts`) before calling domain handlers. -- Malformed invoke payloads return explicit structured errors (for example `{ ok: false, error: ... }`) and malformed fire-and-forget payloads are ignored safely. - -### Runtime state ownership (migrated domains) - -For domains migrated to reducer-style transitions (for example AniList token/queue/media-guess runtime state), follow these rules: - -- Composition/runtime modules own mutable state cells and expose narrow `get*`/`set*` accessors. -- Domain handlers do not mutate foreign state directly; they call explicit transition helpers that encode invariants. -- Transition helpers may sync derived counters/snapshots, but must preserve non-owned metadata unless the transition explicitly owns that metadata. -- Reducer boundary: when a domain has transition helpers in `src/main/state.ts`, new callsites should route updates through those helpers instead of ad-hoc object mutation in `main.ts` or composers. -- Tests for migrated domains should assert both the intended field changes and non-targeted field invariants. +- Composition modules own the mutable state and expose narrow `get*`/`set*` accessors. +- Handlers change another domain's state only through its transition helpers in `src/main/state.ts`, never by mutating the object directly. +- A transition may update derived counters or snapshots, but must leave metadata it does not own untouched. +- Tests for these domains check both the fields that should change and the ones that should not. ## Playback startup flow -Before the app boots, something has to launch mpv, inject the plugin, and bring the overlay up. SubMiner-managed launches own this step - the `subminer` launcher, the app's own playback, and the packaged Windows shortcut all follow the same path. The launcher reads `config.jsonc`, spawns mpv with the IPC socket and the bundled plugin, and passes runtime settings as `--script-opts`. The plugin never reads a config file: the shipped `subminer.conf` is intentionally empty so command-line opts always win. +A SubMiner-managed launch (the `subminer` launcher, the app's own playback, or the packaged Windows shortcut) starts mpv, injects the plugin, and brings up the overlay. The launcher reads `config.jsonc`, spawns mpv with the IPC socket and the bundled plugin, and passes runtime settings as `--script-opts`. The plugin never reads a config file: the shipped `subminer.conf` has no settings, so command-line options always win. -Once mpv is up, exactly one of two triggers brings up the overlay. On a first launch the plugin's `file-loaded` hook self-starts the app once the socket is ready (because the launcher injected `auto_start=yes`). When the app is already running - or for explicit `--start-overlay` and YouTube flows - the launcher instead attaches over the control socket and suppresses the plugin's auto-start, so the two never fire together. Both converge on the same app bring-up, which then runs the Program Lifecycle below. +Once mpv is up, exactly one of two triggers starts the overlay: + +- On a first launch, the launcher sets `auto_start=yes` and the plugin's `file-loaded` hook starts the app once the socket is ready. +- When the app is already running, or for `--start-overlay` and YouTube flows, the launcher attaches over the app control socket and suppresses the plugin's auto-start. + +Both paths end in the same app bring-up, which then runs the program lifecycle below. ```mermaid flowchart TB @@ -312,17 +195,17 @@ flowchart TB Conn --> Show["Transparent overlay over mpv<br/>Yomitan lookup · mine"]:::overlay ``` -The runtime sockets in this flow are detailed in [IPC + Runtime Contracts](./ipc-contracts#runtime-sockets). +The sockets in this flow are described in [IPC + runtime contracts](./ipc-contracts#runtime-sockets). ## Program lifecycle -- **Module-level init:** Before `app.ready`, the composition root registers protocols, sets platform flags, constructs all services, and wires dependency injection. `runAndApplyStartupState()` parses CLI args and detects the compositor backend. -- **Startup:** If `--generate-config` is passed, it writes the template and exits. Otherwise `app-lifecycle.ts` acquires the single-instance lock and registers Electron lifecycle hooks. -- **Critical-path init:** Once `app.whenReady()` fires, `composeAppReadyRuntime()` runs strict config reload, resolves keybindings, creates the `MpvIpcClient` (which immediately connects and subscribes to mpv subtitle/playback properties via `observe_property`), and initializes the `RuntimeOptionsManager`, `SubtitleTimingTracker`, and `ImmersionTrackerService`. -- **Overlay runtime:** `initializeOverlayRuntime()` creates the primary overlay window (interactive Yomitan lookups and subtitle rendering), registers global shortcuts, and sets up bounds tracking via the active window tracker. mpv subtitle suppression is handled by a dedicated `overlay-mpv-sub-visibility` service. -- **Background warmups:** Non-critical services are launched asynchronously: MeCab tokenizer check (with async worker thread), Yomitan extension load, JLPT + frequency dictionary prewarm, optional Jellyfin remote session, Discord presence service, AniList token refresh, and optional AnkiConnect proxy server. Warmup coverage is configurable through `startupWarmups` (including low-power mode that defers all but Yomitan). -- **Runtime:** Event-driven. mpv property changes, IPC messages, CLI commands, overlay shortcuts, and hot-reload notifications route through runtime handlers/composers. Subtitle text flows through the `SubtitleProcessingController` (normalize → tokenize → merge), and results are sent to the main overlay renderer and modal surfaces. -- **Shutdown:** `onWillQuitCleanup` destroys tray + config watcher, unregisters shortcuts, stops WebSocket + texthooker servers, closes the mpv socket + flushes OSD log, stops the window tracker, closes the Yomitan parser window, flushes the immersion tracker (SQLite), stops Jellyfin/Discord services, stops the AnkiConnect proxy server, and cleans Anki/AniList state. +1. **Module init.** Before `app.ready`, the composition root registers protocols, sets platform flags, constructs services, and wires dependencies. `runAndApplyStartupState()` parses CLI args and detects the compositor backend. +2. **Startup.** `--generate-config` writes the template and exits. Otherwise `app-lifecycle.ts` takes the single-instance lock and registers Electron lifecycle hooks. +3. **App ready.** `composeAppReadyRuntime()` reloads config strictly, resolves keybindings, creates the `MpvIpcClient` (which connects and observes subtitle and playback properties), and starts the runtime options manager, subtitle timing tracker, and immersion tracker. +4. **Overlay.** `initializeOverlayRuntime()` creates the overlay window, registers global shortcuts, and tracks mpv's window bounds through the active window tracker. `src/main/runtime/overlay-mpv-sub-visibility.ts` hides mpv's own subtitles while the overlay shows them. +5. **Background warmups.** MeCab, Yomitan, JLPT and frequency dictionaries, the optional Jellyfin remote session, Discord presence, AniList token refresh, and the optional AnkiConnect proxy start asynchronously. `startupWarmups` controls which run; its low-power mode defers everything except Yomitan. +6. **Runtime.** Event-driven. mpv property changes, IPC messages, CLI commands, shortcuts, and config hot-reloads route through handlers and composers. Subtitle text goes through `SubtitleProcessingController` (normalize, tokenize, merge) and out to the overlay renderer and modals. +7. **Shutdown.** `onWillQuitCleanup` tears down the tray, config watcher, shortcuts, WebSocket and texthooker servers, mpv socket, window tracker, and Yomitan parser window. It flushes the immersion tracker to SQLite and stops Jellyfin, Discord, and the AnkiConnect proxy. ```mermaid flowchart TB @@ -386,11 +269,11 @@ flowchart TB style Loop fill:#363a4f,stroke:#494d64,color:#cad3f5 ``` -## Subtitle prefetch pipeline +## Subtitle prefetch -SubMiner can pre-tokenize upcoming subtitle lines before they appear on screen. When an external subtitle file (SRT, VTT, or ASS) is detected on the active track, the `SubtitlePrefetchService` parses all cues via the subtitle cue parser (`subtitle-cue-parser.ts`), identifies a priority window of upcoming lines based on the current playback position, and tokenizes them in the background through the same pipeline used for live subtitles. Results are stored directly into the `SubtitleProcessingController` cache, so when a subtitle actually appears during playback, it hits a warm cache and renders in ~30-50ms instead of ~200-320ms. +SubMiner tokenizes upcoming subtitle lines before they appear, so they render from a warm cache. `SubtitlePrefetchService` (`src/core/services/subtitle-prefetch.ts`) gets the cue list from the active track: an external subtitle file, or for local media an embedded text track extracted with ffmpeg. It parses the cues with `subtitle-cue-parser.ts`, picks a window of upcoming lines from the playback position, and tokenizes them through the live pipeline, storing results in the `SubtitleProcessingController` cache. -The prefetcher yields to live subtitle processing (which always takes priority over background work) and re-computes its priority window on seek. Cache invalidation events (e.g. marking a word as known) trigger re-prefetching of the current window to keep results fresh. +Live subtitle processing always takes priority; the prefetcher pauses while the on-screen line is being processed. It recomputes its window on seek and re-prefetches when the cache is invalidated, for example after a word is marked known. ```mermaid flowchart TB @@ -399,7 +282,7 @@ flowchart TB classDef runtime fill:#8bd5ca,stroke:#494d64,color:#24273a,stroke-width:1.5px classDef warmup fill:#eed49f,stroke:#494d64,color:#24273a,stroke-width:1.5px - SubFile["External Sub File"]:::init + SubFile["Subtitle Track"]:::init Parse["Cue Parser"]:::phase Window["Upcoming Lines"]:::phase Tokenize["Pre-tokenize"]:::warmup @@ -416,22 +299,11 @@ flowchart TB style Render stroke-width:2px ``` -## Why this design - -- **Smaller blast radius:** changing one feature usually touches one service. -- **Better testability:** most behavior can be tested without Electron windows/mpv. -- **Better reviewability:** PRs can be scoped to one subsystem. -- **Backward compatibility:** CLI flags and IPC channels can remain stable while internals evolve. -- **Runtime registry + domain barrels:** `src/main/runtime/registry.ts` and `src/main/runtime/domains/*` reduce direct fan-in inside `main.ts` while keeping domain ownership explicit. -- **Extracted composition root:** `main.ts` delegates to focused modules under `src/main/` and `src/main/runtime/composers/` for lifecycle, IPC, overlay, mpv, shortcut, and integration wiring. -- **Split MPV service layers:** MPV internals are separated into transport (`mpv-transport.ts`), protocol (`mpv-protocol.ts`), and properties/render metrics modules for maintainability. -- **Config by domain:** defaults, option registries, and resolution are split by domain under `src/config/definitions/*` and `src/config/resolve/*`, keeping config evolution localized. - ## Extension rules -- Add behavior to an existing service in `src/core/services/*` or create a focused runtime module under `src/main/runtime/*`; avoid ad-hoc logic in `main.ts`. -- Add new cross-process channels in `src/shared/ipc/contracts.ts` first, validate payloads in `src/shared/ipc/validators.ts`, then wire handlers in IPC runtime modules. -- See also the contributor IPC onboarding page: [IPC + Runtime Contracts](/ipc-contracts). -- If change spans startup/overlay/mpv/integration wiring, prefer composing through `src/main/runtime/domains/*` + `src/main/runtime/composers/*` rather than direct wiring in `main.ts`. -- Keep service APIs explicit and narrowly scoped, and preserve existing CLI flag / IPC channel behavior unless the change is intentionally breaking. -- Add or update focused tests (including malformed-payload IPC tests) when runtime boundaries or contracts change. +- Add behavior to a service in `src/core/services/` or a focused module under `src/main/runtime/`. Keep new logic out of `main.ts`. +- For changes that span startup, overlay, mpv, or integration wiring, compose through `src/main/runtime/domains/` and `src/main/runtime/composers/` instead of wiring directly in `main.ts`. +- Add a cross-process channel in `src/shared/ipc/contracts.ts` first, validate it in `src/shared/ipc/validators.ts`, then wire the handler. See [IPC + runtime contracts](/ipc-contracts#add-a-new-ipc-action). +- Config is split by domain under `src/config/definitions/` and `src/config/resolve/`. Keep config changes in the matching domain file. +- Keep CLI flags and IPC channels stable unless a change is meant to break them. +- Add or update focused tests when a runtime boundary or contract changes, including malformed-payload tests for IPC. diff --git a/docs-site/archive-function.test.ts b/docs-site/archive-function.test.ts new file mode 100644 index 00000000..ddbcaecc --- /dev/null +++ b/docs-site/archive-function.test.ts @@ -0,0 +1,116 @@ +import { expect, test } from 'bun:test'; +import { onRequest, resolveArchiveRoute, type ArchiveBucket } from './functions/v/[[path]]'; + +// In-memory stand-in for the R2 binding, including the range and precondition behavior +// the function relies on. +function fakeBucket(objects: Record<string, string>): ArchiveBucket { + return { + async get(key, options) { + const content = objects[key]; + if (content === undefined) return null; + const bytes = new TextEncoder().encode(content); + const httpEtag = `"${key}"`; + + if (options?.onlyIf?.get('if-none-match') === httpEtag) { + return { size: bytes.length, httpEtag }; + } + + const rangeHeader = options?.range?.get('range'); + const match = rangeHeader ? /^bytes=(\d+)-(\d*)$/.exec(rangeHeader) : null; + if (match) { + const offset = Number(match[1]); + const end = match[2] ? Number(match[2]) : bytes.length - 1; + const slice = bytes.slice(offset, end + 1); + return { + size: bytes.length, + httpEtag, + range: { offset, length: slice.length }, + body: new Blob([slice]).stream(), + }; + } + + return { size: bytes.length, httpEtag, body: new Blob([bytes]).stream() }; + }, + }; +} + +const bucket = fakeBucket({ + 'v/0.19.6/index.html': '<h1>home</h1>', + 'v/0.19.6/usage.html': '<h1>usage</h1>', + 'v/0.19.6/404.html': '<h1>missing</h1>', + 'v/0.19.6/assets/app.abc123.js': 'console.log(1)', +}); + +function request(path: string, init?: RequestInit) { + return onRequest({ + request: new Request(`https://docs.subminer.moe${path}`, init), + env: { DOCS_ARCHIVES: bucket }, + }); +} + +test('archive routes follow the clean-URL layout of the built archives', () => { + expect(resolveArchiveRoute('/v/0.19.6/usage')).toEqual({ + kind: 'lookup', + version: '0.19.6', + keys: ['v/0.19.6/usage.html', 'v/0.19.6/usage/index.html'], + }); + expect(resolveArchiveRoute('/v/0.19.6/')).toEqual({ + kind: 'lookup', + version: '0.19.6', + keys: ['v/0.19.6/index.html'], + }); + expect(resolveArchiveRoute('/v/0.19.6', '?q=1')).toEqual({ + kind: 'redirect', + location: '/v/0.19.6/?q=1', + status: 301, + }); + expect(resolveArchiveRoute('/v/')).toEqual({ + kind: 'redirect', + location: '/versions', + status: 302, + }); + expect(resolveArchiveRoute('/v/0.19.6/%2e%2e/secret')).toEqual({ kind: 'not-found' }); + expect(resolveArchiveRoute('/v/latest/')).toEqual({ kind: 'not-found' }); +}); + +test('serves archive pages and hashed assets with their cache policy', async () => { + const page = await request('/v/0.19.6/usage'); + expect(page.status).toBe(200); + expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(page.headers.get('cache-control')).toBe('public, max-age=3600'); + expect(page.headers.get('x-robots-tag')).toBe('noindex, follow'); + expect(await page.text()).toBe('<h1>usage</h1>'); + + const asset = await request('/v/0.19.6/assets/app.abc123.js'); + expect(asset.headers.get('content-type')).toBe('text/javascript; charset=utf-8'); + expect(asset.headers.get('cache-control')).toContain('immutable'); +}); + +test('missing archive pages fall back to the archive 404 page', async () => { + const response = await request('/v/0.19.6/nope'); + expect(response.status).toBe(404); + expect(await response.text()).toBe('<h1>missing</h1>'); + + const unknownVersion = await request('/v/0.1.0/usage'); + expect(unknownVersion.status).toBe(404); +}); + +test('supports byte ranges, conditional requests, and HEAD', async () => { + const partial = await request('/v/0.19.6/usage', { headers: { Range: 'bytes=4-8' } }); + expect(partial.status).toBe(206); + expect(partial.headers.get('content-range')).toBe('bytes 4-8/14'); + expect(await partial.text()).toBe('usage'); + + const notModified = await request('/v/0.19.6/usage', { + headers: { 'If-None-Match': '"v/0.19.6/usage.html"' }, + }); + expect(notModified.status).toBe(304); + + const head = await request('/v/0.19.6/usage', { method: 'HEAD' }); + expect(head.status).toBe(200); + expect(head.headers.get('content-length')).toBe('14'); + expect(await head.text()).toBe(''); + + const post = await request('/v/0.19.6/usage', { method: 'POST' }); + expect(post.status).toBe(405); +}); diff --git a/docs-site/character-dictionary.md b/docs-site/character-dictionary.md index 55b01bf0..c356e81c 100644 --- a/docs-site/character-dictionary.md +++ b/docs-site/character-dictionary.md @@ -1,313 +1,104 @@ # Character dictionary -SubMiner builds a Yomitan-compatible dictionary of a show's characters from [AniList](https://anilist.co), the online anime and manga database. Once it is loaded, character names in subtitles get recognized and highlighted, and hovering one shows the portrait, role, voice actor, and biography without leaving the overlay. +SubMiner builds a Yomitan dictionary of the characters in the show you are watching, using data from [AniList](https://anilist.co). Character names in subtitles get their own color, and hovering one shows the character's portrait, role, voice actor, and description. -Proper names rarely appear in ordinary dictionaries, so without this every character name reads as an unknown word. That wrecks N+1 highlighting, since a line naming two characters looks like a line with two unknowns. Recognizing them keeps the highlighting pointed at real vocabulary. +Ordinary dictionaries rarely contain character names, so without this every name counts as an unknown word and throws off [N+1 highlighting](/subtitle-annotations#n-1-word-highlighting). -The dictionary is generated per-media, merged across your recently-watched titles, and auto-imported into Yomitan. When a character name appears in a subtitle line, it gets highlighted and becomes available for hover-driven Yomitan profile lookup. +## Turning it on -## How it works - -The feature has three stages: **snapshot**, **merge**, and **match**. - -1. **Snapshot** - When you start watching a new title, SubMiner queries the AniList GraphQL API for the media's character list. Each character's names, reading, role, description, birthday, voice actors, and portrait are fetched and saved as a local JSON snapshot in `character-dictionaries/snapshots/anilist-{mediaId}.json`. Images are downloaded and base64-encoded into the snapshot. - -2. **Merge** - SubMiner maintains a most-recently-used list of media IDs (default: 3). Snapshots from those titles are merged into a single Yomitan ZIP - `character-dictionaries/merged.zip` - which is always named "SubMiner Character Dictionary" so Yomitan treats it as a single stable dictionary across rebuilds. - -3. **Match** - During subtitle rendering, Yomitan scans subtitle text against all loaded dictionaries including the character dictionary. SubMiner only accepts character entries for the current AniList media when that media ID is known, then flags matching tokens with `isNameMatch` and highlights them in the overlay with a distinct color. - -## Enabling the feature - -Character dictionary sync is disabled by default. To turn it on: - -1. Enable **Name Match** in Settings → Subtitle Style, or set `subtitleStyle.nameMatchEnabled: true` in your config. -2. Start watching. SubMiner queries AniList's public GraphQL API, which needs no authentication, and imports the merged dictionary into Yomitan. -3. Optionally enable **Name Match Images** (Settings → Subtitle Style) to show inline circular character portraits next to matched names in subtitles. +1. Set `subtitleStyle.nameMatchEnabled` to `true`, or turn it on in the Settings window under Annotation Display, Character Names. +2. Optionally set `subtitleStyle.nameMatchImagesEnabled` to `true` to show a small portrait next to each name in the subtitle line. +3. Play an episode. ```jsonc { "subtitleStyle": { "nameMatchEnabled": true, - "nameMatchImagesEnabled": true, // optional - inline portraits + "nameMatchImagesEnabled": true, }, } ``` -::: tip -The first sync for a media title takes a few seconds while character data and portraits are fetched from AniList. Subsequent launches reuse the cached media match and snapshot without a fresh AniList lookup. -::: +No AniList account is needed. Logging in to AniList is only for [watch progress sync](/anilist-integration). -::: info -AniList character data is fetched via public GraphQL queries - no account or access token is needed. AniList authentication is only required for the separate [watch-progress sync](/anilist-integration) feature. -::: +The character dictionary does not work when `yomitan.externalProfilePath` is set, because SubMiner then uses another app's Yomitan profile read-only. -::: warning -If `yomitan.externalProfilePath` is set, SubMiner switches to read-only external-profile mode. In that mode SubMiner can reuse another app's installed Yomitan dictionaries/settings, but SubMiner's own character-dictionary features are fully disabled. -::: +## What happens when you play something -## Name generation +When a new show starts, SubMiner: -A single character produces many searchable terms so that names are recognized regardless of how they appear in dialogue. SubMiner generates variants for: +1. Guesses the title from the filename and finds it on AniList. +2. Downloads the cast list and portraits. +3. Builds the dictionary and imports it into SubMiner's Yomitan. -**Spacing and combination:** +A notification shows each step. Once it says the dictionary is ready, names match from the next subtitle line. -- Full name with space: 須々木 心一 -- Combined form: 須々木心一 -- Family name alone: 須々木 -- Given name alone: 心一 +Each character gets entries for the full name, family name, given name, and common honorifics (`さん`, `君`, `ちゃん`, `先生`, and others), so `太郎さん` matches as well as `太郎`. -Unspaced native names (AniList often stores 渡辺真奈美 without a separator) are split into family/given parts with MeCab when it is available: person-name POS tags (姓/名) decide the boundary, validated against AniList's romanized first/last name readings. Without MeCab, a length heuristic based on the romanized readings guesses the boundary. That guess can be ambiguous, since 東紫乃 could be 東+紫乃 or 東紫+乃, so SubMiner generates terms for the top two candidate boundaries and the real surname still matches. Snapshots built without MeCab are regenerated automatically once MeCab becomes available, upgrading them to the exact splits. +SubMiner keeps your most recent shows loaded in one merged dictionary. `anilist.characterDictionary.maxLoaded` sets how many. Starting another show drops the oldest one. Only the current show's characters are highlighted. -**Middle-dot removal** (common in katakana foreign names): +### How long it takes -- ア・リ・ス → アリス (combined), plus individual segments - -**Honorific suffixes** - each base name is expanded with 15 common suffixes: - -| Honorific | Reading | -| --------- | ---------- | -| さん | さん | -| 様 | さま | -| 先生 | せんせい | -| 先輩 | せんぱい | -| 後輩 | こうはい | -| 氏 | し | -| 君 | くん | -| くん | くん | -| ちゃん | ちゃん | -| たん | たん | -| 坊 | ぼう | -| 殿 | どの | -| 博士 | はかせ | -| 社長 | しゃちょう | -| 部長 | ぶちょう | - -**Romanized names** - names stored in romaji on AniList are converted to kana aliases so they can match against Japanese subtitle text. - -This means a character like "太郎" generates entries for 太郎, 太郎さん, 太郎先生, 太郎君, 太郎ちゃん, and so on - all with correct readings. - -## Name matching - -Name matching runs inside Yomitan's scanning pipeline during subtitle tokenization. - -1. Yomitan receives subtitle text and scans for dictionary matches. -2. Entries from "SubMiner Character Dictionary" are checked with exact primary-source matching - the token must match the entry's `originalText` with `isPrimary: true` and `matchType: 'exact'`. -3. When the current AniList media ID is known, entries whose embedded media ID belongs to a different title are ignored for name matching and inline portraits. -4. Matched tokens are flagged `isNameMatch: true` and forwarded to the renderer. -5. If `subtitleStyle.nameMatchEnabled` is enabled, the renderer applies the name-match highlight color (default: `#f5bde6`). -6. If `subtitleStyle.nameMatchImagesEnabled` is enabled, the renderer also injects a small circular AniList portrait from the cached snapshot image data. - -Older snapshot schema versions are regenerated automatically. Current-version snapshots are normally reused, but when `subtitleStyle.nameMatchImagesEnabled` is enabled SubMiner also checks whether the cached snapshot contains usable character portrait data. If it does not, the snapshot is refreshed so the merged dictionary can include images. - -Name matches are visually distinct from [N+1 targeting, frequency highlighting, and JLPT tags](/subtitle-annotations) so you can tell at a glance whether a highlighted word is a character name or a vocabulary target. - -**Key settings:** - -| Option | Default | Description | -| -------------------------------------- | --------- | ----------------------------------------- | -| `subtitleStyle.nameMatchEnabled` | `false` | Enable dictionary sync and highlighting | -| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small AniList portraits beside names | -| `subtitleStyle.nameMatchColor` | `#f5bde6` | Highlight color for matched names | - -## Inline character portraits - -When `subtitleStyle.nameMatchImagesEnabled` is enabled, SubMiner injects a small circular portrait image directly into the subtitle line next to each matched character name. - -Portraits are sourced from the local snapshot - they are embedded at snapshot-generation time and served from the cached ZIP, so no network request happens during playback. Images are downloaded from AniList CDN once per character and stored in `character-dictionaries/img/`. - -If a snapshot was generated before portrait data was available (e.g. during an earlier version or offline sync), SubMiner detects the missing image data on the next media match and automatically refreshes the snapshot so portraits are included in the next merged dictionary build. - -**To enable:** - -- Settings → Subtitle Style → **Name Match Images**, or -- `subtitleStyle.nameMatchImagesEnabled: true` in config. - -The portrait size is controlled by the surrounding subtitle font size and renders as a circle clipped from the character's AniList cover image. - -::: tip -Inline portraits help you quickly associate names with faces while building vocabulary - especially useful for shows with large casts where you're still learning who's who. -::: - -## Dictionary entries - -Each character entry in the Yomitan dictionary includes structured content: - -- **Name** - the matched Japanese name form -- **Known names** - generated non-honorific Japanese aliases for that character, excluding raw romanized/English aliases from lookup results -- **Role badge** - color-coded by role: main / "Protagonist" (score 100), primary / "Main Character" (75), side / "Side Character" (50), appears / "Minor Role" (25). AniList's MAIN maps to main, SUPPORTING to primary, and BACKGROUND to side. -- **Portrait** - character image from AniList, embedded in the ZIP -- **Description** - biography text from AniList (collapsible) -- **Character information** - age, birthday, gender, blood type (collapsible) -- **Voiced by** - voice actor name and portrait (collapsible) - -The three collapsible sections can be configured to start open or closed: - -```jsonc -{ - "anilist": { - "characterDictionary": { - "collapsibleSections": { - "description": false, - "characterInformation": false, - "voicedBy": false, - }, - }, - }, -} -``` - -## Auto-sync lifecycle - -When `subtitleStyle.nameMatchEnabled` is `true`, SubMiner runs an auto-sync routine whenever the active media changes. - -These phases are emitted through the configured notification surface. Some phases are skipped when unnecessary: `generating` only appears on a cache miss, `building` only appears when the merged ZIP must be rebuilt, and `importing` only appears when Yomitan needs a new dictionary import. - -**Phases:** - -1. **checking** - Is there already a cached snapshot for this media ID? -2. **generating** - No cache hit: fetch characters from AniList GraphQL, download portraits (250ms throttle between image requests), save snapshot JSON. -3. MRU update (no notification) - add the media ID to the most-recently-used list and evict old entries beyond `maxLoaded`. -4. **building** - Merge active snapshots into a single Yomitan ZIP. A SHA-1 revision hash is computed from the media set - if it matches the previously imported revision, the import is skipped. -5. **importing** - Push the ZIP into Yomitan. Waits for Yomitan mutation readiness (7-second timeout per operation). -6. **ready** - Dictionary is live. Character names will match on the next subtitle line. - -**State tracking** is persisted in `character-dictionaries/auto-sync-state.json`. AniList media matches are cached separately in `character-dictionaries/anilist-resolution-cache.json` so snapshot hits do not need another AniList search. - -```jsonc -{ - "activeMediaIds": ["170942 - Frieren", "163134 - ...", "154587 - ..."], - "mergedRevision": "a1b2c3d4e5f6", - "mergedDictionaryTitle": "SubMiner Character Dictionary", -} -``` - -(Entries are `"<mediaId> - <title>"` label strings; bare numeric IDs from older versions are still read.) - -The `maxLoaded` setting (default: 3) controls how many media snapshots stay in the active set. When you start a 4th title, the oldest is evicted and the merged dictionary is rebuilt without it. - -## Manual generation - -You can generate a character dictionary from the command line without auto-sync: - -```bash -# Generate for a file or directory -subminer dictionary /path/to/media - -# Generate for current anime (AppImage) -SubMiner.AppImage --dictionary -``` - -This creates a standalone dictionary ZIP for the target media and saves it alongside the snapshots. +The first time you watch a show, most of the time goes into downloading portraits, one at a time. A typical cast takes seconds to a minute. A very large cast takes much longer: One Piece has over a thousand characters and takes around 10 minutes. After that the show is cached, and later episodes load it from disk. ## Correcting AniList matches -SubMiner uses `guessit` to infer the anime title from the active filename before searching AniList. Some filenames can still resolve to the wrong title. For example, `Re - ZERO, Starting Life in Another World (2016)` can be misread as a different `Re...` series. +SubMiner can match the wrong show when a filename is ambiguous, for example `Re - ZERO, Starting Life in Another World (2016)` matching a different `Re...` series. To fix it: -Use the in-app selector or CLI to pin the correct AniList media for the whole series: +1. Press `Ctrl/Cmd+D` to open the character dictionary manager. +2. Click **Override**, edit the title if needed, search, and pick the right result. -- In-app: open the manager with `Ctrl/Cmd+D`, use the **Override** tab/button, edit the prefilled title if needed, then search and choose the correct result. -- CLI: `--dictionary-candidates` still lists matches for the current filename guess. +From the command line: ```bash -# List candidate AniList matches for a file +# List AniList matches for a file subminer dictionary --candidates "/path/to/episode.mkv" -# Save the correct AniList media ID for that series +# Save the correct AniList ID for that series subminer dictionary --select 21355 "/path/to/episode.mkv" - -# Equivalent direct app flags -SubMiner.AppImage --dictionary-candidates --dictionary-target "/path/to/episode.mkv" -SubMiner.AppImage --dictionary-select --dictionary-anilist-id 21355 --dictionary-target "/path/to/episode.mkv" - -# Open the in-app selector from the running app -subminer app --session-action '{"actionId":"openCharacterDictionaryManager"}' ``` -SubMiner stores manual selections in `character-dictionaries/anilist-overrides.json`. The episode's parent directory **and detected season** define the override scope, so later episodes in the same season keep the selected AniList ID even if their filename guesses differ, while a different season never inherits the override - including when every season sits in one flat folder. When you replace a wrong match, SubMiner removes that stale media ID from the merged dictionary's active set and rebuilds/imports the merged character dictionary. +The override applies to every episode of that season in the same folder. Other seasons are not affected, even when they share the folder. The override also sets which entry [AniList watch progress](/anilist-integration) updates, so one fix covers both. -An override also pins the entry used for [AniList watch progress](/anilist-integration), so correcting a wrong match once fixes both the character dictionary and progress tracking. +## Managing loaded shows -## Managing loaded entries +The manager (`Ctrl/Cmd+D`) lists the shows in the merged dictionary and marks the current one. -Open the manager with `Ctrl/Cmd+D` (`shortcuts.openCharacterDictionaryManager`). The manager shows the merged dictionary's active MRU entries, marks the current anime, and lets you adjust eviction priority for the other loaded entries. +- **Remove** drops a show from the dictionary. You cannot remove the show you are watching. +- **Up/Down** changes which show gets dropped first when a new one is added. +- **Override** replaces a show's AniList match. -- **Remove** drops a non-current entry from the active merged dictionary and rebuilds/imports once. -- **Up/Down** changes MRU order for future eviction; the merged dictionary is rebuilt and re-imported after a reorder. -- **Override** opens the AniList selector for that entry's title so you can replace a saved loaded entry. +## Generating from the command line -The current anime cannot be removed while you are watching it; it stays loaded until playback changes. - -## File structure - -All character dictionary data lives under `{userData}/character-dictionaries/`: - -```text -character-dictionaries/ - snapshots/ - anilist-170942.json # Per-media character snapshot - anilist-163134.json - merged.zip # Active merged dictionary (imported into Yomitan) - auto-sync-state.json # Tracks active media IDs and revision - anilist-overrides.json # Manual series-to-AniList overrides - img/ - m170942-c12345.jpg # Character portrait - m170942-va67890.jpg # Voice actor portrait +```bash +subminer dictionary /path/to/media ``` -**Snapshot format** (v19, `CHARACTER_DICTIONARY_FORMAT_VERSION`): each snapshot contains the media ID, title, entry count, timestamp, an array of Yomitan term entries, and base64-encoded images. Snapshots with a different format version are regenerated. +This builds a standalone dictionary file for that file or folder without playing it. With the AppImage directly, use `SubMiner.AppImage --dictionary`. -**ZIP structure** follows the Yomitan dictionary format: +## Configuration -```text -merged.zip - index.json # { title, revision, format: 3, author: "SubMiner", description } - tag_bank_1.json # Tag definitions - term_bank_1.json # Up to 10,000 terms per bank - term_bank_2.json - img/ # Embedded character and VA portraits -``` +Defaults are in the [configuration reference](/configuration). -## Configuration reference - -| Option | Default | Description | -| ---------------------------------------------------------------------- | --------- | --------------------------------------------------------------- | -| `anilist.characterDictionary.maxLoaded` | `3` | Number of recent media snapshots kept in the merged dictionary | -| `anilist.characterDictionary.profileScope` | `"all"` | Apply dictionary to `"all"` Yomitan profiles or `"active"` only | -| `anilist.characterDictionary.collapsibleSections.description` | `false` | Start Description section expanded | -| `anilist.characterDictionary.collapsibleSections.characterInformation` | `false` | Start Character Information section expanded | -| `anilist.characterDictionary.collapsibleSections.voicedBy` | `false` | Start Voiced By section expanded | -| `subtitleStyle.nameMatchEnabled` | `false` | Enable character-dictionary sync and name highlighting | -| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small AniList portraits beside matched names | -| `subtitleStyle.nameMatchColor` | `#f5bde6` | Highlight color for character-name matches | - -## Reference implementation - -SubMiner's character dictionary builder is inspired by the [Japanese Character Name Dictionary](https://github.com/bee-san/Japanese_Character_Name_Dictionary) project - a standalone Rust web service that generates Yomitan character dictionaries from AniList and VNDB data. - -The reference implementation covers the same ground: name variant generation, honorific expansion, structured Yomitan content, and portrait embedding. It also reads VNDB as a source for visual novel characters. Key differences: - -| | SubMiner | Reference Implementation | -| ---------------------- | -------------------------------------------- | ------------------------------------- | -| **Runtime** | TypeScript, runs inside Electron | Rust, standalone web service | -| **Data sources** | AniList only | AniList + VNDB | -| **Delivery** | Auto-synced into bundled Yomitan | ZIP download via web UI | -| **Honorific strategy** | Eager generation at build time | Lazy generation during ZIP export | -| **Caching** | File-based snapshots | Multi-tier (memory + disk + SQLite) | -| **Updates** | Revision-hashed; skips reimport if unchanged | URL-encoded settings for auto-refresh | - -If you work with visual novels or want a standalone dictionary generator independent of SubMiner, the reference implementation is worth checking out. +| Key | What it does | +| ---------------------------------------------------------------------- | ------------------------------------------------ | +| `subtitleStyle.nameMatchEnabled` | Build the dictionary and color character names | +| `subtitleStyle.nameMatchImagesEnabled` | Show a portrait next to matched names | +| `subtitleStyle.nameMatchColor` | Color for character names | +| `anilist.characterDictionary.maxLoaded` | Number of recent shows kept in the dictionary | +| `anilist.characterDictionary.collapsibleSections.description` | Show the description expanded in the popup | +| `anilist.characterDictionary.collapsibleSections.characterInformation` | Show age, birthday, and similar details expanded | +| `anilist.characterDictionary.collapsibleSections.voicedBy` | Show the voice actor section expanded | +| `shortcuts.openCharacterDictionaryManager` | Shortcut for the manager | ## Troubleshooting -- **Names not highlighting:** Confirm `subtitleStyle.nameMatchEnabled` is `true`. Check that the current media has an AniList entry - SubMiner needs a media ID to fetch characters. -- **Inline portraits missing:** Confirm `subtitleStyle.nameMatchImagesEnabled` is `true`. On the next character dictionary sync, SubMiner refreshes current-version snapshots that do not contain usable cached character portrait data. Portraits still require AniList to return an image and the image download to succeed. -- **Sync seems stuck:** The auto-sync debounces for 800ms after media changes and throttles image downloads at 250ms per image. Large casts (50+ characters) take longer. Check the status bar for the current sync phase. -- **Wrong characters showing:** Open the in-app character dictionary manager (`Ctrl/Cmd+D`) to remove/reorder loaded titles, then use **Override** to correct the active AniList match. You can also run `--dictionary-candidates`, then save the correct media with `--dictionary-select --dictionary-anilist-id <id>`. SubMiner ignores character entries from other loaded titles for subtitle name matching and inline portraits once the current media ID is known. -- **Yomitan import fails:** SubMiner waits up to 7 seconds for Yomitan to be ready for mutations. If Yomitan is still loading dictionaries or performing another import, the operation may time out. Restarting the overlay typically resolves this. -- **Portraits missing:** Images are downloaded from AniList CDN during snapshot generation. If the network was unavailable during the initial sync, delete the snapshot file from `character-dictionaries/snapshots/` and let it regenerate. +**It seems stuck.** Check the notification. While generating it shows counts (`image 120/400`), an estimate of time left, and an elapsed clock. If the clock moves, it is still working, and large casts are slow (see [how long it takes](#how-long-it-takes)). If you missed the notification, open the notification history with `Ctrl/Cmd+N`. For errors, check the app log ([log locations](/troubleshooting)). -## Related +**Import failed or timed out.** Yomitan may have been busy importing another dictionary. Play the next episode or restart SubMiner. The import may have finished anyway, so check for the character popup before retrying. -- [Subtitle Annotations](/subtitle-annotations) - how name matches interact with N+1, frequency, and JLPT layers -- [AniList Integration](/anilist-integration) - watch-progress sync and AniList authentication (separate from character dictionary) -- [Configuration Reference](/configuration) - full config options +**Names are not highlighted.** Check that `subtitleStyle.nameMatchEnabled` is `true`, that `yomitan.externalProfilePath` is empty, and that the show was found on AniList. The wrong show's cast means a wrong match. See [correcting AniList matches](#correcting-anilist-matches). + +**Portraits are missing.** Portraits need AniList to have an image and the download to succeed. If you were offline during the first sync, delete that show's file from `character-dictionaries/snapshots/` in the SubMiner config directory and replay it. + +SubMiner's generator is based on the [Japanese Character Name Dictionary](https://github.com/bee-san/Japanese_Character_Name_Dictionary) project, which also supports VNDB and works without SubMiner. diff --git a/docs-site/configuration.md b/docs-site/configuration.md index 1d867b3d..922912d3 100644 --- a/docs-site/configuration.md +++ b/docs-site/configuration.md @@ -8,76 +8,24 @@ outline: [2, 3] import { withBase } from 'vitepress'; </script> -One file, `config.jsonc`, holds everything. Most of it is also editable from the in-app **Settings** window, so hand-editing is rarely necessary. +All SubMiner settings live in one file, `config.jsonc`. Most of them are also editable in the Settings window, so you rarely need to edit the file by hand. This page lists every config block with its keys and defaults. -This page is the full reference. It covers the Settings window, where the config file lives, and every option grouped by topic. If you are just starting out, the Quick Start below and the [Settings window](#settings) are enough. +## Config file {#configuration-file} -## Quick start +| Platform | Path | +| ------------ | ------------------------------------------------------------------------------------- | +| Linux, macOS | `$XDG_CONFIG_HOME/SubMiner/config.jsonc` (`~/.config/SubMiner/config.jsonc` if unset) | +| Windows | `%APPDATA%\SubMiner\config.jsonc` | -Start here: +The file is JSONC, so comments and trailing commas are allowed. If both `config.jsonc` and `config.json` exist, SubMiner uses `config.jsonc`. Only add the keys you want to change. Everything else uses the built-in default. -```json -{ - "ankiConnect": { - "enabled": true, - "deck": "YourDeckName", - "knownWords": { - "decks": { - "YourDeckName": ["Word"] - } - }, - "fields": { - "sentence": "Sentence", - "audio": "Audio", - "image": "Image" - } - } -} -``` +The [generated example config](/config.example.jsonc) lists every option with its default and a comment. Defaults in the tables below come from that file. -Use the known-word deck map to choose which Anki decks and note fields feed the known-word cache. - -Everything else is optional; the sections below cover it. - -## Settings - -Open the **Settings** window from the tray menu, the app's `--settings` flag, or `subminer settings`. It writes straight to `config.jsonc`, so anything you change there is a normal config edit you can inspect afterward. - -The Settings window groups options by workflow instead of mirroring the raw config-file shape: - -- Appearance -- Behavior -- Mining & Anki -- Input -- Integrations -- Tracking & App -- Advanced - -Playback-related fields live as sections inside these groups (for example "Playback Behavior" under **Behavior** and "mpv Playback" / "YouTube Playback Settings" under **Integrations**). - -Each field still writes to its current `config.jsonc` path. For example, subtitle hover pause appears under **Behavior** / playback behavior, but saves to `subtitleStyle.autoPauseVideoOnHover`. Anki-aware fields can query AnkiConnect for deck names, note types, and field names. The AnkiConnect deck field also reads Yomitan's current mining deck and persists it into an empty setting when one is found. Stats mining also uses Yomitan's current mining deck when `ankiConnect.deck` is empty. Keybinding fields use click-to-learn controls instead of raw text boxes. - -The Settings window preserves existing JSONC comments, trailing commas, and unrelated keys. Resetting a field removes the explicit config path so the built-in default applies. - -Secret fields do not display stored values. They show whether a value is configured; entering a new value writes it, and reset clears the explicit path. Prefer command-based secret options such as `jimaku.apiKeyCommand` when available. - -Saving validates the candidate config before writing. Saving only fields marked **LIVE** shows "Saved. Live settings applied." If a save also changes fields that need a restart, the banner lists only the sections containing those changed fields. Live changes still apply in the same save. - -## Configuration file - -The Settings window writes to `config.jsonc` directly, so most users do not need to edit the file by hand. The config file and the option reference below are provided for advanced use, scripting, or cases where you prefer editing config directly. - -Settings are stored in `$XDG_CONFIG_HOME/SubMiner/config.jsonc` (or `~/.config/SubMiner/config.jsonc` when `XDG_CONFIG_HOME` is unset). -On Windows, the default path is `%APPDATA%\SubMiner\config.jsonc`. -When both files exist, SubMiner prefers `config.jsonc` over `config.json`. - -See [config.example.jsonc](/config.example.jsonc) for a comprehensive example with all available options, default values, and detailed comments. Only include the options you want to customize in your config file. - -::: warning One value in that file is platform-specific -The example is generated with a fixed Linux/macOS socket path so it stays reproducible, so it shows `"socketPath": "/tmp/subminer-socket"`. On Windows the real default is `\\\\.\\pipe\\subminer-socket`. Leave `mpv.socketPath` out of your config entirely unless you need a custom path, and SubMiner picks the right one for your platform. +::: warning mpv.socketPath differs on Windows +The example shows `"socketPath": "/tmp/subminer-socket"`. On Windows the default is `\\.\pipe\subminer-socket`. Leave `mpv.socketPath` out of your config unless you need a custom path, and SubMiner picks the right one. ::: -Generate a fresh default config from the centralized config registry: +To write a fresh default config: ```bash SubMiner.AppImage --generate-config @@ -85,89 +33,37 @@ SubMiner.AppImage --generate-config --config-path /tmp/subminer.jsonc SubMiner.AppImage --generate-config --backup-overwrite ``` -- `--generate-config` writes a default JSONC config template. -- JSONC config supports comments and trailing commas. -- If the target file exists, SubMiner prompts to create a timestamped backup and overwrite. -- In non-interactive shells, use `--backup-overwrite` to explicitly back up and overwrite. -- On Windows, generated configs default to `%APPDATA%\SubMiner\config.jsonc`. +If the target file exists, SubMiner asks before backing it up and overwriting it. In non-interactive shells, pass `--backup-overwrite`. -Malformed config syntax (invalid JSON/JSONC) is startup-blocking: SubMiner shows a clear parse error with the config path and asks you to fix the file and restart. +A syntax error in the file stops startup with a message that names the file. A valid file with a bad value logs a warning and uses the default for that key. On macOS, these warnings also open a dialog. -For valid JSON/JSONC with invalid option values, SubMiner uses warn-and-fallback behavior: it logs the bad key/value and continues with the default for that option. +## Settings window {#settings} -On macOS, these validation warnings also open a native dialog with full details (desktop notification banners can truncate long messages). +Open it from the tray menu, with `subminer settings`, or with the app's `--settings` flag. Options are grouped by task (Appearance, Behavior, Mining & Anki, Input, Integrations, Tracking & App, Advanced) rather than by config block, but each field saves to its normal `config.jsonc` path. -### Hot-reload behavior +- Saving keeps your comments, trailing commas, and unrelated keys. Resetting a field removes its key so the default applies. +- Each field is tagged **Live** or **Restart**. After saving, a banner lists any sections that need a restart. +- Anki fields can fetch deck, note type, and field names from AnkiConnect. +- Secret fields never show the stored value, only whether one is set. Prefer the `*Command` variants (such as `jimaku.apiKeyCommand`) to keep keys out of the file. -SubMiner watches the active config file (`config.jsonc` or `config.json`) while running and applies supported updates automatically. +## Hot-reload {#hot-reload-behavior} -Hot-reloadable settings include subtitle appearance, sidebar controls, keybindings, -shortcuts, notifications, logging level, selected source-language preferences, -Jimaku/Subsync and subtitle-generation settings, AniSkip settings (`mpv.aniskipEnabled`, `mpv.aniskipButtonKey`), -stats keys (`stats.toggleKey`, `stats.markWatchedKey`), the secondary-subtitle default -mode, and the Anki deck, known-word, N+1, field, sentence-card, and Kiku options -listed in the reference tables below. +SubMiner watches the config file while running. When it changes, live settings apply immediately and SubMiner shows a notification listing any changed sections that need a restart. If the new file is invalid, the previous config stays active. -When these values change, SubMiner applies them live. Invalid config edits are rejected and the previous valid runtime config remains active. +These apply live: -Restart-required changes: +- `subtitleStyle`, `subtitleSidebar`, `subtitleSelection`, `keybindings`, `shortcuts` +- `logging.level`, `logging.rotation`, `logging.files` +- `secondarySub.defaultMode`, `youtube.primarySubLanguages` +- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey`, `stats.toggleKey`, `stats.markWatchedKey` +- `ankiConnect.deck`, `ankiConnect.fields.*`, `ankiConnect.behavior.autoUpdateNewCards` +- `ankiConnect.media.normalizeAudio`, `media.mirrorMpvVolume`, `media.reviewTiming` +- `ankiConnect.knownWords` (`highlightEnabled`, `refreshMinutes`, `addMinedWordsImmediately`, `matchMode`, `decks`) and `ankiConnect.nPlusOne.*` +- `ankiConnect.isLapis.sentenceCardModel`, `isKiku.fieldGrouping`, `isSenren.fieldGrouping`, `lapisKiku.wordCardKind` -- Any other config sections still require restart. -- AnkiConnect transport/proxy/media/tag fields still require restart unless listed above. -- SubMiner shows an on-screen/system notification listing restart-required sections when they change. +These are read at the start of the next operation, so changes take effect on the next request or run: `jimaku`, `tmdb`, `subsync`, `subtitleGeneration`, `notifications`. -### Configuration options Overview - -The configuration file includes several main sections: - -**Core Settings** - -- [**Logging**](#logging) - Runtime log level -- [**Auto-Start Overlay**](#auto-start-overlay) - Automatically show overlay on MPV connection -- [**Startup Warmups**](#startup-warmups) - Control what preloads on startup vs first-use defer -- [**WebSocket Server**](#websocket-server) - Built-in subtitle broadcasting server -- [**Annotation WebSocket**](#annotation-websocket) - Dedicated annotated subtitle payload stream -- [**Texthooker**](#texthooker) - Control browser opening behavior - -**Subtitle Display** - -- [**Subtitle Style**](#subtitle-style) - Appearance customization -- [**Subtitle Sidebar**](#subtitle-sidebar) - Parsed cue list sidebar modal -- [**Subtitle Position**](#subtitle-position) - Overlay vertical positioning -- [**Secondary Subtitles**](#secondary-subtitles) - Dual subtitle track support - -**Keyboard & Controls** - -- [**Keybindings**](#keybindings) - MPV command shortcuts -- [**Shortcuts Configuration**](#shortcuts-configuration) - Overlay keyboard shortcuts -- [**Controller Support**](#controller-support) - Gamepad support for keyboard-only mode -- [**Manual Card Update Shortcuts**](#manual-card-update-shortcuts) - Shortcuts for manual Anki card workflows -- [**Session Help Modal**](#session-help-modal) - In-overlay shortcut reference -- [**Runtime Option Palette**](#runtime-option-palette) - Live, session-only option toggles - -**Anki Integration** - -- [**AnkiConnect**](#ankiconnect) - Automatic Anki card creation with media -- [**Kiku/Lapis Integration**](#kiku-lapis-integration) - Sentence cards and duplicate handling for Kiku/Lapis/Senren note types -- [**N+1 Word Highlighting**](#n-1-word-highlighting) - Known-word cache and single-target highlighting -- [**Field Grouping Modes**](#field-grouping-modes) - Kiku/Senren duplicate card merging - -**External Integrations** - -- [**Jimaku**](#jimaku) - Jimaku API configuration and defaults -- [**TsukiHime**](#tsukihime) - Multi-language subtitle search and download -- [**TMDB**](#tmdb) - Posters and synopses for live-action dramas and movies in the stats Library -- [**Subtitle Sync**](#subtitle-sync) - Sync current subtitle with `alass`/`ffsubsync` -- [**AniList**](#anilist) - Optional post-watch progress updates -- [**Yomitan**](#yomitan) - Reuse an external read-only Yomitan profile -- [**Jellyfin**](#jellyfin) - Optional Jellyfin auth, library listing, and playback launch -- [**Discord Rich Presence**](#discord-rich-presence) - Optional Discord activity card updates -- [**Immersion Tracking**](#immersion-tracking) - Track subtitle sessions and mining activity in SQLite -- [**Stats Dashboard**](#stats-dashboard) - Local dashboard and overlay for immersion progress -- [**MPV Launcher**](#mpv-launcher) - mpv executable path, profile, and window launch mode -- [**YouTube Playback Settings**](#youtube-playback-settings) - Defaults for YouTube subtitle loading -- [**Updates**](#updates) - Automatic update checks, notifications, and prerelease testing -- [**Notifications**](#notifications) - Overlay notification placement +Everything else needs a restart. ## Core settings @@ -181,941 +77,355 @@ Each backend stores its own dictionaries and mining settings. `yomitan.externalP ### Logging -Control the minimum log level for runtime output: +Log files are named by date (`app-YYYY-MM-DD.log`, `launcher-...`, `mpv-...`). Log export writes a sanitized copy and leaves the originals alone. -```json -{ - "logging": { - "level": "warn", - "rotation": 7, - "files": { - "app": true, - "launcher": true, - "mpv": false - } - } -} -``` - -| Option | Values | Description | -| ---------------- | ---------------------------------------- | -------------------------------------------------------------------- | -| `level` | `"debug"`, `"info"`, `"warn"`, `"error"` | Minimum log level for runtime logging (default: `"warn"`) | -| `rotation` | positive integer | Number of days of app, launcher, and mpv logs to retain (default: 7) | -| `files.app` | boolean | Write SubMiner app runtime logs (default: `true`) | -| `files.launcher` | boolean | Write launcher command logs (default: `true`) | -| `files.mpv` | boolean | Write mpv player logs. Enable temporarily for mpv/plugin debugging. | - -Log filenames use the local calendar date, for example `app-YYYY-MM-DD.log`, `launcher-YYYY-MM-DD.log`, and `mpv-YYYY-MM-DD.log`. -Log export creates a sanitized copy of those files; it does not rewrite the original log files on disk. +| Key | Default | What it does | +| ------------------------ | -------- | ------------------------------------------------------- | +| `logging.level` | `"warn"` | Minimum level: `debug`, `info`, `warn`, `error` | +| `logging.rotation` | `7` | Days of logs to keep | +| `logging.files.app` | `true` | Write app logs | +| `logging.files.launcher` | `true` | Write launcher logs | +| `logging.files.mpv` | `false` | Write mpv logs. Turn on temporarily to debug mpv/plugin | ### Updates -Configure automatic update checks and update notifications: +Manual checks from the tray or `subminer -u` always work, even with automatic checks off. Overlay update notifications include an **Update** button. -```json -{ - "updates": { - "enabled": true, - "checkIntervalHours": 24, - "notificationType": "overlay", - "channel": "stable" - } -} -``` - -| Option | Values | Description | -| -------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| `updates.enabled` | `true`, `false` | Enable automatic background update checks. Manual tray and `subminer -u` checks are always allowed. | -| `checkIntervalHours` | number | Minimum hours between automatic update checks. Default `24`. | -| `notificationType` | `"overlay"` \| `"system"` \| `"both"` \| `"none"` | How SubMiner announces available updates. Default `"overlay"`. `"both"` means overlay + system. | -| `channel` | `"stable"` \| `"prerelease"` | Release channel used for update checks. Use `"prerelease"` to test beta/RC releases. | - -When `notificationType` is `"overlay"` or `"both"`, update-available overlay notifications include an **Update** button that starts the app update flow. - -`osd` and `osd-system` are legacy config-file-only notification values. The Settings window offers `overlay`, `system`, `both`, and `none`; if your config already contains `osd` or `osd-system`, it is shown as the selected value but not offered as a normal choice. If you previously used `both` for mpv OSD + system notifications, set `notificationType` to `"osd-system"` in `config.jsonc` to keep that behavior. +| Key | Default | What it does | +| ---------------------------- | ----------- | --------------------------------------------------------- | +| `updates.enabled` | `true` | Check for updates in the background | +| `updates.checkIntervalHours` | `24` | Minimum hours between automatic checks | +| `updates.notificationType` | `"overlay"` | `overlay`, `system`, `both` (overlay + system), or `none` | +| `updates.channel` | `"stable"` | `stable` or `prerelease` (betas and release candidates) | ### Notifications -Configure where overlay notification cards appear: +Overlay notifications are also kept in a session-only history panel. Toggle it with `shortcuts.toggleNotificationHistory`. The panel opens from the same side as the notification cards. -```json -{ - "notifications": { - "overlayPosition": "top-right" - } -} -``` +| Key | Default | What it does | +| ------------------------------- | ------------- | ---------------------------------------------------------- | +| `notifications.overlayPosition` | `"top-right"` | Where overlay cards appear: `top-left`, `top`, `top-right` | -| Option | Values | Description | -| ----------------- | ---------------------------------------- | ------------------------------------------------------------------ | -| `overlayPosition` | `"top-left"` \| `"top"` \| `"top-right"` | Position for in-overlay notification cards. Default `"top-right"`. | - -#### Notification history panel - -Every overlay notification shown during a session is also recorded in a notification history panel. Press `Ctrl/Cmd+N` (configurable via [`shortcuts.toggleNotificationHistory`](#shortcuts-configuration)) to toggle the panel; the binding works whether the overlay or mpv has focus. The panel slides in from the same edge the notifications use, so left when `overlayPosition` is `"top-left"` and right for `"top-right"` or `"top"` (centered). Character dictionary sync uses one live card but records each distinct phase in history. Each entry can be removed individually, or use **Clear** to empty the history. History is session-only and is not persisted across restarts. - -Startup tokenization, subtitle annotation, and character dictionary status follow the configured notification surface. When the surface is `"overlay"` or `"both"`, SubMiner queues those startup notifications until the overlay renderer is ready instead of falling back to mpv OSD. If loading and ready states both finish before the overlay can paint, the loading card is delivered first and then updates to ready shortly after. With `"both"`, character dictionary checking/building/importing/ready status also goes to system notifications; building and importing are only emitted when that work is actually needed. The bundled mpv plugin only shows its startup OSD messages when `ankiConnect.behavior.notificationType` is set to `"osd"` or `"osd-system"` in `config.jsonc`; AniSkip prompts and skip result messages are playback feedback and still route to overlay notifications when configured. - -The equivalent direct CLI command is `--playback-feedback <text>` (`playbackFeedback` internally). It sends that one non-empty feedback string through the same route controlled by `ankiConnect.behavior.notificationType`; it does not change the saved config. +Mining and startup status notifications use `ankiConnect.behavior.notificationType` (see [AnkiConnect](#ankiconnect)). ### Auto-start overlay -Control whether the overlay automatically becomes visible when it connects to mpv: +When mpv is started by SubMiner or the `subminer` launcher, the launcher passes these settings to the bundled mpv plugin. There is no separate plugin config file. `mpv.autoStartSubMiner` and `mpv.pauseUntilOverlayReady` (see [MPV launcher](#mpv-launcher)) control the background start and the initial pause. -```json -{ - "auto_start_overlay": true -} -``` - -| Option | Values | Description | -| -------------------- | --------------- | ----------------------------------------------------- | -| `auto_start_overlay` | `true`, `false` | Auto-show overlay on mpv connection (default: `true`) | - -When you launch through the SubMiner app or the `subminer` wrapper, the launcher reads these settings from this config and injects them into the mpv plugin at runtime - there is no separate plugin config file to edit. `auto_start_overlay` controls whether the visible overlay shows on auto-start. Two related keys in the `mpv` block tune startup behavior: `mpv.autoStartSubMiner` starts the overlay automatically when a file loads, and `mpv.pauseUntilOverlayReady` pauses mpv on visible auto-start until SubMiner signals overlay/tokenization readiness. On visible-overlay startup, SubMiner brings up the tray and visible overlay shell before tokenization and annotation warmups finish, then releases playback only after autoplay readiness. - -On Windows, packaged plugin installs also rewrite the plugin socket path to `\\.\pipe\subminer-socket`. +| Key | Default | What it does | +| -------------------- | ------- | ------------------------------------------------------------ | +| `auto_start_overlay` | `true` | Show the visible overlay when the mpv plugin starts SubMiner | ### Startup warmups -Control which startup warmups run in the background versus deferring to first real usage: +Warmups load components in the background at startup. Turn one off to load it on first use instead. -```json -{ - "startupWarmups": { - "lowPowerMode": false, - "mecab": true, - "yomitanExtension": true, - "subtitleDictionaries": true, - "jellyfinRemoteSession": false - } -} -``` - -| Option | Values | Description | -| ----------------------- | --------------- | ------------------------------------------------------------------------------------------------- | -| `lowPowerMode` | `true`, `false` | Defer all warmups except Yomitan extension | -| `mecab` | `true`, `false` | Warm up MeCab tokenizer at startup | -| `yomitanExtension` | `true`, `false` | Warm up Yomitan extension at startup | -| `subtitleDictionaries` | `true`, `false` | Warm up JLPT + frequency dictionaries at startup | -| `jellyfinRemoteSession` | `true`, `false` | Warm up Jellyfin remote session at startup (still requires Jellyfin remote auto-connect settings) | - -Defaults warm local tokenizer/dictionary work (`true` for `mecab`, `yomitanExtension`, and `subtitleDictionaries`) with `lowPowerMode: false`; Jellyfin remote session warmup is opt-in (`false` by default). Setting a warmup toggle to `false` defers that work until first usage. +| Key | Default | What it does | +| -------------------------------------- | ------- | ----------------------------------------------------------------------------- | +| `startupWarmups.lowPowerMode` | `false` | Defer every warmup except the Yomitan extension | +| `startupWarmups.mecab` | `true` | Load the MeCab tokenizer | +| `startupWarmups.yomitanExtension` | `true` | Load the Yomitan extension | +| `startupWarmups.subtitleDictionaries` | `true` | Load the JLPT and frequency dictionaries | +| `startupWarmups.jellyfinRemoteSession` | `false` | Connect the Jellyfin remote session (also needs Jellyfin remote auto-connect) | ### WebSocket server -The overlay includes a built-in WebSocket server that broadcasts plain subtitle text to connected clients for external processing. +Broadcasts plain subtitle text to external clients. See [WebSocket / Texthooker API](/websocket-texthooker-api) for payloads and client examples. -For endpoint details, payload examples, and client patterns, see [WebSocket / Texthooker API & Integration](/websocket-texthooker-api). - -By default, the server is disabled. Set `enabled` to `true` to force it on, or `"auto"` to start it unless [mpv_websocket](https://github.com/kuroahna/mpv_websocket) is detected at `~/.config/mpv/mpv_websocket`. - -See `config.example.jsonc` for detailed configuration options. - -```json -{ - "websocket": { - "enabled": false, - "port": 6677 - } -} -``` - -| Option | Values | Description | -| ------------------- | ------------------------- | --------------------------------------------------- | -| `websocket.enabled` | `true`, `false`, `"auto"` | Built-in subtitle websocket mode (default: `false`) | -| `websocket.port` | number | WebSocket server port (default: 6677) | +| Key | Default | What it does | +| ------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `websocket.enabled` | `false` | `true`, `false`, or `"auto"` (start unless the [mpv_websocket](https://github.com/kuroahna/mpv_websocket) plugin is installed) | +| `websocket.port` | `6677` | Server port | ### Annotation WebSocket -SubMiner also exposes a dedicated annotated websocket stream for the bundled texthooker UI and token-aware clients. +A separate stream that adds token data (known word, N+1, frequency, JLPT, character names) to each subtitle. The bundled texthooker uses it. -This stream includes subtitle text plus token metadata (N+1, known-word, frequency, JLPT, and character-name annotation context). - -```json -{ - "annotationWebsocket": { - "enabled": false, - "port": 6678 - } -} -``` - -| Option | Values | Description | -| ----------------------------- | --------------- | -------------------------------------------------------------- | -| `annotationWebsocket.enabled` | `true`, `false` | Toggle annotated websocket stream (independent of `websocket`) | -| `annotationWebsocket.port` | number | Annotation websocket port (default: 6678) | +| Key | Default | What it does | +| ----------------------------- | ------- | ------------------------------------------------------- | +| `annotationWebsocket.enabled` | `false` | Start the annotated stream (independent of `websocket`) | +| `annotationWebsocket.port` | `6678` | Server port | ### Texthooker -Control whether texthooker starts automatically and whether it opens a browser: - -See `config.example.jsonc` for detailed configuration options. - -```json -{ - "texthooker": { - "launchAtStartup": false, - "openBrowser": false - } -} -``` - -| Option | Values | Description | -| ----------------- | --------------- | ----------------------------------------------------------------------- | -| `launchAtStartup` | `true`, `false` | Start texthooker automatically with SubMiner startup (default: `false`) | -| `openBrowser` | `true`, `false` | Open browser tab when texthooker starts (default: `false`) | +| Key | Default | What it does | +| ---------------------------- | ------- | ------------------------------------------------------- | +| `texthooker.launchAtStartup` | `false` | Start the texthooker server when SubMiner starts | +| `texthooker.openBrowser` | `false` | Open the texthooker page in your browser when it starts | ## Subtitle display ### Subtitle style -Customize the appearance of primary and secondary subtitles: +Controls how primary and secondary subtitles look and which annotations they show. `css` and `secondary.css` take CSS declarations with normal property names. See [Subtitle annotations](/subtitle-annotations) for how known-word, N+1, frequency, JLPT, and character-name highlighting work. -See `config.example.jsonc` for detailed configuration options. - -```json +```jsonc { "subtitleStyle": { - "css": { - "font-family": "Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP", - "color": "#cad3f5", - "background-color": "transparent", - "font-size": "35px", - "font-weight": "600", - "line-height": "1.35", - "letter-spacing": "-0.01em", - "word-spacing": "0", - "font-kerning": "normal", - "text-rendering": "geometricPrecision", - "text-shadow": "-1px -1px 2px rgba(0,0,0,0.95), 1px -1px 2px rgba(0,0,0,0.95), -1px 1px 2px rgba(0,0,0,0.95), 1px 1px 2px rgba(0,0,0,0.95), 0 0 8px rgba(0,0,0,0.5)", - "font-style": "normal", - "backdrop-filter": "blur(6px)", - "--subtitle-hover-token-color": "#f4dbd6", - "--subtitle-hover-token-background-color": "transparent" - }, - "secondary": { - "css": { - "font-family": "Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP", - "color": "#cad3f5", - "background-color": "transparent", - "font-size": "24px", - "text-shadow": "-1px -1px 2px rgba(0,0,0,0.95), 1px -1px 2px rgba(0,0,0,0.95), -1px 1px 2px rgba(0,0,0,0.95), 1px 1px 2px rgba(0,0,0,0.95), 0 0 8px rgba(0,0,0,0.5)" - } - } - } + "css": { "font-size": "40px", "color": "#ffffff" }, + "secondary": { "css": { "font-size": "24px" } }, + }, } ``` -| Option | Values | Description | -| ---------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `primaryDefaultMode` | string | Default primary subtitle bar visibility mode: `"hidden"`, `"visible"`, or `"hover"` (default: `"visible"`) | -| `subtitleStyle.css` | object | CSS declaration object applied to primary subtitles after normal style defaults. Use CSS property names such as `font-size`. | -| `secondary.css` | object | CSS declaration object applied to secondary subtitles after normal secondary style defaults. | -| `enableJlpt` | boolean | Enable JLPT level underline styling (`false` by default) | -| `preserveLineBreaks` | boolean | Preserve line breaks in visible overlay subtitle rendering (`false` by default). Enable to mirror mpv line layout. | -| `autoPauseVideoOnHover` | boolean | Pause playback while mouse hovers subtitle text, then resume on leave (`true` by default). | -| `autoPauseVideoOnYomitanPopup` | boolean | Pause playback while the Yomitan popup is open, then resume when the popup closes (`true` by default). | -| `primaryVisibleOnYomitanPopup` | boolean | Keep hover-mode primary subtitles visible while the Yomitan popup is open (`true` by default). | -| `nameMatchEnabled` | boolean | Enable character dictionary sync and subtitle token coloring for character-name matches (`false` by default) | -| `nameMatchImagesEnabled` | boolean | Show small cached AniList character portraits beside matched character-name tokens (`false` by default) | -| `nameMatchColor` | string | Hex color used for subtitle tokens matched from the SubMiner character dictionary (default: `#f5bde6`) | -| `knownWordColor` | string | Hex color used for known-word subtitle highlights (default: `#a6da95`) | -| `knownWordMaturityColors` | object | Per-tier known-word colors used when `ankiConnect.knownWords.maturityEnabled` is on: `new` (`#ee99a0`), `learning` (`#b7bdf8`), `young` (`#91d7e3`), `mature` (`#a6da95`) | -| `nPlusOneColor` | string | Hex color used for the single N+1 target subtitle highlight (default: `#c6a0f6`) | -| `frequencyDictionary.enabled` | boolean | Enable frequency highlighting from dictionary lookups (`false` by default) | -| `frequencyDictionary.sourcePath` | string | Path to a local frequency dictionary root. Leave empty or omit to use installed/default frequency-dictionary search paths. | -| `frequencyDictionary.topX` | number | Only color tokens whose frequency rank is `<= topX` (`10000` by default) | -| `frequencyDictionary.mode` | string | `"single"` or `"banded"` (`"single"` by default) | -| `frequencyDictionary.matchMode` | string | `"headword"` or `"surface"` (`"headword"` by default) | -| `frequencyDictionary.singleColor` | string | Color used for all highlighted tokens in single mode | -| `frequencyDictionary.bandedColors` | string[] | Array of five hex colors used for ranked bands in banded mode | -| `jlptColors` | object | JLPT level underline colors object (`N1`..`N5`) | +| Key | Default | What it does | +| ------------------------------------------------ | ------------ | ----------------------------------------------------------------------------------------------------- | +| `subtitleStyle.primaryDefaultMode` | `"visible"` | Primary bar at startup: `hidden`, `visible`, or `hover` | +| `subtitleStyle.css` | see example | CSS for primary subtitles (font, size `35px`, color, shadow, and so on) | +| `subtitleStyle.secondary.css` | see example | CSS for secondary subtitles (size `24px`) | +| `subtitleStyle.preserveLineBreaks` | `false` | Keep line breaks as mpv shows them instead of one line | +| `subtitleStyle.autoPauseVideoOnHover` | `true` | Pause while the mouse is over subtitle text | +| `subtitleStyle.autoPauseVideoOnYomitanPopup` | `true` | Pause while a Yomitan popup is open | +| `subtitleStyle.primaryVisibleOnYomitanPopup` | `true` | In hover mode, keep the primary bar visible while a popup is open | +| `subtitleStyle.knownWordColor` | `#a6da95` | Known-word highlight color | +| `subtitleStyle.knownWordMaturityColors` | see example | `new`, `learning`, `young`, `mature` colors, used when `ankiConnect.knownWords.maturityEnabled` is on | +| `subtitleStyle.nPlusOneColor` | `#c6a0f6` | N+1 target word color | +| `subtitleStyle.enableJlpt` | `false` | Underline words by JLPT level | +| `subtitleStyle.jlptColors` | see example | Underline colors for `N1` to `N5` | +| `subtitleStyle.nameMatchEnabled` | `false` | Sync the character dictionary and color character names | +| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small character portraits next to matched names | +| `subtitleStyle.nameMatchColor` | `#f5bde6` | Character-name color | +| `subtitleStyle.frequencyDictionary.enabled` | `false` | Color words by frequency rank | +| `subtitleStyle.frequencyDictionary.sourcePath` | `""` | Folder with `term_meta_bank_*.json` files. Empty searches the default locations | +| `subtitleStyle.frequencyDictionary.topX` | `10000` | Only color words ranked at or below this | +| `subtitleStyle.frequencyDictionary.mode` | `"single"` | `single` (one color) or `banded` (five colors, common to rare) | +| `subtitleStyle.frequencyDictionary.matchMode` | `"headword"` | Look up by `headword` (dictionary form) or `surface` (text as shown) | +| `subtitleStyle.frequencyDictionary.singleColor` | `#f5a97f` | Color for `single` mode | +| `subtitleStyle.frequencyDictionary.bandedColors` | see example | Five colors for `banded` mode | -Subtitle CSS custom properties: - -| CSS Property | Default | Description | -| ----------------------------------------- | ------------- | --------------------------------------- | -| `--subtitle-hover-token-color` | `#f4dbd6` | Hovered subtitle token text color | -| `--subtitle-hover-token-background-color` | `transparent` | Hovered subtitle token background color | - -The Settings window keeps subtitle color controls separate, then saves CSS textboxes to -the primary subtitle, secondary subtitle, and sidebar CSS objects. The generated example -uses that same CSS declaration shape. - -Frequency dictionary highlighting uses the same dictionary file format as JLPT bundle lookups (`term_meta_bank_*.json` under discovered dictionary directories). A token is highlighted when it has a positive integer `frequencyRank` (lower is more common) and the rank is within `topX`. - -Lookup behavior: - -- Point the source path at a directory containing `term_meta_bank_*.json` for a fully custom source. -- If `sourcePath` is missing or empty, SubMiner searches default install/runtime locations for `frequency-dictionary` directories (for example app resources, user data paths, and current working directory). -- In both cases, only terms with a valid `frequencyRank` are used; everything else falls back to no highlighting. -- Match mode controls which token text is used for frequency lookups: `headword` (dictionary form) or `surface` (visible subtitle text). -- Frequency highlighting skips tokens that look like non-lexical SFX/interjection noise (for example kana reduplication or short kana endings like `っ`), even when dictionary ranks exist. - -In `single` mode all highlights use `singleColor`; in `banded` mode tokens map to five ascending color bands from most common to least common inside the topX window. - -Character-name highlighting is separate from N+1 and frequency highlighting: - -- `nameMatchEnabled` controls whether SubMiner syncs the character dictionary and includes character-dictionary name matches in subtitle token metadata and renderer styling. -- `nameMatchImagesEnabled` adds small circular portraits beside matched names using the AniList images already cached with character dictionary snapshots. -- `nameMatchColor` sets the highlight color for those matched character names. -- Matches come from the bundled SubMiner character dictionary, including AniList-synced merged dictionaries when name matching is enabled. - -Secondary subtitle styling lives in the secondary subtitle CSS object. Any CSS property not set there falls back to the secondary subtitle defaults, then the normal renderer defaults. - -**See `config.example.jsonc`** for the complete list of subtitle style configuration options. +Two CSS custom properties style the hovered word: `--subtitle-hover-token-color` (`#f4dbd6`) and `--subtitle-hover-token-background-color` (`transparent`). Set them inside `subtitleStyle.css`. ### Subtitle sidebar -Configure the parsed-subtitle sidebar modal. +A scrollable cue list for the current subtitle file. It only works when SubMiner could parse the active subtitle into cues. See [Subtitle sidebar](/subtitle-sidebar). -```json -{ - "subtitleSidebar": { - "enabled": true, - "autoOpen": false, - "layout": "overlay", - "toggleKey": "Backslash", - "pauseVideoOnHover": true, - "autoScroll": true, - "css": { - "font-family": "Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP", - "font-size": "16px", - "color": "#cad3f5", - "background-color": "rgba(73, 77, 100, 0.9)", - "--subtitle-sidebar-max-width": "420px" - } - } -} -``` +| Key | Default | What it does | +| ----------------------------------- | ------------- | ------------------------------------------------------------------------------ | +| `subtitleSidebar.enabled` | `true` | Enable the sidebar | +| `subtitleSidebar.autoOpen` | `false` | Open it once when the overlay starts | +| `subtitleSidebar.layout` | `"overlay"` | `overlay` floats over mpv. `embedded` reserves space on the right of the video | +| `subtitleSidebar.toggleKey` | `"Backslash"` | `KeyboardEvent.code` that opens and closes it | +| `subtitleSidebar.pauseVideoOnHover` | `true` | Pause while hovering the cue list | +| `subtitleSidebar.autoScroll` | `true` | Keep the active cue in view | +| `subtitleSidebar.css` | see example | CSS for the sidebar, plus the custom properties below | -| Option | Values | Description | -| --------------------------- | ------- | ------------------------------------------------------------------------------------------------------- | -| `subtitleSidebar.enabled` | boolean | Enable subtitle sidebar support (`true` by default) | -| `autoOpen` | boolean | Open sidebar automatically on overlay startup (`false` by default) | -| `layout` | string | `"overlay"` floats over mpv; `"embedded"` reserves right-side player space to mimic browser-like layout | -| `subtitleSidebar.toggleKey` | string | `KeyboardEvent.code` used to open/close the sidebar (default: `"Backslash"`) | -| `pauseVideoOnHover` | boolean | Pause playback while hovering the sidebar cue list (`true` by default) | -| `autoScroll` | boolean | Keep the active cue in view while playback advances | -| `subtitleSidebar.css` | object | CSS declaration object applied to the sidebar. Use CSS properties plus sidebar custom properties below. | +Sidebar custom properties: `--subtitle-sidebar-max-width` (`420px`), `--subtitle-sidebar-timestamp-color`, `--subtitle-sidebar-active-line-color`, `--subtitle-sidebar-active-background-color`, `--subtitle-sidebar-hover-background-color`. Their defaults are in the example config. -Direct style keys are also available under `subtitleSidebar` and map to the same visuals as the CSS custom properties: `maxWidth` (default `420`), `opacity` (`0.95`), `backgroundColor`, `textColor`, `fontFamily`, `fontSize` (`16`), `timestampColor`, `activeLineColor`, `activeLineBackgroundColor`, and `hoverLineBackgroundColor`. - -Sidebar CSS custom properties: - -| CSS Property | Default | Description | -| -------------------------------------------- | --------------------------- | ---------------------------- | -| `--subtitle-sidebar-max-width` | `420px` | Maximum sidebar width | -| `--subtitle-sidebar-timestamp-color` | `#a5adcb` | Cue timestamp color | -| `--subtitle-sidebar-active-line-color` | `#f5bde6` | Active cue text color | -| `--subtitle-sidebar-active-background-color` | `rgba(138, 173, 244, 0.22)` | Active cue background color | -| `--subtitle-sidebar-hover-background-color` | `rgba(54, 58, 79, 0.84)` | Hovered cue background color | - -The sidebar is only available when the active subtitle source has been parsed into a cue list. Default colors use Catppuccin Macchiato with a semi-transparent shell so the panel stays readable without feeling like an opaque settings dialog. - -`embedded` layout is intended to act like a split-pane view: it reserves player space with a right-side video margin and keeps interaction in both the player area and sidebar. If you see unexpected offset behavior in your environment, switch back to `overlay` to isolate sidebar placement. - -For full details on layout modes, behavior, and the keyboard shortcut, see the [Subtitle Sidebar](/subtitle-sidebar) page. - -`subtitleStyle.jlptColors` keys are: - -| Key | Default | Description | -| ---- | --------- | ----------------------- | -| `N1` | `#ed8796` | JLPT N1 underline color | -| `N2` | `#f5a97f` | JLPT N2 underline color | -| `N3` | `#f9e2af` | JLPT N3 underline color | -| `N4` | `#8bd5ca` | JLPT N4 underline color | -| `N5` | `#8aadf4` | JLPT N5 underline color | +If `embedded` layout places the video oddly on your system, switch back to `overlay`. ### Subtitle position -Set the initial vertical subtitle position (measured from the bottom of the screen): +You can also drag subtitles with `Right-click + drag` while watching. -```json -{ - "subtitlePosition": { - "yPercent": 10 - } -} -``` - -| Option | Values | Description | -| ---------- | ---------------- | ---------------------------------------------------------------------- | -| `yPercent` | number (0 - 100) | Distance from the bottom as a percent of screen height (default: `10`) | - -In the overlay, you can fine-tune subtitle position at runtime with `Right-click + drag` on subtitle text. +| Key | Default | What it does | +| --------------------------- | ------- | ---------------------------------------------------------------- | +| `subtitlePosition.yPercent` | `10` | Starting distance from the bottom, as a percent of screen height | ### Secondary subtitles -Display a second subtitle track (e.g., English alongside Japanese) in the overlay: +Shows a second track, such as English, above the Japanese line. -See `config.example.jsonc` for detailed configuration options. - -Secondary subtitles do **not** auto-load by default. To turn them on for local and Jellyfin playback, set `autoLoadSecondarySub` to `true` and list the language codes you want: +Secondary subtitles do **not** auto-load by default (`autoLoadSecondarySub`, default: `false`). To load them for local and Jellyfin playback, turn it on and list the languages you want: ```json { "secondarySub": { "secondarySubLanguages": ["eng", "en"], - "autoLoadSecondarySub": true, - "defaultMode": "hover" + "autoLoadSecondarySub": true } } ``` -| Option | Values | Description | -| ----------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -| `secondarySubLanguages` | string[] | Language codes to auto-load (e.g., `["eng", "en"]`); non-Signs/Songs tracks are preferred when several tracks match. Default is empty (`[]`). | -| `autoLoadSecondarySub` | `true`, `false` | Auto-detect and load a matching secondary subtitle track for local/Jellyfin sidecar files (default: `false`) | -| `defaultMode` | `"hidden"`, `"visible"`, `"hover"` | Initial display mode (default: `"hover"`) | +| Key | Default | What it does | +| ------------------------------------ | --------- | --------------------------------------------------------------------------------------- | +| `secondarySub.secondarySubLanguages` | `[]` | Language codes in priority order. Regular tracks win over Signs/Songs tracks | +| `secondarySub.autoLoadSecondarySub` | `false` | Load a matching secondary track when the primary loads | +| `secondarySub.defaultMode` | `"hover"` | `hidden`, `visible` (always shown), or `hover` (shown when you hover the subtitle area) | -These two settings apply to local and Jellyfin playback only. YouTube secondary selection is fixed to English and ignores them; see [YouTube Integration](/youtube-integration#secondary-subtitle-languages). `defaultMode` still controls how the loaded secondary bar is displayed in every case. +YouTube ignores the first two keys and always picks English. See [YouTube integration](/youtube-integration). `defaultMode` applies everywhere. -The secondary-subtitle language list also acts as the fallback secondary-language priority for managed startup subtitle selection on local playback and YouTube playback. +### Subtitle selection {#subtitle-selection} -**Display modes:** +Adds a modal for choosing mpv's primary and secondary subtitle tracks. Open it with `g` then `s` (`shortcuts.openSubtitleSelection`). While enabled, that shortcut replaces mpv's own binding for the same key. See [Keyboard shortcuts](/shortcuts) for sequence conflicts. -- **hidden** - Secondary subtitles not shown -- **visible** - Always visible at top of overlay -- **hover** - Only visible when hovering over the subtitle area (default) - -**See `config.example.jsonc`** for additional secondary subtitle configuration options. +| Key | Default | What it does | +| --------------------------- | ------- | ----------------------------------- | +| `subtitleSelection.enabled` | `false` | Enable the subtitle selection modal | ## Keyboard and controls ### Keybindings -Add a `keybindings` array to configure keyboard shortcuts that send mpv commands or SubMiner session actions: - -See `config.example.jsonc` for detailed configuration options and more examples. - -**Default keybindings:** - -| Key | Command | Description | -| ----------------------- | ----------------------------- | --------------------------------------- | -| `Space` | `["cycle", "pause"]` | Toggle pause | -| `KeyF` | `["cycle", "fullscreen"]` | Toggle fullscreen | -| `KeyJ` | `["cycle", "sid"]` | Cycle primary subtitle track | -| `Shift+KeyJ` | `["cycle", "secondary-sid"]` | Cycle secondary subtitle track | -| `Ctrl+Alt+KeyP` | `["__playlist-browser-open"]` | Open playlist browser | -| `Ctrl+Alt+KeyC` | `["__youtube-picker-open"]` | Open the manual YouTube subtitle picker | -| `ArrowRight` | `["seek", 5]` | Seek forward 5 seconds | -| `ArrowLeft` | `["seek", -5]` | Seek backward 5 seconds | -| `ArrowUp` | `["seek", 60]` | Seek forward 60 seconds | -| `ArrowDown` | `["seek", -60]` | Seek backward 60 seconds | -| `Shift+KeyH` | `["sub-seek", -1]` | Jump to previous subtitle | -| `Shift+KeyL` | `["sub-seek", 1]` | Jump to next subtitle | -| `Ctrl+Shift+ArrowLeft` | `["sub-step", -1]` | Shift subtitle delay to previous cue | -| `Ctrl+Shift+ArrowRight` | `["sub-step", 1]` | Shift subtitle delay to next cue | -| `KeyZ` | `["add", "sub-delay", -0.1]` | Shift subtitles 100 ms earlier | -| `Shift+KeyZ` | `["add", "sub-delay", 0.1]` | Delay subtitles by 100 ms | -| `KeyX` | `["add", "sub-delay", 0.1]` | Delay subtitles by 100 ms | -| `Ctrl+Shift+KeyH` | `["__replay-subtitle"]` | Replay current subtitle, pause at end | -| `Ctrl+Shift+KeyL` | `["__play-next-subtitle"]` | Play next subtitle, pause at end | -| `KeyQ` | `["quit"]` | Quit mpv | -| `Ctrl+KeyW` | `["quit"]` | Quit mpv | - -**Custom keybindings example:** +`keybindings` maps keys to mpv commands or SubMiner actions. Your entries merge with the defaults. The full default list is on [Keyboard shortcuts](/shortcuts). ```json { "keybindings": [ - { "key": "ArrowRight", "command": ["seek", 5] }, - { "key": "ArrowLeft", "command": ["seek", -5] }, { "key": "Shift+ArrowRight", "command": ["seek", 30] }, { "key": "MBTN_BACK", "command": ["sub-seek", -1] }, - { "key": "MBTN_FORWARD", "command": ["sub-seek", 1] }, - { "key": "KeyR", "command": ["script-binding", "immersive/auto-replay"] }, - { "key": "KeyA", "command": ["script-message", "ankiconnect-add-note"] } + { "key": "Space", "command": null } ] } ``` -**Key format:** Use `KeyboardEvent.code` values (`Space`, `ArrowRight`, `KeyR`, etc.) with optional modifiers (`Ctrl+`, `Alt+`, `Shift+`, `Meta+`). Mouse buttons use mpv button names: `MBTN_LEFT`, `MBTN_MID`, `MBTN_RIGHT`, `MBTN_BACK`, and `MBTN_FORWARD`. - -**Disable a default binding:** Set command to `null`: - -```json -{ "key": "Space", "command": null } -``` - -**Special commands:** Commands prefixed with `__` are handled internally by the overlay rather than sent to mpv. `__playlist-browser-open` opens the split-pane playlist browser for the current file's parent directory and the live mpv queue. `__replay-subtitle` replays the current subtitle and pauses at its end. `__play-next-subtitle` seeks to the next subtitle, plays it, and pauses at its end. `__runtime-options-open` opens the runtime options palette. `__runtime-option-cycle:<id>[:next|prev]` cycles a runtime option value. - -**Supported commands:** Any valid mpv JSON IPC command array (`["cycle", "pause"]`, `["seek", 5]`, `["script-binding", "..."]`, etc.) - -Supported, unclaimed single-key keyboard bindings from the connected mpv session are also available -in the overlay automatically. Configured SubMiner bindings, including `null` entries, -take precedence. See [mpv binding discovery](/shortcuts#automatic-mpv-bindings) for session refresh -behavior and limitations. - -Subtitle delay commands (`sub-delay`, `sub-step`) show a native mpv OSD notification after the command runs. Subtitle-position and subtitle-track proxy commands (`sub-pos`, `sid`, `secondary-sid`) show playback feedback through the configured notification surface. - -**See `config.example.jsonc`** for more keybinding examples and configuration options. +- `key` uses `KeyboardEvent.code` names (`Space`, `KeyR`, `ArrowRight`) with optional `Ctrl+`, `Alt+`, `Shift+`, `Meta+`. Mouse buttons are `MBTN_LEFT`, `MBTN_MID`, `MBTN_RIGHT`, `MBTN_BACK`, `MBTN_FORWARD`. +- `command` is any mpv JSON IPC command array. Set it to `null` to disable a default. +- Commands starting with `__` run inside SubMiner: `__playlist-browser-open`, `__youtube-picker-open`, `__replay-subtitle`, `__play-next-subtitle`, `__runtime-options-open`, and `__runtime-option-cycle:<id>[:next|prev]`. +- Unused single-key bindings from your mpv config also work in the overlay. Your SubMiner bindings win on conflicts. ### Shortcuts configuration -Customize or disable the overlay keyboard shortcuts: +`shortcuts` holds SubMiner's own actions (mining, copying, opening modals). Values are [Electron accelerator strings](https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts) such as `"CommandOrControl+S"`. Set one to `null` to disable it. [Keyboard shortcuts](/shortcuts) lists every key, its default, and what it does. Anki shortcuts only run when `ankiConnect.enabled` is on. -See `config.example.jsonc` for detailed configuration options. - -```json -{ - "shortcuts": { - "toggleVisibleOverlayGlobal": "Alt+Shift+O", - "copySubtitle": "CommandOrControl+C", - "copySubtitleMultiple": "CommandOrControl+Shift+C", - "updateLastCardFromClipboard": "CommandOrControl+V", - "triggerFieldGrouping": "CommandOrControl+G", - "triggerSubsync": "Ctrl+Alt+S", - "mineSentence": "CommandOrControl+S", - "mineSentenceMultiple": "CommandOrControl+Shift+S", - "markAudioCard": "CommandOrControl+Shift+A", - "openCharacterDictionaryManager": "CommandOrControl+D", - "openRuntimeOptions": "CommandOrControl+Shift+O", - "openSessionHelp": "CommandOrControl+Slash", - "openControllerSelect": "Alt+C", - "openControllerDebug": "Alt+Shift+C", - "openJimaku": "Ctrl+Shift+J", - "toggleSubtitleSidebar": "Backslash", - "toggleNotificationHistory": "CommandOrControl+N", - "appendClipboardVideoToQueue": "CommandOrControl+A", - "multiCopyTimeoutMs": 3000 - } -} -``` - -| Option | Values | Description | -| -------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `toggleVisibleOverlayGlobal` | string \| `null` | Global accelerator for toggling visible subtitle overlay (default: `"Alt+Shift+O"`) | -| `copySubtitle` | string \| `null` | Accelerator for copying current subtitle (default: `"CommandOrControl+C"`) | -| `copySubtitleMultiple` | string \| `null` | Accelerator for multi-copy mode (default: `"CommandOrControl+Shift+C"`) | -| `updateLastCardFromClipboard` | string \| `null` | Accelerator for updating card from clipboard (default: `"CommandOrControl+V"`) | -| `triggerFieldGrouping` | string \| `null` | Accelerator for Kiku field grouping on last card (default: `"CommandOrControl+G"`; only active when automatic card updates are disabled) | -| `triggerSubsync` | string \| `null` | Accelerator for running Subsync (default: `"Ctrl+Alt+S"`) | -| `mineSentence` | string \| `null` | Accelerator for creating sentence card from current subtitle (default: `"CommandOrControl+S"`) | -| `mineSentenceMultiple` | string \| `null` | Accelerator for multi-mine sentence card mode (default: `"CommandOrControl+Shift+S"`) | -| `multiCopyTimeoutMs` | number | Timeout in ms for multi-copy/mine digit input (default: `3000`) | -| `toggleSecondarySub` | string \| `null` | Accelerator for cycling secondary subtitle mode (default: `"CommandOrControl+Shift+V"`) | -| `markAudioCard` | string \| `null` | Accelerator for marking last card as audio card (default: `"CommandOrControl+Shift+A"`) | -| `openCharacterDictionaryManager` | string \| `null` | Opens the loaded character dictionary manager (default: `"CommandOrControl+D"`) | -| `openRuntimeOptions` | string \| `null` | Opens runtime options palette for live session-only toggles (default: `"CommandOrControl+Shift+O"`) | -| `openSessionHelp` | string \| `null` | Opens the in-overlay session help modal (default: `"CommandOrControl+Slash"`) | -| `openControllerSelect` | string \| `null` | Opens the controller config/remap modal (default: `"Alt+C"`) | -| `openControllerDebug` | string \| `null` | Opens the controller debug modal (default: `"Alt+Shift+C"`) | -| `openJimaku` | string \| `null` | Opens the Jimaku search modal (default: `"Ctrl+Shift+J"`) | -| `toggleSubtitleSidebar` | string \| `null` | Dispatches the subtitle sidebar toggle action (default: `"Backslash"`). `subtitleSidebar.toggleKey` remains the primary bare-key setting. | -| `toggleNotificationHistory` | string \| `null` | Toggles the overlay notification history panel (default: `"CommandOrControl+N"`). The panel slides in from the same edge as notifications (right when notifications are centered). | -| `appendClipboardVideoToQueue` | string \| `null` | Appends a video file path from the clipboard to the mpv playlist (default: `"CommandOrControl+A"`). Works whether the overlay or mpv has focus. | - -**See `config.example.jsonc`** for the complete list of shortcut configuration options. - -Set any shortcut to `null` to disable it. - -Feature-dependent shortcuts/keybindings only run when their related integration is enabled. For example, Anki/Kiku shortcuts require `ankiConnect.enabled` (and Kiku-specific behavior where applicable), and Jellyfin remote startup behavior requires Jellyfin to be enabled. +| Key | Default | What it does | +| ------------------------------ | ------- | -------------------------------------------------------- | +| `shortcuts.multiCopyTimeoutMs` | `3000` | How long multi-copy and multi-mine wait for a digit (ms) | ### Controller support -SubMiner can read controllers through the Chrome Gamepad API and map them onto the existing keyboard-only overlay workflow. +Gamepad input for the overlay, through the browser Gamepad API. It only works while keyboard-only mode is on. Use the `Alt+C` modal to pick a controller and learn bindings, and `Alt+Shift+C` to see raw button and axis values. Default button actions are on [Keyboard shortcuts](/shortcuts). -Important behavior: +| Key | Default | What it does | +| ---------------------------------- | -------- | ------------------------------------------------------------------------------------- | +| `controller.enabled` | `false` | Enable controller support. The `Alt+C` and `Alt+Shift+C` modals stay closed while off | +| `controller.smoothScroll` | `true` | Smooth popup scrolling | +| `controller.scrollPixelsPerSecond` | `900` | Popup scroll speed | +| `controller.horizontalJumpPixels` | `160` | Popup page-jump distance | +| `controller.stickDeadzone` | `0.2` | Stick deadzone | +| `controller.triggerInputMode` | `"auto"` | `auto`, `digital`, or `analog`. Use `analog` if your L2/R2 report analog values | +| `controller.triggerDeadzone` | `0.5` | Trigger threshold for `auto` and `analog` | +| `controller.repeatDelayMs` | `320` | Delay before a held button repeats | +| `controller.repeatIntervalMs` | `120` | Repeat interval for held buttons | -- Controller input is only active while keyboard-only mode is enabled. -- Keyboard-only mode continues to work normally without a controller. -- By default SubMiner uses the first connected controller. -- Fresh installs keep controller support disabled until you set `controller.enabled` to `true`. -- `Alt+C` opens the controller config modal by default, and you can remap that shortcut through `shortcuts.openControllerSelect`. -- The `Alt+C` config modal and `Alt+Shift+C` debug modal stay closed while controller support is disabled. -- Click the binding badge, edit pencil, or `Learn`, then press the next fresh button, trigger, or stick direction you want to bind for that overlay action. -- Click the reset button beside the edit pencil to restore one binding to the built-in default. -- Learned bindings are saved under `controller.profiles` for the selected controller id. Global `controller.bindings` remains the fallback for controllers without a profile. -- `Alt+Shift+C` opens the debug modal by default, and you can remap that shortcut through `shortcuts.openControllerDebug`. -- The debug modal shows raw axes/button values plus a ready-to-copy `buttonIndices` config block. -- The button-index map is a semantic reference mapping. Changing it does not rewrite the raw numeric descriptor values already stored under controller bindings. -- Turning keyboard-only mode off clears the keyboard-only token highlight state. -- Closing the Yomitan popup clears the temporary native text-selection fill, but keeps controller token selection active. - -```jsonc -{ - "controller": { - "enabled": true, - "preferredGamepadId": "", - "preferredGamepadLabel": "", - "smoothScroll": true, - "scrollPixelsPerSecond": 900, - "horizontalJumpPixels": 160, - "stickDeadzone": 0.2, - "triggerInputMode": "auto", - "triggerDeadzone": 0.5, - "repeatDelayMs": 320, - "repeatIntervalMs": 120, - "buttonIndices": { - "select": 6, - "buttonSouth": 0, - "buttonEast": 1, - "buttonWest": 2, - "buttonNorth": 3, - "leftShoulder": 4, - "rightShoulder": 5, - "leftStickPress": 9, - "rightStickPress": 10, - "leftTrigger": 6, - "rightTrigger": 7, - }, - "bindings": { - "toggleLookup": { "kind": "button", "buttonIndex": 0 }, - "closeLookup": { "kind": "button", "buttonIndex": 1 }, - "toggleKeyboardOnlyMode": { "kind": "button", "buttonIndex": 3 }, - "mineCard": { "kind": "button", "buttonIndex": 2 }, - "quitMpv": { "kind": "button", "buttonIndex": 6 }, - "previousAudio": { "kind": "none" }, - "nextAudio": { "kind": "button", "buttonIndex": 5 }, - "playCurrentAudio": { "kind": "button", "buttonIndex": 4 }, - "toggleMpvPause": { "kind": "button", "buttonIndex": 9 }, - "leftStickHorizontal": { "kind": "axis", "axisIndex": 0, "dpadFallback": "horizontal" }, - "leftStickVertical": { "kind": "axis", "axisIndex": 1, "dpadFallback": "vertical" }, - "rightStickHorizontal": { "kind": "axis", "axisIndex": 3, "dpadFallback": "none" }, - "rightStickVertical": { "kind": "axis", "axisIndex": 4, "dpadFallback": "none" }, - }, - "profiles": { - "Xbox Wireless Controller": { - "label": "Xbox Wireless Controller", - "bindings": { - "toggleLookup": { "kind": "button", "buttonIndex": 0 }, - "mineCard": { "kind": "button", "buttonIndex": 2 }, - }, - }, - }, - }, -} -``` - -Default logical mapping: - -- Left stick up/down: scroll Yomitan popup -- Left stick left/right: move subtitle token selection -- Right stick up/down: page-jump through Yomitan popup -- Right stick left/right: unused by default -- `A`: toggle lookup -- `B`: close lookup -- `Y`: toggle keyboard-only mode -- `X`: mine card -- `Minus` / `Select`: quit mpv -- `L1`: play current Yomitan audio (falls back to the first available track) -- `R1`: move to the next available Yomitan audio track -- `L3`: toggle mpv pause -- `L2` / `R2`: unbound by default - -Discrete bindings may use raw button indices or raw axis directions, and analog bindings use raw axis indices with optional D-pad fallback. The `Alt+C` learn flow writes those descriptors under `controller.profiles["<controller id>"]` for the selected controller. Manual edits are only needed when you want to script or copy exact mappings. - -If you bind a discrete action to an axis manually, include `direction`: - -```jsonc -{ - "controller": { - "bindings": { - "toggleLookup": { "kind": "axis", "axisIndex": 5, "direction": "positive" }, - }, - }, -} -``` - -Treat the button-index map as reference-only unless you are copying values from the debug modal. Updating it alone does not rewrite the hardcoded raw numeric values already present in controller bindings or controller profiles. If you need a real remap, prefer the `Alt+C` learn flow so both the source and the descriptor shape stay correct. - -If you choose to bind `L2` or `R2` manually, set `triggerInputMode` to `analog` and tune `triggerDeadzone` when your controller reports triggers as analog values instead of digital pressed/not-pressed buttons. `digital` forces pressed/not-pressed handling; `auto` accepts either style and remains the default. - -If one controller reports non-standard raw button numbers, override that controller profile's button-index map using values from the `Alt+Shift+C` debug modal. Use the global button-index map only when the mapping should apply to every controller without a profile. - -If you update this controller documentation or the generated controller examples, run `bun run docs:test` and `bun run docs:build` before merging. - -Tune `scrollPixelsPerSecond`, `horizontalJumpPixels`, deadzones, repeat timing, and profile `buttonIndices` to match your controller. See [config.example.jsonc](/config.example.jsonc) for the full generated comments for every controller field. - -### Manual card update shortcuts - -When automatic card updates are disabled, new cards are detected but not automatically updated. Use these keyboard shortcuts for manual control: - -| Shortcut | Action | -| -------------- | ------------------------------------------------------------------------------------------------------------- | -| `Ctrl+C` | Copy the current subtitle line to clipboard (preserves line breaks) | -| `Ctrl+Shift+C` | Enter multi-copy mode. Press `1-9` to copy that many recent lines, or `Esc` to cancel. Timeout: 3 seconds | -| `Ctrl+V` | Update the last added Anki card using subtitles from clipboard | -| `Ctrl+G` | Trigger Kiku duplicate field grouping for the last added card (only when automatic card updates are disabled) | -| `Ctrl+S` | Create a sentence card from the current subtitle line | -| `Ctrl+Shift+S` | Enter multi-mine mode. Press `1-9` to create a sentence card from that many recent lines, or `Esc` to cancel | -| `Ctrl+Shift+V` | Cycle secondary subtitle display mode (hidden → visible → hover) | -| `Ctrl+Shift+A` | Mark the last added Anki card as an audio card (sets IsAudioCard, SentenceAudio, Sentence, Picture) | -| `Ctrl+D` | Open loaded character dictionary manager | -| `Ctrl+Shift+O` | Open runtime options palette (session-only live toggles) | -| `Ctrl/Cmd+A` | Append clipboard video path to MPV playlist (configurable via `shortcuts.appendClipboardVideoToQueue`) | - -**Multi-line copy workflow:** - -1. Press `Ctrl+Shift+C` -2. Press a number key (`1-9`) within 3 seconds -3. The specified number of most recent subtitle lines are copied -4. Press `Ctrl+V` to update the last added card with the copied lines - -These shortcuts are only active when the overlay window is visible and automatically disabled when hidden. - -### Session help modal - -The session help modal opens from the overlay with `Ctrl/Cmd+/` by default. The mpv plugin also exposes it through the `y-h` chord. It shows the current session keybindings and color legend. - -You can filter the modal quickly with `/`: - -- Type any part of the action name or shortcut in the search bar. -- Search is case-insensitive and ignores spaces/punctuation (`+`, `-`, `_`, `/`) so `ctrl w`, `ctrl+w`, and `ctrl+s` all match. -- Results are filtered across active MPV shortcuts, configured overlay shortcuts, and color legend items. - -While the modal is open: - -- `Esc`: close the modal (or clear the filter when text is entered) -- `↑/↓`, `j/k`: move selection -- Mouse/trackpad: click to select and activate rows - -The list is generated at runtime from: - -- Your active mpv keybindings (`keybindings`). -- Your configured overlay shortcuts (`shortcuts`, including runtime-loaded config values). -- Current subtitle color settings from `subtitleStyle`. - -When config hot-reload updates shortcut/keybinding/style values, close and reopen the help modal to refresh the displayed entries. - -### Runtime option palette - -Use the runtime options palette to toggle settings live while SubMiner is running. These changes are session-only and reset on restart. - -Current runtime options cover automatic card updates, media timing review, -known-word highlighting, known-word maturity coloring, N+1 annotation, JLPT -underlines, frequency highlighting, known-word match mode, and Kiku field -grouping mode. - -Annotation toggles only apply to new subtitle lines after the toggle. The currently displayed line is not re-tokenized in place. - -Default shortcut: `Ctrl+Shift+O` - -Palette controls: - -- `Arrow Up/Down`: select option -- `Arrow Left/Right`: change selected value -- `Enter`: apply selected value -- `Esc`: close +Bindings are set with `Alt+C` learn mode, which saves them per controller. ## Anki integration ### AnkiConnect -Enable automatic Anki card creation and updates with media generation: +Creates and updates Anki cards with sentence, audio, and screenshot. Needs the [AnkiConnect](https://github.com/FooSoft/anki-connect) add-on and ffmpeg. See [Anki integration](/anki-integration) for setup, the proxy, and media options in detail. ```json { "ankiConnect": { - "enabled": true, - "url": "http://127.0.0.1:8765", - "pollingRate": 3000, - "proxy": { - "enabled": true, - "host": "127.0.0.1", - "port": 8766, - "upstreamUrl": "http://127.0.0.1:8765" - }, - "tags": ["SubMiner"], - "deck": "Learning::Japanese", - "fields": { - "word": "Expression", - "audio": "SentenceAudio", - "image": "Picture", - "sentence": "Sentence", - "miscInfo": "MiscInfo" - }, - "media": { - "generateAudio": true, - "generateImage": true, - "imageType": "static", - "imageFormat": "jpg", - "imageQuality": 92, - "imageMaxWidth": 0, - "imageMaxHeight": 0, - "animatedFps": 10, - "animatedMaxWidth": 640, - "animatedMaxHeight": 0, - "animatedCrf": 35, - "normalizeAudio": true, - "mirrorMpvVolume": true, - "reviewTiming": false, - "audioPadding": 0, - "fallbackDuration": 3, - "maxMediaDuration": 30 - }, - "behavior": { - "autoUpdateNewCards": true, - "overwriteAudio": true, - "overwriteImage": true - }, - "metadata": { - "pattern": "[SubMiner] %f (%t)" - }, - "isLapis": { - "enabled": false, - "sentenceCardModel": "Lapis" - }, - "isKiku": { - "enabled": false, - "fieldGrouping": "disabled", - "deleteDuplicateInAuto": true - } + "deck": "Mining", + "fields": { "audio": "SentenceAudio", "image": "Picture" }, + "knownWords": { "highlightEnabled": true, "decks": { "Mining": ["Expression"] } } } } ``` -This example is intentionally compact. The option table below documents available `ankiConnect` settings and behavior. +**Connection** -**Requirements:** [AnkiConnect](https://github.com/FooSoft/anki-connect) plugin must be installed and running in Anki. ffmpeg must be installed for media generation. +| Key | Default | What it does | +| ------------------------------- | ------------------------- | ------------------------------------------------------------------------------ | +| `ankiConnect.enabled` | `true` | Enable Anki integration | +| `ankiConnect.url` | `"http://127.0.0.1:8765"` | AnkiConnect URL | +| `ankiConnect.pollingRate` | `3000` | Milliseconds between checks for new cards (polling mode) | +| `ankiConnect.proxy.enabled` | `true` | Run a local AnkiConnect proxy so cards added through it are updated right away | +| `ankiConnect.proxy.host` | `"127.0.0.1"` | Proxy bind host | +| `ankiConnect.proxy.port` | `8766` | Proxy bind port | +| `ankiConnect.proxy.upstreamUrl` | `"http://127.0.0.1:8765"` | Where the proxy forwards requests | +| `ankiConnect.tags` | `["SubMiner"]` | Tags added to mined and updated cards. `[]` disables | +| `ankiConnect.deck` | `""` | Deck for duplicate checks and enrichment. Empty uses Yomitan's mining deck | -| Option | Values | Description | -| ------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ankiConnect.enabled` | `true`, `false` | Enable AnkiConnect integration (default: `true`) | -| `url` | string (URL) | AnkiConnect API URL (default: `http://127.0.0.1:8765`) | -| `pollingRate` | number (ms) | How often to check for new cards in polling mode (default: `3000`; ignored for direct proxy `addNote`/`addNotes` updates) | -| `proxy.enabled` | `true`, `false` | Enable local AnkiConnect-compatible proxy for push-based auto-enrichment (default: `true`) | -| `proxy.host` | string | Bind host for local AnkiConnect proxy (default: `127.0.0.1`) | -| `proxy.port` | number | Bind port for local AnkiConnect proxy (default: `8766`) | -| `proxy.upstreamUrl` | string (URL) | Upstream AnkiConnect URL that proxy forwards to (default: `http://127.0.0.1:8765`) | -| `tags` | array of strings | Tags automatically added to cards mined/updated by SubMiner (default: `['SubMiner']`; set `[]` to disable automatic tagging). | -| `ankiConnect.deck` | string | Restrict duplicate detection and card enrichment to this Anki deck. Leave empty to use the Yomitan mining deck when available. In Settings, this dropdown auto-fills and persists Yomitan's current mining deck when available. | -| `fields.word` | string | Card field for mined word / expression text (default: `Expression`) | -| `fields.audio` | string | Card field for the generated sentence audio clip (default: `ExpressionAudio`). Set this to a dedicated field such as `SentenceAudio` so it does not collide with the word audio Yomitan writes. | -| `fields.wordAudio` | string | Existing word-audio field read for the animated image's opening freeze. Independent of the sentence-audio destination in `fields.audio`; this mapping does not write audio. See [config.example.jsonc](/config.example.jsonc) for defaults. | -| `fields.image` | string | Card field for images (default: `Picture`) | -| `fields.sentence` | string | Card field for sentences (default: `Sentence`) | -| `fields.miscInfo` | string | Card field for metadata (default: `"MiscInfo"`, set to `null` to disable) | -| `media.generateAudio` | `true`, `false` | Generate audio clips from video (default: `true`) | -| `media.normalizeAudio` | `true`, `false` | Normalize generated sentence-audio loudness during media extraction (default: `true`). Set to `false` to keep raw source loudness. Changes apply live. | -| `media.mirrorMpvVolume` | `true`, `false` | Apply mpv's cubic software-volume curve to each generated sentence-audio clip (default: `true`). This ignores mpv's separate mute state, falls back to unity scaling if volume cannot be read, and applies changes live. | -| `media.reviewTiming` | `true`, `false` | Pause playback and review word, sentence, and audio card timing before media generation (default: `false`). Clipboard updates and stats-dashboard mining do not open the review. | -| `media.generateImage` | `true`, `false` | Generate image/animation screenshots (default: `true`) | -| `media.imageType` | `"static"`, `"avif"` | Image type: static screenshot or animated AVIF (default: `"static"`) | -| `media.imageFormat` | `"jpg"`, `"png"`, `"webp"` | Image format (default: `"jpg"`) | -| `media.imageQuality` | number (1-100) | Image quality for JPG/WebP; PNG ignores this (default: `92`). JPG values are mapped onto FFmpeg's 2-31 quality scale; WebP uses the value directly. | -| `media.imageMaxWidth` | number (px) | Optional max width for static screenshots. Unset keeps source width. | -| `media.imageMaxHeight` | number (px) | Optional max height for static screenshots. Unset keeps source height. | -| `media.animatedFps` | number (1-60) | FPS for animated AVIF (default: `10`) | -| `media.animatedMaxWidth` | number (px) | Max width for animated AVIF (default: `640`) | -| `media.animatedMaxHeight` | number (px) | Optional max height for animated AVIF. Unset keeps source aspect-constrained height. | -| `media.animatedCrf` | number (0-63) | CRF quality for AVIF; lower = higher quality (default: `35`) | -| `media.syncAnimatedImageToWordAudio` | `true`, `false` | Whether animated AVIF includes an opening frame synced to sentence word-audio timing (default: `true`). | -| `media.audioPadding` | number (seconds) | Optional padding around generated sentence media timing (default: `0`). Animated AVIF clips include the same padded source range as sentence audio. | -| `media.fallbackDuration` | number (seconds) | Default duration if timing unavailable (default: `3.0`) | -| `media.maxMediaDuration` | number (seconds) | Maximum generated clip duration for overlay and stats-dashboard mining. See the [configuration example](/config.example.jsonc) for the default and disabling the cap. | -| `behavior.overwriteAudio` | `true`, `false` | Replace existing audio on updates; when `false`, new audio is appended/prepended using the configured media insert mode; manual clipboard updates always replace generated sentence audio (default: `true`) | -| `behavior.overwriteImage` | `true`, `false` | Replace existing images on updates; when `false`, new images are appended/prepended using the configured media insert mode (default: `true`) | -| `behavior.mediaInsertMode` | `"append"`, `"prepend"` | Where to insert new media when overwrite is off (default: `"append"`) | -| `behavior.highlightWord` | `true`, `false` | Highlight the word in sentence context (default: `true`) | -| `ankiConnect.knownWords.highlightEnabled` | `true`, `false` | Enable fast local highlighting for words already known in Anki (default: `false`) | -| `ankiConnect.knownWords.addMinedWordsImmediately` | `true`, `false` | Add words from successful mines into the local known-word cache immediately (default: `true`) | -| `ankiConnect.knownWords.matchMode` | `"headword"`, `"surface"` | Matching strategy for known-word highlighting (default: `"headword"`). `headword` uses token headwords; `surface` uses visible subtitle text. | -| `ankiConnect.knownWords.refreshMinutes` | number | Minutes between known-word cache refreshes (default: `1440`) | -| `ankiConnect.knownWords.decks` | object | Deck→fields mapping used for known-word cache query scope (e.g. `{ "Kaishi 1.5k": ["Word"] }`). | -| `ankiConnect.knownWords.maturityEnabled` | `true`, `false` | Color known words by Anki card maturity (new/learning/young/mature) instead of one color. Requires `knownWords.highlightEnabled` (default: `false`). Tier colors come from `subtitleStyle.knownWordMaturityColors`. | -| `ankiConnect.knownWords.matureThresholdDays` | number | Card interval in days at which a known word counts as mature (default: `21`, matching Anki's own convention) | -| `ankiConnect.nPlusOne.enabled` | `true`, `false` | Enable N+1 subtitle highlighting (highlights the one unknown word in a sentence). Independent from `knownWords.highlightEnabled`. Requires known-word cache data (default: `false`). | -| `ankiConnect.nPlusOne.minSentenceWords` | number | Minimum number of words required in a sentence before single unknown-word N+1 highlighting can trigger (default: `3`). | -| `behavior.notificationType` | `"overlay"`, `"system"`, `"both"`, `"none"` | Notification type on card update (default: `"overlay"`). `"both"` means overlay + system. `osd` and `osd-system` are legacy config-file-only values; use `"osd-system"` to keep the old OSD + system behavior. | -| `behavior.autoUpdateNewCards` | `true`, `false` | Automatically update cards on creation (default: `true`) | -| `metadata.pattern` | string | Format pattern for metadata: `%f`=filename, `%F`=filename+ext, `%t`=time, `%T`=time with milliseconds, `<br>`=newline | -| `isLapis` | object | Lapis/shared sentence-card config: `{ enabled, sentenceCardModel }`. Sentence/audio field names are fixed to `Sentence` and `SentenceAudio`. | -| `isKiku` | object | Kiku-only config: `{ enabled, fieldGrouping, deleteDuplicateInAuto }` (shared sentence/audio/model settings are inherited from `isLapis`) | -| `isSenren` | object | Senren-only config: `{ enabled, fieldGrouping, deleteDuplicateInAuto }`. Merges duplicates using Senren's scene-switching markup. Mutually exclusive with `isKiku.enabled`. | +**Fields** -### Kiku/Lapis integration +| Key | Default | What it does | +| ------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `ankiConnect.fields.word` | `"Expression"` | Word field | +| `ankiConnect.fields.audio` | `"ExpressionAudio"` | Field that receives sentence audio. Set a separate field such as `SentenceAudio` so it does not overwrite Yomitan's word audio | +| `ankiConnect.fields.wordAudio` | `"ExpressionAudio"` | Existing word-audio field, read only to time animated images | +| `ankiConnect.fields.image` | `"Picture"` | Screenshot field | +| `ankiConnect.fields.sentence` | `"Sentence"` | Sentence field | +| `ankiConnect.fields.miscInfo` | `"MiscInfo"` | Metadata field. `null` disables | +| `ankiConnect.metadata.pattern` | `"[SubMiner] %f (%t)"` | MiscInfo template: `%f` filename, `%F` filename with extension, `%t` time, `%T` time with ms, `<br>` newline | -SubMiner is intentionally built for [Kiku](https://kiku.youyoumu.my.id/) and [Lapis](https://github.com/donkuri/lapis) workflows, with note-type-specific behavior built into Anki settings. +**Media** -```jsonc -"ankiConnect": { - "isLapis": { - "enabled": true, - "sentenceCardModel": "Japanese sentences" - }, - "isKiku": { - "enabled": true, - "fieldGrouping": "manual", - "deleteDuplicateInAuto": true - }, - "lapisKiku": { - "wordCardKind": "word-and-sentence" - } -} -``` +| Key | Default | What it does | +| ------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| `ankiConnect.media.generateAudio` | `true` | Cut a sentence audio clip | +| `ankiConnect.media.generateImage` | `true` | Capture a screenshot or animation | +| `ankiConnect.media.imageType` | `"static"` | `static` or `avif` (animated) | +| `ankiConnect.media.imageFormat` | `"jpg"` | Static format: `jpg`, `png`, `webp` | +| `ankiConnect.media.imageQuality` | `92` | JPG/WebP quality. PNG ignores it | +| `ankiConnect.media.imageMaxWidth` | `0` | Max static width in px. `0` keeps the source size | +| `ankiConnect.media.imageMaxHeight` | `0` | Max static height in px. `0` keeps the source size | +| `ankiConnect.media.animatedFps` | `10` | AVIF frame rate | +| `ankiConnect.media.animatedMaxWidth` | `640` | AVIF max width | +| `ankiConnect.media.animatedMaxHeight` | `0` | AVIF max height. `0` keeps the aspect ratio | +| `ankiConnect.media.animatedCrf` | `35` | AVIF quality. Lower is better and larger | +| `ankiConnect.media.syncAnimatedImageToWordAudio` | `true` | Hold the first AVIF frame for the length of the word audio | +| `ankiConnect.media.normalizeAudio` | `true` | Normalize clip loudness | +| `ankiConnect.media.mirrorMpvVolume` | `true` | Apply mpv's current volume to the clip | +| `ankiConnect.media.reviewTiming` | `false` | Pause and let you adjust clip timing before media is created | +| `ankiConnect.media.audioPadding` | `0` | Seconds added to both ends of audio and AVIF clips | +| `ankiConnect.media.fallbackDuration` | `3` | Clip length in seconds when subtitle timing is missing | +| `ankiConnect.media.maxMediaDuration` | `30` | Longest allowed clip in seconds. `0` removes the cap | -- Enable `isLapis` to mine dedicated sentence cards. SubMiner sets `IsSentenceCard` to `"x"` and fills the sentence fields for the configured model. -- Enable `isKiku` to turn on duplicate merge behavior for mined Word/Expression hits. -- When both are enabled, Kiku behavior is applied for grouping while sentence-card model settings are still read from `isLapis`. -- `isKiku.fieldGrouping` supports `disabled`, `auto`, and `manual` merge modes; see [Field Grouping Modes](#field-grouping-modes). -- For [Senren](https://github.com/BrenoAqua/Senren) note types, enable `isSenren` instead of `isKiku`. Duplicate merges then use Senren's scene-switching markup (including grouped `miscInfo` entries), and `isSenren.fieldGrouping` supports the same three modes (default: `auto`). Kiku and Senren are mutually exclusive; if both are enabled, Kiku wins and Senren is turned off with a config warning. -- `lapisKiku.wordCardKind` picks the card-type flag set on word cards; see [Word Card Type](#word-card-type). It is read only while `isLapis` or `isKiku` is enabled. +**Behavior** + +| Key | Default | What it does | +| ----------------------------------------- | ----------- | ------------------------------------------------------------------------ | +| `ankiConnect.behavior.autoUpdateNewCards` | `true` | Fill new cards automatically. When off, use the manual shortcuts | +| `ankiConnect.behavior.overwriteAudio` | `true` | Replace existing audio. When off, add alongside it | +| `ankiConnect.behavior.overwriteImage` | `true` | Replace existing images. When off, add alongside them | +| `ankiConnect.behavior.mediaInsertMode` | `"append"` | `append` or `prepend` when not overwriting | +| `ankiConnect.behavior.highlightWord` | `true` | Bold the mined word in the sentence field | +| `ankiConnect.behavior.notificationType` | `"overlay"` | Where mining and status messages go: `overlay`, `system`, `both`, `none` | + +**Known words and N+1** + +| Key | Default | What it does | +| ------------------------------------------------- | ------------ | -------------------------------------------------------------------------------- | +| `ankiConnect.knownWords.highlightEnabled` | `false` | Highlight words that already exist in your Anki decks | +| `ankiConnect.knownWords.decks` | `{}` | Decks and word fields to read, for example `{ "Kaishi 1.5k": ["Word"] }` | +| `ankiConnect.knownWords.matchMode` | `"headword"` | Match by `headword` or `surface` text | +| `ankiConnect.knownWords.refreshMinutes` | `1440` | Minutes between cache refreshes | +| `ankiConnect.knownWords.addMinedWordsImmediately` | `true` | Add newly mined words to the cache right away | +| `ankiConnect.knownWords.maturityEnabled` | `false` | Color known words by card maturity using `subtitleStyle.knownWordMaturityColors` | +| `ankiConnect.knownWords.matureThresholdDays` | `21` | Interval in days at which a card counts as mature | +| `ankiConnect.nPlusOne.enabled` | `false` | Highlight the only unknown word in a sentence. Needs known-word data | +| `ankiConnect.nPlusOne.minSentenceWords` | `3` | Minimum words in a sentence before N+1 applies | + +Use word fields such as `Expression` or `Word` in `knownWords.decks`, not reading fields. See [Subtitle annotations](/subtitle-annotations) for how matching and maturity tiers work. + +### Kiku/Lapis integration {#kiku-lapis-integration} + +Note-type behavior for [Lapis](https://github.com/donkuri/lapis), [Kiku](https://kiku.youyoumu.my.id/), and [Senren](https://github.com/BrenoAqua/Senren). With both Lapis and Kiku on, Kiku handles duplicates and the sentence-card model comes from `isLapis`. Kiku and Senren are mutually exclusive. If both are on, Kiku wins and SubMiner logs a warning. See [Anki integration](/anki-integration) for details. + +| Key | Default | What it does | +| -------------------------------------------- | --------------------- | ------------------------------------------------------ | +| `ankiConnect.isLapis.enabled` | `false` | Mine dedicated sentence cards (`IsSentenceCard`) | +| `ankiConnect.isLapis.sentenceCardModel` | `"Lapis"` | Note type used for sentence cards | +| `ankiConnect.isKiku.enabled` | `false` | Merge duplicate word cards | +| `ankiConnect.isKiku.fieldGrouping` | `"disabled"` | `auto`, `manual`, or `disabled`. See below | +| `ankiConnect.isKiku.deleteDuplicateInAuto` | `true` | Delete the duplicate after an `auto` merge | +| `ankiConnect.isSenren.enabled` | `false` | Merge duplicates using Senren's scene-switching format | +| `ankiConnect.isSenren.fieldGrouping` | `"auto"` | `auto`, `manual`, or `disabled` | +| `ankiConnect.isSenren.deleteDuplicateInAuto` | `true` | Delete the duplicate after an `auto` merge | +| `ankiConnect.lapisKiku.wordCardKind` | `"word-and-sentence"` | Card-type flag set on word cards. See below | ### Word card type -When SubMiner fills the sentence on a mined word card - from Yomitan auto-enrichment, a manual clipboard update, or stats-dashboard word mining - it marks which card that note should generate. `ankiConnect.lapisKiku.wordCardKind` chooses the flag: +When SubMiner fills the sentence on a word card, it sets one card-type flag and clears the others. Only applies while `isLapis` or `isKiku` is on. Cards from Mine Sentence and Mine Audio keep their own flag. -| Value | Flag set | +| `wordCardKind` | Flag set | | ----------------------------- | ----------------------- | | `word-and-sentence` (default) | `IsWordAndSentenceCard` | | `click` | `IsClickCard` | | `sentence` | `IsSentenceCard` | | `audio` | `IsAudioCard` | -| `none` | none; flags left as-is | - -The other card-type flags are cleared so a note never claims two card types at once. Notes are skipped when the note type has no field for the chosen flag, and when the note was already mined as a sentence or audio card. Cards created by Mine Sentence and Mine Audio keep their own flag regardless of this setting. - -### N+1 word highlighting - -When known-word highlighting is enabled, SubMiner builds a local cache of known words from Anki to highlight already learned tokens in subtitle rendering. - -Known-word cache policy: - -- Initial sync runs when the integration starts if the cache is missing or stale. -- The refresh interval controls the minimum time between syncs; between refreshes, cached words are reused without querying Anki. -- `subtitleStyle.nPlusOneColor` sets the color for the single target token when exactly one eligible unknown word exists. -- The N+1 minimum sentence-word setting controls the token count required before N+1 highlighting can trigger. -- `subtitleStyle.knownWordColor` sets the known-word highlight color for tokens already in Anki. -- Set `ankiConnect.knownWords.maturityEnabled` to `true` to color known words by Anki card maturity instead, using the four `subtitleStyle.knownWordMaturityColors` tiers. See [Known-Word Maturity Highlighting](/subtitle-annotations#known-word-maturity-highlighting) for how tiers are derived. Changing it or `matureThresholdDays` forces a full cache refresh. -- The known-word deck map accepts an object keyed by deck name. -- Prefer expression/word fields such as `Expression` or `Word`. Avoid reading-only fields unless you intentionally want homophone readings to count as known words. -- Cache state is persisted to `known-words-cache.json` under the app `userData` directory. -- The cache is automatically invalidated when the configured scope changes (for example, when deck changes). -- Cache lookups are in-memory. By default, token headwords are matched against cached `Expression` / `Word` values; set known-word matching to `"surface"` for raw subtitle text matching. -- A known-word cache match always receives known-word highlighting, even when part-of-speech filters suppress N+1, frequency, or JLPT annotations for that token. -- If AnkiConnect is unreachable, the cache remains in its previous state and an on-screen/system status message is shown. -- Known-word sync activity is logged at `INFO`/`DEBUG` level with the `anki` logger scope and includes scope, notes returned, and word counts. - -To refresh roughly once per day, set: - -```json -{ - "ankiConnect": { - "knownWords": { - "highlightEnabled": true, - "refreshMinutes": 1440 - }, - "nPlusOne": { - "minSentenceWords": 3 - } - } -} -``` +| `none` | none, flags left as-is | ### Field grouping modes -| Mode | Behavior | -| ---------- | -------------------------------------------------------------------------------------------------------------------------- | -| `auto` | Automatically merges the new card's content into the original; duplicate deletion is controlled by `deleteDuplicateInAuto` | -| `manual` | Shows an overlay popup to choose which card to keep and whether to delete the duplicate after merge | -| `disabled` | No field grouping; duplicate cards are left as-is | - -`deleteDuplicateInAuto` controls whether `auto` mode deletes the duplicate after merge (default: `true`). In `manual` mode, the popup asks each time whether to delete the duplicate. -When the manual merge popup opens, SubMiner pauses playback and closes any open Yomitan popup first so the merge flow can take focus. +| Mode | What happens when you mine a duplicate | +| ---------- | ---------------------------------------------------------------------------------------------------------- | +| `auto` | Merges the new card into the existing one. `deleteDuplicateInAuto` decides whether the new card is deleted | +| `manual` | Pauses playback and opens a dialog to choose which card to keep and whether to delete the other | +| `disabled` | Leaves both cards as they are | <video controls playsinline preload="metadata" :poster="withBase('/assets/kiku-integration-poster.jpg')" style="width: 100%; max-width: 960px;"> <source :src="withBase('/assets/kiku-integration.webm')" type="video/webm" /> @@ -1123,518 +433,181 @@ When the manual merge popup opens, SubMiner pauses playback and closes any open Your browser does not support the video tag. </video> -<a :href="withBase('/assets/kiku-integration.webm')" target="_blank" rel="noreferrer">Open demo in a new tab</a> - -## Subtitle Selection - -Enable **Settings → Behavior → Subtitle Selection → Enabled** to choose mpv's primary and secondary subtitle tracks from a SubMiner modal. The feature is disabled by default. The dialog uses the same overlay focus and subtitle suppression behavior as the other modals. - -Press `g` then `s` to open it. Both selectors include **None**. Choose different tracks and click **Apply** to load them into mpv, or close the dialog to keep the current selection. Embedded and already-loaded external subtitle tracks are listed with their title, language, and codec when available. - -`subtitleSelection.enabled` controls the feature. `shortcuts.openSubtitleSelection` changes its shortcut, or accepts `null` to unbind it. Enabling the feature overrides mpv's binding for that shortcut when its first key is free; disabling it restores mpv's binding. Existing single-key actions take priority over sequences; see [shortcut conflicts](/shortcuts). Both settings apply immediately. See the [generated configuration example](/config.example.jsonc) for defaults. - ## External integrations ### Jimaku -Configure Jimaku API access and defaults: +Search and download Japanese subtitles from [Jimaku](https://jimaku.cc). See [Jimaku integration](/jimaku-integration). -```json -{ - "jimaku": { - "apiKey": "YOUR_API_KEY", - "apiKeyCommand": "cat ~/.jimaku_key", - "apiBaseUrl": "https://jimaku.cc", - "languagePreference": "ja", - "maxEntryResults": 10 - } -} -``` - -Jimaku is rate limited; if you hit a limit, SubMiner will surface the retry delay from the API response. +| Key | Default | What it does | +| --------------------------- | --------------------- | ---------------------------------------------------------- | +| `jimaku.apiKey` | `""` | API key. Optional, but raises your rate limit | +| `jimaku.apiKeyCommand` | `""` | Shell command that prints the key. Use instead of `apiKey` | +| `jimaku.apiBaseUrl` | `"https://jimaku.cc"` | API base URL | +| `jimaku.languagePreference` | `"ja"` | Preferred language: `ja`, `en`, or `none` | +| `jimaku.maxEntryResults` | `10` | Maximum search results | ### TsukiHime -TsukiHime subtitle search works out of the box and needs no account or API key. It does require the `xz` binary on your `PATH`, because TsukiHime serves extracted subtitles xz-compressed. +Subtitle search that needs no account or key. It does need `xz` on your `PATH`. The shortcut is `shortcuts.openTsukihime`. See [TsukiHime integration](/tsukihime-integration). -```json -{ - "tsukihime": { - "apiBaseUrl": "https://api.tsukihime.org/v1", - "maxSearchResults": 10 - } -} -``` - -| Option | Values | Description | -| ---------------------------- | ------------ | ----------------------------------------------------------------------------------------------------- | -| `tsukihime.apiBaseUrl` | string (URL) | Base URL of the TsukiHime API (default: `https://api.tsukihime.org/v1`). Only change it for a mirror. | -| `tsukihime.maxSearchResults` | number | Maximum releases returned per search (default: `10`; the API caps this at 100) | - -The keyboard shortcut lives under `shortcuts.openTsukihime` (default `Ctrl+Shift+T`; set to `null` to disable). The older `animetosho` section and `shortcuts.openAnimetosho` are still accepted as deprecated aliases, with the current names taking precedence when both are set. - -See [TsukiHime Integration](/tsukihime-integration) for the modal workflow, language tabs, and troubleshooting. +| Key | Default | What it does | +| ---------------------------- | -------------------------------- | ---------------------------------------------------- | +| `tsukihime.apiBaseUrl` | `"https://api.tsukihime.org/v1"` | API base URL. Only change it for a mirror | +| `tsukihime.maxSearchResults` | `10` | Maximum releases per search (the API caps it at 100) | ### TMDB -TMDB (The Movie Database) supplies posters, synopses, and show grouping for live-action dramas and movies in the stats [Library](/immersion-tracking#library). AniList only covers anime, so TMDB is what gives live-action titles a cover and a description. +Posters, synopses, and show grouping for live-action titles in the stats [Library](/immersion-tracking). Release builds include a TMDB key, so you only need your own to use your own quota or when running from source. Get one free under **Settings > API** on [themoviedb.org](https://www.themoviedb.org/settings/api). Either the API key or the read access token works. -Release builds ship with a project TMDB key, so nothing needs to be configured. Set your own key to use your own quota, or when running SubMiner from source, where no key is bundled. Create one for free under **Settings > API** on [themoviedb.org](https://www.themoviedb.org/settings/api); either the short API key or the long "API Read Access Token" works. - -```json -{ - "tmdb": { - "apiKey": "", - "apiKeyCommand": "cat ~/.tmdb_key" - } -} -``` - -| Option | Values | Description | -| -------------------- | ------ | -------------------------------------------------------------------------------------------------- | -| `tmdb.apiKey` | string | Your own TMDB API key or read access token; overrides the bundled key (default: empty) | -| `tmdb.apiKeyCommand` | string | Shell command that prints the key to stdout, used instead of `apiKey` to keep it out of the config | - -Successful `apiKeyCommand` output is cached for the running client until `tmdb.apiKey` or `tmdb.apiKeyCommand` changes. Failed or empty command output uses the bundled key when available and waits 30 seconds before the next request can retry the command. Changing either credential setting resets this cooldown. - -Changes apply to the next TMDB request without a restart. +| Key | Default | What it does | +| -------------------- | ------- | ---------------------------------------------------------- | +| `tmdb.apiKey` | `""` | Your TMDB key or token. Overrides the bundled key | +| `tmdb.apiKeyCommand` | `""` | Shell command that prints the key. Use instead of `apiKey` | This product uses the TMDB API but is not endorsed or certified by TMDB. ### Japanese subtitle generation -Open the standalone modal with `Ctrl+Shift+G`, configurable through `shortcuts.openSubtitleGeneration`, or use the subtitle sidebar button. See [shortcuts](/shortcuts) for the shared mpv and overlay keybindings. +Transcribes Japanese subtitles locally with whisper.cpp. Open it with `Ctrl+Shift+G` (`shortcuts.openSubtitleGeneration`) or from the subtitle sidebar. See [Subtitle generation](/subtitle-generation). -`subtitleGeneration` configures local Japanese transcription for both the launcher and overlay. In **Settings → Integrations → Japanese Subtitle Generation**, set `modelPath` to an existing multilingual whisper.cpp GGML model, or leave it empty and choose a `managedModel` as the default. The generation modal lets you select another model for the current session, with download sizes and accuracy versus speed guidance. Downloads are explicit. Leave `whisperPath`, `ffmpegPath`, and `ffprobePath` empty to find the executables on `PATH`, or set them to override the executable paths. `threads` controls the CPU thread count. Settings apply to the next operation. See [subtitle generation](/subtitle-generation) for setup and behavior, and the [generated configuration example](/config.example.jsonc) for defaults. - -The generation modal offers an optional **Focus on spoken dialogue** checkbox and a separate Silero model download. Set `subtitleGeneration.vadModelPath` to a Silero GGML VAD model to make dialogue mode the default. `vadPath` overrides the speech detector executable. See [dialogue generation setup](/subtitle-generation#prioritizing-spoken-dialogue) for session behavior, the additional tool, and limitations. +| Key | Default | What it does | +| --------------------------------- | --------- | ----------------------------------------------------------------------- | +| `subtitleGeneration.modelPath` | `""` | Path to a multilingual whisper.cpp GGML model. Overrides `managedModel` | +| `subtitleGeneration.managedModel` | `"small"` | Model SubMiner downloads and uses when `modelPath` is empty | +| `subtitleGeneration.threads` | `4` | CPU threads | +| `subtitleGeneration.vadModelPath` | `""` | Silero VAD model. Set it to focus on spoken dialogue by default | +| `subtitleGeneration.whisperPath` | `""` | `whisper-cli` path. Empty searches `PATH` | +| `subtitleGeneration.vadPath` | `""` | Speech detector path. Empty searches `PATH` | +| `subtitleGeneration.ffmpegPath` | `""` | `ffmpeg` path. Empty searches `PATH` | +| `subtitleGeneration.ffprobePath` | `""` | `ffprobe` path. Empty searches `PATH` | ### Subtitle sync -Sync a subtitle track from the overlay picker using `alass` or `ffsubsync`. The picker lets you choose which track gets retimed (the active primary track by default) and, for alass, which reference it is aligned against (the secondary subtitle track by default). Both are **optional external tools** that must be installed separately and available on your `PATH` (or configured via the path options below). +Retimes a subtitle track with [`alass`](https://github.com/kaegi/alass) (against another subtitle or the video) or [`ffsubsync`](https://github.com/smacke/ffsubsync) (against the video's audio). Install them yourself. Open the picker with `Ctrl+Alt+S` (`shortcuts.triggerSubsync`). -- [`alass`](https://github.com/kaegi/alass) - fast, audio-independent sync using another subtitle as reference; it can also take the local video file as reference (alass extracts the audio itself) -- [`ffsubsync`](https://github.com/smacke/ffsubsync) - audio-based sync using the video file as reference +| Key | Default | What it does | +| ------------------------ | ------- | ------------------------------------------------------------------- | +| `subsync.alass_path` | `""` | `alass` path. Empty uses `/usr/bin/alass` | +| `subsync.ffsubsync_path` | `""` | `ffsubsync` path. Empty uses `/usr/bin/ffsubsync` | +| `subsync.ffmpeg_path` | `""` | `ffmpeg` path. Empty uses `/usr/bin/ffmpeg` | +| `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `<name>_retimed.<ext>` | -```json -{ - "subsync": { - "alass_path": "", - "ffsubsync_path": "", - "ffmpeg_path": "", - "replace": true - } -} -``` - -| Option | Values | Description | -| ---------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `alass_path` | string path | Path to `alass` executable. Empty falls back to `/usr/bin/alass`. `alass` must be installed separately. | -| `ffsubsync_path` | string path | Path to `ffsubsync` executable. Empty falls back to `/usr/bin/ffsubsync`. `ffsubsync` must be installed separately. | -| `ffmpeg_path` | string path | Path to `ffmpeg` (used for internal subtitle extraction). Empty or `null` falls back to `/usr/bin/ffmpeg`. | -| `replace` | `true`, `false` | When `true` (default), overwrite the active subtitle file on successful sync. When `false`, write `<name>_retimed.<ext>`. | - -Default trigger is `Ctrl+Alt+S` via `shortcuts.triggerSubsync`. -Customize it there, or set it to `null` to disable. +If a tool lives somewhere else, such as on macOS or Windows, set its path. ### AniList -AniList integration is opt-in and disabled by default. Enable it to allow SubMiner to update watched episode progress after playback. +Updates your AniList watch progress after an episode, and controls the character dictionary. With `enabled` on and no token, SubMiner opens a login window. See [AniList integration](/anilist-integration) and [Character dictionary](/character-dictionary). -```json -{ - "anilist": { - "enabled": true, - "accessToken": "", - "characterDictionary": { - "maxLoaded": 3, - "profileScope": "all", - "collapsibleSections": { - "description": false, - "characterInformation": false, - "voicedBy": false - } - } - } -} -``` - -| Option | Values | Description | -| -------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------- | -| `anilist.enabled` | `true`, `false` | Enable AniList post-watch progress updates (default: `false`) | -| `accessToken` | string | Optional explicit AniList access token override (default: empty string) | -| `characterDictionary.maxLoaded` | number | Maximum number of most-recently-used AniList media snapshots included in the merged dictionary (default: `3`) | -| `characterDictionary.refreshTtlHours` | number | Hours before a cached media snapshot is refreshed (default: `168`, clamped to 1–8760) | -| `characterDictionary.evictionPolicy` | `"delete"`, `"disable"` | What happens to snapshots evicted beyond `maxLoaded` (default: `"delete"`) | -| `characterDictionary.collapsibleSections.description` | `true`, `false` | Open the Description section by default in generated dictionary entries | -| `characterDictionary.collapsibleSections.characterInformation` | `true`, `false` | Open the Character Information section by default in generated dictionary entries | -| `characterDictionary.collapsibleSections.voicedBy` | `true`, `false` | Open the Voiced by section by default in generated dictionary entries | -| `characterDictionary.profileScope` | `"all"`, `"active"` | Apply dictionary settings updates to all Yomitan profiles or only active profile | - -When `enabled` is `true` and `accessToken` is empty, SubMiner opens an AniList setup helper window. Keep `enabled` as `false` to disable all AniList setup/update behavior. - -Character dictionary sync behavior: - -- Snapshot identity is still AniList **media ID**. -- Sync/import runs only for the currently watched media when media path/title changes. -- SubMiner keeps a most-recently-used list of synced AniList media snapshots and rebuilds one merged Yomitan dictionary from that active set. -- `maxLoaded` controls how many recent AniList media snapshots stay in the merged dictionary at once. -- The merged dictionary title stays stable as `SubMiner Character Dictionary`, so Yomitan sees one rotating dictionary instead of one dictionary per anime. - -Current post-watch behavior: - -- SubMiner attempts an update near episode completion using the shared default minimum watch ratio (`0.85`, or `>=85%`) from `src/shared/watch-threshold.ts`, and requires at least `10` minutes watched. The same ratio is also used by local episode watched state transitions. -- Episode/title detection is `guessit`-first with fallback to SubMiner's filename parser. -- If `guessit` is unavailable, updates still work via fallback parsing but title matching can be less accurate. -- If embedded AniList auth UI fails to render, SubMiner opens the authorize URL in your default browser and shows fallback instructions in-app. -- Failed updates are retried with a persistent backoff queue in the background. - -Setup flow details: - -1. Set `anilist.enabled` to `true`. -2. Leave the AniList access-token field empty and restart SubMiner (or run `--anilist-setup`) to trigger setup. -3. Approve access in AniList. -4. Callback flow returns to SubMiner via `subminer://anilist-setup?...`, and SubMiner stores the token automatically. - - Encryption backend: Linux defaults to `gnome-libsecret`. - Override with `--password-store=<backend>` (for example `--password-store=basic_text`). - -Token + detection notes: - -- The AniList access token can be set directly in config; when blank, SubMiner uses the locally stored encrypted token from setup. -- Detection quality is best when `guessit` is installed and available on `PATH`. -- When `guessit` cannot parse or is missing, SubMiner falls back automatically to internal filename parsing. - -AniList CLI commands: - -- `--anilist-status`: print current AniList token resolution state and retry queue counters. -- `--anilist-logout`: clear stored AniList token from local persisted state. -- `--anilist-setup`: open AniList setup/auth flow helper window. -- `--anilist-retry-queue`: process one ready retry queue item immediately. +| Key | Default | What it does | +| ---------------------------------------------------------------------- | ------- | ------------------------------------------------------------- | +| `anilist.enabled` | `false` | Enable progress updates | +| `anilist.accessToken` | `""` | Token override. Empty uses the token saved during login | +| `anilist.characterDictionary.maxLoaded` | `3` | How many recent shows stay in the merged character dictionary | +| `anilist.characterDictionary.collapsibleSections.description` | `false` | Open the Description section by default | +| `anilist.characterDictionary.collapsibleSections.characterInformation` | `false` | Open the Character Information section by default | +| `anilist.characterDictionary.collapsibleSections.voicedBy` | `false` | Open the Voiced by section by default | ### Yomitan -SubMiner normally uses its bundled Yomitan profile under the app config directory. If you want to reuse dictionaries and profile settings from another Electron app, point SubMiner at that app's Yomitan Electron profile in read-only mode. +Point SubMiner at another app's Yomitan Electron profile to reuse its dictionaries and settings. For GameSentenceMiner on Linux this is usually `~/.config/gsm_overlay`. -For GameSentenceMiner on Linux, the default overlay profile path is typically `~/.config/gsm_overlay`. +| Key | Default | What it does | +| ----------------------------- | ------- | ----------------------------------------------------------------------- | +| `yomitan.externalProfilePath` | `""` | Absolute or `~` path to the external profile. Empty uses SubMiner's own | -```json -{ - "yomitan": { - "externalProfilePath": "/home/you/.config/gsm_overlay" - } -} -``` - -| Option | Values | Description | -| --------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `externalProfilePath` | string path | Optional absolute path, or a path beginning with `~` (expanded to your home directory), to another app's Yomitan Electron profile. SubMiner loads that profile read-only and reuses its dictionaries/settings. | - -External-profile mode behavior: - -- SubMiner uses the external profile's Yomitan extension/session instead of its local copy. -- SubMiner reads the external profile's currently active Yomitan profile selection and installed dictionaries. -- SubMiner does not open its own Yomitan settings window in this mode. -- SubMiner does not import, delete, or update dictionaries/settings in the external profile. -- SubMiner character-dictionary features are fully disabled in this mode, including auto-sync, manual generation, and subtitle-side character-dictionary annotations. -- First-run setup does not require any internal dictionaries while this mode is configured. If you later launch without an external Yomitan profile, setup will require at least one internal Yomitan dictionary unless SubMiner already finds one. +In external-profile mode, SubMiner only reads the profile. It does not open its own Yomitan settings, does not change dictionaries, and turns off all character-dictionary features. ### Jellyfin -Jellyfin integration is optional and disabled by default. When enabled, SubMiner can authenticate, list libraries/items, and resolve direct/transcoded playback URLs for mpv launch. +Log in to a Jellyfin server, browse libraries, and play or cast to SubMiner. Login tokens are stored encrypted, not in this file. See [Jellyfin integration](/jellyfin-integration). -```json -{ - "jellyfin": { - "enabled": true, - "serverUrl": "http://127.0.0.1:8096", - "recentServers": ["http://127.0.0.1:8096"], - "username": "", - "remoteControlEnabled": true, - "remoteControlAutoConnect": true, - "autoAnnounce": false, - "defaultLibraryId": "", - "directPlayPreferred": true, - "directPlayContainers": ["mkv", "mp4", "webm", "mov", "flac", "mp3", "aac"], - "transcodeVideoCodec": "h264" - } -} -``` - -| Option | Values | Description | -| -------------------------- | --------------- | ------------------------------------------------------------------------------------------------------ | -| `jellyfin.enabled` | `true`, `false` | Enable Jellyfin integration and CLI commands (default: `false`) | -| `serverUrl` | string (URL) | Jellyfin server base URL | -| `recentServers` | string[] | Recent Jellyfin server URLs shown in setup; entries are trimmed, deduped, and capped at 5 | -| `username` | string | Default username used by `--jellyfin-login` | -| `defaultLibraryId` | string | Default library id for `--jellyfin-items` when CLI value is omitted | -| `remoteControlEnabled` | `true`, `false` | Enable Jellyfin cast/remote-control session support | -| `remoteControlAutoConnect` | `true`, `false` | Auto-connect Jellyfin remote session on app startup (requires Jellyfin integration and remote control) | -| `autoAnnounce` | `true`, `false` | Auto-run cast-target visibility announce check on connect (default: `false`) | -| `pullPictures` | `true`, `false` | Enable poster/icon fetching for launcher Jellyfin pickers | -| `iconCacheDir` | string | Cache directory for launcher-fetched Jellyfin poster icons | -| `directPlayPreferred` | `true`, `false` | Prefer direct stream URLs before transcoding | -| `directPlayContainers` | string[] | Container allowlist for direct play decisions | -| `transcodeVideoCodec` | string | Preferred transcode video codec fallback (default: `h264`) | - -Jellyfin auth session (`accessToken` + `userId`) is stored in local encrypted storage after login/setup. SubMiner reports the Jellyfin client as `SubMiner`, derives the Jellyfin device id and visible device name from the OS hostname, and owns the client version internally. The Settings window also hides low-level default library fields (`defaultLibraryId`) so normal setup stays focused on server, auth, playback, and remote-control behavior. - -- On Linux, token storage defaults to `gnome-libsecret` for `safeStorage`. Override with `--password-store=<backend>` on launcher/app invocations when needed. - -Launcher subcommands: - -- `subminer jellyfin` (or `subminer jf`) opens setup. -- `subminer jellyfin -l --server ... --username ... --password ...` logs in. -- `subminer jellyfin --logout` clears stored credentials. -- `subminer jellyfin -p` opens play picker. -- `subminer jellyfin -d` starts cast discovery mode in background/tray mode. -- These launcher commands also accept `--password-store=<backend>` to override the launcher-app forwarded Electron switch. - -See [Jellyfin Integration](/jellyfin-integration) for the full setup and cast-to-device guide. - -Jellyfin remote auto-connect runs only when Jellyfin integration, remote control, and remote auto-connect are all enabled. - -Jellyfin playback auto-launched through SubMiner loads the mpv plugin the same way regular playback does, and shows the visible subtitle overlay automatically so `subtitleStyle` applies to subtitles selected from Jellyfin. - -When Jellyfin is enabled with a server URL and SubMiner is running, the tray menu also shows a `Jellyfin Discovery` checkbox. It starts or stops discovery for the current runtime session only and does not write config. Starting discovery still requires a valid stored or environment-provided Jellyfin auth session. +| Key | Default | What it does | +| ----------------------------------- | -------------------------------- | ----------------------------------------------- | +| `jellyfin.enabled` | `false` | Enable Jellyfin | +| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` | +| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` | +| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner | +| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup | +| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect | +| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers | +| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder | +| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding | +| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding | ### Discord rich presence -Discord Rich Presence is enabled by default. SubMiner publishes a polished activity card that reflects current media title, playback state, and session timer unless you turn it off. +Shows what you are watching on your Discord profile. Needs the Discord desktop app running. If Discord is closed, SubMiner skips updates. -```json -{ - "discordPresence": { - "enabled": true, - "presenceStyle": "default", - "updateIntervalMs": 3000, - "debounceMs": 750 - } -} -``` - -| Option | Values | Description | -| ------------------------- | ------------------------------------------------ | ---------------------------------------------------------- | -| `discordPresence.enabled` | `true`, `false` | Enable Discord Rich Presence updates (default: `true`) | -| `presenceStyle` | `"default"`, `"meme"`, `"japanese"`, `"minimal"` | Card text preset (default: `"default"`) | -| `updateIntervalMs` | number | Minimum interval between activity updates in milliseconds | -| `debounceMs` | number | Debounce window for bursty playback events in milliseconds | - -Setup steps: - -1. Leave `discordPresence.enabled` as `true` or set it explicitly if you previously disabled it. -2. Optionally set `discordPresence.presenceStyle` to choose a card text preset. -3. Restart SubMiner. - -#### Presence style presets - -While playing media, the **Details** line always shows the current media title and **State** shows `Playing mm:ss / mm:ss` or `Paused mm:ss / mm:ss`. The preset controls what appears when idle and the tooltip text on images. - -| Preset | Idle details | Small image text | Vibe | -| ------------- | ---------------------------------- | ------------------ | --------------------------------------- | -| **`default`** | `Sentence Mining` | `日本語学習中` | Clean, bilingual flair | -| `meme` | `Mining and crafting (Anki cards)` | `Sentence Mining` | Minecraft-inspired joke | -| `japanese` | `文の採掘中` | `イマージョン学習` | Fully Japanese | -| `minimal` | `SubMiner` | _(none)_ | Bare essentials, no small image overlay | - -All presets use the `subminer-logo` large image with `SubMiner` tooltip. No activity button is shown by default. - -Troubleshooting: - -- If the card does not appear, verify Discord desktop app is running. -- If images do not render, confirm asset keys exactly match uploaded Discord asset names. -- If Discord is closed/not installed/disconnects, SubMiner continues running and quietly skips presence updates. +| Key | Default | What it does | +| ---------------------------------- | ----------- | ------------------------------------------------------------------ | +| `discordPresence.enabled` | `true` | Enable rich presence | +| `discordPresence.presenceStyle` | `"default"` | Card text: `default`, `meme`, `japanese` (all Japanese), `minimal` | +| `discordPresence.updateIntervalMs` | `3000` | Minimum ms between updates | +| `discordPresence.debounceMs` | `750` | Debounce for bursts of playback events | ### Immersion tracking -Enable or disable local immersion analytics stored in SQLite for mined subtitles and media sessions. This data also powers the stats dashboard: +Records watch sessions, subtitle lines, and mining in a local SQLite database that feeds the stats dashboard. See [Immersion tracking](/immersion-tracking) for retention and storage details. To turn it off for one run, start with `SUBMINER_DISABLE_IMMERSION_TRACKING=1 subminer`. -```json -{ - "immersionTracking": { - "enabled": true, - "dbPath": "", - "batchSize": 25, - "flushIntervalMs": 500, - "queueCap": 1000, - "payloadCapBytes": 256, - "maintenanceIntervalMs": 86400000, - "retentionMode": "preset", - "retentionPreset": "balanced", - "retention": { - "eventsDays": 0, - "telemetryDays": 0, - "sessionsDays": 0, - "dailyRollupsDays": 0, - "monthlyRollupsDays": 0, - "vacuumIntervalDays": 0 - }, - "lifetimeSummaries": { - "global": true, - "anime": true, - "media": true - } - } -} -``` - -| Option | Values | Description | -| ------------------------------ | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| `immersionTracking.enabled` | `true`, `false` | Enable immersion tracking. Defaults to `true`. | -| `dbPath` | string | Optional SQLite database path. Leave empty to use default app-data path at `<config dir>/immersion.sqlite`. | -| `batchSize` | integer (`1`-`10000`) | Buffered writes per transaction. Default `25`. | -| `flushIntervalMs` | integer (`50`-`60000`) | Maximum queue delay before flush. Default `500ms`. | -| `queueCap` | integer (`100`-`100000`) | In-memory queue cap. Overflow drops oldest writes. Default `1000`. | -| `payloadCapBytes` | integer (`64`-`8192`) | Event payload byte cap before truncation marker. Default `256`. | -| `maintenanceIntervalMs` | integer (`60000`-`604800000`) | Prune + rollup maintenance cadence. Default `86400000` (24h). | -| `retentionMode` | `preset`,`advanced` | Retention mode. `preset` applies `retentionPreset`, `advanced` uses explicit values only. Default `preset`. | -| `retentionPreset` | `minimal`,`balanced`,`deep-history` | Retention preset used when `retentionMode = "preset"`. Default `balanced`. | -| `retention.eventsDays` | integer (`0`-`3650`) | Raw event retention window in days. Default `0` (keep all). | -| `retention.telemetryDays` | integer (`0`-`3650`) | Telemetry retention window in days. Default `0` (keep all). | -| `retention.sessionsDays` | integer (`0`-`3650`) | Session retention window in days. Default `0` (keep all). | -| `retention.dailyRollupsDays` | integer (`0`-`36500`) | Daily rollup retention window. Default `0` (keep all). | -| `retention.monthlyRollupsDays` | integer (`0`-`36500`) | Monthly rollup retention window. Default `0` (keep all). | -| `retention.vacuumIntervalDays` | integer (`0`-`3650`) | Minimum spacing between `VACUUM` passes. `0` disables vacuum. Default `0` (disabled). | -| `lifetimeSummaries.global` | `true`, `false` | Maintain global lifetime stats rows (default: `true`). | -| `lifetimeSummaries.anime` | `true`, `false` | Maintain per-anime lifetime stats rows (default: `true`). | -| `lifetimeSummaries.media` | `true`, `false` | Maintain per-media lifetime stats rows (default: `true`). | - -You can also disable immersion tracking for a single session using: - -```bash -SUBMINER_DISABLE_IMMERSION_TRACKING=1 subminer -``` - -When this is set, SubMiner skips immersion-tracker startup and does not initialize or read the immersion SQLite database for that session. - -Default behavior keeps raw events, telemetry, sessions, and rollups forever while still maintaining lifetime summary tables and daily/monthly rollups for faster reads. If you later want bounded retention, switch `retentionMode` or set explicit `retention.*` values. - -When `dbPath` is blank or omitted, SubMiner writes telemetry and session summaries to the default app-data location: - -```text -<config directory>/immersion.sqlite -``` - -Set `dbPath` only if you want to relocate the database (for backup, syncing, or inspection workflows). The database is created when tracking starts for the first time. - -See [Immersion Tracking Storage](/immersion-tracking) for schema details, query templates, dashboard access, retention/rollup behavior, backend portability notes, and the dedicated SQLite verification command. +| Key | Default | What it does | +| ------------------------------------------------ | ------------ | ----------------------------------------------------------------- | +| `immersionTracking.enabled` | `true` | Enable tracking | +| `immersionTracking.dbPath` | `""` | Database path. Empty uses `immersion.sqlite` in the config folder | +| `immersionTracking.batchSize` | `25` | Writes per transaction | +| `immersionTracking.flushIntervalMs` | `500` | Maximum ms before queued writes are saved | +| `immersionTracking.queueCap` | `1000` | Queue size. The oldest writes drop when full | +| `immersionTracking.payloadCapBytes` | `256` | Maximum event payload size before truncation | +| `immersionTracking.maintenanceIntervalMs` | `86400000` | How often pruning and rollups run (24 h) | +| `immersionTracking.retentionMode` | `"preset"` | `preset` uses `retentionPreset`. `advanced` uses `retention.*` | +| `immersionTracking.retentionPreset` | `"balanced"` | `minimal`, `balanced`, or `deep-history` | +| `immersionTracking.retention.eventsDays` | `0` | Days to keep raw events. `0` keeps everything | +| `immersionTracking.retention.telemetryDays` | `0` | Days to keep telemetry | +| `immersionTracking.retention.sessionsDays` | `0` | Days to keep sessions | +| `immersionTracking.retention.dailyRollupsDays` | `0` | Days to keep daily rollups | +| `immersionTracking.retention.monthlyRollupsDays` | `0` | Days to keep monthly rollups | +| `immersionTracking.retention.vacuumIntervalDays` | `0` | Days between `VACUUM` runs. `0` disables | +| `immersionTracking.lifetimeSummaries.global` | `true` | Keep all-time totals | +| `immersionTracking.lifetimeSummaries.anime` | `true` | Keep per-show totals | +| `immersionTracking.lifetimeSummaries.media` | `true` | Keep per-file totals | ### Stats dashboard -Configure the local stats UI served from SubMiner and the in-app stats overlay toggle: +A local web dashboard at `http://127.0.0.1:<serverPort>`, also available as an overlay inside SubMiner. It reads the immersion tracking database, so tracking must be on. See [Immersion tracking](/immersion-tracking). -```json -{ - "stats": { - "toggleKey": "Backquote", - "markWatchedKey": "KeyW", - "serverPort": 6969, - "autoStartServer": true, - "autoOpenBrowser": false - } -} -``` - -| Option | Values | Description | -| ----------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------- | -| `stats.toggleKey` | Electron key code | Overlay-local key code used to toggle the stats overlay. Default `Backquote`. | -| `markWatchedKey` | Electron key code | Key code to mark the current video as watched and advance to the next playlist entry. Default `KeyW`. | -| `serverPort` | integer | Localhost port for the browser stats UI. Default `6969`. | -| `autoStartServer` | `true`, `false` | Start the local stats HTTP server automatically once immersion tracking is active. Default `true`. | -| `autoOpenBrowser` | `true`, `false` | When `subminer stats` starts the server on demand, also open the dashboard in your default browser. Default `false`. | - -Usage notes: - -- The browser UI is served at `http://127.0.0.1:<serverPort>`. -- The overlay toggle is local to the focused visible overlay window; it is not registered as a global OS shortcut. -- The dashboard reads from the same immersion-tracking database, so keep `immersionTracking.enabled` on if you want data to appear. -- The UI includes Overview, Library, Trends, Vocabulary, Search, and Sessions tabs. +| Key | Default | What it does | +| ----------------------- | ------------- | ------------------------------------------------------------------ | +| `stats.toggleKey` | `"Backquote"` | Key that toggles the stats overlay (overlay focus only) | +| `stats.markWatchedKey` | `"KeyW"` | Key that marks the video watched and plays the next playlist entry | +| `stats.serverPort` | `6969` | Dashboard port | +| `stats.autoStartServer` | `true` | Start the dashboard server once tracking is active | +| `stats.autoOpenBrowser` | `false` | Open the browser when `subminer stats` starts the server | ### MPV launcher -Configure the mpv executable, profile, and window state for SubMiner-managed mpv launches (launcher playback, Windows `--launch-mpv`, and Jellyfin idle mpv startup): +Settings for mpv instances that SubMiner starts, and for the bundled mpv plugin. See [mpv plugin](/mpv-plugin). -```json -{ - "mpv": { - "executablePath": "", - "launchMode": "normal", - "profile": "", - "socketPath": "/tmp/subminer-socket", - "backend": "auto", - "autoStartSubMiner": true, - "pauseUntilOverlayReady": true, - "subminerBinaryPath": "", - "aniskipEnabled": true, - "aniskipButtonKey": "TAB" - } -} -``` - -| Option | Values | Description | -| ------------------------ | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `executablePath` | string | Absolute path to `mpv.exe` for Windows launch flows. Leave empty to auto-discover from `SUBMINER_MPV_PATH` or `PATH` (default `""`) | -| `profile` | string | mpv profile name passed as `--profile=<name>`. Leave empty to pass no profile (default `""`) | -| `launchMode` | `"normal"` \| `"maximized"` \| `"fullscreen"` | Window state when SubMiner spawns mpv (default `"normal"`) | -| `socketPath` | string | mpv IPC socket path used by SubMiner-managed playback and the bundled mpv plugin (platform-dependent default: `/tmp/subminer-socket`, or `\\\\.\\pipe\\subminer-socket` on Windows) | -| `backend` | `"auto"` \| `"hyprland"` \| `"sway"` \| `"x11"` \| `"macos"` \| `"windows"` | Window tracking backend passed to the bundled mpv plugin. Auto detects the current platform (default: `"auto"`) | -| `autoStartSubMiner` | `true`, `false` | Start SubMiner in the background when SubMiner-managed mpv loads a file (default: `true`) | -| `pauseUntilOverlayReady` | `true`, `false` | Pause mpv on visible-overlay auto-start until SubMiner signals subtitle tokenization readiness, with a 30-second fallback (default: `true`) | -| `subminerBinaryPath` | string | SubMiner app binary path passed to the bundled mpv plugin. Leave empty to use the launcher-detected app path (default: `""`) | -| `aniskipEnabled` | `true`, `false` | Enable AniSkip intro detection, chapter markers, and the skip-intro key (default: `true`) | -| `aniskipButtonKey` | string | mpv key used to skip the detected intro while the skip prompt is visible (default: `"TAB"`) | - -If `mpv.profile` is configured and the launcher also receives `--profile`, SubMiner passes both as a comma-separated mpv profile list. - -Launch mode behavior: - -- **`normal`** - mpv opens at its default window size with no extra flags. -- **`maximized`** - mpv starts maximized via `--window-maximized=yes`, keeping taskbar access. -- **`fullscreen`** - mpv starts in true fullscreen via `--fullscreen`. +| Key | Default | What it does | +| ---------------------------- | ----------------- | --------------------------------------------------------------------------- | +| `mpv.executablePath` | `""` | Path to `mpv.exe` on Windows. Empty checks `SUBMINER_MPV_PATH`, then `PATH` | +| `mpv.launchMode` | `"normal"` | Window state: `normal`, `maximized`, or `fullscreen` | +| `mpv.profile` | `""` | mpv profile to pass. Combined with a launcher `--profile` if both are set | +| `mpv.socketPath` | platform-specific | mpv IPC socket. See the warning under [Config file](#configuration-file) | +| `mpv.backend` | `"auto"` | Window tracking: `auto`, `hyprland`, `sway`, `x11`, `macos`, `windows` | +| `mpv.autoStartSubMiner` | `true` | Start SubMiner in the background when mpv loads a file | +| `mpv.pauseUntilOverlayReady` | `true` | Keep mpv paused until subtitles are ready, up to 30 seconds | +| `mpv.subminerBinaryPath` | `""` | SubMiner app path for the plugin. Empty uses the detected path | +| `mpv.aniskipEnabled` | `true` | Detect intros with AniSkip and show a skip prompt | +| `mpv.aniskipButtonKey` | `"TAB"` | mpv key that skips the intro while the prompt is shown | ### YouTube playback settings -Set defaults used by managed subtitle auto-selection and the `subminer` launcher YouTube flow: +Language and card-media settings for YouTube playback. YouTube always loads a Japanese primary and English secondary track, preferring manual uploads over auto captions. See [YouTube integration](/youtube-integration). -```json -{ - "youtube": { - "primarySubLanguages": ["ja", "jpn"], - "mediaCache": { - "mode": "direct", - "maxHeight": 720 - } - } -} -``` +| Key | Default | What it does | +| ------------------------------ | --------------- | -------------------------------------------------------------------------------------------- | +| `youtube.primarySubLanguages` | `["ja", "jpn"]` | Languages that count as a valid primary track, also used for local playback | +| `youtube.mediaCache.mode` | `"direct"` | `direct` cuts card media from the stream. `background` downloads the video with yt-dlp first | +| `youtube.mediaCache.maxHeight` | `720` | Maximum download height in `background` mode. `0` is unlimited | -| Option | Values | Description | -| ---------------------- | ------------------------ | ------------------------------------------------------------------------------------------------ | -| `primarySubLanguages` | string[] | Primary subtitle language priority for managed subtitle auto-selection (default `["ja", "jpn"]`) | -| `mediaCache.mode` | `direct` \| `background` | YouTube card audio/image extraction mode (default `direct`) | -| `mediaCache.maxHeight` | number | Maximum background cache download height. Set `0` for unlimited (default `720`) | - -`mediaCache.mode: "direct"` extracts card media from the active YouTube stream URL. `mediaCache.mode: "background"` starts a separate yt-dlp media download after YouTube playback has loaded, including YouTube URLs opened directly in mpv and resolved stream URLs when mpv still exposes the original YouTube playlist entry. Playback and subtitle loading do not wait for that download. Use background mode if direct card media generation hits YouTube `403` errors from expiring stream URLs. - -Background cache downloads are capped by `mediaCache.maxHeight`, which defaults to 720p; set it to `0` to let yt-dlp choose the best available height. Downloads use IPv4 and yt-dlp retry flags to reduce YouTube throttling failures. SubMiner announces when the background cache download starts and when the cache is ready, using the configured notification surface; overlay and OSD messages queue until the overlay or mpv is ready. If you mine cards before the cache is ready, SubMiner creates the text fields immediately, queues the audio/image work for those note IDs, shows a status notification, and fills the media fields once the cached file is ready. If the cache download fails, SubMiner shows a failure notification, shows queued-card failure notifications, and clears the pending updates. - -Current launcher behavior: - -- For YouTube URLs, SubMiner probes subtitle tracks with yt-dlp after mpv bootstrap and binds auto-selected tracks before normal playback resumes. -- If YouTube/mpv already exposes an authoritative matching subtitle track, SubMiner reuses it; otherwise it downloads and injects only the missing side. -- SubMiner loads the primary subtitle plus a best-effort secondary subtitle. -- Playback waits only for primary subtitle readiness; secondary failures do not block playback. -- Native mpv secondary subtitle rendering stays hidden during this flow so the SubMiner overlay remains the visible secondary subtitle surface. -- If primary subtitle loading fails, use `Ctrl+Alt+C` to open the subtitle modal and pick a track. - -Track selection: - -- YouTube auto-selection always targets a Japanese primary track and an English secondary track, preferring manual uploads over auto-generated captions. -- `youtube.primarySubLanguages` (default `["ja","jpn"]`) defines which loaded track counts as a satisfactory primary for the "primary subtitle missing" notification and for managed local/playlist subtitle selection. -- Local playback applies these priorities after mpv reports subtitle track metadata, so sidecar/internal mixed sets can override an incorrect initial `sid=auto` pick. -- Tracks are resolved and loaded before mpv starts; the older launcher mode switch has been removed. - -These settings come from `config.jsonc` (or built-in defaults); there are no CLI flags or environment variables for subtitle language selection. - -#### YouTube subtitle generation (`youtubeSubgen`) - -An advanced, template-hidden section for Whisper-based YouTube subtitle generation: `whisperBin`, `whisperModel`, `whisperVadModel`, and `whisperThreads` (default `4`). These keys are accepted in `config.jsonc` but the generated template omits them. +Use `background` if card media fails with YouTube `403` errors. Cards mined before the download finishes get their text right away and their audio and image once the file is ready. diff --git a/docs-site/demos.md b/docs-site/demos.md index c947fb40..667e1a90 100644 --- a/docs-site/demos.md +++ b/docs-site/demos.md @@ -2,7 +2,7 @@ Short recordings from real playback sessions. -Some vocabulary for what follows. _Yomitan_ is the pop-up dictionary. _Jimaku_ is a community subtitle database. _alass_ and _ffsubsync_ retime subtitles against the audio. _Jellyfin_ is a self-hosted media server. A _texthooker_ is a web page that mirrors the current subtitle as selectable text so browser tools can read it. +_Yomitan_ is the pop-up dictionary. _Jimaku_ is a community subtitle database. _alass_ and _ffsubsync_ retime subtitles against the audio. _Jellyfin_ is a self-hosted media server. A _texthooker_ is a web page that mirrors the current subtitle as selectable text. <script setup> import { withBase } from 'vitepress'; @@ -18,7 +18,7 @@ Mine a card from Yomitan or straight from a subtitle line. SubMiner attaches the <source :src="withBase(`/assets/minecard.webm?v=${v}`)" type="video/webm" /> <source :src="withBase(`/assets/minecard.mp4?v=${v}`)" type="video/mp4" /> <a :href="withBase(`/assets/minecard.webm?v=${v}`)" target="_blank" rel="noreferrer"> - <img :src="withBase(`/assets/minecard.webp?v=${v}`)" alt="SubMiner demo Animated fallback" style="width: 100%; height: auto;" /> + <img :src="withBase(`/assets/minecard.webp?v=${v}`)" alt="Animated demo of mining a card" style="width: 100%; height: auto;" /> </a> </video> @@ -36,7 +36,7 @@ Search Jimaku, download a track, then retime it with alass or ffsubsync without ## Jellyfin integration -Browse your Jellyfin library, cast to a device, and start playback from SubMiner. Watch progress goes back to the Jellyfin server. +Browse your Jellyfin library and play from SubMiner, or cast to SubMiner from another Jellyfin client. Watch progress syncs back to the server. <!-- <video controls playsinline preload="metadata" :poster="withBase(`/assets/demos/jellyfin-poster.jpg?v=${v}`)"> <source :src="withBase(`/assets/demos/jellyfin.webm?v=${v}`)" type="video/webm" /> diff --git a/docs-site/development.md b/docs-site/development.md index 71a7a793..87f7538b 100644 --- a/docs-site/development.md +++ b/docs-site/development.md @@ -1,12 +1,12 @@ # Building and testing -Architecture and workflow guidance lives in `docs/README.md` at the repo root. This page covers build and test commands only. +Build, run, and test SubMiner from source. Architecture and workflow rules live in the repo's internal docs, starting at [`docs/README.md`](https://github.com/ksyasuda/SubMiner/blob/main/docs/README.md). Module boundaries and layering rules are in [`docs/architecture/README.md`](https://github.com/ksyasuda/SubMiner/blob/main/docs/architecture/README.md). The lane-by-lane test guide is [`docs/workflow/verification.md`](https://github.com/ksyasuda/SubMiner/blob/main/docs/workflow/verification.md). ## Prerequisites -- [Bun](https://bun.sh) -- A system `lua` interpreter for `bun run test:launcher` / `bun run test:plugin:src` -- macOS builds compile a Swift helper via `scripts/prepare-build-assets.mjs` (skip with `SUBMINER_SKIP_MACOS_HELPER_BUILD=1`) +- [Bun](https://bun.sh), at the version pinned in `package.json` +- A system `lua` interpreter for the mpv plugin tests (`bun run test:launcher`, `bun run test:env`) +- macOS only: `bun run build` compiles a Swift window helper. Set `SUBMINER_SKIP_MACOS_HELPER_BUILD=1` to skip it. ## Setup @@ -16,36 +16,20 @@ cd SubMiner make deps ``` -`make deps` initializes submodules and installs root, `stats/`, and `vendor/texthooker-ui` dependencies. The Yomitan submodule installs its own dependencies on demand during `bun run build`. +`make deps` initializes submodules and installs dependencies for the root, `stats/`, and `vendor/texthooker-ui`. The Yomitan submodule installs its own dependencies during `bun run build`. -## Building +## Build ```bash -# Main app build -bun run build - -# Platform packages +bun run build # app build, including bundled Yomitan from vendor/subminer-yomitan bun run build:appimage # Linux AppImage bun run build:mac # macOS DMG + ZIP (signed) bun run build:mac:unsigned # macOS DMG + ZIP (unsigned) bun run build:win # Windows NSIS installer + ZIP - -# Optional launcher artifact only -make build-launcher -# output: dist/launcher/subminer +make build-launcher # launcher only, output: dist/launcher/subminer ``` -`bun run build` includes the Yomitan build step. It builds the bundled Chrome extension directly from the `vendor/subminer-yomitan` submodule into `build/yomitan` using Bun. - -## Launcher artifact workflow - -- Source of truth: `launcher/*.ts` -- Generated output: `dist/launcher/subminer` -- Do not hand-edit generated launcher output. -- Repo-root `./subminer` is a stale artifact path and is rejected by verification checks. -- Install targets (`make install-linux`, `make install-macos`) copy from `dist/launcher/subminer`. - -Verify the workflow: +The launcher source is `launcher/*.ts`. `dist/launcher/subminer` is generated, so never edit it by hand. The repo-root `./subminer` is a stale path and verification rejects it. `make install-linux` and `make install-macos` copy from `dist/launcher/subminer`. To check the launcher build: ```bash make build-launcher @@ -53,20 +37,17 @@ dist/launcher/subminer --help >/dev/null bash scripts/verify-generated-launcher.sh ``` -## Running locally +## Run locally ```bash -bun run dev # builds + launches with --start --dev -electron . --start --dev --log-level debug # equivalent Electron launch with verbose logging -electron . --background # tray/background mode, minimal default logging -make dev-start # build + launch via Makefile -make dev-watch # watch TS + renderer and launch Electron (faster edit loop) -make dev-watch-macos # same as dev-watch, forcing --backend macos +bun run dev # build, then launch with --start --dev +make dev-watch # watch TS + renderer and relaunch Electron +make dev-watch-macos # same, forcing --backend macos +electron . --start --dev --log-level debug # verbose launch of an existing build +electron . --background # tray/background mode ``` -For mpv-plugin-driven testing without exporting `SUBMINER_BINARY_PATH` each run, set a one-time -dev binary path with `mpv.subminerBinaryPath` in your SubMiner config. The launcher injects it into -the mpv plugin at runtime: +To test through the mpv plugin without exporting `SUBMINER_BINARY_PATH` each time, point `mpv.subminerBinaryPath` in your config at the dev script. The launcher passes it to the plugin at runtime: ```json { @@ -76,35 +57,9 @@ the mpv plugin at runtime: } ``` -## Testing +## Test -Default lanes: - -```bash -bun run test # alias for test:fast -bun run test:fast # full source lanes: src + launcher-unit + scripts + runtime compat -bun run test:runtime:compat # compiled/runtime compatibility slice only -bun run test:env # launcher/plugin + env-sensitive verification -bun run test:stats # stats dashboard UI suite -bun run test:immersion:sqlite # SQLite persistence lane -bun run test:subtitle # maintained alass/ffsubsync subtitle surface -``` - -Test lane membership is defined once in `scripts/test-lanes.ts` and discovered by -directory, so new test files join their lane automatically. `scripts/run-test-lane.mjs` -runs each test file in its own `bun test` process (per-file isolation) so a hanging -test or leaked global in one file cannot cascade into the rest of the lane; pass -`--jobs N` to parallelize or `--single-process` for one shared process. - -- `bun run test` and `bun run test:fast` cover the full discovered `src/**` suite, launcher unit tests, `scripts/**` tests, and the compiled/runtime compatibility lane. -- `bun run test:runtime:compat` covers the compiled/runtime slice directly: `ipc`, `anki-jimaku-ipc`, `overlay-manager`, `config-validation`, `startup-config`, and `registry`. -- `bun run test:env` covers environment-sensitive checks: launcher smoke/plugin verification plus the Bun source SQLite lane. -- `bun run test:stats` runs the stats dashboard suite under `stats/src/**`. -- `bun run test:immersion:sqlite` is the reproducible persistence lane when you need real DB-backed SQLite coverage under Bun. - -The Bun-managed discovery lanes intentionally exclude a small compiled/runtime-focused set: `src/core/services/ipc.test.ts`, `src/core/services/anki-jimaku-ipc.test.ts`, `src/core/services/overlay-manager.test.ts`, `src/main/config-validation.test.ts`, `src/main/runtime/startup-config.test.ts`, and `src/main/runtime/registry.test.ts`. `bun run test:runtime:compat` keeps them in the standard workflow via `dist/**`. - -Suggested local gate before handoff: +Run the handoff gate before submitting substantial changes: ```bash bun run typecheck @@ -114,133 +69,111 @@ bun run build bun run test:smoke:dist ``` -If you changed docs in `docs-site/`, also run: +For smaller changes, start with the cheapest lane that covers what you touched: + +| Command | Covers | +| ------------------------------- | ------------------------------------------------------------------------ | +| `bun run test` / `test:fast` | All `src/**` tests, launcher unit tests, and `scripts/**` tests | +| `bun run test:config` | Config schema, defaults, and `config.example.jsonc` generation | +| `bun run test:launcher` | Launcher tests plus the Lua plugin tests | +| `bun run test:env` | Launcher e2e smoke, Lua plugin tests, SQLite immersion tests from source | +| `bun run test:scripts` | Build and release scripts under `scripts/**` | +| `bun run test:stats` | Stats dashboard UI under `stats/src/**` | +| `bun run test:runtime:compat` | Compiled-runtime smoke against `dist/` (run `bun run build` first) | +| `bun run test:immersion:sqlite` | Compiles, then runs the SQLite-backed immersion tracker tests | +| `bun run test:subtitle` | alass/ffsubsync subtitle sync | +| `bun run test:docs:kb` | Internal docs, `AGENTS.md`, and repo skills | + +Lane membership is defined in `scripts/test-lanes.ts` and discovered by directory, so a new test file joins its lane automatically. Do not hand-list test files in `package.json`. `scripts/run-test-lane.mjs` runs each file in its own `bun test` process, so a hanging test cannot take down the rest of the lane. Pass `--jobs N` to parallelize or `--single-process` to share one process while debugging. + +Launcher smoke artifacts go to `.tmp/launcher-smoke`. CI uploads them when the smoke step fails. + +## Format ```bash -bun run docs:test -bun run docs:build +make pretty # format the maintained source and stats files +bun run format:check:src # check the same set without writing ``` -For production docs routing, run the versioned build: +`bun run format` runs Prettier over the whole repo. Use it only when you mean to. + +## Config generation + +```bash +bun run electron . --generate-config # write a default config to ~/.config/SubMiner/config.jsonc (%APPDATA%\SubMiner\config.jsonc on Windows) +bun run generate:config-example # regenerate config.example.jsonc from the defaults +``` + +`make generate-config` and `make generate-example-config` wrap the same commands. + +Config definitions are split by domain under `src/config/definitions/`: + +- defaults: `defaults-*.ts` +- option metadata: `options-*.ts` +- generated template sections and comments: `template-sections.ts` + +`src/config/definitions.ts` composes them into the public API (`DEFAULT_CONFIG`, registries, template export). A new key also needs a resolver entry under `src/config/resolve/`, or the resolved config keeps the default. + +## Documentation site + +The user docs live in `docs-site/` (VitePress). + +```bash +bun --cwd docs-site install +bun run docs:dev # dev server at http://localhost:5173 +bun run docs:test # docs regression tests (links, pinned strings) +bun run docs:build # production build into docs-site/.vitepress/dist +bun run docs:preview # preview the build at http://localhost:4173 +``` + +Run `bun run docs:test` and `bun run docs:build` whenever you change `docs-site/`. + +Production uses the versioned build: ```bash bun run docs:build:versioned ``` -The versioned build writes `.tmp/docs-versioned-site` with latest stable docs at `/`, development docs at `/main/`, and stable archives under `/v/<version>/`. Prerelease tags are skipped. Public assets from `docs-site/public/assets` are shared from root `/assets/` so large demo media is not duplicated into every version archive; generated VitePress CSS and JS assets stay under each version route. Stale `.tmp/docs-versioned-archive-cache` generations are pruned after a successful build, and intermediate `.tmp/docs-versioned-build` workspaces are removed. +It writes `.tmp/docs-versioned-site`: the latest stable docs at `/` with a generated `/versions` page, and development docs at `/main/`. Prerelease tags are skipped. Stable archives under `/v/<version>/` are built once and stored in R2. Without R2 credentials the build skips archive sync, so a local run only produces `/` and `/main/`. -Focused commands: +The `docs-pages` GitHub Actions workflow uploads that output to Cloudflare Pages with Wrangler. Cloudflare's Git-integration builds are disabled on purpose, so do not re-enable them in the dashboard. `docs-site/README.md` has the full deployment setup. -```bash -bun run test:config # Source-level config schema/validation tests -bun run test:launcher # Launcher regression tests (config discovery + command routing) -bun run test:launcher:smoke:src # Launcher e2e smoke: launcher -> mpv IPC -> overlay start/stop wiring -bun run test:env # Launcher smoke + Lua plugin gate -bun run test:src # Bun-managed maintained src/** discovery lane -bun run test:launcher:unit:src # Bun-managed maintained launcher unit lane -bun run test:scripts # Bun-managed scripts/** test lane -bun run test:immersion:sqlite:src # Bun source lane -``` +## Makefile targets -Dist-level tests are now an explicit smoke lane used to validate compiled/runtime assumptions. +Run `make help` for the full list. -Launcher smoke artifacts are written to `.tmp/launcher-smoke` locally and uploaded by CI/release workflows when the smoke step fails. - -Smoke and optional deep dist commands: - -```bash -bun run build # compile dist artifacts -bun run test:immersion:sqlite # compile + run SQLite-backed immersion tests under Bun -bun run test:smoke:dist # explicit smoke scope for compiled runtime -``` - -Use `bun run test:immersion:sqlite` when you need real DB-backed coverage for the immersion tracker. - -## Formatting - -Use the scoped formatter for normal app-repo work: - -```bash -make pretty -bun run format:check:src -``` - -- `make pretty` runs the maintained Prettier allowlists (`format:src` and `format:stats`). -- `bun run format:check:src` checks the same scoped set without writing changes. -- `bun run format` remains the broad repo-wide Prettier command; use it intentionally. - -## Config generation - -```bash -# Generate default config to ~/.config/SubMiner/config.jsonc (or %APPDATA%\SubMiner\config.jsonc on Windows) -bun run electron . --generate-config - -# Regenerate the repo's config.example.jsonc from centralized defaults -bun run generate:config-example -``` - -Convenience wrappers still exist: - -- `make generate-config` -- `make generate-example-config` - -## Documentation site - -The docs site now lives in `docs-site/` inside the main repo. - -From the SubMiner app repo: - -```bash -bun --cwd docs-site install -bun run docs:dev # Dev server at http://localhost:5173 -bun run docs:build # Production build into docs-site/.vitepress/dist -bun run docs:preview # Preview built site at http://localhost:4173 -bun run docs:test # Docs regression tests -``` - -Deployment: production docs are built with `bun run docs:build:versioned` and uploaded directly to Cloudflare Pages by the `docs-pages` GitHub Actions workflow using Wrangler (from `.tmp/docs-versioned-site`). Cloudflare's automatic Git-integration deployments are intentionally disabled - see `docs-site/README.md` for the deployment contract. Do not re-enable Pages build settings in the Cloudflare dashboard. - -## Makefile reference - -Run `make help` for a full list of targets. Key ones: - -| Target | Description | -| --------------------------- | ----------------------------------------------------------------- | -| `make build` | Build platform package for detected OS | -| `make build-launcher` | Generate launcher wrappers and CLI payload in `dist/launcher/` | -| `make install` | Install platform artifacts (wrapper, theme, AppImage/app bundle) | -| `make deps` | Init submodules and install root/stats/texthooker-ui deps | -| `make pretty` | Run scoped Prettier formatting for maintained source/config files | -| `make generate-config` | Generate default config from centralized registry | -| `make build-linux` | Convenience wrapper for Linux packaging | -| `make build-macos` | Convenience wrapper for signed macOS packaging | -| `make build-macos-unsigned` | Convenience wrapper for unsigned macOS packaging | +| Target | Description | +| --------------------------- | ------------------------------------------------------------ | +| `make deps` | Init submodules and install root, stats, and texthooker deps | +| `make build` | Build the platform package for the current OS | +| `make build-linux` | Build the Linux package | +| `make build-macos` | Build the signed macOS package | +| `make build-macos-unsigned` | Build the unsigned macOS package | +| `make build-launcher` | Generate the launcher in `dist/launcher/` | +| `make install` | Install platform artifacts (wrapper, theme, AppImage or app) | +| `make pretty` | Run scoped Prettier formatting | +| `make generate-config` | Generate a default config | ## Contributor notes -- To add/change a config default, edit the matching domain file in `src/config/definitions/defaults-*.ts`. -- To add/change config option metadata, edit the matching domain file in `src/config/definitions/options-*.ts`. -- To add/change generated config template blocks/comments, update `src/config/definitions/template-sections.ts`. -- Keep `src/config/definitions.ts` as the composed public API (`DEFAULT_CONFIG`, registries, template export) that wires domain modules together. -- Overlay window/visibility state is owned by `src/core/services/overlay-manager.ts`. -- Runtime architecture/module-boundary conventions are summarized in [Architecture](/architecture), with canonical internal guidance in `docs/architecture/README.md` at the repo root. -- Linux packaged desktop launches pass `--background` using electron-builder `build.linux.executableArgs` in `package.json`. -- Prefer direct inline deps objects in `src/main/` modules for simple pass-through wiring. -- Add a helper/adapter service only when it performs meaningful adaptation, validation, or reuse (not identity mapping). +- See [Architecture](/architecture) for module boundaries and [IPC + runtime contracts](/ipc-contracts) before adding IPC channels. +- `src/core/services/overlay-manager.ts` owns overlay window and visibility state. +- In `src/main/` modules, pass simple dependencies as inline objects. Add a helper or adapter only when it adapts, validates, or gets reused. +- Packaged Linux desktop launches pass `--background` through `build.linux.executableArgs` in `package.json`. ## Environment variables -| Variable | Description | -| ---------------------------------- | ------------------------------------------------------------------------------ | -| `SUBMINER_APPIMAGE_PATH` | Override SubMiner app binary path for launcher playback commands | -| `SUBMINER_BINARY_PATH` | Alias for `SUBMINER_APPIMAGE_PATH` | -| `SUBMINER_ROFI_THEME` | Override rofi theme path for launcher picker | -| `SUBMINER_MPV_PLUGIN_PATH` | Override the mpv plugin directory injected by the launcher | -| `SUBMINER_LOG_LEVEL` | Override app logger level (`debug`, `info`, `warn`, `error`) | -| `SUBMINER_MPV_LOG` | Override mpv/app shared log file path | -| `SUBMINER_JIMAKU_API_KEY` | Override Jimaku API key for launcher subtitle downloads | -| `SUBMINER_JIMAKU_API_KEY_COMMAND` | Command used to resolve Jimaku API key at runtime | -| `SUBMINER_JIMAKU_API_BASE_URL` | Override Jimaku API base URL | -| `SUBMINER_JELLYFIN_ACCESS_TOKEN` | Override Jellyfin access token (used before stored encrypted session fallback) | -| `SUBMINER_JELLYFIN_USER_ID` | Optional Jellyfin user ID override | -| `SUBMINER_SKIP_MACOS_HELPER_BUILD` | Set to `1` to skip building the macOS helper binary during `bun run build` | +| Variable | Description | +| ---------------------------------- | ---------------------------------------------------------------- | +| `SUBMINER_APPIMAGE_PATH` | SubMiner app binary the launcher uses for playback | +| `SUBMINER_BINARY_PATH` | Alias for `SUBMINER_APPIMAGE_PATH` | +| `SUBMINER_ROFI_THEME` | rofi theme for the launcher picker | +| `SUBMINER_MPV_PLUGIN_PATH` | mpv plugin directory the launcher injects | +| `SUBMINER_LOG_LEVEL` | App log level (`debug`, `info`, `warn`, `error`) | +| `SUBMINER_MPV_LOG` | Shared mpv/app log file path | +| `SUBMINER_JIMAKU_API_KEY` | Jimaku API key for launcher subtitle downloads | +| `SUBMINER_JIMAKU_API_KEY_COMMAND` | Command that prints the Jimaku API key | +| `SUBMINER_JIMAKU_API_BASE_URL` | Jimaku API base URL | +| `SUBMINER_JELLYFIN_ACCESS_TOKEN` | Jellyfin access token, used before the stored encrypted session | +| `SUBMINER_JELLYFIN_USER_ID` | Jellyfin user ID | +| `SUBMINER_SKIP_MACOS_HELPER_BUILD` | Set to `1` to skip the macOS helper build during `bun run build` | diff --git a/docs-site/docs-sync.test.ts b/docs-site/docs-sync.test.ts index 35e8e2a1..89065610 100644 --- a/docs-site/docs-sync.test.ts +++ b/docs-site/docs-sync.test.ts @@ -8,7 +8,6 @@ const installationContents = readFileSync(new URL('./installation.md', import.me const mpvPluginContents = readFileSync(new URL('./mpv-plugin.md', import.meta.url), 'utf8'); const developmentContents = readFileSync(new URL('./development.md', import.meta.url), 'utf8'); const changelogContents = readFileSync(new URL('./changelog.md', import.meta.url), 'utf8'); -const docsPackageContents = readFileSync(new URL('./package.json', import.meta.url), 'utf8'); const ankiIntegrationContents = readFileSync( new URL('./anki-integration.md', import.meta.url), 'utf8', @@ -101,15 +100,6 @@ test('docs state the real secondary-subtitle and Anki field-matching behavior', expect(ankiIntegrationContents).toContain('case-insensitively'); }); -test('docs dev server links version navigation to local dev routes', () => { - expect(docsPackageContents).toContain('scripts/build-versioned-docs.ts'); - expect(docsPackageContents).toContain( - 'SUBMINER_DOCS_VERSION_LINK_ORIGIN=local bun run ../scripts/build-versioned-docs.ts', - ); - expect(docsPackageContents).toContain('SUBMINER_DOCS_VERSION_LINK_ORIGIN=local'); - expect(docsPackageContents).toContain('SUBMINER_DOCS_VERSION_MANIFEST'); -}); - test('docs changelog keeps the current minor release headings aligned with the root changelog', () => { const docsHeadings = extractCurrentMinorHeadings(changelogContents); expect(docsHeadings.length).toBeGreaterThan(0); diff --git a/docs-site/functions/v/[[path]].ts b/docs-site/functions/v/[[path]].ts new file mode 100644 index 00000000..11ff5e7a --- /dev/null +++ b/docs-site/functions/v/[[path]].ts @@ -0,0 +1,212 @@ +// Cloudflare Pages Function serving frozen `/v/<version>/` doc archives from R2. +// Archives are uploaded by scripts/build-versioned-docs.ts and never ship in the Pages +// deployment itself, so they do not count toward the Pages file limit. Requires an R2 +// binding named DOCS_ARCHIVES on the Pages project (see docs-site/README.md). + +// Minimal slice of the Workers R2 API used here; avoids a workers-types dependency. +type R2Range = { offset: number; length?: number } | { suffix: number }; + +type R2ObjectMeta = { + size: number; + httpEtag: string; + range?: R2Range; +}; + +type R2ObjectBody = R2ObjectMeta & { body: ReadableStream }; + +type R2GetOptions = { range?: Headers; onlyIf?: Headers }; + +export type ArchiveBucket = { + get(key: string, options?: R2GetOptions): Promise<R2ObjectMeta | R2ObjectBody | null>; +}; + +type ArchiveContext = { + request: Request; + env: { DOCS_ARCHIVES: ArchiveBucket }; +}; + +export type ArchiveRoute = + | { kind: 'redirect'; location: string; status: 301 | 302 } + | { kind: 'lookup'; version: string; keys: string[] } + | { kind: 'not-found' }; + +const CONTENT_TYPES: Record<string, string> = { + css: 'text/css; charset=utf-8', + gif: 'image/gif', + html: 'text/html; charset=utf-8', + ico: 'image/x-icon', + jpeg: 'image/jpeg', + jpg: 'image/jpeg', + js: 'text/javascript; charset=utf-8', + json: 'application/json; charset=utf-8', + jsonc: 'application/json; charset=utf-8', + mjs: 'text/javascript; charset=utf-8', + mkv: 'video/x-matroska', + mp4: 'video/mp4', + png: 'image/png', + svg: 'image/svg+xml', + ttf: 'font/ttf', + txt: 'text/plain; charset=utf-8', + webm: 'video/webm', + webp: 'image/webp', + woff: 'font/woff', + woff2: 'font/woff2', + xml: 'application/xml; charset=utf-8', +}; + +function extensionOf(path: string): string | null { + const name = path.slice(path.lastIndexOf('/') + 1); + const dot = name.lastIndexOf('.'); + return dot > 0 ? name.slice(dot + 1).toLowerCase() : null; +} + +function contentTypeFor(key: string): string { + return CONTENT_TYPES[extensionOf(key) ?? ''] ?? 'application/octet-stream'; +} + +// Maps a request path onto candidate R2 keys, mirroring the Pages clean-URL rules the +// archives were built for (`cleanUrls: true`). +export function resolveArchiveRoute(pathname: string, search = ''): ArchiveRoute { + if (pathname === '/v' || pathname === '/v/') { + return { kind: 'redirect', location: '/versions', status: 302 }; + } + + const match = /^\/v\/(\d+\.\d+\.\d+)(\/.*)?$/.exec(pathname); + if (!match) return { kind: 'not-found' }; + + const version = match[1]!; + const rest = match[2]; + if (!rest) { + return { kind: 'redirect', location: `/v/${version}/${search}`, status: 301 }; + } + + let decoded: string; + try { + decoded = decodeURIComponent(rest); + } catch { + return { kind: 'not-found' }; + } + if (decoded.split('/').some((segment) => segment === '..' || segment === '.')) { + return { kind: 'not-found' }; + } + + const prefix = `v/${version}`; + const path = `${prefix}${decoded}`; + const keys = decoded.endsWith('/') + ? [`${path}index.html`] + : extensionOf(decoded) + ? [path] + : [`${path}.html`, `${path}/index.html`]; + + return { kind: 'lookup', version, keys }; +} + +function cacheControlFor(key: string): string { + // VitePress content-hashes everything it emits under assets/. + if (/\/assets\//.test(key) && extensionOf(key) !== 'html') { + return 'public, max-age=31536000, immutable'; + } + return 'public, max-age=3600'; +} + +function hasBody(object: R2ObjectMeta | R2ObjectBody): object is R2ObjectBody { + return 'body' in object && object.body !== undefined; +} + +function contentRange(range: R2Range, size: number): { start: number; end: number } { + if ('suffix' in range) { + const length = Math.min(range.suffix, size); + return { start: size - length, end: size - 1 }; + } + const length = range.length ?? size - range.offset; + return { start: range.offset, end: range.offset + length - 1 }; +} + +async function respondWithObject(options: { + request: Request; + bucket: ArchiveBucket; + key: string; + status: number; +}): Promise<Response | null> { + const { request, bucket, key } = options; + // Ranges and conditional requests only make sense for the page that was asked for, + // not the 404 fallback. + const isRequestedObject = options.status === 200; + const wantsRange = isRequestedObject && request.headers.has('range'); + + let object: R2ObjectMeta | R2ObjectBody | null; + try { + object = await bucket.get(key, { + range: wantsRange ? request.headers : undefined, + onlyIf: isRequestedObject ? request.headers : undefined, + }); + } catch { + // R2 rejects unsatisfiable ranges. + return new Response(null, { status: 416 }); + } + if (!object) return null; + + const headers = new Headers({ + 'Content-Type': contentTypeFor(key), + 'Cache-Control': cacheControlFor(key), + ETag: object.httpEtag, + 'Accept-Ranges': 'bytes', + 'X-Robots-Tag': 'noindex, follow', + }); + + // R2 returns the object without a body when an If-None-Match/If-Modified-Since + // precondition matched. + if (!hasBody(object)) { + return new Response(null, { status: 304, headers }); + } + + let status = options.status; + if (wantsRange && object.range) { + const { start, end } = contentRange(object.range, object.size); + status = 206; + headers.set('Content-Range', `bytes ${start}-${end}/${object.size}`); + headers.set('Content-Length', String(end - start + 1)); + } else { + headers.set('Content-Length', String(object.size)); + } + + return new Response(request.method === 'HEAD' ? null : object.body, { status, headers }); +} + +export async function onRequest({ request, env }: ArchiveContext): Promise<Response> { + if (request.method !== 'GET' && request.method !== 'HEAD') { + return new Response('Method Not Allowed', { status: 405, headers: { Allow: 'GET, HEAD' } }); + } + + const url = new URL(request.url); + const route = resolveArchiveRoute(url.pathname, url.search); + + if (route.kind === 'redirect') { + return Response.redirect(new URL(route.location, url).toString(), route.status); + } + + if (route.kind === 'lookup') { + for (const key of route.keys) { + const response = await respondWithObject({ + request, + bucket: env.DOCS_ARCHIVES, + key, + status: 200, + }); + if (response) return response; + } + + const notFoundPage = await respondWithObject({ + request, + bucket: env.DOCS_ARCHIVES, + key: `v/${route.version}/404.html`, + status: 404, + }); + if (notFoundPage) return notFoundPage; + } + + return new Response('Not Found', { + status: 404, + headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex, follow' }, + }); +} diff --git a/docs-site/immersion-tracking.md b/docs-site/immersion-tracking.md index 46d616ea..dce70d03 100644 --- a/docs-site/immersion-tracking.md +++ b/docs-site/immersion-tracking.md @@ -1,18 +1,19 @@ # Immersion tracking -SubMiner logs your watching and mining activity to a local SQLite database and shows it in the built-in stats dashboard. Tracking is on by default; turn it off if you would rather not keep the data. +SubMiner records what you watch and mine in a local SQLite database and shows it in a stats dashboard. Tracking is on by default. Nothing leaves your machine. -"Immersion" here means time spent watching and reading native Japanese content. **All of it stays on your machine.** Nothing is uploaded anywhere. SQLite is a single file on disk, so there is no database server to install or run. +## What gets tracked -Each session records watch time, subtitle lines seen, words encountered, and cards mined. SubMiner also keeps exact lifetime summary tables and daily and monthly rollups. Read it through the stats UI, or point any SQLite tool at the file. +- Watch sessions: time watched, subtitle lines seen, words seen, cards mined, pauses and seeks. +- Every primary subtitle line you see, with its timing, so you can search and mine from it later. +- Vocabulary and kanji you encounter, with how often and where. +- Library entries per show and episode, with cover art from AniList (or TMDB for live action) and YouTube channel metadata. -::: tip For most users -Leave tracking on and use the [Stats Dashboard](#stats-dashboard). The retention, performance, SQL, and schema sections below are reference material for querying or tuning the database yourself. Skip them. -::: +An episode counts as watched once you reach 85% of it. -Episode completion for local `watched` state uses the shared `DEFAULT_MIN_WATCH_RATIO` (`85%`) value from `src/shared/watch-threshold.ts`. +## Setup -## Enabling +Tracking needs no setup. To turn it off or move the database: ```jsonc { @@ -23,382 +24,104 @@ Episode completion for local `watched` state uses the shared `DEFAULT_MIN_WATCH_ } ``` -- Leave `dbPath` empty to use the default location (`immersion.sqlite` in SubMiner's app-data directory). -- Set an explicit path to move the database (useful for backups, cloud syncing, or external tools). -- To share stats and watch history between two machines, use [`subminer sync <host>`](/launcher-script#sync-between-machines) instead of file-level cloud sync. It merges both databases instead of letting one side overwrite the other. +An empty `dbPath` stores `immersion.sqlite` in SubMiner's config directory (`~/.config/SubMiner/` on Linux). Set a path to keep it elsewhere. + +To share stats and watch history between machines, use [`subminer sync <host>`](/launcher-script#sync-between-machines). It merges both databases. Copying the file with a cloud sync tool makes one side overwrite the other. + +## Open the dashboard + +- In the overlay: focus it and press the `stats.toggleKey` key (Backquote by default). +- In a browser: run `subminer stats`, then open `http://127.0.0.1:6969` (or your `stats.serverPort`). Set `stats.autoOpenBrowser` to open it automatically. +- Background server: `subminer stats -b` starts a stats server that keeps running without the launcher attached. `subminer stats -s` stops it. You can still start SubMiner for playback while it runs. + +`subminer stats` fails if `immersionTracking.enabled` is `false`. The server only answers on localhost, so reverse proxies and Tailscale Serve URLs do not work. ## Stats dashboard -The same immersion data powers the stats dashboard. +### Overview -The browser dashboard and in-app stats overlay both load from the local HTTP server. -The server accepts loopback hosts only and rejects requests from other browser origins, -including opaque origins such as `file://`. API clients without a browser origin can -still use the local API. Mutation requests with a body must use `application/json`; -bodyless deletion and Anki browse requests remain supported. Requests rejected by the -host or origin checks receive `403`; mutation bodies without a JSON content type -receive `415`. - -Use the loopback dashboard URL directly. Reverse-proxied dashboards and Tailscale -Serve URLs are unsupported because their host or browser origin is not the local -server's origin. SSH stats synchronization is unchanged. - -Scripts sending a JSON body must include the content type. For example, this -requests a duplicate-line cleanup preview without changing the database. Replace -the port if you configured a different `stats.serverPort`: - -```bash -curl http://127.0.0.1:6969/api/stats/maintenance/duplicate-lines \ - -H 'Content-Type: application/json' \ - -d '{"dryRun":true}' -``` - -- In-app overlay: focus the visible overlay, then press the key from `stats.toggleKey` (default: `` ` `` / `Backquote`). -- Launcher command: run `subminer stats` to start the local stats server on demand (it also opens the dashboard in your browser when `stats.autoOpenBrowser` is enabled; the default is `false`). -- Background server: run `subminer stats -b` to start or reuse a dedicated background stats daemon without keeping the launcher attached, and `subminer stats -s` to stop that daemon. -- Maintenance commands: run `subminer stats cleanup` or `subminer stats cleanup -v` to backfill/repair vocabulary metadata (`headword`, `reading`, POS) and purge stale or excluded rows from `imm_words` on demand; `subminer stats cleanup -l` repairs lifetime summary tables non-destructively (recomputed from per-episode history, so lifetime totals older than the session retention window are kept); `subminer stats cleanup --duplicate-lines` collapses repeated lines left behind by typeset subtitles (see [Repeated Line Cleanup](#repeated-line-cleanup)). `subminer stats rebuild` and `subminer stats backfill` rebuild or backfill rollup data. -- Browser page: open `http://127.0.0.1:6969` directly if the local stats server is already running. - -SubMiner waits for the local server to bind before reporting that the dashboard is available. If another process already uses the configured port, the command reports the startup error and the desktop app stays open. Opening the in-app dashboard also reports startup failures through your configured status notifications. - -`subminer stats -s` stops a background stats server or cancels a pending background start. It leaves a foreground-only server running, so an open in-app dashboard stays connected. Shutdown gives active HTTP requests one second to finish before closing their connections and finalizing stats. - -### Stats API resource IDs - -Resource IDs in URLs must be positive safe integers written as decimal digits without leading zeros, fractions, or exponent notation. ID lists in JSON bodies must contain positive safe integer numbers. Invalid IDs or list entries return `400` before any mutation; bulk requests do not apply just the valid subset. Pagination limits keep their existing rounding and bounds. - -### Dashboard tabs - -#### Overview - -Recent sessions, streak calendar, watch-time history, and a tracking snapshot with completed episodes/anime totals. +Recent sessions, a streak calendar, watch-time history, and totals for completed episodes and shows. ![Stats Overview](/screenshots/stats-overview.png) -#### Library +### Library -Cover-art library with search and sorting, per-series progress, episode drill-down, and direct links into mined cards. +Your shows as cover-art cards with search, sorting, per-series progress, and an episode list linking to mined cards. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector filters the grid. YouTube videos are grouped by channel. -Local files and Jellyfin items with detected season numbers are split into season-specific library entries, so `Season 1` and `Season 2` folders do not merge into one show card. +Seasons get separate cards when a season number is detected. Live-action titles that AniList cannot match are looked up on [TMDB](/configuration#tmdb). If a title gets no match, open it and use **Link to TMDB** to pick one by hand. -When older stats already grouped multiple seasons under one series entry, SubMiner moves parsed episodes into the season-specific entries on startup and rebuilds the affected summaries. +The same show can end up on several cards when release names disagree. To fix that: -**Live-action dramas and movies.** Anime covers come from AniList, which has no live-action titles. A title that AniList cannot match is looked up on [TMDB](/configuration#tmdb) instead (release builds bundle a key; source builds need your own): only a Japanese-language, non-animated result whose known titles match the parsed filename exactly is accepted, and it supplies the poster, synopsis, English and Japanese titles, and episode count. If nothing matches automatically, open the title and use **Link to TMDB** to search and pick it by hand. A TMDB show spans all of its seasons, so entries that resolve to the same TMDB title are merged into one card regardless of the season folder they came from, and the merged season titles are remembered so later episodes land on the same card. The **All Titles** / **Anime** / **Live Action** / **YouTube** selector above the grid narrows the Library to one kind, and a title's detail view shows whether it is a drama or a movie. Linking a title to AniList again turns it back into an anime entry. Changing providers downloads the replacement cover before saving the new link; a failed download leaves the previous link and artwork intact. A title without a cover clears the previous artwork. Automatic TMDB matching leaves existing AniList links unchanged. +- Merge: click **Select**, tick the duplicate cards, choose **Merge Selected**, and pick the entry to keep. Sessions, cards, and watch time move over, and future episodes with those names join the kept entry. +- Move one episode: hover its row in the episode list and click **→** to assign it to another entry. SubMiner remembers the correction. +- Suggested merges appear as **Possible duplicate** above the grid. Choose **Review merge** or **Not duplicates**. -Jellyfin stream URLs are normalized to stable item links before stats titles are shown, so playback query parameters are not displayed in the dashboard. - -When YouTube channel metadata is available, the Library tab groups videos by creator/channel. Use the kind selector above the grid (**All Titles**, **Anime**, **Live Action**, **YouTube**) to filter the library. Channel pages show tracked videos and their stats without AniList controls. Existing channel entries are classified as YouTube automatically on startup, preserving viewing history and manual video assignments. Anime and YouTube entries with the same normalized title remain separate, including during stats sync. Channels are excluded from anime metadata matching, season repair, and duplicate recommendations. - -A library entry is identified by its parsed title plus any detected season, so the same show can end up on several cards when releases disagree about the title or omit the season tag. Two fixes are available: - -- **Merge duplicates.** Hit **Select** above the grid, tick the cards that are the same show, and choose **Merge Selected**. Pick which entry to keep in the dialog; every episode moves onto it and the other cards are removed. Nothing is deleted, so sessions, mined cards and watch time all carry over. AniList-linked and TMDB-linked entries cannot be merged together, and YouTube channels cannot be merged with anime or live-action entries. SubMiner remembers the merged title variants, so future episodes parsed with one of those names join the kept entry instead of recreating a duplicate card. -- **Move a single episode.** Hover an episode row in a title's episode list and use the **→** button to reassign it to another library entry. Anime and live-action entries are interchangeable here, but a YouTube video can only move between channels. The correction is remembered, so later filename parsing or Jellyfin metadata cannot move that episode back. For local files, later episodes in the same directory inherit the correction when their detected seasons are compatible and every manual correction there points to the same entry; a file that parses to a title which already has its own library entry keeps that identity instead. Conflicting seasons or manual destinations are left for review. If the move empties the old entry, that card is removed and you are returned to the grid. - -Once cover art resolves a series to an AniList entry, cards with compatible seasons are folded together automatically only when the searched title exactly matches an AniList title or synonym. A fuzzy result that points at an AniList entry already used by another card appears as a **Possible duplicate** review above the Library grid instead. Choose **Review merge** to compare the cards and pick which one to keep, or **Not duplicates** to dismiss that suggestion permanently. Entries with conflicting explicit season numbers are left alone rather than merged or suggested. - -Open a title and use **Delete Entry** in its header to remove a mistakenly tracked show outright. This deletes every episode of that title along with their sessions, subtitle lines, rollups and cover art, drops the words and kanji that were only seen there, and removes the card from the Library grid. Individual episodes and sessions can still be deleted on their own from the episode list and session rows. Entry deletion is refused while that title is the one currently playing. +**Delete Entry** in a title's header removes the show with all its episodes, sessions, and lines. You cannot delete the title that is currently playing. ![Stats Library](/screenshots/stats-library.png) -#### Trends +### Trends -Grouped into Activity (per-day/month watch time, cards, words, sessions), Cumulative Totals (running totals incl. new words seen and episodes), Efficiency (words/min, cards/hour, lookups per 100 words), Patterns (watch time by day of week and hour), and per-anime Library charts. Every chart takes a configurable date range and grouping. +Charts for watch time, cards, words, and sessions per day or month, running totals, efficiency (words per minute, cards per hour), and viewing patterns by weekday and hour. Each chart has its own date range and grouping. ![Stats Trends](/screenshots/stats-trends.png) -#### Sessions +### Sessions -Expandable session history with new-word activity, cumulative totals, and pause/seek/card markers. Each session row exposes a hover-revealed ↗ button that navigates to the anime media-detail view for that session; pressing the back button there returns to the Sessions tab. +Session history with new-word activity and pause, seek, and card markers. The **↗** button on a row opens that show's detail view. ![Stats Sessions](/screenshots/stats-sessions.png) -#### Vocabulary +### Vocabulary -The summary cards show all unique vocabulary and kanji recorded in the local tracking database; **New This Week** is the only weekly figure and uses a rolling seven-day window. The word and kanji tables load first while those complete totals calculate separately. Top Repeated Words and New Words by Day use complete tracking history rather than the table's browsing page. New-word history is maintained as a permanent daily lexical rollup using the same token-visibility rules as the totals, including normalization of older timestamps stored in either seconds or milliseconds and retroactive corrections when tracked material is removed or reprocessed. On the first launch after an applicable upgrade, that history is version-rebuilt in the background and the chart refreshes when it is ready; if it remains unavailable, polling stops and an inline Retry control appears. The cards and charts also refresh automatically after the word exclusion list changes. The rest of the tab includes cross-title and frequency rank tables with Hide Known / Hide Kana filters, kanji breakdown, word exclusion list, and click-through occurrence drilldown with Mine Word / Mine Sentence / Mine Audio buttons. +Unique words and kanji you have seen, new words per day, frequency rank tables with Hide Known and Hide Kana filters, and a kanji breakdown. Click a word to see every line it appeared in. + +- **Exclusions** hides words from every vocabulary view. You can restore them from the same dialog. +- **Duplicates** cleans up lines repeated by karaoke openings and animated signs (see [Repeated lines](#repeated-lines)). ![Stats Vocabulary](/screenshots/stats-vocabulary.png) -#### Search +### Search -Realtime search across tracked primary subtitle lines and media titles. Results show the source media, session, line number, timing, and sentence text. Secondary subtitle text is not shown or searched here because separate subtitle tracks may not line up sentence-for-sentence. Sentence cards can be mined from any result with a valid local source and timing. Word and audio card buttons appear only when the searched word exactly appears in the primary sentence text; matching text is highlighted in the result. +Searches the primary subtitle lines and titles in your history. **Search by headword** is on by default, so `知らない` also finds inflected forms. Turn it off for exact text matching. Secondary subtitles are not searched. -Stats server config lives under `stats`: +## Mining from the dashboard -```jsonc -{ - "stats": { - "toggleKey": "Backquote", - "markWatchedKey": "KeyW", - "serverPort": 6969, - "autoStartServer": true, - "autoOpenBrowser": false, - }, -} -``` +Search results and the Vocabulary word panel can create cards from past lines, as long as the source video file is still available: -- `toggleKey` is overlay-local, not a system-wide shortcut. -- `markWatchedKey` toggles the watched state of the highlighted entry inside the stats dashboard. -- `serverPort` controls the localhost dashboard URL. -- `autoStartServer` starts the local stats HTTP server on launch once immersion tracking is active, or reuses the dedicated background stats server when one is already running. Background app launches (`subminer app`) start the stats server immediately, registering it so later launches reuse it instead of starting another one. -- `autoOpenBrowser` decides whether `subminer stats` opens the dashboard URL in your browser once the server is up. -- `subminer stats` forces the dashboard server to start even when `autoStartServer` is `false`. -- `subminer stats -b` starts or reuses the dedicated background stats daemon and exits after startup acknowledgement. -- The background stats daemon is separate from the normal SubMiner overlay app, so you can leave it running and still launch SubMiner later to watch or mine from video. -- `subminer stats -s` stops the dedicated background stats daemon without closing any browser tabs. -- `subminer stats` fails with an error when `immersionTracking.enabled` is `false`. -- `subminer stats cleanup` defaults to vocabulary cleanup, repairs stale `headword`, `reading`, and `part_of_speech` values, attempts best-effort MeCab backfill for legacy rows, and removes rows that still fail vocab filtering. +- **Mine Word**: looks up the word with the selected dictionary backend (Yomitan or Hachidori), plus sentence, audio, and image. The history line you picked is the card's sentence, even while mpv plays another line. Hachidori uses its own Anki template, dictionary aliases, and frequency data. +- **Mine Sentence**: a sentence card with `IsSentenceCard` set, for Lapis and Kiku note types. +- **Mine Audio**: an audio card with `IsAudioCard` set. -## Mining cards from the stats page +Word and audio mining appear only when the word occurs in the sentence. All three use your `ankiConnect` deck, note type, fields, and media settings. Anki must be running, and Mine Word needs dictionaries in the selected backend. -The Search tab and the Vocabulary tab's word detail panel both mine from subtitle lines in your viewing history. Search matches sentence text and media titles, and **Search by headword** is enabled by default so dictionary-form searches such as `知らない` can find tracked subtitle lines with inflected variants. Turn that toggle off for exact text/title matching only. Each line with a valid source file offers sentence-card mining; word/audio mining is available when the selected word or searched word appears in the sentence: +Dashboard cards also get the `SubMiner::Stats` tag. With the Anki proxy off, SubMiner uses it to keep the chosen history line when polling picks up the card. -- **Mine Word** - looks up the word with the selected dictionary backend, Yomitan or Hachidori, then enriches the card with sentence audio, a screenshot or animated AVIF clip, the highlighted sentence, full-sentence readings in `SentenceFurigana` when that field exists, and metadata extracted from the source video file. The selected history line supplies the card's context even while another subtitle is playing in mpv. Hachidori uses its configured Anki template, dictionary aliases, and frequency metadata. Requires Anki and the selected backend's dictionaries to be loaded. -- **Mine Sentence** - creates a sentence card directly with the `IsSentenceCard` flag set (for Lapis/Kiku workflows), along with audio and image from the source video. -- **Mine Audio** - creates an audio-only card with the `IsAudioCard` flag, attaching only the sentence audio clip. +## Repeated lines -All three modes respect your `ankiConnect` config: deck, model, field mappings, media settings (static vs AVIF, quality, dimensions), audio padding, metadata pattern, and tags. Media generation runs in parallel for faster card creation. +Karaoke openings and animated signs repeat the same text once per frame. SubMiner collapses these as it records, so one lyric is stored once. Stats recorded before that can hold hundreds of copies and skew Top Repeated Words. -Stats cards also receive the `SubMiner::Stats` tag. SubMiner uses it to preserve their selected history context when detecting new cards through polling with the Anki proxy disabled. - -Secondary subtitle text is stored alongside primary subtitles during playback, but the Search tab does not use it for display or matching. - -### Word exclusion list - -The Vocabulary tab toolbar includes an **Exclusions** button for hiding words from all vocabulary views. Excluded words are stored in the immersion database, with older browser localStorage exclusions imported on first load after upgrade. They can be managed (restored or cleared) from the exclusion modal. Exclusions affect stat cards, charts, the frequency rank table, and the word list. - -### Repeated line cleanup - -Karaoke openings and animated signs are authored as one subtitle event per animation frame, all carrying the same text. Playback reports every one of those frames, so a single OP lyric could be recorded hundreds of times and dominate "Top Repeated Words". - -Recording now collapses those runs as they happen, matching what the subtitle sidebar shows: - -- When a typeset ASS file stores a clean lyric or sign in a timed authoring comment, or in full-line events surrounding generated fragments, the matching complete line is recorded once. The repeated glyph or clip-animation frames are not recorded. Dialogue spoken while such an animation is on screen records as itself, without the fragment lines beside it. -- When karaoke styling redraws the same complete lyric across consecutive color or highlight phases, those phases are combined into one line with their full timing. Repeated ordinary dialogue remains separate. -- When the active subtitle source has been parsed, its cue list has already had duplicate events and animation bursts merged. A line landing inside a surviving cue but after that cue's start is a frame the sidebar merged away, and is not recorded. -- When no parsed cue covers the live timing, including while a subtitle source is changing or shifted, the strict metadata-free rule applies: a run of identical, contiguous lines each shorter than 0.1s stops being recorded after a few frames. Runs are tracked per line of text, so dual-line karaoke (a kanji and a romaji line frame-flipped together) collapses both lines. Ordinary repeated dialogue, and lines held for a normal beat, always record. - -For stats recorded before this, the Vocabulary tab toolbar has a **Duplicates** button: - -- Pick how far back to look (7 days, 30 days, 90 days, 1 year, or all time). A narrower window does less work and keeps older history untouched. -- **Scan** reports the bursts found, the lines they added, and the word and kanji counts they inflated, without writing anything. -- **Clean Up** applies exactly what the scan reported: each run collapses to its first line (extended to cover the run), and the removed lines' word and kanji occurrences are subtracted from the vocabulary aggregates. - -The same thing runs from the terminal: +To clean them, use **Duplicates** in the Vocabulary tab: pick a time window, **Scan** to preview, then **Clean Up**. Or from the terminal: ```bash subminer stats cleanup --duplicate-lines --dry-run --lookback-days 30 subminer stats cleanup --duplicate-lines --lookback-days 30 ``` -`--duplicate-lines` (short: `-d`) picks the cleanup mode, so it cannot be combined with `--vocab` or `--lifetime`, and `--dry-run` and `--lookback-days <days>` only apply to it. Omitting `--lookback-days` scans all history; the value must be at least one day. +Leave out `--lookback-days` to scan all history. Word and kanji counts are corrected. Watch time and session totals are not changed. -The cleanup chains runs per line of text, so interleaved dual-line karaoke collapses each of its lines. It also removes the short residue the live rule stores before a run is long enough to recognize: a run one frame short of the usual minimum qualifies when every event is under the strict 0.1s bound. +## Maintenance commands -Runs never cross a session boundary, so rewatching an episode keeps both watches. Session telemetry (watch time, lines seen, tokens seen) and the rollups derived from it are left as recorded: they are cumulative samples taken during playback, and cannot be recomputed for sessions whose raw rows have since been pruned. +| Command | What it does | +| ------------------------------------------ | ------------------------------------------------------------------------- | +| `subminer stats cleanup` | Repair word readings and part of speech, drop words that fail the filters | +| `subminer stats cleanup -l` | Recompute lifetime totals from episode history, keeping old totals | +| `subminer stats cleanup --duplicate-lines` | Collapse repeated karaoke and sign lines (see above) | -## Retention defaults +`subminer stats rebuild` and `subminer stats backfill` run the same lifetime repair as `cleanup -l`. -By default, SubMiner keeps all retention tables and raw data (`0` means keep all) while continuing daily/monthly rollup maintenance: +## Retention -| Data type | Retention | -| --------------- | ------------ | -| Raw events | 0 (keep all) | -| Telemetry | 0 (keep all) | -| Sessions | 0 (keep all) | -| Daily rollups | 0 (keep all) | -| Monthly rollups | 0 (keep all) | +By default SubMiner keeps everything. To limit history, set `immersionTracking.retentionPreset` to `minimal`, `balanced`, or `deep-history`, or set the `immersionTracking.retention.*Days` values yourself (`0` keeps all). Lifetime totals and vocabulary counts are stored separately and stay exact when old sessions are pruned. -Maintenance runs on startup and every 24 hours. Vacuum runs only when `retention.vacuumIntervalDays` is non-zero. - -In practice: - -- Overview totals read from lifetime summary tables, so all-time watch time/cards/words stay exact even if raw query paths evolve. -- Anime and episode pages keep lifetime totals from summary tables while session drill-down still reads retained sessions directly. With the current defaults, both are kept forever. -- Trends can read the full available history because daily/monthly rollups are also kept forever by default. -- Vocabulary and kanji totals are cumulative and not bounded by the raw session retention knobs. -- New-word charts use their own permanent lexical daily rollups, which are not pruned by activity-rollup retention. - -## Storage / performance model - -The defaults keep everything, and the schema is shaped around that: - -- Exact all-time totals live in dedicated lifetime summary tables (`imm_lifetime_global`, `imm_lifetime_anime`, `imm_lifetime_media`). -- Ended-session totals are persisted onto `imm_sessions`, so most dashboard reads do not need to rescan raw telemetry. -- Daily and monthly rollups remain available for chart queries and coarse trend views. -- Subtitle text is stored once in `imm_subtitle_lines`; subtitle-line event payloads keep compact metadata only. -- Cover-art binaries are deduplicated through a shared blob store so episodes in the same series do not each carry duplicate image bytes. -- Hot tables have dedicated indexes for session time ranges, telemetry sample windows, frequency-ranked vocabulary, and cover-art lookup keys. - -## Configurable knobs - -All policy options live under `immersionTracking` in your config: - -| Option | Description | -| ------------------------------ | ------------------------------------------------------------------ | -| `batchSize` | Writes per flush batch | -| `flushIntervalMs` | Max delay between flushes (default: 500ms) | -| `queueCap` | Max queued writes before oldest are dropped | -| `payloadCapBytes` | Max payload size per write | -| `maintenanceIntervalMs` | How often maintenance runs | -| `retention.eventsDays` | Raw event retention | -| `retention.telemetryDays` | Telemetry retention | -| `retention.sessionsDays` | Session retention | -| `retention.dailyRollupsDays` | Daily rollup retention | -| `retention.monthlyRollupsDays` | Monthly rollup retention | -| `retention.vacuumIntervalDays` | Minimum spacing between vacuums | -| `retentionMode` | `preset` or `advanced` | -| `retentionPreset` | `minimal`, `balanced`, or `deep-history` (used by `retentionMode`) | -| `lifetimeSummaries.global` | Maintain global lifetime totals | -| `lifetimeSummaries.anime` | Maintain per-anime lifetime totals | -| `lifetimeSummaries.media` | Maintain per-media lifetime totals | - -## Query templates - -### Session timeline - -```sql -SELECT - sample_ms, - total_watched_ms, - active_watched_ms, - lines_seen, - tokens_seen, - cards_mined -FROM imm_session_telemetry -WHERE session_id = ? -ORDER BY sample_ms DESC, telemetry_id DESC -LIMIT ?; -``` - -### Session throughput summary - -```sql -SELECT - s.session_id, - s.video_id, - s.started_at_ms, - s.ended_at_ms, - COALESCE(s.active_watched_ms, 0) AS active_watched_ms, - COALESCE(s.tokens_seen, 0) AS tokens_seen, - COALESCE(s.cards_mined, 0) AS cards_mined, - CASE - WHEN COALESCE(s.active_watched_ms, 0) > 0 - THEN COALESCE(s.tokens_seen, 0) / (COALESCE(s.active_watched_ms, 0) / 60000.0) - ELSE NULL - END AS tokens_per_min, - CASE - WHEN COALESCE(s.active_watched_ms, 0) > 0 - THEN (COALESCE(s.cards_mined, 0) * 60.0) / (COALESCE(s.active_watched_ms, 0) / 60000.0) - ELSE NULL - END AS cards_per_hour -FROM imm_sessions s -ORDER BY s.started_at_ms DESC -LIMIT ?; -``` - -### Lifetime anime totals - -```sql -SELECT - a.anime_id, - a.canonical_title, - la.total_sessions, - la.total_active_ms, - la.total_cards, - la.total_tokens_seen, - la.total_lines_seen, - la.first_watched_ms, - la.last_watched_ms -FROM imm_lifetime_anime la -JOIN imm_anime a ON a.anime_id = la.anime_id -ORDER BY la.last_watched_ms DESC -LIMIT ?; -``` - -### Daily rollups - -```sql -SELECT - rollup_day, - video_id, - total_sessions, - total_active_min, - total_lines_seen, - total_tokens_seen, - total_cards, - cards_per_hour, - tokens_per_min, - lookup_hit_rate -FROM imm_daily_rollups -ORDER BY rollup_day DESC, video_id DESC -LIMIT ?; -``` - -### Monthly rollups - -```sql -SELECT - rollup_month, - video_id, - total_sessions, - total_active_min, - total_lines_seen, - total_tokens_seen, - total_cards -FROM imm_monthly_rollups -ORDER BY rollup_month DESC, video_id DESC -LIMIT ?; -``` - -## Technical details - -- Write path is asynchronous and queue-backed. Hot paths (subtitle parsing, render, token flows) enqueue telemetry and never await SQLite writes. -- Queue overflow policy: drop oldest queued writes, keep newest. -- SQLite tunings: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `busy_timeout=2500`, bounded WAL growth via `journal_size_limit`. -- Maintenance executes `PRAGMA optimize` after periodic cleanup. -- Rollups run incrementally from the last processed telemetry sample; startup performs a one-time bootstrap pass. -- Cover-art blobs are deduplicated into `imm_cover_art_blobs` and referenced from `imm_media_art`. -- Large-table reads are index-backed for `sample_ms`, session time windows, frequency-ranked words/kanji, and cover-art identity lookups. -- Workload-dependent tuning knobs remain at defaults unless you change them: `cache_size`, `mmap_size`, `temp_store`, `auto_vacuum`. - -### Schema (v24) - -The exact schema version lives in `SCHEMA_VERSION` (`src/core/services/immersion-tracker/types.ts`) and is recorded in the `imm_schema_version` table. - -Core tables: - -- `imm_videos` - video key/title/source metadata -- `imm_anime` - series or YouTube channel metadata referenced by videos and lifetime tables, including the media kind (`anime`, `live_action` or `youtube`) and the AniList or TMDB link -- `imm_anime_title_aliases` - alternate titles that resolve to the same anime row -- `imm_anime_merge_recommendations` - candidate duplicate-series merges surfaced in the dashboard -- `imm_sessions` - session UUID, video reference, timing/status, final denormalized totals -- `imm_session_telemetry` - high-frequency session aggregates over time -- `imm_session_events` - event stream with compact numeric event types -- `imm_subtitle_lines` - persisted subtitle text and timing per session/video -- `imm_youtube_videos` - YouTube video/channel metadata for tracked videos - -Lifetime summary tables: - -- `imm_lifetime_global` -- `imm_lifetime_anime` -- `imm_lifetime_media` -- `imm_lifetime_applied_sessions` - -Rollup tables: - -- `imm_daily_rollups` -- `imm_monthly_rollups` -- `imm_lexical_daily_rollups` - permanent first-discovery counts for vocabulary and kanji chart history -- `imm_rollup_state` - incremental rollup progress bookkeeping - -Vocabulary tables: - -- `imm_words(id, headword, word, reading, part_of_speech, pos1, pos2, pos3, first_seen, last_seen, frequency, frequency_rank)` with `UNIQUE(headword, word, reading)` -- `imm_kanji(id, kanji, first_seen, last_seen, frequency)` -- `imm_word_line_occurrences` / `imm_kanji_line_occurrences` - word/kanji ↔ subtitle-line occurrence links -- `imm_stats_excluded_words` - vocabulary exclusion list managed from the dashboard - -Media-art tables: - -- `imm_media_art` - per-video cover metadata plus shared blob reference -- `imm_cover_art_blobs` - deduplicated image bytes keyed by blob hash +See [Immersion tracking](/configuration#immersion-tracking) and [Stats dashboard](/configuration#stats-dashboard) in the config reference for every option and default. diff --git a/docs-site/installation.md b/docs-site/installation.md index 557b2aaf..20ac38d5 100644 --- a/docs-site/installation.md +++ b/docs-site/installation.md @@ -1,52 +1,41 @@ # Installation -SubMiner draws an interactive overlay on top of the [mpv](https://mpv.io) video player. While you watch Japanese media, hover any word in the subtitles to look it up, then turn it into an Anki card without switching apps. +SubMiner draws an interactive overlay on top of the [mpv](https://mpv.io) video player. While you watch Japanese media, you hover a word in the subtitles to look it up, then turn it into an Anki card without leaving the video. -Building cards from the content you are actually watching is called **sentence mining**, and it is the whole point of SubMiner. It bundles its own copy of **Yomitan** (a pop-up dictionary) and talks to **AnkiConnect** (the add-on that lets other programs write cards into Anki), so the sentence, audio, and screenshot fields get filled in for you. +Building cards from what you watch is called **sentence mining**. SubMiner bundles its own copy of **Yomitan** (a pop-up dictionary) and talks to **AnkiConnect** (an Anki add-on that lets other programs create cards), so it can fill in the sentence, audio, and screenshot for you. -Three steps to get started: +Getting started takes three steps: -1. **Install requirements** - mpv and a few optional extras -2. **Install SubMiner** - from the AUR, or download from GitHub Releases -3. **Launch the app** - first-run setup walks you through dictionaries, the launcher, and everything else +1. Install mpv and the optional extras you want. +2. Install SubMiner. +3. Launch it and follow the first-run setup. ## 1. Install requirements -Only **mpv** is strictly required. Everything else is optional, though you will want ffmpeg 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. -Some rows below matter only for the `subminer` command-line launcher's picker features. On Windows, the **SubMiner mpv** shortcut remains the recommended playback entry point. +| Dependency | Needed for | Platforms | +| ------------------------ | ------------------------------------------------------------------------------------------- | ------------ | +| mpv | Required. The player SubMiner draws over. | All | +| fuse2 | Required to run the AppImage. | Linux | +| ffmpeg | Recommended. Audio clips and screenshots on cards. Without it those fields stay empty. | All | +| MeCab + mecab-ipadic | Recommended. More accurate N+1, JLPT, and frequency highlighting. | All | +| yt-dlp | YouTube playback. | All | +| xz | [TsukiHime](/tsukihime-integration) subtitle downloads. Most Linux distros already have it. | All | +| guessit | Better title, season, and episode detection for [AniSkip](/aniskip-integration). | All | +| alass or ffsubsync | Subtitle syncing. You need at least one to use it. | All | +| fzf, rofi | The file pickers in the `subminer` command (rofi is Linux only). | Linux, macOS | +| chafa, ffmpegthumbnailer | Thumbnail previews in the pickers. | Linux, macOS | -[Local Japanese subtitle generation](/subtitle-generation) additionally requires whisper.cpp's `whisper-cli`, FFmpeg, and `ffprobe`. Configure their executable paths in Settings if needed. SubMiner can download a speech model explicitly, or use your existing multilingual GGML model. - -Optional [dialogue-focused generation](/subtitle-generation#prioritizing-spoken-dialogue) also uses whisper.cpp's speech segment detector and a separate Silero GGML VAD model. - -| Dependency | Status | Platforms | What it does | -| -------------------- | ----------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| mpv | Required | All | The video player SubMiner overlays on. Must support `--input-ipc-server`. | -| ffmpeg | Recommended | All | Audio extraction and screenshots for Anki cards. Without it SubMiner still runs, but media fields will be empty. | -| MeCab + mecab-ipadic | Recommended | All | Part-of-speech filtering for more precise N+1, JLPT, and frequency annotations. Without it annotations still render, but POS-based filtering is less accurate. | -| yt-dlp | Optional | All | YouTube playback and subtitle extraction. | -| xz | Optional | All | Required for TsukiHime subtitle downloads (subtitles are served xz-compressed). Preinstalled on most Linux distros; not present on Windows by default. | -| guessit | Optional | All | Better AniSkip title/season/episode parsing. | -| alass | Optional | All | Subtitle sync engine (preferred). Disabled without alass or ffsubsync. | -| ffsubsync | Optional | All | Audio-based subtitle sync engine. Disabled without alass or ffsubsync. | -| fzf | Optional | Linux, macOS | Terminal-based video picker in the `subminer` launcher. | -| rofi | Optional | Linux | GUI-based video picker in the `subminer` launcher. | -| chafa | Optional | Linux, macOS | Thumbnail previews in the fzf picker. | -| ffmpegthumbnailer | Optional | Linux, macOS | Video thumbnail generation for the pickers. | -| fuse2 | Required | Linux | Needed to run the AppImage. | +To generate Japanese subtitles from audio, you also need whisper.cpp. See [Subtitle generation](/subtitle-generation). ### Linux -**Window backend** - you need one of these depending on your compositor: +SubMiner needs to track the mpv window, and how it does that depends on your desktop: -- **Hyprland** - native Wayland support (uses `hyprctl`) -- **Sway** - native Wayland support (uses `swaymsg`) -- **X11 / Xwayland** - for X11 sessions or any other Wayland compositor (uses `xdotool` and `xwininfo`) - -::: warning Wayland support is compositor-specific -Wayland has no universal API for window positioning. Each compositor exposes its own IPC, so SubMiner needs a backend per compositor. Only Hyprland and Sway have native Wayland backends. If you run a different Wayland compositor (GNOME, KDE Plasma, river, etc.), both mpv **and** SubMiner must run under X11 or Xwayland. The `subminer` launcher handles this automatically when `--backend x11` is set or the X11 backend is auto-detected. -::: +- **Hyprland**: supported natively through `hyprctl`. +- **Sway**: supported natively through `swaymsg`. +- **Anything else** (X11, GNOME, KDE Plasma, other Wayland compositors): mpv and SubMiner must run under X11 or Xwayland. Install `xdotool` and `xwininfo`. The `subminer` command picks the X11 backend automatically, or you can force it with `--backend x11`. <details> <summary><b>Arch Linux</b></summary> @@ -57,9 +46,9 @@ sudo pacman -S --needed mpv ffmpeg sudo pacman -S --needed mecab mecab-ipadic # Optional sudo pacman -S --needed yt-dlp fzf rofi chafa ffmpegthumbnailer -# Optional: subtitle sync (at least one needed for subtitle syncing) +# Optional: subtitle sync (install at least one) paru -S --needed alass python-ffsubsync -# X11 / Xwayland (required for non-Hyprland/Sway compositors) +# Only for desktops other than Hyprland or Sway sudo pacman -S --needed xdotool xorg-xwininfo ``` @@ -74,11 +63,11 @@ sudo apt install mpv ffmpeg sudo apt install mecab libmecab-dev mecab-ipadic-utf8 # Optional sudo apt install yt-dlp fzf rofi chafa ffmpegthumbnailer -# X11 / Xwayland (required for non-Hyprland/Sway compositors) +# Only for desktops other than Hyprland or Sway sudo apt install xdotool x11-utils # Optional: subtitle sync pip install ffsubsync -# alass is not in apt - install via cargo: cargo install alass-cli +cargo install alass-cli ``` </details> @@ -92,18 +81,18 @@ sudo dnf install mpv ffmpeg sudo dnf install mecab mecab-ipadic # Optional sudo dnf install yt-dlp fzf rofi chafa ffmpegthumbnailer -# X11 / Xwayland (required for non-Hyprland/Sway compositors) +# Only for desktops other than Hyprland or Sway sudo dnf install xdotool xorg-x11-utils # Optional: subtitle sync pip install ffsubsync -# alass: cargo install alass-cli +cargo install alass-cli ``` </details> ### macOS -macOS 11 (Big Sur) or later. Accessibility permission - the macOS setting that lets one app observe and position another app's windows - is required so the overlay can follow the mpv window (see [step 2](#macos-dmg)). +You need macOS 11 (Big Sur) or later. ```bash brew install mpv ffmpeg @@ -116,161 +105,99 @@ brew install alass pip install ffsubsync ``` +`mecab` must be on your `PATH` when SubMiner starts. Homebrew puts it in `/opt/homebrew/bin` on Apple Silicon and `/usr/local/bin` on Intel. + ### Windows -Windows 10 or later. No compositor tools or window helpers are needed - native window tracking is built in. - -You need **mpv** (required) and **ffmpeg** (strongly recommended, for card audio and screenshots). Put mpv on `PATH` or set `mpv.executablePath` during setup. ffmpeg must be on `PATH`. - -::: tip What is PATH? -`PATH` is the list of folders Windows searches when a program asks to run another program by name. SubMiner uses it to find ffmpeg and, unless an executable path is configured, mpv. The routes below mostly handle `PATH` for you; the manual route explains how to add a folder yourself. -::: - -You can install these with a package manager or by hand. Coverage differs, so pick based on what you need: - -| Dependency | winget | Scoop | -| ---------------- | --------------- | ------------- | -| mpv (required) | `shinchiro.mpv` | `extras/mpv` | -| ffmpeg | `Gyan.FFmpeg` | `main/ffmpeg` | -| yt-dlp (YouTube) | `yt-dlp.yt-dlp` | `main/yt-dlp` | -| xz (TsukiHime) | not packaged | `main/xz` | - -Use **winget** if you want Microsoft's first-party tool and don't need TsukiHime subtitle downloads. Use **Scoop** if you want one package manager to cover everything, since it is the only one that also packages `xz`. - -#### Recommended: winget - -[winget](https://learn.microsoft.com/windows/package-manager/winget/) is Microsoft's own package manager and ships with Windows 11 and current Windows 10 (it comes with **App Installer** from the Microsoft Store). In **PowerShell** or **Command Prompt**: +You need Windows 10 or later. Install mpv and ffmpeg with [winget](https://learn.microsoft.com/windows/package-manager/winget/), which ships with Windows 11 and current Windows 10. In PowerShell or Command Prompt: ```powershell winget install shinchiro.mpv winget install Gyan.FFmpeg +winget install yt-dlp.yt-dlp # optional, for YouTube ``` -Close and reopen your terminal, then check that both are found: +Close and reopen the terminal, then check both commands work: ```powershell mpv --version ffmpeg -version ``` -`ffmpeg` is installed as a portable package, so winget links it into a folder that is already on your `PATH` and it should work right away. - -`mpv` uses a regular installer, and depending on the version it may **not** add itself to `PATH`. If `mpv --version` says `not recognized`, you have two easy options: - -- Note where it installed (usually `%LOCALAPPDATA%\Programs\mpv`) and add that folder to `PATH` using the manual steps below, or -- Skip `PATH` entirely and set `mpv.executablePath` to the full path of `mpv.exe` during first-run setup. - -Once `mpv --version` works, or you have the full path to `mpv.exe` ready, continue to [step 2](#_2-install-subminer). +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`). <details> -<summary><b>Alternative: Scoop (covers every dependency, no admin rights)</b></summary> +<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary> -[Scoop](https://scoop.sh) installs into your user profile, needs no administrator prompt, and always puts commands on `PATH`. It is the only Windows package manager that carries all of SubMiner's optional dependencies, including `xz`, so it is the best choice if you want a single tool to manage everything. +[Scoop](https://scoop.sh) installs into your user profile and always adds commands to `PATH`. It is the only Windows package manager that also packages `xz`, which [TsukiHime](/tsukihime-integration) downloads need. ```powershell -# One-time Scoop setup (skip if you already have it) +# One-time Scoop setup Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression -# mpv lives in the "extras" bucket; everything else is in "main" scoop bucket add extras scoop install extras/mpv main/ffmpeg - -# Optional: yt-dlp for YouTube playback, xz for TsukiHime subtitle downloads +# Optional scoop install main/yt-dlp main/xz ``` -Close and reopen your terminal, then verify with `mpv --version` and `ffmpeg -version`. - </details> <details> -<summary><b>Manual install (download the zips yourself)</b></summary> +<summary><b>Alternative: manual download</b></summary> -1. Download mpv from [mpv.io/installation](https://mpv.io/installation/) (the Windows builds link) and ffmpeg from [ffmpeg.org/download.html](https://ffmpeg.org/download.html). -2. Unzip each one somewhere permanent, for example `C:\Tools\mpv` and `C:\Tools\ffmpeg`. Note the folder that actually contains `mpv.exe` and the one containing `ffmpeg.exe` (for ffmpeg this is usually a `bin` subfolder). -3. Press `Win`, type **Edit the system environment variables**, and open it. Click **Environment Variables…**, select **Path** under **User variables**, click **Edit…**, then use **New** to add each of those two folders. Confirm with **OK** on every dialog. Microsoft documents this in more detail under [environment variables](https://learn.microsoft.com/windows/deployment/usmt/usmt-recognized-environment-variables). -4. Close and reopen your terminal, since `PATH` changes only apply to newly opened windows. Then check: +1. Download mpv from [mpv.io/installation](https://mpv.io/installation/) and ffmpeg from [ffmpeg.org/download.html](https://ffmpeg.org/download.html). +2. Unzip each into a permanent folder, for example `C:\Tools\mpv` and `C:\Tools\ffmpeg`. Find the folders that contain `mpv.exe` and `ffmpeg.exe` (for ffmpeg this is usually `bin`). +3. Press `Win`, search for **Edit the system environment variables**, and open it. Click **Environment Variables**, select **Path** under **User variables**, click **Edit**, and add both folders with **New**. +4. Open a new terminal and run `mpv --version` and `ffmpeg -version`. If either says `not recognized`, the folder you added does not contain the `.exe`. -```powershell -mpv --version -ffmpeg -version -``` - -If you see `not recognized as the name of a cmdlet`, the folder you added is not the one holding the `.exe`. Reopen the Path editor and double-check. - -::: tip mpv can skip PATH, ffmpeg cannot -If you would rather not edit `PATH` for mpv, set `mpv.executablePath` to the full path of `mpv.exe` during first-run setup instead. - -There is no equivalent setting for ffmpeg: SubMiner invokes it by bare name when generating card audio and screenshots, so ffmpeg has to be on `PATH`. Without it, cards are still created but their audio and image fields come out empty. (`subsync.ffmpeg_path` only affects subtitle sync, not card media.) -::: +For `xz` without Scoop, download [XZ Utils](https://tukaani.org/xz/) and add its folder to `PATH` the same way. </details> -**Optional extras:** [MeCab for Windows](https://taku910.github.io/mecab/#download) with the UTF-8 dictionary improves annotation accuracy; it is not in any package manager, so install it from that page. `xz` is needed only for [TsukiHime](/tsukihime-integration) subtitle downloads and is not packaged by winget or Chocolatey, so use `scoop install main/xz` or download [XZ Utils](https://tukaani.org/xz/) and add its folder to `PATH`. - -The launcher's picker tools (`fzf`, `rofi`, `chafa`, `ffmpegthumbnailer`) are for Linux and macOS. On Windows, use the **SubMiner mpv** shortcut for playback or install the optional `subminer` terminal wrapper during setup. +For more accurate highlighting, install [MeCab for Windows](https://taku910.github.io/mecab/#download) with the UTF-8 dictionary. The fzf and rofi pickers do not apply on Windows. ## 2. Install SubMiner ### Arch Linux (AUR) {#arch-aur} -Install [`subminer-bin`](https://aur.archlinux.org/packages/subminer-bin) from the AUR. The package includes the SubMiner AppImage and its launcher wrapper. Bun is included with the app, so the package has no Bun dependency. Install updates through your AUR helper or package manager. +Install [`subminer-bin`](https://aur.archlinux.org/packages/subminer-bin). It includes the AppImage and the `subminer` command. ```bash paru -S subminer-bin ``` -Or manually: - -```bash -git clone https://aur.archlinux.org/subminer-bin.git -cd subminer-bin -makepkg -si -``` - ### Linux (AppImage) {#linux-appimage} -Download the latest AppImage from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest): - ```bash mkdir -p ~/.local/bin wget https://github.com/ksyasuda/SubMiner/releases/latest/download/SubMiner.AppImage -O ~/.local/bin/SubMiner.AppImage chmod +x ~/.local/bin/SubMiner.AppImage ``` -::: tip Launcher install is optional -First-run setup can install the `subminer` command-line launcher for you. It uses Bun bundled with the AppImage, so it does not need a separate Bun installation or a Bun entry on `PATH`. The downloaded wrapper works the same way. See [manual launcher install](#manual-launcher-install-linux). -::: +First-run setup can install the `subminer` command for you. ### macOS (DMG) {#macos-dmg} -Download the DMG from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest), open it, and drag `SubMiner.app` into `/Applications`. A ZIP artifact is also available as a fallback. +1. Download the DMG from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest), open it, and drag `SubMiner.app` into `/Applications`. +2. If macOS blocks the app on first launch, right-click it and choose **Open**, or run: -**Gatekeeper:** If macOS blocks SubMiner on first launch, right-click the app and select **Open** to bypass the warning. Alternatively: + ```bash + xattr -d com.apple.quarantine /Applications/SubMiner.app + ``` -```bash -xattr -d com.apple.quarantine /Applications/SubMiner.app -``` +3. Open **System Settings > Privacy & Security > Accessibility** and enable SubMiner (add it if it is missing). The overlay cannot follow the mpv window without this. -**Accessibility permission:** Grant accessibility permission so the overlay can track the mpv window: - -1. Open **System Settings** → **Privacy & Security** → **Accessibility** -2. Enable SubMiner in the list (add it if it does not appear) - -::: tip Launcher install is optional -First-run setup can install the `subminer` command-line launcher for you. It uses Bun bundled inside `SubMiner.app`, so it does not need a separate Bun installation or a Bun entry on `PATH`. The downloaded wrapper works the same way. See [manual launcher install](#manual-launcher-install-macos). -::: +First-run setup can install the `subminer` command for you. ### Windows (installer) {#windows-installer} -Download the latest installer from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest): +Download from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest): -- `SubMiner-<version>.exe` - installer (recommended) -- `SubMiner-<version>-win.zip` - portable fallback -- `subminer.cmd` - optional terminal launcher wrapper - -Make sure `mpv.exe` is on your `PATH`, or set `mpv.executablePath` in the config during first-run setup. +- `SubMiner-<version>.exe`: the installer. Use this one. +- `SubMiner-<version>-win.zip`: portable version. +- `subminer.cmd`: optional terminal command (setup can install it for you). ### From source @@ -282,14 +209,10 @@ git clone --recurse-submodules https://github.com/ksyasuda/SubMiner.git cd SubMiner make deps bun run build - -# Optional: build AppImage -bun run build:appimage +bun run build:appimage # optional: package an AppImage ``` -Bundled Yomitan is built during `bun run build`. - -Source and development commands use Bun installed on your system. +Building from source needs [Bun](https://bun.sh) installed. </details> @@ -303,7 +226,7 @@ make deps make build-macos ``` -The built app will be in the `release` directory (`.dmg` and `.zip`). For unsigned local builds: `bun run build:mac:unsigned`. +The `.dmg` and `.zip` land in `release/`. For an unsigned local build, run `bun run build:mac:unsigned`. </details> @@ -326,125 +249,80 @@ bun run build:win </details> -### Bundled Bun runtime {#bundled-bun-runtime} - -Every package includes an unmodified copy of Bun 1.3.5 that runs the command-line launcher. Bun is MIT licensed and statically links JavaScriptCore under LGPL 2.0 and TinyCC under LGPL 2.1. The license texts, third-party notices, and a `SOURCE.md` describing the corresponding source ship inside the app under `resources/bun/licenses` (`SubMiner.app/Contents/Resources/bun/licenses` on macOS). Each GitHub release also publishes `bun-v1.3.5-source.tar.gz` with the matching Bun, WebKit, and dependency sources and instructions for rebuilding Bun against a modified JavaScriptCore. - ## 3. Launch and first-run setup -Launch SubMiner and the setup wizard opens on its own: +Start SubMiner. The setup window opens on first launch. -```bash -# Linux (AUR install) -subminer app --setup +- **Linux (AUR)**: `subminer app --setup` +- **Linux (AppImage)**: `~/.local/bin/SubMiner.AppImage --setup` +- **macOS**: open `SubMiner.app` from `/Applications` +- **Windows**: run SubMiner from the Start menu -# Linux (AppImage directly) -~/.local/bin/SubMiner.AppImage --setup +Setup walks you through: -# macOS - launch SubMiner.app from /Applications, or: -subminer app --setup -``` +1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows). +2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser. +3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`. +4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached. -On **Windows**, just run `SubMiner.exe` - the setup wizard opens automatically on first launch. - -The setup wizard walks you through: - -- **Config file** - auto-created at `~/.config/SubMiner/config.jsonc` (Linux/macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows) -- **Yomitan dictionaries** - import at least one dictionary so word lookups work -- **`subminer` launcher** _(optional)_ - installs a wrapper into a writable terminal PATH directory. The wrapper uses Bun packaged with the app, with no separate runtime setup. If the included runtime is unavailable, the launcher controls show an error asking you to reinstall SubMiner. -- **Windows shortcut** _(Windows only)_ - create a `SubMiner mpv` Start Menu/Desktop shortcut - -The `Finish setup` button requires a config file and at least one Yomitan dictionary. The launcher is optional and never blocks setup completion. - -On Linux and macOS, setup selects a writable directory already on your terminal `PATH`. If it cannot find one, it creates `~/.local/bin` and shows the `export PATH=...` command to run. Add that command to your shell configuration yourself if you want it in future terminals. Setup never edits shell configuration files. On Windows, setup adds only the wrapper directory to the user `PATH`. Setup stores a custom app location so the wrapper can find an AppImage or app bundle outside the usual install directories. - -> [!TIP] -> You can re-open the setup wizard at any time with `subminer app --setup` or `SubMiner.AppImage --setup`. +**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`. ### Play a video -Once setup is complete: - ```bash subminer video.mkv ``` -The overlay appears over mpv. If a subtitle track loaded, its text shows up in the overlay as hoverable words. +On Windows, double-click the **SubMiner mpv** shortcut or drag a video onto it. -On **Windows**, the recommended way to play video is with the **SubMiner mpv** shortcut created during setup - double-click it, or drag a video file onto it. +The overlay appears over mpv, and the subtitle text becomes hoverable. See [Usage](/usage) for everyday use. -### Verify setup - -Run the built-in diagnostic: +### Check your setup ```bash subminer doctor ``` -This checks for the app binary, mpv, ffmpeg, yt-dlp, fzf, rofi, your config file, and the mpv socket path. Only the app binary and mpv are hard failures; the rest are reported as optional. Fix any hard failures before continuing. +This checks for the SubMiner app, mpv, ffmpeg, yt-dlp, fzf, rofi, your config file, and the mpv socket path. Only a missing app or mpv counts as a failure. The rest are reported as optional. -## Anki setup (recommended) +## Anki setup -If you plan to mine Anki cards: +To create cards: -1. Install [Anki](https://apps.ankiweb.net/) -2. Install [AnkiConnect](https://ankiweb.net/shared/info/2055492159) - open Anki → **Tools → Add-ons → Get Add-ons** → enter code `2055492159` -3. Restart Anki and keep it running while using SubMiner +1. Install [Anki](https://apps.ankiweb.net/). +2. In Anki, open **Tools > Add-ons > Get Add-ons** and enter `2055492159` to install [AnkiConnect](https://ankiweb.net/shared/info/2055492159). +3. Restart Anki. Keep it open while you use SubMiner. -AnkiConnect listens on `http://127.0.0.1:8765` by default. SubMiner connects automatically with no extra config needed. - -For enrichment configuration (sentence, audio, screenshot fields), see [Anki Integration](/anki-integration). +SubMiner connects to AnkiConnect at its default address with no extra setup. To choose your deck and card fields, see [Anki integration](/anki-integration). ## Updates ```bash subminer -u -# or -subminer --update ``` -SubMiner verifies AppImage, launcher, and Linux support-asset downloads against `SHA256SUMS.txt`. On Linux those support assets include the launcher-managed runtime plugin copy under `SubMiner/plugin/subminer`, the rofi theme at `SubMiner/themes/subminer.rasi`, and the scoped Matroska thumbnailer registration under `SubMiner/thumbnailers`. If the binary is in a protected path, SubMiner shows the exact command to run rather than elevating itself. +The tray menu's **Check for Updates** also installs updates on Linux, macOS, and Windows. If the AppImage sits in a folder you cannot write to, SubMiner prints the command to run instead of asking for admin rights. -The tray "Check for Updates" entry installs the new app automatically on Linux, macOS, and Windows. Current `subminer` wrappers remain small bootstraps that locate the installed app and its private runtime. On Linux the updater replaces the running `.AppImage` in place via `electron-updater` and refreshes managed support assets from `subminer-assets.tar.gz`. The next launcher invocation detects the changed AppImage fingerprint and prepares the matching Bun and CLI cache before running the command. App startup also refreshes this payload and migrates recognized writable legacy launchers, including the launcher path an update deferred. AppImages managed by a system package, for example the AUR `/opt/SubMiner/SubMiner.AppImage`, are skipped so the package manager stays in charge. +If you installed from the AUR, update through your package manager instead. -On Linux, `subminer -u` updates the AppImage and managed support assets directly, even when the app is not running. The launcher cache refreshes when the app fingerprint changes. AUR installs remain under package-manager control and should be updated through the package manager. +## Launching mpv yourself -## How it all fits together +The `subminer` command and the Windows shortcut start mpv with the IPC socket SubMiner needs. If you start mpv another way, add this option or the overlay starts without subtitles: -SubMiner is an overlay window that sits on top of mpv. It talks to mpv over an IPC socket, renders each subtitle line as interactive text backed by the bundled Yomitan dictionary engine, and writes Anki cards through AnkiConnect when you ask it to. +```bash +--input-ipc-server=/tmp/subminer-socket # Linux and macOS +--input-ipc-server=\\.\pipe\subminer-socket # Windows +``` -The `subminer` launcher handles mpv IPC socket setup automatically. If you launch mpv yourself or from another tool, you must pass `--input-ipc-server=/tmp/subminer-socket` (or `\\.\pipe\subminer-socket` on Windows) - without it the overlay starts but subtitles won't appear. - -SubMiner injects the bundled mpv plugin at runtime, so there is nothing to install separately. On Linux, the `subminer` launcher checks for its managed runtime plugin copy, rofi theme, and scoped thumbnailer registration before every mpv-managed launch and installs those support assets from the bundled app automatically if one is missing. For a rofi picker launch, this check runs before the picker opens. The plugin adds in-player keybindings (the `y` chord) for driving the overlay from mpv. See [MPV Plugin](/mpv-plugin) for the full keybinding and configuration reference. - -## Platform notes - -### macOS - -**MeCab paths (Homebrew):** - -- Apple Silicon (M1/M2): `/opt/homebrew/bin/mecab` -- Intel: `/usr/local/bin/mecab` - -`mecab` has to be on your PATH when SubMiner launches. - -**Fullscreen:** The overlay follows mpv into fullscreen. If it does not, accessibility permission is the usual cause. - -### Windows - -- The **SubMiner mpv** shortcut is the recommended way to launch playback. It starts `mpv.exe` with the right IPC socket and subtitle defaults. -- First-run setup adds only `%LOCALAPPDATA%\SubMiner\bin` to the HKCU user PATH. It does not add `SubMiner.exe` to PATH. -- IPC socket on Windows is `\\.\pipe\subminer-socket` - do not use `/tmp/subminer-socket`. -- Config is stored at `%APPDATA%\SubMiner\config.jsonc`. +SubMiner loads its mpv plugin automatically, so there is nothing else to install. See [mpv plugin](/mpv-plugin) for the in-player keybindings. ## Manual launcher install -Current launcher downloads use Bun included in the SubMiner app. The wrapper searches normal install locations and honors `SUBMINER_BINARY_PATH`; Linux also honors `SUBMINER_APPIMAGE_PATH`. +Use these if you skipped the launcher during setup. The launcher finds SubMiner in the usual install locations. For a custom location, set `SUBMINER_BINARY_PATH` to the app executable. ### Linux {#manual-launcher-install-linux} ```bash -# Download the launcher wget https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer -O ~/.local/bin/subminer chmod +x ~/.local/bin/subminer ``` @@ -452,36 +330,16 @@ chmod +x ~/.local/bin/subminer ### macOS {#manual-launcher-install-macos} ```bash -# Download the launcher sudo curl -fSL https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer -o /usr/local/bin/subminer sudo chmod +x /usr/local/bin/subminer ``` ### Windows {#manual-launcher-install-windows} -Download `subminer.cmd` from GitHub Releases and place it in a directory on your user `PATH`. It finds the installed app in the normal per-user or Program Files location. Set `SUBMINER_BINARY_PATH` if you use a portable or custom install. +Download `subminer.cmd` from [GitHub Releases](https://github.com/ksyasuda/SubMiner/releases/latest) and put it in a folder on your user `PATH`. -Launchers installed before the private-runtime change may still be bundled JavaScript with a Bun shebang. Those old files need system Bun until a current app startup migrates a recognized writable launcher, or until you replace one with the current release wrapper. +## Bundled Bun runtime {#bundled-bun-runtime} -## Optional extras +The `subminer` command runs on a copy of [Bun](https://bun.sh) 1.3.5 that ships inside the app, so you do not need to install Bun. Bun is MIT licensed and statically links JavaScriptCore (LGPL 2.0) and TinyCC (LGPL 2.1). License texts and a `SOURCE.md` ship in the app under `resources/bun/licenses`, and each GitHub release includes `bun-v1.3.5-source.tar.gz` with the matching sources. -### Linux support assets - -SubMiner ships the Linux rofi theme, scoped Matroska thumbnailer registration, launcher-managed runtime plugin copy, and the bundled Bun license notices in `subminer-assets.tar.gz`: - -```bash -wget https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer-assets.tar.gz -O /tmp/subminer-assets.tar.gz -tar -xzf /tmp/subminer-assets.tar.gz -C /tmp -mkdir -p ~/.local/share/SubMiner/themes -cp /tmp/assets/themes/subminer.rasi ~/.local/share/SubMiner/themes/subminer.rasi -mkdir -p ~/.local/share/SubMiner/thumbnailers -cp /tmp/assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer ~/.local/share/SubMiner/thumbnailers/ -mkdir -p ~/.local/share/SubMiner/plugin -cp -R /tmp/plugin/subminer ~/.local/share/SubMiner/plugin/subminer -``` - -`subminer -u` and the tray updater keep those Linux support assets in sync automatically once the `SubMiner` data dir exists. Normal Linux launcher playback also auto-installs all three assets from the bundled app if one is missing, so manual extraction is mainly useful for pre-seeding or custom setups. Rofi receives the SubMiner data path through its process-local `XDG_DATA_DIRS`, so the thumbnailer registration does not change the desktop-wide configuration. - -Override the theme path with `SUBMINER_ROFI_THEME=/absolute/path/to/theme.rasi`. - -Next: [Usage](/usage) - learn about the `subminer` wrapper, keybindings, and YouTube playback. +Next: [Usage](/usage). diff --git a/docs-site/ipc-contracts.md b/docs-site/ipc-contracts.md index 71770631..bcd6e5d7 100644 --- a/docs-site/ipc-contracts.md +++ b/docs-site/ipc-contracts.md @@ -1,12 +1,12 @@ # IPC + runtime contracts -SubMiner's Electron app runs two isolated processes, main and renderer, and IPC channels are the only way they talk. That boundary is deliberate. The renderer is an untrusted surface: it loads Yomitan, renders subtitle text SubMiner did not write, and runs in a Chromium sandbox. Every message crossing the bridge goes through a validator before any domain code sees it. +The Electron main and renderer processes talk only through IPC channels. The renderer is an untrusted surface: it loads Yomitan and renders subtitle text SubMiner did not write. Every payload that crosses the bridge goes through a validator before domain code sees it. -Channel names, payload shapes, and validators all live together, so they change together. Touching an IPC surface means updating the contract, the validator, the preload bridge, and the handler in one commit. Drift between those four layers is a bug, not a style preference. +Channel names, payload validators, the preload bridge, and the handler change together. When you touch an IPC surface, update all four in the same commit. ## Message flow -Renderer-initiated calls (`invoke`) pass through four boundaries before reaching a service. Fire-and-forget messages (`send`) follow the same path but skip the response leg. Malformed payloads are caught at the validator and never reach domain code. +Renderer calls pass through the preload bridge, the main-process handler, and a validator before they reach a service. Malformed payloads stop at the validator. ```mermaid flowchart TB @@ -36,12 +36,18 @@ flowchart TB style E fill:#ed8796,stroke:#494d64,color:#24273a,stroke-width:1.5px ``` +`IPC_CHANNELS` in `src/shared/ipc/contracts.ts` groups channels by pattern: + +- `request`: invoke channels. The renderer awaits a result, for example lookups, config reads, and mining actions. Invalid payloads return a structured failure such as `{ ok: false, ... }` instead of throwing. +- `command`: fire-and-forget sends, for example focus events, UI state hints, and position updates. Invalid payloads are dropped. +- `event`: messages pushed from main to the renderer. + ## Runtime sockets -The renderer↔main bridge above lives *inside* the Electron app. A separate set of OS sockets connects the app to the other runtimes - mpv and the launcher/plugin. These carry no renderer payloads and bypass the contract/validator layer; they are command and property channels between processes. +The bridge above lives inside the Electron app. Separate OS sockets connect the app to mpv and to the launcher and plugin. They carry no renderer payloads and do not go through the contract and validator layer. -- **mpv IPC socket** (`/tmp/subminer-socket`, or `\\.\pipe\subminer-socket` on Windows): the `MpvIpcClient` in the main process connects here to send JSON commands and subscribe to playback/subtitle properties via `observe_property`. Created by mpv's `--input-ipc-server`. -- **App control socket** (`/tmp/subminer-control-<uid>-<hash>.sock`, or a named pipe on Windows): the launcher and the mpv plugin send CLI-style commands (`--start`, `--show-visible-overlay`, `--texthooker`) to a running app here. It also dedupes a second `subminer` invocation into the existing instance instead of launching twice. +- **mpv IPC socket**: `/tmp/subminer-socket`, or `\\.\pipe\subminer-socket` on Windows. mpv creates it with `--input-ipc-server`. The app's `MpvIpcClient` sends JSON commands here and observes playback and subtitle properties. +- **App control socket**: `subminer-control-<uid>-<hash>.sock` in the temp directory, or `\\.\pipe\subminer-control-<hash>` on Windows. The launcher and plugin send CLI-style commands (`--start`, `--show-visible-overlay`, `--texthooker`) to a running app here. It also routes a second `subminer` invocation into the existing instance. ```mermaid flowchart LR @@ -65,60 +71,44 @@ flowchart LR style MpvProc fill:#363a4f,stroke:#494d64,color:#cad3f5 ``` -How these sockets are established during launch is covered in [Playback Startup Flow](./architecture#playback-startup-flow). +[Playback startup flow](./architecture#playback-startup-flow) shows when each socket comes up during a launch. -## Core surfaces +## Core files -| File | Role | -| --- | --- | -| `src/shared/ipc/contracts.ts` | Canonical channel names and payload type contracts. Single source of truth for both processes. | -| `src/shared/ipc/validators.ts` | Runtime payload parsers and type guards. Every `invoke` payload is validated here before the handler runs. | -| `src/preload.ts` | Renderer-side bridge. Exposes a typed API surface to the renderer - only approved channels are accessible. | -| `src/main/ipc-runtime.ts` | Main-process handler registration and routing. Wires validated channels to domain handlers. | -| `src/core/services/ipc.ts` | Service-level invoke handling. Applies guardrails (validation, error wrapping) before calling domain logic. | -| `src/core/services/anki-jimaku-ipc.ts` | Integration-specific IPC boundary for Anki and Jimaku operations. | -| `src/main/cli-runtime.ts` | CLI/runtime command boundary. Handles commands that originate from the launcher or mpv plugin rather than the renderer. | +| File | Role | +| -------------------------------------- | ----------------------------------------------------------------------------------- | +| `src/shared/ipc/contracts.ts` | Channel names and payload types, shared by both processes | +| `src/shared/ipc/validators.ts` | Runtime payload parsers and type guards | +| `src/preload.ts` | Typed renderer API; only approved channels are exposed | +| `src/core/services/ipc.ts` | Registers overlay handlers and validates payloads before calling domain logic | +| `src/core/services/anki-jimaku-ipc.ts` | Same boundary for Anki and Jimaku operations | +| `src/main/ipc-runtime.ts` | Builds handler dependencies (via `src/main/dependencies.ts`) and registers handlers | +| `src/main/cli-runtime.ts` | Handles commands from the launcher or mpv plugin, not the renderer | ## Contract rules -These rules exist to prevent a class of bugs where the renderer and main process silently disagree about message shapes - which surfaces as undefined fields, swallowed errors, or state corruption. - -- **Use shared constants.** Channel names come from `contracts.ts`, never ad-hoc literal strings. This makes channels greppable and refactor-safe. -- **Validate before handling.** Every `invoke` payload passes through `validators.ts` before reaching domain logic. This catches shape drift at the boundary instead of deep inside a service. -- **Return structured failures.** Handlers return `{ ok: false, error: string }` on failure rather than throwing. The renderer can always distinguish success from failure without try/catch. -- **Keep payloads narrow.** Send only what the handler needs. Avoid passing entire state objects across the bridge - it couples the renderer to internal main-process structure. -- **Co-evolve all layers.** When a payload shape changes, update `contracts.ts`, `validators.ts`, `preload.ts`, and the handler in the same commit. Partial updates are treated as bugs. - -## Two message patterns - -**Invoke (request/response):** The renderer calls a typed bridge method and awaits a result. The main process validates the payload, runs the handler, and returns a structured response. Used for operations where the renderer needs a result - lookups, config reads, mining actions. - -**Fire-and-forget (send):** The renderer sends a message with no response. The main process validates and handles it silently. Malformed payloads are dropped. Used for notifications where the renderer doesn't need confirmation - UI state hints, focus events, position updates. +- **Use the shared constants.** Take channel names from `contracts.ts`, never string literals. +- **Validate before handling.** Every renderer payload goes through `validators.ts` before domain logic. +- **Return structured failures.** Invoke handlers return `{ ok: false, ... }` on failure instead of throwing, so the renderer can tell success from failure without try/catch. +- **Keep payloads narrow.** Send only what the handler needs, not whole state objects. +- **Keep handlers thin.** Validate, delegate to a service or composer, return. Route shared state changes through the transition helpers in `src/main/state.ts`. ## Add a new IPC action 1. Add the channel constant in `src/shared/ipc/contracts.ts`. -2. Add or extend the payload validator in `src/shared/ipc/validators.ts`. +2. Add or extend the validator in `src/shared/ipc/validators.ts`. 3. Expose a typed bridge method in `src/preload.ts`. -4. Register the handler in `src/main/ipc-runtime.ts` (or the relevant domain runtime module). -5. Add tests for both valid and malformed payload cases in `src/core/services/*`. -6. Update renderer tests when behavior or state transitions change. - -## Runtime state notes - -- Prefer runtime/domain composition via `src/main/runtime/composers/*` and `src/main/runtime/domains/*`. IPC handlers should delegate to composers rather than containing orchestration logic. -- Route shared mutable state updates through transition helpers in `src/main/state.ts` for migrated domains. Direct mutation from IPC handlers bypasses invariant checks. -- Keep IPC handlers thin - they validate, delegate, and return. Business logic belongs in services. +4. Register the handler in `src/core/services/ipc.ts` (or `anki-jimaku-ipc.ts`), and supply any new dependency through `src/main/ipc-runtime.ts`. +5. Test valid and malformed payloads in `src/core/services/*`. +6. Update renderer tests if behavior or state transitions change. ## Troubleshooting -- **Unknown payload in handler:** The validator is not being applied before the handler runs. Check that the channel is routed through `ipc-runtime.ts` with validation, not registered directly. -- **Renderer invoke fails:** Verify the preload bridge method exists and matches the channel constant. Check that the handler is registered and returning (not throwing). -- **Contract drift:** When invoke calls return unexpected shapes, compare the shared contract, validator, preload bridge, and main handler signatures side by side. One of them was updated without the others. +- **Handler receives an unexpected payload:** the validator is not applied. Check that the channel is registered through the IPC service with validation, not directly. +- **Renderer invoke fails:** check that the preload method exists, uses the right channel constant, and that the handler is registered and returns instead of throwing. +- **Invoke returns an unexpected shape:** compare the contract, validator, preload method, and handler side by side. One of them changed without the others. ## Related docs - [Architecture](/architecture) -- [Development](/development) -- [Configuration](/configuration) -- [Troubleshooting](/troubleshooting) +- [Building and testing](/development) diff --git a/docs-site/jellyfin-integration.md b/docs-site/jellyfin-integration.md index ba3ecab8..2c66c07c 100644 --- a/docs-site/jellyfin-integration.md +++ b/docs-site/jellyfin-integration.md @@ -1,122 +1,60 @@ # Jellyfin integration -[Jellyfin](https://jellyfin.org) is a free, self-hosted media server, a private streaming service for video you already own. If your anime lives on a Jellyfin server, SubMiner plays episodes from it through mpv with the mining overlay attached. +If your anime lives on a [Jellyfin](https://jellyfin.org) server, SubMiner can appear as a cast target in any Jellyfin client. Cast an episode and it plays in SubMiner's mpv with the overlay and Yomitan lookup attached. -::: tip Who needs this? -This page only matters if you already run a Jellyfin server or have access to one. Watching local files or YouTube? Skip it. Otherwise start with the in-app setup window (`subminer jellyfin`). -::: +## Setup -SubMiner can register itself as a **cast-to-device target**, the way jellyfin-mpv-shim does. Sign in once, turn on discovery, and SubMiner appears in the "Play on" menu of any Jellyfin client, whether that is the web app, your phone, or a TV. Cast an episode and it opens in SubMiner's mpv window with the overlay and Yomitan lookup live. +You need a Jellyfin server (Jellyfin 12 is supported) and your username and password. -This is the recommended way to use Jellyfin with SubMiner. A terminal-only option is covered in [Launcher playback](#launcher-playback) at the end. +1. Start SubMiner and leave it in the system tray. +2. Open the tray menu and click **Configure Jellyfin**. You can also run `subminer jellyfin`. +3. Enter the **Server URL** (for example `http://127.0.0.1:8096`), **Username**, and **Password**, then click **Login**. -## Requirements +SubMiner stores an encrypted session token, not your password, and turns the integration on. Reopen the same window to switch servers or log out. -- A Jellyfin server plus your username and password (Jellyfin 12, which disables legacy authorization by default, is supported) -- SubMiner installed and running (see [Installation](/installation)) -- On Linux, the session token is stored with `gnome-libsecret` by default +## Casting from Jellyfin -## Quick start +After you sign in, SubMiner connects to Jellyfin at startup and shows up in the cast ("Play on") menu under your computer's hostname. To connect for the current session only, tick **Jellyfin Discovery** in the tray menu. -### 1. start SubMiner +1. In the Jellyfin web or mobile app, start playing an episode. +2. Open the cast menu and pick your computer. -Launch SubMiner and leave it in the system tray. +SubMiner starts mpv if it is not already running. Pause, seek, stop, and track changes in the Jellyfin app are mirrored in mpv, and watch progress syncs back to Jellyfin. Playback resumes from Jellyfin's saved position. -### 2. sign in to your server +SubMiner selects a Japanese subtitle track automatically and resets mpv's subtitle delay to zero. It direct-plays files when it can and asks Jellyfin to transcode the rest. -Open the tray menu and click **Configure Jellyfin**. In the window that opens, enter your **Server URL** (for example `http://127.0.0.1:8096`), **Username**, and **Password**, then click **Login**. +On Windows, casting finds mpv through `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then `PATH`. An invalid `mpv.executablePath` stops mpv from starting. -On success, SubMiner: +## Playing from the terminal -- saves an encrypted session token - your password is never stored, -- turns the Jellyfin integration on, and -- remembers the server and username for next time. +The launcher can browse your libraries and play an item without a Jellyfin client: -Reopen this window any time to switch servers or **Logout**. - -### 3. turn on discovery - -Discovery is what makes SubMiner appear as a cast target. Two ways to enable it: - -- **For the current session** - open the tray menu and tick **Jellyfin Discovery**. (This item appears once you've signed in.) -- **Automatically on every launch** - already on by default. After your first sign-in, SubMiner auto-connects to Jellyfin at startup, so the cast target is ready without touching the tray. You can change this under [Settings](#settings). - -### 4. cast from any Jellyfin app - -In the Jellyfin web UI or mobile app, start playing something, open the **cast / "Play on"** menu, and pick your device - SubMiner appears there named after your computer's hostname. Playback opens in SubMiner. - -From then on, pause / resume / seek / stop and audio or subtitle track changes you make in the Jellyfin app are mirrored in SubMiner, and your watch progress syncs back to Jellyfin (now-playing and resume position). - -## What happens during playback - -- **mpv launches automatically.** If mpv isn't already running when you cast, SubMiner starts it with SubMiner defaults and the bundled mpv plugin, so keybindings work right away. -- **Windows respects your mpv settings.** Casting checks `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then `PATH`. An invalid configured path prevents automatic startup. -- **The overlay is managed by SubMiner,** so your configured `subtitleStyle` controls how subtitles look. Use the [overlay-toggle shortcut](/shortcuts) to hide it for a session. -- **Resume works.** If Jellyfin has a saved position for the item, SubMiner seeks there on load. -- **Titles and credentials stay separate.** AniList, character dictionaries, Anki source fields, and Discord presence use media titles, never authenticated stream URLs. If a usable title is unavailable, lookups are skipped and source fields show an unknown-media label. Stats identifies Jellyfin videos by server and item ID without the stream URL or API key. -- **Direct play first.** When the source allows it and the container is in your direct-play allowlist, SubMiner streams the original file; otherwise it requests a transcoded stream from Jellyfin. -- **Japanese subtitles are auto-selected,** preferring Jellyfin's default and embedded tracks over external sidecar files when several match. -- **Downloaded subtitles keep their original timing.** SubMiner removes Jellyfin's server-selected subtitle stream from the mpv load URL, suppresses the mpv plugin's one-shot subtitle auto-selection and overlay auto-start for managed Jellyfin loads, stages the subtitle files exposed by Jellyfin without letting mpv auto-switch between tracks, resets mpv's subtitle delay to zero, then selects the Japanese track. SubMiner does not compare Japanese and English cue timelines or save an inferred delay. - -On startup, SubMiner clears cached anime parser metadata containing both API-key text and Jellyfin stream markers. Metadata containing only one of these is preserved. - -## Settings - -All Jellyfin options live under **Settings → Integrations → Jellyfin** (open settings from the tray's **Open SubMiner Settings**). The ones that matter for casting: - -| Setting | Default | What it does | -| ------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | -| **Enabled** | Off | Turns the Jellyfin integration on. Switched on for you when you sign in. | -| **Server Url** | - | Your Jellyfin server. Filled in when you sign in. | -| **Remote Control Enabled** | On | Lets SubMiner act as a cast target. | -| **Remote Control Auto Connect** | On | Connects to Jellyfin at startup so discovery is automatic. Turn off if you'd rather start it from the tray each time. | -| **Auto Announce** | Off | Re-broadcasts visibility on connect. Enable if your device is slow to appear in the cast menu. | - -Prefer editing the config file? The same keys live under `jellyfin` in `config.jsonc`: - -```jsonc -{ - "jellyfin": { - "enabled": true, - "serverUrl": "http://127.0.0.1:8096", - "remoteControlEnabled": true, - "remoteControlAutoConnect": true, - }, -} +```bash +subminer jellyfin -p # fzf picker; `jf` is an alias for `jellyfin` +subminer -R jellyfin -p # rofi picker ``` -See [Configuration](/configuration) for the full list (transcode codec, direct-play containers, default library, and more). +Sign in first. See [Launcher script](/launcher-script) for the other `jellyfin` subcommands. + +## Options + +All options are under **Settings > Integrations > Jellyfin**, or `jellyfin` in `config.jsonc`. See [Configuration](/configuration#jellyfin) for the full list and defaults. + +| Key | What it does | +| -------------------------- | -------------------------------------------------------------------- | +| `enabled` | Turns the integration on. Set for you when you sign in. | +| `serverUrl` | Your Jellyfin server. Filled in when you sign in. | +| `remoteControlEnabled` | Lets SubMiner act as a cast target. | +| `remoteControlAutoConnect` | Connects at startup. Turn off to start discovery from the tray. | +| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. | +| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. | + +For headless setups, `SUBMINER_JELLYFIN_ACCESS_TOKEN` and `SUBMINER_JELLYFIN_USER_ID` supply a session without the sign-in window. Treat the token store and `config.jsonc` as secrets. ## Troubleshooting -**SubMiner doesn't appear in the cast menu** +**SubMiner is missing from the cast menu.** Check that SubMiner is running, that you are signed in (log in again if the token expired), and that discovery is on. The Jellyfin client and SubMiner must use the same server. -- Make sure SubMiner is running. -- Make sure you're signed in - reopen **Configure Jellyfin** and log in again if your token expired. -- Make sure discovery is on (tray **Jellyfin Discovery**, or **Remote Control Auto Connect** in settings). -- Make sure SubMiner and the Jellyfin client point at the same server. +**Casting starts but nothing plays.** Confirm the item plays in another Jellyfin client. If mpv was closed, give SubMiner a few seconds to start it. -**Casting starts but nothing plays** - -- Confirm the item plays normally in another Jellyfin client. -- If mpv was closed, give it a moment - SubMiner launches it on demand and retries. - -**SubMiner keeps disconnecting** - -- Check server/network stability and whether the session token has expired. - -## Security notes - -- The Jellyfin session (access token + user ID) is kept in SubMiner's local encrypted token storage. Your password is used only to log in and is never saved. -- Treat the token storage and your `config.jsonc` as secrets - don't commit them. -- Advanced/headless: the `SUBMINER_JELLYFIN_ACCESS_TOKEN` and `SUBMINER_JELLYFIN_USER_ID` environment variables can supply a session without the sign-in window. - -## Launcher playback - -If you'd rather stay in the terminal, the `subminer` launcher can browse and play Jellyfin media directly, without casting from a Jellyfin app: - -```bash -subminer jellyfin -p # alias: subminer jf -p -``` - -This opens an fzf picker (add `-R` for rofi) to browse your libraries and episodes, then plays the selected item in SubMiner's mpv with the same overlay, resume, and subtitle behavior described above. Sign in first (step 2) so the launcher can reach your server. See [Launcher Script](/launcher-script) for the rest of the launcher's features. +**Linux token storage fails.** SubMiner stores the token with `gnome-libsecret` by default. Start your keyring, or pass `--password-store=basic_text`. diff --git a/docs-site/jimaku-integration.md b/docs-site/jimaku-integration.md index 424df300..51af5f7a 100644 --- a/docs-site/jimaku-integration.md +++ b/docs-site/jimaku-integration.md @@ -1,118 +1,62 @@ # Jimaku integration -[Jimaku](https://jimaku.cc) is a community subtitle repository for anime and Japanese live action, built from files other learners uploaded. SubMiner talks to the Jimaku API, so you search, browse, and download Japanese subtitle files from inside the overlay. No alt-tabbing, no moving files around. A downloaded track loads into mpv right away. +[Jimaku](https://jimaku.cc) is a community archive of Japanese subtitles for anime and live action. SubMiner searches it from the overlay, downloads the file you pick, and loads it into mpv. -::: tip Prerequisite: a free API key -You need a Jimaku account and an API key (a personal access string) before this feature works. Create an account at [jimaku.cc](https://jimaku.cc), copy your key, and add it to your config as shown under [Configuration](#configuration) below. Without a key, the search modal will report "Jimaku API key not set." -::: +## Setup -## How it works - -The Jimaku integration runs through an in-overlay modal accessible via a keyboard shortcut (`Ctrl+Shift+J` by default). - -When you open the modal, SubMiner parses the current video filename to extract a title, season, and episode number. It handles `S01E03`, `1x03`, `E03`, and dash-separated episode numbers. If the filename yields a high-confidence match (title + episode), SubMiner auto-searches immediately. - -From there: - -1. **Pick a catalogue** - The **Anime** and **Live action** tabs at the top of the modal choose which Jimaku catalogue to search. Switching tabs re-runs the current search. The choice persists until SubMiner restarts. -2. **Search** - SubMiner queries the Jimaku API with the parsed title. Results appear as a list of entries (Japanese and English names). -3. **Browse entries** - Select an entry to load its available subtitle files, filtered by episode if one was detected. -4. **Browse files** - Files show name, size, and last-modified date. If a language preference is configured, files are sorted accordingly (e.g., Japanese-tagged files first). -5. **Download** - Selecting a file downloads it to the same directory as the video (or a temp directory for remote/streamed media) and loads it into mpv as a new subtitle track. - -If no files match the current episode filter, a "Show all files" button lets you broaden the search to all episodes for that entry. - -### Modal keyboard shortcuts - -| Key | Action | -| ---------------------------- | --------------------------------------------- | -| `Enter` (in text field) | Search | -| `Enter` (in list) | Select entry / download file | -| `Arrow Up` / `Arrow Down` | Navigate entries or files | -| `Arrow Left` / `Arrow Right` | Switch between the Anime and Live action tabs | -| `Escape` | Close modal | - -## Configuration - -Add a `jimaku` section to your `config.jsonc`: +1. Create a free account at [jimaku.cc](https://jimaku.cc) and copy your API key. +2. Add the key to `config.jsonc`, either directly or through a command that prints it: ```jsonc { "jimaku": { "apiKey": "YOUR_API_KEY", - "apiKeyCommand": "cat ~/.jimaku_key", - "apiBaseUrl": "https://jimaku.cc", - "languagePreference": "ja", - "maxEntryResults": 10, + // or, to keep it out of the config file: + // "apiKeyCommand": "pass jimaku/api-key", }, } ``` -| Option | Type | Default | Description | -| --------------------------- | ---------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `jimaku.apiKey` | `string` | - | Jimaku API key (plaintext). Mutually exclusive with `apiKeyCommand`. | -| `jimaku.apiKeyCommand` | `string` | - | Shell command that prints the API key to stdout. Useful for secret managers (e.g., `pass jimaku/api-key`). | -| `jimaku.apiBaseUrl` | `string` | `"https://jimaku.cc"` | Base URL for the Jimaku API. Only change this if using a mirror or local instance. | -| `jimaku.languagePreference` | `"ja"` \| `"en"` \| `"none"` | `"ja"` | Sort subtitle files by language tag. `"ja"` pushes Japanese-tagged files to the top; `"en"` does the same for English. `"none"` preserves the API order. | -| `jimaku.maxEntryResults` | `number` | `10` | Maximum number of entries returned per search. | +If both are set, `apiKey` wins. `apiKeyCommand` must print the key within 10 seconds. Without a key, the modal shows "Jimaku API key not set." -The keyboard shortcut is configured separately under `shortcuts`: +## Usage -```jsonc -{ - "shortcuts": { - "openJimaku": "Ctrl+Shift+J", - }, -} -``` +1. Press `Ctrl+Shift+J` during playback. +2. SubMiner fills in the title, season, and episode from the file name. If it finds both a title and an episode, it searches right away. Otherwise, fix the fields and press `Enter`. +3. Pick the **Anime** or **Live action** tab. Switching tabs repeats the search. +4. Select an entry, then select a file. Files are filtered to the current episode. Click **Broaden search (all files)** to see every file in the entry. -### API key +The file is saved next to the video (or to a temp directory for streams) and loaded into mpv as a new subtitle track. -An API key is required to use the Jimaku integration. You can get one from [jimaku.cc](https://jimaku.cc). There are two ways to provide it: +| Key | Action | +| ---------------- | -------------------------------------- | +| `Enter` | Search, or select the highlighted item | +| `Up` / `Down` | Move through entries or files | +| `Left` / `Right` | Switch tabs | +| `Escape` | Close | -- **`apiKey`** - set the key directly in config. Simple, but the key is stored in plaintext. -- **`apiKeyCommand`** - a shell command that outputs the key. Runs with a 10-second timeout. Preferred if you use a secret manager like `pass`, `gpg`, or a keychain tool. +You can also open the modal with `subminer app --open-jimaku`, or change the shortcut with `shortcuts.openJimaku`. -If both are set, `apiKey` takes priority. +The file name parser understands `S01E03`, `1x03`, `E03`, `EP03`, and `Title - 03 -` patterns, and reads the season from a parent folder such as `Season 2`. It ignores bracket tags like `[SubGroup]` and year tags like `(2024)`. -## Filename parsing +## Options -SubMiner extracts media info from the current video path to pre-fill the search fields. The parser handles: +| Key | What it does | +| --------------------------- | ------------------------------------------------------------------- | +| `jimaku.apiKey` | API key in plain text. | +| `jimaku.apiKeyCommand` | Shell command that prints the API key. | +| `jimaku.languagePreference` | Sorts files tagged with this language first: `ja`, `en`, or `none`. | +| `jimaku.maxEntryResults` | Maximum entries per search. | +| `jimaku.apiBaseUrl` | API address. Change only for a mirror. | -- **Season + episode patterns:** `S01E03`, `1x03` -- **Episode-only patterns:** `E03`, `EP03`, or dash-separated numbers like `Title - 03 -` -- **Season folders:** a parent directory named `Season 2` or `S2` fills in the season when the filename lacks one -- **Bracket tags:** `[SubGroup]`, `[1080p]`, `[HEVC]` - stripped before title extraction -- **Year tags:** `(2024)` - stripped -- **Dots and underscores:** treated as spaces -- **Remote/streamed URLs:** SubMiner checks URL query parameters (`title`, `name`, `q`) and path segments to extract a meaningful title - -If the parser produces a high-confidence result (title + episode both detected), the search runs automatically when the modal opens. Otherwise, you can adjust the fields manually before searching. +See [Configuration](/configuration#jimaku) for defaults. ## Troubleshooting -**"Jimaku API key not set"** +**"Jimaku API key not set."** Set `jimaku.apiKey` or `jimaku.apiKeyCommand`. Run the command in your shell to confirm it prints only the key. -Configure `jimaku.apiKey` or `jimaku.apiKeyCommand` in your config. If using `apiKeyCommand`, verify the command works in your shell: it should print the key and exit cleanly. +**HTTP 429.** You hit Jimaku's rate limit. Wait for the time shown in the message and retry. -**"Jimaku request failed" or HTTP 429** +**No entries found.** Search with just the show's name, without season or episode words. Jimaku matches against its own titles. -The Jimaku API has rate limits. If you see 429 errors, wait for the retry duration shown in the OSD message and try again. - -**No entries found** - -Try simplifying the title - remove season/episode qualifiers and search with just the anime name. Jimaku's search matches against its own database of anime titles, so the exact spelling matters. - -**No files found for this episode** - -The entry may not have per-episode files, or files may be named differently. Click "Show all files" to see everything available for the entry. - -**Downloaded subtitle not loading** - -Verify mpv is running and connected via IPC. SubMiner loads the subtitle by issuing a `sub-add` command over the mpv socket. If mpv is not connected, the download succeeds but the subtitle cannot be loaded. - -## Related - -- [Configuration Reference](/configuration#jimaku) - full config options -- [Mining Workflow](/mining-workflow#related-features) - how Jimaku fits into the sentence mining loop -- [Troubleshooting](/troubleshooting#jimaku) - additional error guidance +**The subtitle downloads but does not load.** SubMiner loads it over the mpv socket. Make sure mpv is still running and connected. diff --git a/docs-site/launcher-script.md b/docs-site/launcher-script.md index 4e1d04f3..bd459095 100644 --- a/docs-site/launcher-script.md +++ b/docs-site/launcher-script.md @@ -1,225 +1,195 @@ # Launcher script -The `subminer` launcher handles video selection, mpv startup, and overlay management in one script. It guarantees mpv starts with the right IPC socket and SubMiner defaults. On Windows, the **SubMiner mpv** shortcut remains the recommended playback entry point. +`subminer` is the command-line entry point for SubMiner. It starts mpv with the socket and options SubMiner needs, opens file pickers, and runs helper commands. This page is the reference for its subcommands and flags. For everyday use, start with [Usage](/usage). -The launcher is a small wrapper around the CLI bundled in the desktop app. It locates a normal SubMiner installation, or uses `SUBMINER_BINARY_PATH` when you set a custom executable. Linux also accepts `SUBMINER_APPIMAGE_PATH`. First-run setup records the selected app location for the wrapper. You do not need Bun installed or on `PATH`; only the directory containing `subminer` needs to be on `PATH`. +You do not need Bun or anything else installed to run it. It uses the runtime bundled with the app. On Windows, the **SubMiner mpv** shortcut is the simpler way to play files (see [Windows mpv shortcut](/usage#windows-mpv-shortcut)). -On macOS, the wrapper runs Bun and the CLI directly from `SubMiner.app/Contents/Resources`. On Windows, `subminer.cmd` stages a versioned private Bun copy under `%LOCALAPPDATA%\SubMiner\launcher-runtime/<version>` and runs the CLI from the current app. Keeping the executable outside the app avoids locking an updater-owned file while a launcher is running. Old runtime versions are removed when no running launcher is using them. +```bash +subminer [options] [file | directory | URL] +subminer <subcommand> [options] +``` -On Linux, the first launch caches Bun and its matching CLI and license files under `${XDG_DATA_HOME:-~/.local/share}/SubMiner/launcher`. Later launches make one `stat` call against the AppImage and run the cache without starting Electron. A missing cache or changed app fingerprint rebuilds it. App startup also refreshes the managed payload after an update. +Run `subminer -h` or `subminer <subcommand> -h` for built-in help. -The downloaded `subminer` and `subminer.cmd` release assets use the same private runtime flow. Older launcher scripts that were installed before this change cannot update their own code retroactively and still need system Bun until the app migrates them at startup or you download a current wrapper. +## Options -::: tip Windows users -On Windows, the recommended way to launch playback is the **SubMiner mpv** shortcut created during first-run setup - double-click it, drag a file onto it, or run `SubMiner.exe --launch-mpv` from a terminal. See [Windows mpv Shortcut](/usage#windows-mpv-shortcut) for details. -::: +| Flag | Description | +| --------------------- | ----------------------------------------------------------------------------------- | +| `-d, --directory` | Directory to browse (default: current directory) | +| `-r, --recursive` | Search subdirectories | +| `-R, --rofi` | Use rofi instead of fzf | +| `-H, --history` | Browse [watch history](#watch-history) | +| `-b, --backend` | Window backend: `auto`, `hyprland`, `sway`, `x11`, `macos`, `windows` | +| `-p, --profile` | mpv profile to load | +| `-a, --args` | Extra mpv options as one quoted string, e.g. `--args "--volume=80"` | +| `--start` | Start the overlay after mpv launches. Only needed if `mpv.autoStartSubMiner` is off | +| `-S, --start-overlay` | Show the overlay on start | +| `-T, --no-texthooker` | Do not start the texthooker server | +| `--settings` | Open the settings window | +| `--log-level` | `debug`, `info`, `warn`, or `error` | +| `-u, --update` | Check for and install updates | +| `-v, --version` | Print the launcher's version | + +The target can be a video file, a directory (opens the picker there), a URL, or `ytsearch:"query"` for the first YouTube search result. + +App flags such as `--setup` and `--dev` are not launcher flags. Pass them through with `subminer app`, for example `subminer app --setup`. + +## Subcommands + +| Command | What it does | +| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | +| `subminer stats` | Start the stats dashboard server. Opens your browser if `stats.autoOpenBrowser` is on | +| `subminer stats -b` / `-s` | Start (or reuse) the stats server in the background / stop it | +| `subminer stats cleanup` | Backfill vocabulary metadata and prune stale rows (same as `-v`) | +| `subminer stats cleanup -l` | Rebuild lifetime totals from the retained sessions | +| `subminer stats cleanup -d` | Collapse repeated lines from typeset subtitles. Add `--dry-run` to preview, `--lookback-days <n>` to limit the range | +| `subminer stats rebuild` / `backfill` | Same as `stats cleanup -l` | +| `subminer sync <host>` | Sync stats and watch history with another machine. See [below](#sync-between-machines) | +| `subminer doctor` | Check the app, mpv, ffmpeg, yt-dlp, pickers, config, and mpv socket | +| `subminer doctor --refresh-known-words` | Refresh the known-word cache from Anki | +| `subminer settings` | Open the settings window | +| `subminer generate-subs [video]` | Generate [Japanese subtitles](/subtitle-generation) with whisper.cpp | +| `subminer jellyfin` / `jf` | [Jellyfin](/jellyfin-integration) actions: `setup`, `login`, `logout`, `play`, `discovery` | +| `subminer dictionary <path>` / `dict` | Build a [character dictionary](/character-dictionary) for a file or directory | +| `subminer dictionary --candidates <path>` | List AniList matches for that target | +| `subminer dictionary --select <id> <path>` | Pin an AniList ID for that target | +| `subminer texthooker` | Run only the texthooker server. `-o` opens it in your browser | +| `subminer logs -e` | Export a sanitized log ZIP and print its path | +| `subminer config path` / `show` | Print the config file path or its contents | +| `subminer mpv status` | Exit 0 if the mpv socket is ready, 1 if not | +| `subminer mpv socket` | Print the mpv socket path | +| `subminer mpv idle` | Start an idle mpv in the background with SubMiner's options | +| `subminer app` / `bin` | Pass arguments to the SubMiner app, e.g. `subminer app --stop` | + +`stats cleanup` runs one mode at a time. `--lookback-days` must be at least 1. Without it, cleanup scans all history. + +`generate-subs` options: `--download-model`, `--model <name>`, `--model-path <file>`, `--output <file>`, and `--audio-stream <index>` (an ffprobe stream index). `--model-path` cannot be combined with `--model` or `--download-model`. + +A texthooker is a web page that shows the current subtitle as plain text, so browser extensions and other tools can read along. ## Video picker -Run `subminer` with no file and it opens an interactive picker. That is **fzf** in the terminal by default, or **rofi** with `-R`. +With no file argument, `subminer` opens a picker for the current directory, or for `-d <dir>`. Add `-r` to include subdirectories. -### fzf (default) +- **fzf** (default) runs in the terminal. With `chafa` installed, it shows thumbnail previews. +- **rofi** (`-R`, Linux) opens a graphical menu with thumbnails. + +Thumbnails come from your system thumbnail cache, or are generated with `ffmpegthumbnailer` or `ffmpeg`. + +The launcher installs its rofi theme automatically. To use your own, set `SUBMINER_ROFI_THEME`: ```bash -subminer # pick from current directory -subminer -d ~/Videos # pick from a specific directory -subminer -r -d ~/Anime # recursive search -``` - -fzf shows video files in a fuzzy-searchable list. If `chafa` is installed, you get thumbnail previews in the right pane. Thumbnails are sourced from the freedesktop thumbnail cache first, then generated on the fly with `ffmpegthumbnailer` or `ffmpeg` as fallback. - -| Optional tool | Purpose | -| ------------------- | --------------------------------- | -| `chafa` | Render thumbnails in the terminal | -| `ffmpegthumbnailer` | Generate thumbnails on the fly | - -### rofi - -```bash -subminer -R # rofi picker, current directory -subminer -R -d ~/Videos # rofi picker, specific directory -subminer -R -r -d ~/Anime # rofi picker, recursive -subminer -R /directory # rofi picker, directory shortcut -``` - -rofi shows a GUI menu with icon thumbnails when available. SubMiner ships the rofi theme, a scoped `ffmpegthumbnailer` MIME registration, and the Linux launcher-managed runtime plugin copy in the release assets tarball: - -```bash -wget https://github.com/ksyasuda/SubMiner/releases/latest/download/subminer-assets.tar.gz -O /tmp/subminer-assets.tar.gz -tar -xzf /tmp/subminer-assets.tar.gz -C /tmp -mkdir -p ~/.local/share/SubMiner/themes -cp /tmp/assets/themes/subminer.rasi ~/.local/share/SubMiner/themes/subminer.rasi -mkdir -p ~/.local/share/SubMiner/thumbnailers -cp /tmp/assets/thumbnailers/subminer-ffmpegthumbnailer.thumbnailer ~/.local/share/SubMiner/thumbnailers/ -mkdir -p ~/.local/share/SubMiner/plugin -cp -R /tmp/plugin/subminer ~/.local/share/SubMiner/plugin/subminer -``` - -Once the `SubMiner` data dir exists, `subminer -u` refreshes these assets automatically. Normal Linux launcher playback checks for all three assets and installs them from the bundled app when one is missing. For `subminer -R`, this repair runs before rofi opens. - -When `ffmpegthumbnailer` is installed, SubMiner prepends its own data directory to `XDG_DATA_DIRS` for the rofi process only. This lets rofi recognize the canonical Matroska MIME types used by newer GLib versions without changing the desktop-wide MIME or thumbnailer configuration. An existing registration in your own `$XDG_DATA_HOME/thumbnailers` still takes priority. - -The theme is auto-detected from these paths (first match wins): - -- `$SUBMINER_ROFI_THEME` environment variable (absolute path) -- `$XDG_DATA_HOME/SubMiner/themes/subminer.rasi` (default: `~/.local/share/SubMiner/themes/subminer.rasi`) -- `/usr/local/share/SubMiner/themes/subminer.rasi` -- `/usr/share/SubMiner/themes/subminer.rasi` -- macOS: `~/Library/Application Support/SubMiner/themes/subminer.rasi` -- `assets/themes/subminer.rasi` next to the launcher script (final fallback) - -Override with the `SUBMINER_ROFI_THEME` environment variable: - -```bash -SUBMINER_ROFI_THEME=/path/to/custom-theme.rasi subminer -R +SUBMINER_ROFI_THEME=/path/to/theme.rasi subminer -R ``` ## Watch history -`subminer -H` (or `--history`) browses your local watch history, sourced from the immersion tracker database. It works with both pickers: fzf by default, rofi with `-R -H`. +`subminer -H` lists the shows you have watched, most recent first. Add `-R` to use rofi. Pick a show, then choose: -```bash -subminer -H # fzf history browser -subminer -R -H # rofi history browser +- **Previous episode** or **Next episode**, moving into the neighboring season folder when needed +- **Replay last watched** +- **Browse episodes**, with a season menu first if the show has several season folders +- **Quit SubMiner** + +When an episode ends, the menu comes back for the same show. Press `Escape` to leave. + +History comes from the immersion stats database, which SubMiner fills during playback. Shows whose folders are not reachable, such as an unmounted network drive, are hidden. + +## mpv options and profiles + +The launcher starts mpv with these options: + +``` +--input-ipc-server=/tmp/subminer-socket +--alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us +--slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us +--sub-auto=fuzzy +--sub-file-paths=.;subs;subtitles +--sid=auto +--secondary-sid=auto +--sub-visibility=no +--secondary-sub-visibility=no ``` -The first menu lists every locally watched series, most recently watched first, using the parsed media title (e.g. the anime title) when available and the directory name otherwise. Selecting a series opens an action menu: +mpv's own subtitles are hidden because the overlay draws them. Add more options with `-a`, or load an mpv profile with `-p <name>` or `mpv.profile` in the config. No profile is loaded by default. -- **Previous episode**: plays the episode before the last watched one and continues into the previous season directory when the season starts -- **Replay last watched**: replays the most recently watched episode -- **Next episode**: plays the episode after the last watched one and continues into the next season directory when the season ends -- **Browse episodes**: lists the video files in the series directory in episode order, using the same fzf/rofi episode picker as directory browsing; if the series has multiple season directories, a season menu appears first -- **Quit SubMiner**: closes the history session without starting an episode +To launch mpv yourself with the same setup, put the options in a profile in `~/.config/mpv/mpv.conf`: -After an episode ends or you close mpv, the launcher returns to an action menu for the same series. The menu lists Previous, Rewatch, Next, Select episode, and Quit SubMiner in that order, omitting Previous or Next when no episode exists in that direction. Choosing Previous or Next can move between season directories. After you play another episode, Previous, Rewatch, and Next use it instead of the older database entry. Pressing Escape closes the history session. +```ini +[subminer] +input-ipc-server=/tmp/subminer-socket +alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us +slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us +sub-auto=fuzzy +sub-file-paths=.;subs;subtitles +sid=auto +secondary-sid=auto +secondary-sub-visibility=no +``` -Series whose directories are not currently accessible (e.g. an unmounted network share) are hidden from the list. Watch history requires the immersion tracker database (`immersionTracking.dbPath`, default `<config dir>/immersion.sqlite`), which SubMiner populates during playback. +Launches through `subminer` start the overlay automatically unless `mpv.autoStartSubMiner` is off. mpv started outside SubMiner does not start the overlay on its own. ## Sync between machines -`subminer sync <host>` merges immersion stats and watch history between two machines over SSH, so both end up with the union of sessions, lifetime totals, vocabulary counts, daily/monthly charts, and `--history` entries. `<host>` is anything `ssh` accepts (`user@hostname` or an ssh config alias); SubMiner must be installed on both machines at the same version. The sync engine runs only inside the app (`SubMiner --sync-cli sync ...`): the sync window spawns it that way, `subminer sync` is a thin proxy that forwards to the installed app, and the remote side is found automatically whether it has the launcher or just the app. The command-line launcher is optional everywhere. +`subminer sync <host>` merges immersion stats and watch history between two computers over SSH. Both end up with the combined sessions, totals, vocabulary, charts, and `-H` history. `<host>` is anything `ssh` accepts, such as `user@hostname` or an alias from your SSH config. + +Both machines need the same SubMiner version. The remote only needs the app. The `subminer` command is optional there. ```bash -subminer sync macbook # two-way sync with the host "macbook" -subminer sync macbook --push # merge local data into macbook only -subminer sync macbook --pull # merge macbook data into local only -subminer sync user@192.168.1.20 # explicit user@host -subminer sync macbook --remote-cmd ~/bin/subminer # custom remote SubMiner/launcher path -subminer sync macbook --check # test SSH + remote SubMiner without syncing -subminer sync --ui # open the sync window (also in the tray menu) +subminer sync macbook # two-way sync +subminer sync macbook --push # send local data to macbook only +subminer sync macbook --pull # bring macbook data here only +subminer sync macbook --check # test SSH and the remote install, change nothing +subminer sync macbook --remote-cmd ~/Apps/SubMiner.AppImage # SubMiner in a custom place on the remote +subminer sync --ui # open the sync window ``` -How it works: each side takes a consistent snapshot of its database (`VACUUM INTO`), the snapshots are exchanged over SSH, and each machine merges the other's snapshot into its own database. The merge is an insert-only union keyed on stable identifiers (session UUIDs, video keys, series title keys, word/kanji identity), so it is safe to re-run at any time. Syncing twice changes nothing, and nothing is ever overwritten or summed twice. Lifetime totals and rollup charts are updated incrementally, so history older than the session retention window is preserved on both sides. +Syncing only adds data. It never overwrites or double-counts, so you can run it as often as you like. `--push` and `--pull` do not delete anything on the receiving side. -On macOS and Linux, sync automatically uses compressed `rsync` transfers when compatible `rsync` commands are available on both machines. The last successfully received snapshot supplies matching blocks for later transfers, so unchanged data can be reused without sending it again. Only unmatched data needs to cross the connection, with compression reducing it further. Without a cached snapshot, sync sends a full compressed snapshot. Windows endpoints and machines without compatible `rsync` use compressed `scp` automatically. No extra configuration is required, and both methods work across different networks, including Tailscale connections. +Before a command-line sync, close SubMiner on both machines and stop the stats server with `subminer stats -s`, or pass `--force`. The sync window does not need this. It syncs while SubMiner and playback are running, and skips the session in progress until it finishes. -For a one-way transfer, `--push` snapshots the local database and merges it into the host without changing the local database. `--pull` snapshots the host and merges it into the local database without changing the host. These modes add missing data; they do not delete destination-only data or make the destination an exact mirror. +Transfers are compressed. When both machines have `rsync` (macOS and Linux), later syncs send only what changed. Windows machines use `scp`. -Each rsync transfer explicitly uses SSH and has a 30-minute time limit. A timed-out transfer stops the sync before merging the incomplete snapshot. +Known-word status from Anki does not sync. Each machine reads it from its own Anki collection. -Transfers write separate temporary files and verify the reconstructed content before merging. Cached comparison snapshots are preserved throughout the transfer. After a successful rsync sync, each receiver keeps one snapshot per peer/database identity in `sync-transfer-cache/` under its SubMiner config directory. This uses roughly one database-sized file per identity; deleting that cache is safe and only makes the next sync transfer more data. Missing or unwritable caches do not prevent syncing. Older peers without the cache helper still support compressed transfers, but cannot retain the upload comparison copy. +<details> +<summary><b>More sync options</b></summary> -Command-line sync defaults to a cold-start safety check: close SubMiner (and stop the background stats daemon with `subminer stats -s`) on both machines before running it, or pass `--force`. Syncs started from the Sync window use live mode automatically, including scheduled auto-syncs while SubMiner or playback is active. SQLite WAL provides a consistent snapshot, the transactional merge serializes with live writes, and each machine's unfinished session is excluded from the transfer; that session syncs normally after it finishes. The mpv safety check requires a live socket connection, so a stale socket file left after mpv exits does not block command-line sync. Both machines must be on the same SubMiner version; otherwise, the sync aborts on a stats schema mismatch. +| Option | Description | +| ------------------- | ----------------------------------------------------------- | +| `-f, --force` | Skip the check that SubMiner is closed | +| `--db <file>` | Use a different local stats database | +| `--json` | Print progress as NDJSON | +| `--snapshot <file>` | Write a snapshot of the local database, e.g. to copy by USB | +| `--merge <file>` | Merge a snapshot file into the local database | -On the remote, sync looks for the `subminer` launcher first (PATH and `~/.local/bin`), then the app binary in `--sync-cli` mode (`SubMiner` on PATH, then the standard macOS `/Applications` and `~/Applications` installs), checking standard SubMiner and Bun locations (`~/.local/bin`, `~/.bun/bin`, Homebrew, `/usr/local/bin`, `/usr/bin`, and `/bin`) even when the non-interactive SSH shell omits them from `PATH`. An AppImage in a custom location can be addressed with `--remote-cmd /path/to/SubMiner.AppImage` (or symlink it as `SubMiner` somewhere on the remote PATH). +A Windows remote needs the built-in **OpenSSH Server** enabled. SubMiner finds itself in the default install location there. -Windows remotes are supported: enable Windows' built-in **OpenSSH Server** and sync detects the remote shell (cmd or PowerShell) automatically, finding SubMiner in its default install location (`%LOCALAPPDATA%\Programs\SubMiner`), the launcher shim (`%LOCALAPPDATA%\SubMiner\bin`), or on PATH. Temp files on the remote are created and removed by SubMiner itself (`sync --make-temp` / `--remove-temp`), so no POSIX tools are required on the remote side. +If the remote cannot find SubMiner, point `--remote-cmd` at the app or launcher, or link it as `SubMiner` somewhere on the remote `PATH`. -Two lower-level modes are used internally over SSH and also work standalone for manual transfers (e.g. via a USB drive): +Received snapshots are cached in `sync-transfer-cache/` in the config directory to speed up later syncs. Deleting it is safe. -```bash -subminer sync --snapshot /tmp/stats.sqlite # write a consistent snapshot of the local database -subminer sync --merge /tmp/stats.sqlite # merge a snapshot file into the local database -``` - -Unfinished sessions (a crash mid-playback) are skipped until the app finalizes them; they sync on the next run. Word/kanji "known" state from Anki is not part of the database and does not sync. Each machine derives it from its own Anki collection. - -`subminer sync <host> --check` verifies a host without touching any data: it probes the SSH connection, locates SubMiner on the remote (launcher or app binary), and reports its version. `--json` switches any sync mode to machine-readable NDJSON progress output (this is what the sync window consumes). - -`sync --make-temp` creates a restricted temporary directory and prints its path; `sync --remove-temp <dir>` removes one created by that command. The internal `--transfer-cache <key>` option seeds the temporary directory from a previous received snapshot when creating it, or saves the received snapshot before removing it after a successful sync. Keys are 64-character lowercase hexadecimal identifiers. These are internal SSH transfer helpers, exposed for compatibility but normally invoked only by sync itself. `SubMiner --sync-cli sync ...` is the packaged app's headless compatibility entrypoint; use `SubMiner --sync-cli --help` for its sync-specific help. The `subminer sync` launcher command selects this entrypoint automatically and runs AppImages in Node-only mode, so remote sync does not require a graphical session. +</details> ### Sync window -`subminer sync --ui` opens a dedicated window for the same engine in a detached app process, returning the shell immediately. Closing that standalone-launched window exits its app instance. Opening **Sync Stats & History** from the tray keeps the resident app running when the window closes: +`subminer sync --ui`, or **Sync Stats & History** in the tray, opens a window where you can: -- **Devices:** saved hosts with a per-host direction (two-way / push / pull), an auto-sync toggle, last-sync status, and one-click **Sync now** / **Test** / **Remove**. Hosts synced from the command line appear here automatically. -- **Add a device:** test SSH + remote SubMiner availability before saving, with a setup checklist for first-time SSH configuration. -- **Activity:** live stage-by-stage progress, remote output, and separate merge summaries (sessions, words, kanji, rollups) for each machine updated by the run. Runs can be cancelled and can proceed while the app, stats server, or playback is active. -- **Snapshots:** create manual database snapshots (stored in `/tmp/subminer-db-snapshots/` by default), merge a snapshot file into the local database, or reveal/delete existing snapshots. +- Save devices, each with a direction (two-way, push, or pull), and run **Sync now** or **Test**. +- Turn on **Auto-sync** for a device. It syncs in the background every 60 minutes by default, including during playback. +- Watch progress and see what was merged on each machine. +- Create, merge, or delete database snapshots. -Hosts with **Auto-sync** enabled are synced in the background on a configurable interval (default every 60 minutes), including during active playback; results surface as overlay notifications. The unfinished playback session is skipped until a later sync sees it finalized. Host bookkeeping lives in `<config dir>/sync-hosts.json`. +Saved devices live in `sync-hosts.json` in the config directory. -## Common commands +## Environment variables -```bash -subminer video.mkv # play a specific file (managed launches auto-start the visible overlay by default) -subminer https://youtu.be/... # YouTube playback (requires yt-dlp) -subminer --backend x11 video.mkv # Force x11 backend for a specific file -subminer -u # check for SubMiner updates -subminer logs -e # export sanitized log ZIP -subminer stats # open immersion dashboard -subminer stats -b # start background stats daemon -``` - -## Subcommands - -| Subcommand | Purpose | -| ------------------------------------------ | ------------------------------------------------------------------------------------------------- | -| `subminer jellyfin` / `jf` | Jellyfin workflows (`-d` discovery, `-p` play, `-l` login, `--logout`, `--setup`) | -| `subminer stats` | Start the stats server (opens the dashboard when `stats.autoOpenBrowser` is on) | -| `subminer stats -b` / `-s` | Start/reuse or stop the background stats daemon | -| `subminer stats cleanup` | Backfill vocabulary metadata and prune stale rows (`-v` vocab, `-l` lifetime summaries) | -| `subminer stats cleanup -d` | Collapse repeated lines from typeset subs (`--dry-run`, `--lookback-days <n>`) | -| `subminer stats rebuild` / `backfill` | Rebuild or backfill rollup data | -| `subminer doctor` | Dependency + config + socket diagnostics (`--refresh-known-words` refreshes the known-word cache) | -| `subminer settings` | Open the SubMiner settings window | -| `subminer generate-subs [video]` | Generate [Japanese subtitles](/usage#generate-japanese-subtitles-locally) locally | -| `subminer logs -e` | Export a sanitized local-date log ZIP and print its path | -| `subminer config path` | Print active config file path | -| `subminer config show` | Print active config contents | -| `subminer mpv status` | Check mpv socket readiness | -| `subminer mpv socket` | Print active socket path | -| `subminer mpv idle` | Launch detached idle mpv instance | -| `subminer sync <host>` | Two-way stats/history sync with another machine over SSH | -| `subminer sync <host> --push` | Merge local stats/history into another machine only | -| `subminer sync <host> --pull` | Merge another machine's stats/history into the local database only | -| `subminer sync <host> --check` | Test SSH connection and remote launcher availability | -| `subminer sync --ui` | Open the sync window (saved devices, auto-sync, snapshots) | -| `subminer dictionary <path>` / `dict` | Generate character dictionary ZIP from file/dir target | -| `subminer dictionary --candidates <path>` | List AniList candidate matches for character dictionary correction | -| `subminer dictionary --select <id> <path>` | Pin an AniList media ID for that target series | -| `subminer texthooker` | Launch texthooker-only mode | -| `subminer texthooker -o` | Launch texthooker and open it in the default browser | -| `subminer app` / `bin` | Pass arguments directly to SubMiner binary (e.g. `subminer app --setup`) | - -Use `subminer <subcommand> -h` for command-specific help. - -## Options - -| Flag | Description | -| --------------------- | ---------------------------------------------------------------------------- | -| `-d, --directory` | Video search directory (default: cwd) | -| `-r, --recursive` | Search directories recursively | -| `-R, --rofi` | Use rofi instead of fzf | -| `-H, --history` | Browse local watch history (see [Watch History](#watch-history)) | -| `-v, --version` | Print the launcher's own version (can differ from the installed app binary) | -| `-u, --update` | Check for SubMiner updates and update the app/launcher when possible | -| `--start` | Explicitly start overlay after mpv launches | -| `-S, --start-overlay` | Force the visible overlay on start | -| `-T, --no-texthooker` | Disable texthooker server | -| `-p, --profile` | mpv profile name (no default; omitted unless set) | -| `-a, --args` | Pass additional mpv arguments as a quoted string | -| `-b, --backend` | Force window backend (`auto`, `hyprland`, `sway`, `x11`, `macos`, `windows`) | -| `--settings` | Open the SubMiner settings window | -| `--log-level` | Logger verbosity (`debug`, `info`, `warn`, `error`) | - -App-binary flags such as `--setup`, `--dev`, and `--debug` are not launcher flags - pass them through with `subminer app`, for example `subminer app --setup`. - -On Linux, `subminer -u` updates from the launcher process itself. It can check and replace the AppImage, launcher, runtime plugin copy, and rofi theme even when SubMiner is already running in the tray. - -Managed launches inject `auto_start=yes`, `auto_start_visible_overlay=yes`, and `auto_start_pause_until_ready=yes` as plugin script-opts from SubMiner's config defaults (`mpv.autoStartSubMiner`, `auto_start_overlay`), so explicit start flags are usually unnecessary. The plugin's own built-in defaults are off - mpv launched outside SubMiner does not auto-start the overlay. +| Variable | Use | +| ------------------------ | --------------------------------------------------------------------- | +| `SUBMINER_BINARY_PATH` | Path to the SubMiner app, if it is not in a standard install location | +| `SUBMINER_APPIMAGE_PATH` | Same, for an AppImage (Linux) | +| `SUBMINER_ROFI_THEME` | Path to a custom rofi theme | ## Logging -- Default log level is `warn` (launcher and app; configurable via `logging.level`) -- `--dev` / `--debug` are app-binary flags that control app dev-mode, not logging verbosity - use `--log-level` for that +The default log level is `warn`. Change it for one run with `--log-level`, or permanently with `logging.level` in the config. The app's `--dev` and `--debug` flags turn on developer mode. They do not change the log level. diff --git a/docs-site/mining-workflow.md b/docs-site/mining-workflow.md index 5c1dd219..d8e12227 100644 --- a/docs-site/mining-workflow.md +++ b/docs-site/mining-workflow.md @@ -1,190 +1,87 @@ # Mining workflow -This guide walks the whole sentence mining loop, from starting a video to ending up with an Anki card that has audio, a screenshot, and the surrounding sentence. +SubMiner turns lines from the video you are watching into Anki cards. You look up a word on the overlay, add it with Yomitan, and SubMiner fills in the sentence, an audio clip, and a screenshot. For Anki setup, field mapping, and media options, see [Anki integration](/anki-integration). -## Overview +## Look up a word -_Sentence mining_ means turning sentences you hit while watching native video into Anki cards, so you learn a word in the context where you first met it. The idea is old. The tedious part is everything between spotting the word and having a finished card, and that is the part SubMiner does for you. +1. Hover the subtitle line on the overlay. Each word is its own hover target. +2. Press your Yomitan scan key or modifier (whatever your Yomitan profile uses, for example `Shift`). +3. The Yomitan popup opens for that word. -SubMiner draws a transparent overlay on top of mpv and renders each subtitle line as interactive text. Hover a word, trigger a Yomitan lookup with your configured key or modifier, then add the card. SubMiner attaches the sentence, an audio clip, and a screenshot on its own, so there is nothing to copy-paste or screenshot by hand. +Playback pauses while you hover the subtitle and while the Yomitan popup is open. Turn this off with `subtitleStyle.autoPauseVideoOnHover` and `subtitleStyle.autoPauseVideoOnYomitanPopup`. -> **Yomitan** is the popup dictionary that shows definitions when you hover or scan a word. **AnkiConnect** is the add-on that lets SubMiner talk to Anki. Both are set up during installation - see [Anki Integration](/anki-integration) if you have not configured them yet. +## Add a word card -## Creating Anki cards +Click the add button in the Yomitan popup. SubMiner sees the new note and fills it in: -There are four ways to create or enrich cards, depending on your workflow. +| Field | Content | +| -------- | ------------------------------------------------------ | +| Sentence | The current subtitle line, with the mined word in bold | +| Audio | A clip cut from the video using the subtitle's timing | +| Image | A screenshot, or an animated AVIF clip of the line | +| MiscInfo | Source file name and timestamp | -### 1. Auto-update from Yomitan +Which note fields receive each item is set in [`ankiConnect.fields`](/anki-integration#field-mapping). With the default proxy mode the card is filled as soon as Yomitan adds it. If you disable the proxy, SubMiner polls Anki and fills the card a few seconds later. -This is the most common flow. Yomitan creates a card in Anki, and SubMiner enriches it automatically. +## Update the last card by hand -1. Hover a word, then trigger Yomitan lookup → Yomitan popup appears. -2. Click the Anki icon in Yomitan to add the word. -3. SubMiner receives or detects the new card: - - **Proxy mode** (default, `ankiConnect.proxy.enabled: true`): immediate enrich after a successful `addNote` / `addNotes` is pushed through the local proxy. - - **Polling mode** (fallback, when the proxy is disabled): detects new cards via AnkiConnect polling (`ankiConnect.pollingRate`, default 3 seconds). -4. SubMiner updates the card with: - - **Sentence**: The current subtitle line. - - **Audio**: Extracted from the video using the subtitle's start/end timing (plus optional configured padding). - - **Image**: A screenshot or animated clip from the current playback position. - - **MiscInfo**: Metadata like filename and timestamp. +Use this when auto-update is off, or when the line you want is not the one on screen. -Configure which fields to fill in `ankiConnect.fields`. See [Anki Integration](/anki-integration) for details. +1. Add the word with Yomitan. +2. Press `Ctrl/Cmd+C` to copy the current line. To combine lines, press `Ctrl/Cmd+Shift+C`, then a digit `1` to `9` for how many recent lines to include. +3. Press `Ctrl/Cmd+V`. SubMiner writes the clipboard text into the last-added card's sentence field and adds fresh audio and an image. -### 2. manual update from clipboard +A manual update always replaces the sentence audio, even when `ankiConnect.behavior.overwriteAudio` is `false`. -If you prefer a hands-on approach (animecards-style), you can copy the current subtitle to the clipboard and then paste it onto the last-added Anki card: +## Mine a sentence card -1. Add a word via Yomitan as usual. -2. Press `Ctrl/Cmd+C` to copy the current subtitle line to the clipboard. - - For multiple lines: press `Ctrl/Cmd+Shift+C`, then a digit `1`–`9` to select how many recent subtitle lines to combine. The combined text is copied to the clipboard. -3. Press `Ctrl/Cmd+V` to update the last-added card with the clipboard contents plus audio and image, the same fields auto-update would fill. +Press `Ctrl/Cmd+S` to create a sentence card from the current line without a Yomitan lookup. Press `Ctrl/Cmd+Shift+S`, then a digit `1` to `9`, to combine several recent lines into one card. The digit prompt closes after `shortcuts.multiCopyTimeoutMs`. -Manual clipboard updates always replace generated sentence audio in `ankiConnect.fields.audio`, even when `ankiConnect.behavior.overwriteAudio` is disabled. Normal word-card updates use the configured sentence and audio fields even when Lapis or Kiku support is enabled. +Sentence cards use the note type named in `ankiConnect.isLapis.sentenceCardModel` and write to its `Sentence` and `SentenceAudio` fields. That note type must exist in Anki. See [sentence cards](/anki-integration#sentence-cards-lapis). -Use this when auto-update is off, or when the line you want on the card is not the line currently on screen. +## Mark an audio card -| Shortcut | Action | Config key | -| -------------------------- | ------------------------------- | --------------------------------------- | -| `Ctrl/Cmd+C` | Copy current subtitle | `shortcuts.copySubtitle` | -| `Ctrl/Cmd+Shift+C` + digit | Copy multiple recent lines | `shortcuts.copySubtitleMultiple` | -| `Ctrl/Cmd+V` | Update last card from clipboard | `shortcuts.updateLastCardFromClipboard` | +After adding a word, press `Ctrl/Cmd+Shift+A`. SubMiner sets the Lapis/Kiku `IsAudioCard` flag on the last-added card and fills `Sentence`, `SentenceAudio`, the image, and MiscInfo. -### 3. mine Sentence (hotkey) +## Merge repeated words -Create a standalone sentence card without going through Yomitan: +If you mine a word you already have a card for, SubMiner can merge the new sentence, audio, and image into the existing card instead of keeping a duplicate. This needs the Kiku or Senren note type with field grouping turned on. In manual mode a dialog shows both cards and lets you pick which one to keep. See [field grouping](/anki-integration#field-grouping-kiku-senren). -- **Mine current sentence**: `Ctrl/Cmd+S` (configurable via `shortcuts.mineSentence`) -- **Mine multiple lines**: `Ctrl/Cmd+Shift+S` followed by a digit 1–9 to select how many recent subtitle lines to combine (the digit selector times out after 3 seconds, configurable via `shortcuts.multiCopyTimeoutMs`). +## Subtitle display -The sentence card uses the note type configured in `isLapis.sentenceCardModel` and always maps sentence/audio to `Sentence` and `SentenceAudio`. +The overlay has a primary subtitle bar (the Japanese line you mine from) and a secondary bar for a translation track. Each bar is hidden, visible, or shown only on hover. -::: warning Requires Lapis/Kiku note type -Sentence card creation requires `ankiConnect.isLapis.sentenceCardModel` to name a [Lapis](https://github.com/donkuri/lapis) or [Kiku](https://github.com/youyoumu/kiku) compatible note type that exists in Anki (default: `"Lapis"`). See [Anki Integration - Sentence Cards](/anki-integration#sentence-cards-lapis) for setup. -::: +| Shortcut | Action | +| ------------------ | ---------------------------------- | +| `V` | Cycle primary bar mode | +| `Ctrl/Cmd+Shift+V` | Cycle secondary bar mode | +| `Shift+J` | Cycle the secondary subtitle track | +| Right-click | Pause or resume | +| Right-click + drag | Move the subtitles | -### 4. mark as audio card +Set the starting modes with `subtitleStyle.primaryDefaultMode` and `secondarySub.defaultMode`. The full list of keys is on [Keyboard shortcuts](/shortcuts). -After adding a word via Yomitan, press the audio card shortcut (`Ctrl/Cmd+Shift+A` by default, `shortcuts.markAudioCard`) to mark the card as an audio card. This sets the audio-card flag and fills sentence, image, and metadata fields alongside the full-subtitle audio clip. +## Controller -::: warning Requires Lapis/Kiku note type -Audio card marking uses the same `ankiConnect.isLapis.sentenceCardModel` note type as sentence cards. See [Anki Integration - Sentence Cards](/anki-integration#sentence-cards-lapis) for setup. -::: +With a gamepad and keyboard-only mode on, you can mine without a mouse: move across words with the left stick, look up with `A`, mine with `X`, and close the popup with `B`. The keyboard keeps working alongside it. See [controller support](/usage#controller-support). -### Field grouping (Kiku/Senren) +## Fix subtitle timing (subsync) -If you mine the same word from different sentences, SubMiner can merge the cards instead of creating duplicates. This is built for [Kiku](https://github.com/youyoumu/kiku) and [Senren](https://github.com/BrenoAqua/Senren) note types that support grouped fields (Senren calls it scene switching). +If the subtitles are out of sync, press `Ctrl+Alt+S` to open the subsync dialog. It uses [alass](https://github.com/kaegi/alass) or [ffsubsync](https://github.com/smacke/ffsubsync), which you install separately. -1. You add a word via Yomitan. -2. SubMiner detects the new card and checks if a card with the same expression already exists. -3. If a duplicate is found (this requires Kiku or Senren to be enabled with a field grouping mode of `"auto"` or `"manual"`): - - **Auto mode**: Merges automatically. Both sentences, audio clips, images, and source info are combined into the existing card. The duplicate is optionally deleted. - - **Manual mode**: A modal appears showing both cards side by side. You choose which card to keep and preview the merged result before confirming. +1. Pick the engine. +2. For alass, pick a reference: a subtitle track with correct timing (the secondary track by default) or the video file. +3. Pick the track to retime (the active primary track by default). +4. Run it. SubMiner loads the retimed subtitle back into the same slot. -See [Anki Integration - Field Grouping](/anki-integration#field-grouping-kiku-senren) for configuration options, merge behavior, and modal keyboard shortcuts. - -## Overlay model - -SubMiner uses one overlay window with modal surfaces. It carries two subtitle bars - a primary reading bar and a secondary translation/context bar - plus modal dialogs that open on top. - -Toggle the entire overlay window with `Alt+Shift+O` (global) or `y-t` (mpv plugin). - -### Primary subtitle layer - -The primary bar renders each subtitle as separate hoverable word spans, each carrying its reading and headword. Its styling is independent of mpv's own subtitle rendering. It supports: - -- Word-level hover targets for Yomitan lookup -- Auto pause/resume on subtitle hover (enabled by default via `subtitleStyle.autoPauseVideoOnHover`) -- Auto pause/resume while the Yomitan popup is open (enabled by default via `subtitleStyle.autoPauseVideoOnYomitanPopup`) -- Right-click to pause/resume -- Right-click + drag to reposition subtitles -- **Reading annotations** - known words, N+1 targets, character-name matches, JLPT levels, and frequency hits can all be visually highlighted - -### Secondary subtitle bar - -The secondary bar is a compact top-strip region in the same overlay window. It shows a secondary subtitle track, usually English, above the primary reading line. Use it to sanity-check your comprehension without breaking out of the mining flow. - -For local media, SubMiner can parse supported embedded secondary tracks into timed cues. For remote URLs and files on network mounts, it uses mpv's live secondary subtitle text instead of scanning the media with ffmpeg. - -The `secondarySub` config controls it, and it opens and closes with the main overlay window. Cycle which track feeds it with `Shift+J`. - -SubMiner collapses duplicate ASS layers in parsed secondary tracks. Exact repeated lines collapse at any length, while distinct simultaneous short lines remain separate. Long dialogue and positioned-sign copies also collapse when they differ only in whitespace or terminal punctuation. Dense multi-row sign layouts, such as translated timetables, are excluded instead of being concatenated into the secondary bar. - -### Display modes - -Both the primary and secondary subtitle bars share the same three visibility modes, and each can be changed independently at runtime: - -- **Hidden** - the bar is not shown. -- **Visible** - the bar is always shown. -- **Hover** - the bar is revealed only while you hover over the overlay. - -By default the **primary** bar is `visible` (`subtitleStyle.primaryDefaultMode`) and the **secondary** bar is `hover` (`secondarySub.defaultMode`). - -Cycle each bar's mode at runtime with its own shortcut: - -| Shortcut | Action | Config key | -| ------------------ | -------------------------------------------------------- | ------------------------------ | -| `V` | Cycle primary subtitle mode (hidden → visible → hover) | overlay-local | -| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle mode (hidden → visible → hover) | `shortcuts.toggleSecondarySub` | - -### Modal surfaces - -Jimaku search, field-grouping, runtime options, and manual subsync open as modal surfaces on top of the same overlay window. - -## Looking up words - -1. Hover over the subtitle area - the overlay activates pointer events. -2. Hover the word you want. SubMiner keeps per-token boundaries so Yomitan can target that token cleanly. -3. Trigger Yomitan lookup with your configured lookup key/modifier (for example `Shift` if that is how your Yomitan profile is set up). -4. Yomitan opens its lookup popup for the hovered token. -5. From the popup, add the word to Anki. - -### Controller workflow - -With a gamepad connected and keyboard-only mode enabled, the full mining loop works without a mouse or keyboard: - -1. **Navigate** - push the left stick left/right to move the token highlight across subtitle words. -2. **Look up** - press `A` to trigger Yomitan lookup on the highlighted word. -3. **Browse the popup** - push the left stick up/down to smooth-scroll through the Yomitan popup, or use the right stick for larger jumps. -4. **Cycle audio** - press `R1` to move to the next dictionary audio entry, `L1` to play the current one. -5. **Mine** - press `X` to create an Anki card for the current sentence (same as `Ctrl+S`). -6. **Close** - press `B` to dismiss the Yomitan popup and return to subtitle navigation. -7. **Pause/resume** - press `L3` (left stick click) to toggle mpv pause at any time. - -Once controller support is on, the controller and keyboard both stay live. You can drop the controller mid-episode and keep going with the keyboard. Toggle keyboard-only mode with `Y` on the controller. - -See [Usage - Controller Support](/usage#controller-support) for setup details and [Configuration - Controller Support](/configuration#controller-support) for the full mapping and tuning options. - -## Subtitle sync (subsync) - -If your subtitle file is out of sync with the audio, SubMiner can resynchronize it using [alass](https://github.com/kaegi/alass) or [ffsubsync](https://github.com/smacke/ffsubsync). - -1. Open the subsync modal from the overlay. -2. Select the sync engine (alass or ffsubsync). -3. For alass, pick the **reference** - the subtitle with correct timing. This defaults to the secondary subtitle track. The loaded video file can also be used as the reference (alass extracts the audio itself), but it is never the default. -4. Pick the **out-of-sync subtitle** - the track that gets retimed. This defaults to the active primary subtitle track and applies to both engines. -5. SubMiner runs the sync and reloads the corrected subtitle into the slot the out-of-sync track came from: retiming the secondary track keeps it secondary and leaves the primary track selected. - -The reference and the out-of-sync subtitle must be different tracks; the reference list hides whichever track is selected as the target. - -For remote streams, including Jellyfin playback, the modal only offers alass with a subtitle reference. Jellyfin subtitle URLs are cached as temporary subtitle files so alass can read them, but the video stream is not downloaded. ffsubsync and the video-file reference need direct access to the local media file and are unavailable for stream URLs. - -Install the sync tools separately - see [Troubleshooting](/troubleshooting#subtitle-sync-subsync) if the tools are not found. +For remote streams such as Jellyfin, only alass with a subtitle reference is available, because ffsubsync and the video reference need the local file. If the tools are not found, see [Troubleshooting](/troubleshooting#subtitle-sync-subsync). ## Texthooker -SubMiner serves a texthooker UI from a local HTTP server at `http://127.0.0.1:5174`. The port is fixed unless you override it with the mpv plugin's `texthooker_port` script-opt. External tools read subtitle text from it as lines arrive, which is how you would feed a browser-based Yomitan instance. - -The texthooker page displays the current subtitle and updates as new lines arrive. This is useful if you prefer to do lookups in a browser rather than through the overlay's built-in Yomitan. - -If you want to build your own browser client, websocket consumer, or automation relay, see [WebSocket / Texthooker API & Integration](/websocket-texthooker-api). +SubMiner can serve a texthooker page at `http://127.0.0.1:5174` that shows each subtitle line as it arrives, so you can do lookups in a browser instead of on the overlay. Start it with `texthooker.launchAtStartup`, the `--texthooker` flag, or the mpv plugin's `texthooker_enabled` option. Change the port with the plugin's `texthooker_port` option. To build your own client, see the [WebSocket / texthooker API](/websocket-texthooker-api). ## Related features -These feed into the mining loop but each has its own page: - -- **[Jimaku subtitle search](/jimaku-integration)** - search and download anime subtitle files directly from the overlay (`Ctrl+Shift+J` by default), then load them into mpv. -- **[N+1 word highlighting](/subtitle-annotations#n-1-word-highlighting)** - reads your Anki decks and highlights words you already know, so a line with exactly one unknown word stands out while you watch. -- **[Immersion tracking](/immersion-tracking)** - log watching and mining activity to a local database and view session times, words seen, and cards mined in the built-in stats dashboard. - -Next: [Anki Integration](/anki-integration) - field mapping, media generation, and card enrichment configuration. +- [Jimaku](/jimaku-integration): search and download subtitle files from the overlay (`Ctrl+Shift+J`). +- [Subtitle annotations](/subtitle-annotations): highlight known words, N+1 targets, JLPT levels, and frequency. +- [Immersion tracking](/immersion-tracking): log watch time and cards mined, and view them in the stats dashboard. diff --git a/docs-site/mpv-plugin.md b/docs-site/mpv-plugin.md index 16036993..0f05818e 100644 --- a/docs-site/mpv-plugin.md +++ b/docs-site/mpv-plugin.md @@ -1,155 +1,112 @@ # MPV plugin -The SubMiner mpv plugin is a small Lua script that runs _inside_ mpv. It binds in-player keys for controlling the overlay, so start, stop, toggle, and skip-intro all work without leaving the player window. +The SubMiner mpv plugin is a Lua script that runs inside mpv. It adds in-player keys to start, stop, and toggle the overlay, and it runs your SubMiner shortcuts from inside mpv. -Most people never touch it. Any SubMiner-managed launch, whether from the app, the `subminer` launcher, or the Windows shortcut, injects the bundled plugin for that session, and nothing lands in mpv's global `scripts` directory. Keep reading if you launch mpv from some other tool and still want the in-player controls, or you want to script mpv against SubMiner. +## Setup -The plugin is a modular Lua package under `plugin/subminer/`. `main.lua` is the entry point and loads `init.lua` plus its sibling modules. Earlier releases installed a single global `main.lua`; runtime loading replaced that. +You usually do not install anything. Every SubMiner-managed launch (the app, the `subminer` launcher, and the Windows SubMiner mpv shortcut) loads the bundled plugin for that session only. Regular mpv playback is not affected. -## Runtime loading +On Linux, the launcher's copy lives in `$XDG_DATA_HOME/SubMiner/plugin/subminer` (default `~/.local/share/SubMiner/plugin/subminer`), or under `/usr/local/share/SubMiner` or `/usr/share/SubMiner` for system installs. `subminer -u` and the tray updater keep it current. -Launch mpv through the SubMiner app, the `subminer` launcher, or the packaged Windows SubMiner mpv shortcut. These paths pass mpv a bundled plugin path for that playback session only, leaving regular mpv playback untouched. +To use the plugin when mpv is started by another program, load its `main.lua` and enable IPC: -On Linux, the launcher-managed runtime plugin copy lives under the SubMiner data dir (`$XDG_DATA_HOME/SubMiner/plugin/subminer` by default, plus `/usr/local/share/SubMiner` or `/usr/share/SubMiner` for system installs). `subminer -u` and the tray updater keep that managed copy current. This is separate from mpv's global `scripts/` directory. +```bash +mpv --script="$HOME/.local/share/SubMiner/plugin/subminer/main.lua" \ + --input-ipc-server=/tmp/subminer-socket video.mkv +``` -If setup detects an older global SubMiner plugin in mpv's `scripts` directory, use **Remove legacy mpv plugin** in first-run setup. The global plugin is not needed once runtime loading is available. - -mpv must have IPC enabled for SubMiner to connect: +To enable IPC for every mpv session, add it to `mpv.conf`: ```ini -# ~/.config/mpv/mpv.conf input-ipc-server=/tmp/subminer-socket ``` -On Windows, use a named pipe instead: +On Windows, use a named pipe: ```ini input-ipc-server=\\.\pipe\subminer-socket ``` -## Configuration (script-opts) - -The plugin reads options from `script-opts` with the `subminer-` prefix (for example `--script-opts=subminer-backend=hyprland`). Managed launches inject these automatically from your SubMiner config; the shipped `subminer.conf` is intentionally empty so command-line opts always win. - -| Option | Default | Description | -| -------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------- | -| `binary_path` | `""` | Path to the SubMiner binary; empty enables [auto-detection](#binary-auto-detection) | -| `socket_path` | platform default | mpv IPC socket path (`/tmp/subminer-socket`, or `\\.\pipe\subminer-socket` on Windows) | -| `texthooker_enabled` | `no` | Start the texthooker server with the overlay | -| `texthooker_port` | `5174` | Texthooker server port | -| `backend` | `auto` | Window backend (`auto`, `hyprland`, `sway`, `x11`, `macos`) | -| `auto_start` | `no` | Start the overlay app on `file-loaded` (managed launches set this from `mpv.autoStartSubMiner`) | -| `auto_start_visible_overlay` | `no` | Show the visible overlay on auto-start (from `auto_start_overlay` in config) | -| `overlay_loading_osd` | `no` | Show an OSD loading spinner while the overlay starts | -| `auto_start_pause_until_ready` | `yes` | Keep mpv paused until the overlay reports tokenization-ready | -| `auto_start_pause_until_ready_timeout_seconds` | `30` | Timeout before resuming playback anyway | -| `osd_messages` | `yes` | Show plugin OSD status messages | -| `log_level` | `info` | Plugin log verbosity | +If first-run setup finds an old SubMiner plugin in mpv's global `scripts` directory, click **Remove legacy mpv plugin**. It is no longer needed. ## Keybindings -Most plugin actions use a `y` chord prefix - press `y`, then the second key (a "chord"): +Most plugin keys are chords: press `y`, then the second key. -| Chord | Action | -| --------------- | -------------------------------------- | -| `y-y` | Open menu | -| `y-s` | Start overlay | -| `y-S` | Stop overlay | -| `y-t` | Toggle visible overlay | -| `y-o` | Open settings window | -| `y-r` | Restart overlay | -| `y-c` | Check status | -| `y-h` | Open session help / keybinding modal | -| `v` | Toggle primary subtitle bar visibility | -| `TAB` (default) | Skip intro (AniSkip) | +| Key | Action | +| ----- | -------------------------------------- | +| `y-y` | Open the SubMiner menu | +| `y-s` | Start the overlay | +| `y-S` | Stop the overlay | +| `y-t` | Toggle the visible overlay | +| `y-o` | Open the settings window | +| `y-r` | Restart the overlay | +| `y-c` | Check status | +| `y-h` | Open the session help modal | +| `v` | Toggle SubMiner's primary subtitle bar | -The AniSkip key is **not** a `y` chord and is not bound by the plugin: the SubMiner app binds it over the mpv IPC socket while it is connected. It defaults to `TAB` and is configurable via `mpv.aniskipButtonKey`. When a custom key (other than `TAB` or `y-k`) is configured, the legacy `y-k` chord is also bound as a fallback. See [AniSkip Integration](/aniskip-integration) for setup and details. +`v` replaces mpv's own subtitle visibility toggle. -The bare `v` binding is a forced mpv binding. It overrides mpv's default primary subtitle visibility toggle and routes the action to SubMiner's primary subtitle bar instead. +The skip-intro key (`TAB` by default) comes from the SubMiner app, not the plugin. See [AniSkip integration](/aniskip-integration). -## Shared shortcuts (session bindings) +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-*` chords above are built into the plugin. Everything else you configure under [`shortcuts.*`](/shortcuts) - plus any custom [`keybindings`](/configuration) and the stats toggle/mark-watched keys - is **injected into mpv at runtime**, so the same shortcut works both inside mpv and in the SubMiner overlay. You do not edit any mpv config to enable them. +## Your shortcuts in mpv -How it works: +Everything you set under [`shortcuts`](/shortcuts), your custom `keybindings`, and the stats keys also work while mpv has focus. SubMiner writes them to `session-bindings.json` in its config directory, and the plugin registers them as mpv keys. When you change a shortcut, mpv picks it up immediately. -1. The SubMiner app compiles your configured shortcuts, custom keybindings, and stats keys into a normalized list and writes it to `session-bindings.json` in the SubMiner config directory. -2. On load, the plugin reads that file and registers each entry as a forced mpv key binding, translating each accelerator into the matching mpv key name. -3. When a binding fires, the plugin either runs a SubMiner action (by invoking the SubMiner binary with the corresponding CLI flag, e.g. `--mine-sentence`) or runs a raw mpv command, depending on what the shortcut maps to. +`CommandOrControl` becomes `Cmd` on macOS and `Ctrl` elsewhere. Multi-line copy and mine shortcuts wait for a digit key `1` to `9`, and `Esc` cancels. If two shortcuts map to the same key, or a key has no mpv equivalent, SubMiner logs a warning and skips it. -Because the bindings come from the same configuration the overlay uses, you maintain one set of shortcuts for both surfaces. +## Script options -Live updates: changing a shortcut in the app rewrites `session-bindings.json` and sends the plugin a `subminer-reload-session-bindings` script message, so mpv re-registers the bindings immediately - no mpv restart required. +The plugin reads `script-opts` with the `subminer-` prefix, for example `--script-opts=subminer-backend=hyprland`. Managed launches set these from your SubMiner config, so edit the config instead. The shipped `plugin/subminer.conf` is empty on purpose, so it never overrides those values. -Notes: +| Option | Default | SubMiner config key | What it does | +| ---------------------------------------------- | ---------------- | ---------------------------- | --------------------------------------------------------------------- | +| `binary_path` | `""` | `mpv.subminerBinaryPath` | SubMiner binary. Empty uses [auto-detection](#binary-auto-detection). | +| `socket_path` | platform default | `mpv.socketPath` | mpv IPC socket | +| `backend` | `auto` | `mpv.backend` | Window backend: `auto`, `hyprland`, `sway`, `x11`, `macos` | +| `auto_start` | `no` | `mpv.autoStartSubMiner` | Start SubMiner when a file loads | +| `auto_start_visible_overlay` | `no` | `auto_start_overlay` | Show the overlay when auto-starting | +| `auto_start_pause_until_ready` | `yes` | `mpv.pauseUntilOverlayReady` | Keep mpv paused until subtitles are ready | +| `auto_start_pause_until_ready_timeout_seconds` | `30` | | Resume anyway after this many seconds | +| `overlay_loading_osd` | `no` | | Show a loading message while the overlay starts | +| `texthooker_enabled` | `no` | | Start the texthooker with the overlay | +| `texthooker_port` | `5174` | | Texthooker port | +| `osd_messages` | `yes` | | Show plugin status messages in mpv | +| `log_level` | `info` | | Plugin log level | -- Accelerators are normalized per platform - `CommandOrControl` resolves to `Cmd` on macOS and `Ctrl` elsewhere. -- Multi-line actions (`copySubtitleMultiple`, `mineSentenceMultiple`) register temporary `1`–`9` digit follow-up bindings after the trigger key, with `Esc` to cancel. -- If two shortcuts compile to the same key, or an accelerator can't be mapped to an mpv key, the app logs a warning and skips that binding instead of registering a broken one. +Without script options, `socket_path` is `/tmp/subminer-socket`, or `\\.\pipe\subminer-socket` on Windows. On Windows, the plugin also rewrites `/tmp/subminer-socket` to the named pipe. -## Menu - -Press `y-y` to open an interactive menu (rendered with mpv's console selector): - -```text -SubMiner: -1. Start overlay -2. Stop overlay -3. Toggle overlay -4. Open options -5. Restart overlay -6. Check status -7. Stats -``` - -Select an item by pressing its number. +The table's defaults are the plugin's own. Managed launches override them from your config; see [Configuration](/configuration#mpv-launcher). ## Binary auto-detection -When `binary_path` is empty, the plugin searches platform-specific locations: +With `binary_path` empty, the plugin looks in these places: -**Linux:** - -1. `~/.local/bin/SubMiner.AppImage` -2. `/opt/SubMiner/SubMiner.AppImage` -3. `/usr/local/bin/SubMiner` / `/usr/local/bin/subminer` -4. `/usr/bin/SubMiner` / `/usr/bin/subminer` - -**macOS:** - -1. `/Applications/SubMiner.app/Contents/MacOS/SubMiner` -2. `~/Applications/SubMiner.app/Contents/MacOS/SubMiner` - -**Windows:** - -A PowerShell system lookup runs first (running SubMiner process, registry App Paths, `Get-Command`), then static paths: - -1. `%LOCALAPPDATA%\Programs\SubMiner\SubMiner.exe` (the default per-user install location) -2. `C:\Program Files\SubMiner\SubMiner.exe` -3. `C:\Program Files (x86)\SubMiner\SubMiner.exe` -4. `C:\SubMiner\SubMiner.exe` - -On Windows the plugin also normalizes a Unix-style `socket_path` (`/tmp/subminer-socket`) to the named pipe `\\.\pipe\subminer-socket` at runtime. +| Platform | Locations | +| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Linux | `~/.local/bin/SubMiner.AppImage`, `/opt/SubMiner/SubMiner.AppImage`, `/usr/local/bin/SubMiner` or `subminer`, `/usr/bin/SubMiner` or `subminer` | +| macOS | `/Applications/SubMiner.app`, `~/Applications/SubMiner.app` | +| Windows | A running SubMiner process, the App Paths registry entry, `SubMiner.exe` on `PATH`, then `%LOCALAPPDATA%\Programs\SubMiner`, `C:\Program Files\SubMiner`, `C:\Program Files (x86)\SubMiner`, `C:\SubMiner` | ## Backend detection -When `backend=auto`, the plugin detects the window manager: +With `backend=auto`, the plugin picks the first match: -1. **macOS** - detected via platform or `OSTYPE`. -2. **Hyprland** - detected via `HYPRLAND_INSTANCE_SIGNATURE`. -3. **Sway** - detected via `SWAYSOCK`. -4. **X11** - detected via `XDG_SESSION_TYPE=x11` or `DISPLAY`. -5. **Fallback** - defaults to X11 with a warning. +1. macOS +2. Hyprland (`HYPRLAND_INSTANCE_SIGNATURE` is set) +3. Sway (`SWAYSOCK` is set) +4. X11 (`XDG_SESSION_TYPE=x11` or `DISPLAY` is set) +5. Otherwise X11, with a warning -::: tip Wayland is compositor-specific -Native Wayland support is only available for Hyprland and Sway. If you use a different Wayland compositor, auto-detection will fall back to X11 - both mpv and SubMiner must be running under Xwayland, and `xdotool` and `xwininfo` must be installed. -::: +Native Wayland support covers only Hyprland and Sway. On other Wayland compositors, run both mpv and SubMiner under Xwayland and install `xdotool` and `xwininfo`. ## Script messages -The plugin can be controlled from other mpv scripts or the mpv command line using script messages: +Other mpv scripts, `input.conf`, or the mpv console can control the plugin: -``` +```text script-message subminer-start script-message subminer-stop script-message subminer-toggle @@ -157,46 +114,21 @@ script-message subminer-menu script-message subminer-options script-message subminer-restart script-message subminer-status -script-message subminer-autoplay-ready -script-message subminer-stats-toggle -script-message subminer-visible-overlay-shown -script-message subminer-visible-overlay-hidden -script-message subminer-managed-subtitles-loading -script-message subminer-overlay-loading-ready -script-message subminer-reload-session-bindings ``` -The last five are primarily used by the SubMiner app to notify the plugin of overlay/loading state and to trigger session-binding reloads. +`subminer-start` accepts overrides: -The AniSkip messages (`subminer-skip-intro`, `subminer-aniskip-refresh`) still exist, but they are handled by the SubMiner app over the IPC socket rather than by the plugin - see [AniSkip Integration](/aniskip-integration#triggering-from-mpv). - -The `subminer-start` message accepts overrides: - -``` +```text script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug ``` -`log-level` here controls only logging verbosity passed to SubMiner. -`--debug` is a separate app/dev-mode flag in the main CLI and should not be used here for logging. +`log-level` sets SubMiner's log verbosity. Do not use `--debug` for this; it turns on the app's dev mode. -## Lifecycle +The plugin also handles messages the SubMiner app sends it (`subminer-autoplay-ready`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv). -For how the plugin's auto-start fits into the full launch sequence - including when the launcher starts the overlay instead of the plugin - see [Playback Startup Flow](./architecture#playback-startup-flow). +## Auto-start behavior -- **File loaded**: If `auto_start=yes`, the plugin starts the overlay. -- **Auto-start pause gate**: If `auto_start_visible_overlay=yes` and `auto_start_pause_until_ready=yes`, launcher starts mpv paused. On cold managed background startup, SubMiner opens the tray and visible overlay shell before tokenization warmups finish, then the plugin resumes playback after SubMiner reports tokenization-ready (with a 30-second timeout fallback). -- **Duplicate auto-start events**: Repeated `file-loaded` hooks while overlay is already running are ignored for auto-start triggers (prevents duplicate start attempts). -- **MPV shutdown**: The plugin clears its hover/OSD/gate state on shutdown; the overlay app notices the closed IPC socket and shuts itself down. -- **Texthooker**: When `texthooker_enabled=yes`, the plugin appends `--texthooker` to the overlay start command so the app starts the texthooker server alongside the overlay. - -## Using with the `subminer` wrapper - -The `subminer` wrapper script handles mpv launch, socket setup, and overlay lifecycle automatically. You do not need the plugin if you always use the wrapper. - -The plugin is useful when you: - -- Launch mpv from other tools (file managers, media centers). -- Want on-demand overlay control without the wrapper. -- Use mpv's built-in file browser or playlist features. - -You can install both - the plugin provides chord keybindings for convenience, while the wrapper handles the full lifecycle. +- With `auto_start=yes`, the plugin starts SubMiner on each file load. Repeated loads while SubMiner is running do not start it again. +- With `auto_start_visible_overlay=yes` and `auto_start_pause_until_ready=yes`, mpv stays paused until SubMiner reports that subtitles are ready, or until the timeout passes. +- With `texthooker_enabled=yes`, the texthooker starts with the overlay. +- When mpv quits, SubMiner sees the closed socket and shuts down its overlay. diff --git a/docs-site/package.json b/docs-site/package.json index 747f333d..83a425e5 100644 --- a/docs-site/package.json +++ b/docs-site/package.json @@ -5,10 +5,10 @@ "description": "In-repo VitePress documentation site for SubMiner", "packageManager": "bun@1.3.5", "scripts": { - "docs:dev": "SUBMINER_DOCS_VERSION_LINK_ORIGIN=local bun run ../scripts/build-versioned-docs.ts && SUBMINER_DOCS_VERSION_LINK_ORIGIN=local SUBMINER_DOCS_VERSION_MANIFEST=\"$(bun run ../scripts/print-docs-version-manifest.ts)\" VITE_EXTRA_EXTENSIONS=jsonc vitepress dev --host 0.0.0.0 --port 5173 --strictPort", + "docs:dev": "VITE_EXTRA_EXTENSIONS=jsonc vitepress dev --host 0.0.0.0 --port 5173 --strictPort", "docs:build": "VITE_EXTRA_EXTENSIONS=jsonc vitepress build", "docs:preview": "VITE_EXTRA_EXTENSIONS=jsonc vitepress preview --host 0.0.0.0 --port 4173 --strictPort", - "test": "bun test plausible.test.ts index.assets.test.ts docs-sync.test.ts links.test.ts seo.test.ts .vitepress/theme/status-line.test.ts ../scripts/docs-versioning.test.ts" + "test": "bun test plausible.test.ts index.assets.test.ts archive-function.test.ts docs-sync.test.ts links.test.ts seo.test.ts .vitepress/theme/status-line.test.ts ../scripts/docs-versioning.test.ts" }, "dependencies": { "@catppuccin/vitepress": "^0.1.2", diff --git a/docs-site/plausible.test.ts b/docs-site/plausible.test.ts index 25cbb2b2..905d0c5b 100644 --- a/docs-site/plausible.test.ts +++ b/docs-site/plausible.test.ts @@ -42,27 +42,11 @@ test('versioned docs reuse current VitePress internals for old page snapshots', expect(versionedBuildContents).toContain('overlayCurrentVitePress(snapshotDocsSite)'); }); -test('versioned docs build reports archive cache hits and rebuilds', () => { - expect(versionedBuildContents).toContain( - 'console.info(`[docs] archive cache key ${archiveCacheKey.slice(0, 12)}`)', - ); - expect(versionedBuildContents).toContain('console.info(`[docs] cache hit ${version}`)'); - expect(versionedBuildContents).toContain('console.info(`[docs] rebuilding archive ${version}`)'); -}); - -test('versioned docs build deduplicates public assets and prunes stale workspaces', () => { +test('versioned docs build deduplicates main public assets and removes build workspaces', () => { expect(versionedBuildContents).toContain('dedupeVersionedPublicAssets({'); - expect(versionedBuildContents).toContain('pruneArchiveCacheGenerations({'); expect(versionedBuildContents).toContain('rmSync(buildRoot, { recursive: true, force: true });'); }); -test('versioned docs archive cache key ignores generated and test-only files', () => { - expect(versionedBuildContents).toContain('isSharedInternalsHashIgnoredPath(path)'); - expect(versionedBuildContents).toContain('|| /\\.test\\.[cm]?[jt]s$/.test(path)'); - expect(versionedBuildContents).toContain('process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN'); - expect(versionedBuildContents).not.toContain('hash.update(String(stat.mode))'); -}); - test('docs builds exclude the internal README from VitePress page entries', () => { expect(docsConfigContents).toContain("srcExclude: ['subagents/**', 'README.md']"); }); diff --git a/docs-site/seo.test.ts b/docs-site/seo.test.ts index 99980516..9b682fe0 100644 --- a/docs-site/seo.test.ts +++ b/docs-site/seo.test.ts @@ -1,7 +1,4 @@ import { expect, test } from 'bun:test'; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { TransformContext } from 'vitepress'; import docsConfig from './.vitepress/config'; @@ -63,19 +60,17 @@ test('main docs canonical uses /main/ and emits noindex', async () => { }); test.each([ - ['latest stable', 'v0.14.0', '/v/0.14.0/', 'https://docs.subminer.moe/v/0.14.0/usage'], - ['superseded', 'v0.12.0', '/v/0.12.0/', 'https://docs.subminer.moe/v/0.12.0/usage'], + ['v0.14.0', '/v/0.14.0/', 'https://docs.subminer.moe/v/0.14.0/usage'], + ['v0.12.0', '/v/0.12.0/', 'https://docs.subminer.moe/v/0.12.0/usage'], ])( '%s archive keeps a self-referential canonical and stays out of the index', - async (_label, version, base, expectedCanonical) => { + async (version, base, expectedCanonical) => { const previousChannel = process.env.SUBMINER_DOCS_CHANNEL; const previousBase = process.env.SUBMINER_DOCS_BASE; const previousVersion = process.env.SUBMINER_DOCS_VERSION; - const previousLatest = process.env.SUBMINER_DOCS_LATEST_STABLE; process.env.SUBMINER_DOCS_CHANNEL = 'stable-archive'; process.env.SUBMINER_DOCS_BASE = base; process.env.SUBMINER_DOCS_VERSION = version; - process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0'; try { const { default: archiveConfig } = await import(`./.vitepress/config?archive-${version}`); @@ -89,36 +84,19 @@ test.each([ process.env.SUBMINER_DOCS_CHANNEL = previousChannel; process.env.SUBMINER_DOCS_BASE = previousBase; process.env.SUBMINER_DOCS_VERSION = previousVersion; - process.env.SUBMINER_DOCS_LATEST_STABLE = previousLatest; } }, ); -test('stable archive theme links stay on the selected version', async () => { +test('archive nav keeps page links in-version and version links release-independent', async () => { const previousCwd = process.cwd(); const previousChannel = process.env.SUBMINER_DOCS_CHANNEL; const previousBase = process.env.SUBMINER_DOCS_BASE; const previousVersion = process.env.SUBMINER_DOCS_VERSION; - const previousLatest = process.env.SUBMINER_DOCS_LATEST_STABLE; - const previousManifest = process.env.SUBMINER_DOCS_VERSION_MANIFEST; - const previousVersionLinkOrigin = process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN; process.chdir(docsSiteDir); process.env.SUBMINER_DOCS_CHANNEL = 'stable-archive'; process.env.SUBMINER_DOCS_BASE = '/v/0.12.0/'; process.env.SUBMINER_DOCS_VERSION = 'v0.12.0'; - process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0'; - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = 'production'; - process.env.SUBMINER_DOCS_VERSION_MANIFEST = JSON.stringify({ - latestStable: 'v0.14.0', - channels: [ - { label: 'Latest stable', path: '/' }, - { label: 'main', path: '/main/' }, - ], - versions: [ - { version: 'v0.14.0', path: '/v/0.14.0/' }, - { version: 'v0.12.0', path: '/v/0.12.0/' }, - ], - }); try { const { default: archiveConfig } = await import('./.vitepress/config?stable-archive-links'); @@ -131,39 +109,24 @@ test('stable archive theme links stay on the selected version', async () => { text: string; items?: Array<{ text: string; link: string }>; }>; - const configurationNav = nav.find((item) => item.text === 'Configuration'); - const versionNav = nav.find((item) => item.text === 'v0.12.0'); - const referenceSidebar = sidebar.find((item) => item.text === 'Reference'); - const configurationSidebar = referenceSidebar?.items?.find( - (item) => item.text === 'Configuration', - ); + const configurationSidebar = sidebar + .find((item) => item.text === 'Reference') + ?.items?.find((item) => item.text === 'Configuration'); - expect(configurationNav?.link).toBe('/configuration'); + expect(nav.find((item) => item.text === 'Configuration')?.link).toBe('/configuration'); expect(configurationSidebar?.link).toBe('/configuration'); - expect(versionNav?.items).toContainEqual({ - text: 'Latest stable (v0.14.0)', - link: 'https://docs.subminer.moe/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'main', - link: 'https://docs.subminer.moe/main/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'v0.14.0', - link: 'https://docs.subminer.moe/v/0.14.0/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'v0.12.0', - link: 'https://docs.subminer.moe/v/0.12.0/', - target: '_self', - noIcon: true, - }); + // Frozen archives must not embed the release list, or every new tag would + // invalidate them. They point at the root-only /versions page instead. + expect(nav.find((item) => item.text === 'v0.12.0')?.items).toEqual([ + { text: 'Latest stable', link: 'https://docs.subminer.moe/', target: '_self', noIcon: true }, + { text: 'main', link: 'https://docs.subminer.moe/main/', target: '_self', noIcon: true }, + { + text: 'All versions', + link: 'https://docs.subminer.moe/versions', + target: '_self', + noIcon: true, + }, + ]); expect(archiveConfig.themeConfig?.logo).toEqual({ light: '/assets/SubMiner.png', dark: '/assets/SubMiner.png', @@ -173,268 +136,9 @@ test('stable archive theme links stay on the selected version', async () => { process.env.SUBMINER_DOCS_CHANNEL = previousChannel; process.env.SUBMINER_DOCS_BASE = previousBase; process.env.SUBMINER_DOCS_VERSION = previousVersion; - process.env.SUBMINER_DOCS_LATEST_STABLE = previousLatest; - process.env.SUBMINER_DOCS_VERSION_MANIFEST = previousManifest; - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = previousVersionLinkOrigin; } }); -test('local stable archive version links stay on the dev server', async () => { - const previousCwd = process.cwd(); - const previousChannel = process.env.SUBMINER_DOCS_CHANNEL; - const previousBase = process.env.SUBMINER_DOCS_BASE; - const previousVersion = process.env.SUBMINER_DOCS_VERSION; - const previousLatest = process.env.SUBMINER_DOCS_LATEST_STABLE; - const previousManifest = process.env.SUBMINER_DOCS_VERSION_MANIFEST; - const previousVersionLinkOrigin = process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN; - process.chdir(docsSiteDir); - process.env.SUBMINER_DOCS_CHANNEL = 'stable-archive'; - process.env.SUBMINER_DOCS_BASE = '/v/0.10.0/'; - process.env.SUBMINER_DOCS_VERSION = 'v0.10.0'; - process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0'; - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = 'local'; - process.env.SUBMINER_DOCS_VERSION_MANIFEST = JSON.stringify({ - latestStable: 'v0.14.0', - channels: [ - { label: 'Latest stable', path: '/' }, - { label: 'main', path: '/main/' }, - ], - versions: [ - { version: 'v0.14.0', path: '/v/0.14.0/' }, - { version: 'v0.10.0', path: '/v/0.10.0/' }, - ], - }); - try { - const { default: archiveConfig } = await import('./.vitepress/config?local-archive-links'); - - const nav = archiveConfig.themeConfig?.nav as Array<{ - text: string; - items?: Array<{ text: string; link: string }>; - }>; - const versionNav = nav.find((item) => item.text === 'v0.10.0'); - - expect(versionNav?.items).toContainEqual({ - text: 'Latest stable (v0.14.0)', - link: '../../', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'main', - link: '../../main/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'v0.14.0', - link: '../0.14.0/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'v0.10.0', - link: './', - target: '_self', - noIcon: true, - }); - } finally { - process.chdir(previousCwd); - process.env.SUBMINER_DOCS_CHANNEL = previousChannel; - process.env.SUBMINER_DOCS_BASE = previousBase; - process.env.SUBMINER_DOCS_VERSION = previousVersion; - process.env.SUBMINER_DOCS_LATEST_STABLE = previousLatest; - process.env.SUBMINER_DOCS_VERSION_MANIFEST = previousManifest; - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = previousVersionLinkOrigin; - } -}); - -test('dev docs version links use local targets for version route testing', async () => { - const previousCwd = process.cwd(); - const previousChannel = process.env.SUBMINER_DOCS_CHANNEL; - const previousBase = process.env.SUBMINER_DOCS_BASE; - const previousVersion = process.env.SUBMINER_DOCS_VERSION; - const previousLatest = process.env.SUBMINER_DOCS_LATEST_STABLE; - const previousManifest = process.env.SUBMINER_DOCS_VERSION_MANIFEST; - const previousVersionLinkOrigin = process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN; - process.chdir(docsSiteDir); - delete process.env.SUBMINER_DOCS_CHANNEL; - delete process.env.SUBMINER_DOCS_BASE; - delete process.env.SUBMINER_DOCS_VERSION; - // Set explicitly (like the sibling version-nav tests) so this assertion stays - // pinned to the manifest under test instead of the config's fallback constant. - process.env.SUBMINER_DOCS_LATEST_STABLE = 'v0.14.0'; - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = 'local'; - process.env.SUBMINER_DOCS_VERSION_MANIFEST = JSON.stringify({ - latestStable: 'v0.14.0', - channels: [ - { label: 'Latest stable', path: '/' }, - { label: 'main', path: '/main/' }, - ], - versions: [ - { version: 'v0.14.0', path: '/v/0.14.0/' }, - { version: 'v0.12.0', path: '/v/0.12.0/' }, - { version: 'v0.11.2', path: '/v/0.11.2/' }, - ], - }); - try { - const { default: devConfig } = await import('./.vitepress/config?dev-version-links'); - - const nav = devConfig.themeConfig?.nav as Array<{ - text: string; - items?: Array<{ text: string; link: string }>; - }>; - const versionNav = nav.find((item) => item.text === 'v0.14.0'); - - expect(versionNav?.items).toContainEqual({ - text: 'Latest stable (v0.14.0)', - link: '/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'main', - link: '/main/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items).toContainEqual({ - text: 'v0.12.0', - link: '/v/0.12.0/', - target: '_self', - noIcon: true, - }); - expect(versionNav?.items?.map((item) => item.text)).toEqual([ - 'Latest stable (v0.14.0)', - 'main', - 'v0.14.0', - 'v0.12.0', - 'v0.11.2', - ]); - } finally { - process.chdir(previousCwd); - process.env.SUBMINER_DOCS_CHANNEL = previousChannel; - process.env.SUBMINER_DOCS_BASE = previousBase; - process.env.SUBMINER_DOCS_VERSION = previousVersion; - process.env.SUBMINER_DOCS_LATEST_STABLE = previousLatest; - process.env.SUBMINER_DOCS_VERSION_MANIFEST = previousManifest; - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = previousVersionLinkOrigin; - } -}); - -test('dev server redirects unserved version routes to production docs', () => { - let routeHandler: - | ((req: { url?: string }, res: DevRedirectResponse, next: () => void) => void) - | undefined; - const fakeServer = { - middlewares: { - use(handler: typeof routeHandler) { - routeHandler = handler; - }, - }, - }; - const plugins = Array.isArray(docsConfig.vite?.plugins) - ? docsConfig.vite.plugins - : [docsConfig.vite?.plugins].filter(Boolean); - const redirectPlugin = plugins.find( - (plugin): plugin is { name: string; configureServer: (server: never) => void } => - Boolean(plugin) && - typeof plugin === 'object' && - 'name' in plugin && - plugin.name === 'subminer-docs-local-version-redirects' && - 'configureServer' in plugin, - ); - expect(redirectPlugin).toBeDefined(); - redirectPlugin?.configureServer(fakeServer as never); - - const response = new DevRedirectResponse(); - let nextCalled = false; - routeHandler?.({ url: '/v/0.14.0/?from=dev' }, response, () => { - nextCalled = true; - }); - - expect(nextCalled).toBe(false); - expect(response.statusCode).toBe(302); - expect(response.headers.location).toBe('https://docs.subminer.moe/v/0.14.0/?from=dev'); - - const rootResponse = new DevRedirectResponse(); - routeHandler?.({ url: '/configuration' }, rootResponse, () => { - nextCalled = true; - }); - expect(rootResponse.ended).toBe(false); - expect(nextCalled).toBe(true); -}); - -test('dev server serves local archive files for local version links', async () => { - const previousVersionLinkOrigin = process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN; - const previousArchiveDir = process.env.SUBMINER_DOCS_LOCAL_ARCHIVE_DIR; - const archiveDir = mkdtempSync(join(tmpdir(), 'subminer-docs-archive-')); - mkdirSync(join(archiveDir, 'v/0.14.0'), { recursive: true }); - writeFileSync(join(archiveDir, 'v/0.14.0/index.html'), '<h1>local archive</h1>'); - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = 'local'; - process.env.SUBMINER_DOCS_LOCAL_ARCHIVE_DIR = archiveDir; - try { - const { default: localDevConfig } = await import( - `./.vitepress/config?local-dev-redirects-${Date.now()}` - ); - let routeHandler: - | ((req: { url?: string }, res: DevRedirectResponse, next: () => void) => void) - | undefined; - const fakeServer = { - middlewares: { - use(handler: typeof routeHandler) { - routeHandler = handler; - }, - }, - }; - const plugins = Array.isArray(localDevConfig.vite?.plugins) - ? localDevConfig.vite.plugins - : [localDevConfig.vite?.plugins].filter(Boolean); - const redirectPlugin = plugins.find( - (plugin): plugin is { name: string; configureServer: (server: never) => void } => - Boolean(plugin) && - typeof plugin === 'object' && - 'name' in plugin && - plugin.name === 'subminer-docs-local-version-redirects' && - 'configureServer' in plugin, - ); - redirectPlugin?.configureServer(fakeServer as never); - - const response = new DevRedirectResponse(); - let nextCalled = false; - routeHandler?.({ url: '/v/0.14.0/?from=dev' }, response, () => { - nextCalled = true; - }); - - expect(nextCalled).toBe(false); - expect(response.statusCode).toBe(200); - expect(response.headers['content-type']).toBe('text/html; charset=utf-8'); - expect(response.headers.location).toBeUndefined(); - expect(response.body).toBe('<h1>local archive</h1>'); - } finally { - process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN = previousVersionLinkOrigin; - process.env.SUBMINER_DOCS_LOCAL_ARCHIVE_DIR = previousArchiveDir; - rmSync(archiveDir, { recursive: true, force: true }); - } -}); - -class DevRedirectResponse { - statusCode = 200; - headers: Record<string, string> = {}; - ended = false; - body = ''; - - setHeader(name: string, value: string) { - this.headers[name.toLowerCase()] = value; - } - - end(chunk?: string | Uint8Array) { - if (chunk) { - this.body = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk); - } - this.ended = true; - } -} - test('docs sitemap excludes duplicate README page from indexable URLs', async () => { const items = [{ url: '' }, { url: 'README' }, { url: 'usage' }]; diff --git a/docs-site/shortcuts.md b/docs-site/shortcuts.md index c16a0ee8..4a0d64f4 100644 --- a/docs-site/shortcuts.md +++ b/docs-site/shortcuts.md @@ -1,194 +1,144 @@ # Keyboard shortcuts -This page is the complete reference for every keystroke SubMiner responds to. If you are just getting started, focus on the **Mining Shortcuts** and **Overlay Controls** sections - those cover the day-to-day mining loop. The rest can wait until you need them. +Every key SubMiner responds to, with its default binding. `Ctrl/Cmd` means `Ctrl` on Windows and Linux and `Cmd` on macOS (`CommandOrControl` in config). -A few terms used throughout: +Shortcuts work when the overlay has focus. With the [mpv plugin](/mpv-plugin), `shortcuts.*` and `keybindings` entries also work while mpv has focus. If a key does nothing, click the video once. Set any shortcut to `null` to disable it. Changes to `shortcuts`, `keybindings`, and `subtitleSidebar` apply without a restart. -- **Overlay** - the transparent SubMiner window that sits on top of mpv and shows the interactive subtitles. Most shortcuts only work while this window has focus (click the video once if a shortcut seems to do nothing). -- **`Ctrl/Cmd`** - use `Ctrl` on Windows/Linux and `Cmd` (⌘) on macOS. In the config file this is written as `CommandOrControl`. -- **Accelerator** - Electron's name for a shortcut string like `Alt+Shift+O`. +## Global -All shortcuts are configurable in `config.jsonc` under `shortcuts` and `keybindings`. Set any shortcut to `null` to disable it. +| Shortcut | Action | Config key | +| ------------- | ------------------------------- | -------------------------------------- | +| `Alt+Shift+O` | Toggle visible overlay | `shortcuts.toggleVisibleOverlayGlobal` | +| `Alt+Shift+Y` | Open active dictionary settings | Fixed | -## App-wide shortcuts +`Alt+Shift+Y` opens Yomitan or Hachidori settings, whichever backend is running. It is registered with the OS and works from any app. If another app already uses it, SubMiner cannot take it and you cannot rebind it. -| Shortcut | Action | Scope | Configurable | -| ------------- | ---------------------- | -------------------------------------------- | -------------------------------------- | -| `Alt+Shift+O` | Toggle visible overlay | Works while the overlay or mpv has focus | `shortcuts.toggleVisibleOverlayGlobal` | -| `Alt+Shift+Y` | Open active dictionary settings | OS-global (registered with the OS) | Fixed (not configurable) | +## Mining -::: tip -`Alt+Shift+O` is dispatched by the overlay window and the mpv plugin, so it works from either surface without OS registration. Only `Alt+Shift+Y` is registered with the OS; if it conflicts with another application, that binding cannot be changed. All `shortcuts.*` keys hot-reload - no restart needed. -::: +| Shortcut | Action | Config key | +| ------------------ | --------------------------------------------------- | --------------------------------------- | +| `Ctrl/Cmd+S` | Mine current line as a sentence card | `shortcuts.mineSentence` | +| `Ctrl/Cmd+Shift+S` | Mine several lines as one sentence card | `shortcuts.mineSentenceMultiple` | +| `Ctrl/Cmd+C` | Copy current line | `shortcuts.copySubtitle` | +| `Ctrl/Cmd+Shift+C` | Copy several lines | `shortcuts.copySubtitleMultiple` | +| `Ctrl/Cmd+V` | Update last-added card from the clipboard | `shortcuts.updateLastCardFromClipboard` | +| `Ctrl/Cmd+G` | Run the field grouping check on the last-added card | `shortcuts.triggerFieldGrouping` | +| `Ctrl/Cmd+Shift+A` | Mark last-added card as an audio card | `shortcuts.markAudioCard` | -## Mining shortcuts +After a multi-line shortcut, press `1` to `9` for how many lines to combine, counting back from and including the current line. The prompt closes after `shortcuts.multiCopyTimeoutMs`. -These work when the overlay window has focus. +When text is selected in the [subtitle sidebar](/subtitle-sidebar), `Ctrl/Cmd+C` copies that selection instead. -When text is selected in the [subtitle sidebar](./subtitle-sidebar.md#selecting-and-copying-dialogue), `Ctrl/Cmd+C` copies that selection without timestamps, taking priority over the current-subtitle action. `Escape` clears the sidebar selection. +## Playback -| Shortcut | Action | Config key | -| ------------------ | ----------------------------------------------- | --------------------------------------- | -| `Ctrl/Cmd+S` | Mine current subtitle as sentence card | `shortcuts.mineSentence` | -| `Ctrl/Cmd+Shift+S` | Mine multiple lines (press 1–9 to select count) | `shortcuts.mineSentenceMultiple` | -| `Ctrl/Cmd+C` | Copy current subtitle text | `shortcuts.copySubtitle` | -| `Ctrl/Cmd+Shift+C` | Copy multiple lines (press 1–9 to select count) | `shortcuts.copySubtitleMultiple` | -| `Ctrl/Cmd+V` | Update last Anki card from clipboard text | `shortcuts.updateLastCardFromClipboard` | -| `Ctrl/Cmd+G` | Trigger field grouping (Kiku merge check) | `shortcuts.triggerFieldGrouping` | -| `Ctrl/Cmd+Shift+A` | Mark last card as audio card | `shortcuts.markAudioCard` | +These are the default `keybindings` entries. Remap or disable them in the `keybindings` array. -The multi-line shortcuts open a digit selector with a 3-second timeout (`shortcuts.multiCopyTimeoutMs`). Press `1`–`9` to select the total number of subtitle lines to combine, ending at the current line and moving backward through the subtitle timeline. The current line counts toward the selected total. When the shortcut starts from mpv, SubMiner focuses the visible overlay for that selector instead of reserving the number keys in the mpv plugin. +| Shortcut | Action | +| ------------------ | ---------------------------------------- | +| `Space` | Pause or resume | +| `F` | Toggle fullscreen | +| `J` | Cycle primary subtitle track | +| `Shift+J` | Cycle secondary subtitle track | +| `ArrowRight` | Seek forward 5 seconds | +| `ArrowLeft` | Seek back 5 seconds | +| `ArrowUp` | Seek forward 60 seconds | +| `ArrowDown` | Seek back 60 seconds | +| `Shift+H` | Jump to previous subtitle | +| `Shift+L` | Jump to next subtitle | +| `Ctrl+Shift+Left` | Shift subtitle delay to the previous cue | +| `Ctrl+Shift+Right` | Shift subtitle delay to the next cue | +| `Z` | Subtitle delay -100 ms | +| `Shift+Z` | Subtitle delay +100 ms | +| `X` | Subtitle delay +100 ms | +| `Ctrl+Shift+H` | Replay current subtitle, then pause | +| `Ctrl+Shift+L` | Play next subtitle, then pause | +| `Ctrl+Alt+P` | Open playlist browser | +| `Ctrl+Alt+C` | Open YouTube subtitle picker | +| `Q` | Quit mpv | +| `Ctrl+W` | Quit mpv | -## Overlay controls +Built into the overlay, not configurable: -These control playback and subtitle display. They require overlay window focus. +| Input | Action | +| ------------------------- | -------------------------------------------------- | +| `V` | Cycle primary subtitle bar: hidden, visible, hover | +| Right-click | Pause or resume (outside the subtitle area) | +| Right-click + drag | Move the subtitles | +| Drop files on the overlay | Replace the mpv playlist | +| `Shift` + drop files | Append to the mpv playlist | -| Shortcut | Action | -| -------------------- | ---------------------------------------------------------- | -| `Space` | Toggle mpv pause | -| `F` | Toggle fullscreen | -| `V` | Cycle primary subtitle bar mode (hidden → visible → hover) | -| `J` | Cycle primary subtitle track | -| `Shift+J` | Cycle secondary subtitle track | -| `Ctrl+Alt+P` | Open playlist browser for current directory + queue | -| `ArrowRight` | Seek forward 5 seconds | -| `ArrowLeft` | Seek backward 5 seconds | -| `ArrowUp` | Seek forward 60 seconds | -| `ArrowDown` | Seek backward 60 seconds | -| `Shift+H` | Jump to previous subtitle | -| `Shift+L` | Jump to next subtitle | -| `Ctrl+Shift+Left` | Shift subtitle delay to previous subtitle cue | -| `Ctrl+Shift+Right` | Shift subtitle delay to next subtitle cue | -| `z` | Shift subtitles 100 ms earlier | -| `Shift+Z` | Delay subtitles by 100 ms | -| `x` | Delay subtitles by 100 ms | -| `Ctrl+Shift+H` | Replay current subtitle (play to end, then pause) | -| `Ctrl+Shift+L` | Play next subtitle (jump, play to end, then pause) | -| `Q` | Quit mpv | -| `Ctrl+W` | Quit mpv | -| `Right-click` | Toggle pause (outside subtitle area) | -| `Right-click + drag` | Reposition subtitles (on subtitle area) | +## Overlay features -The mpv-command rows above (`Space`, `F`, `J`, `Shift+J`, the seek/sub-seek/sub-step/sub-delay keys, replay/play-next, and quit) are merged from the `keybindings` config array and can be remapped or disabled there. `V` and the mouse actions are built-in overlay behaviors and are not part of the `keybindings` array. The playlist browser opens a split overlay modal with sibling video files on the left and the live mpv playlist on the right. +| Shortcut | Action | Config key | +| ------------------ | ------------------------------------------------------ | ------------------------------------------ | +| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle bar: hidden, visible, hover | `shortcuts.toggleSecondarySub` | +| `Ctrl/Cmd+Shift+O` | Open runtime options | `shortcuts.openRuntimeOptions` | +| `Ctrl/Cmd+/` | Open session help | `shortcuts.openSessionHelp` | +| `Ctrl/Cmd+D` | Open character dictionary manager | `shortcuts.openCharacterDictionaryManager` | +| `Ctrl/Cmd+N` | Toggle notification history | `shortcuts.toggleNotificationHistory` | +| `Ctrl/Cmd+A` | Append the video path on the clipboard to the playlist | `shortcuts.appendClipboardVideoToQueue` | +| `Ctrl+Shift+J` | Open Jimaku subtitle search | `shortcuts.openJimaku` | +| `Ctrl+Shift+T` | Open TsukiHime subtitle search | `shortcuts.openTsukihime` | +| `Ctrl+Shift+G` | Open Japanese subtitle generation | `shortcuts.openSubtitleGeneration` | +| `Ctrl+Alt+S` | Open subtitle sync (subsync) | `shortcuts.triggerSubsync` | +| `g` then `s` | Pick primary and secondary subtitles (when enabled) | `shortcuts.openSubtitleSelection` | +| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` | +| `` ` `` | Toggle stats overlay | `stats.toggleKey` | +| `W` | Mark video watched and play the next one in the queue | `stats.markWatchedKey` | +| `Alt+C` | Open controller setup and remapping | `shortcuts.openControllerSelect` | +| `Alt+Shift+C` | Open controller debug view | `shortcuts.openControllerDebug` | -On macOS managed playback, SubMiner disables mpv's menu-bar shortcuts so configured SubMiner shortcuts like `Cmd+Shift+O` reach the mpv plugin instead of opening native mpv menu actions. +The sidebar key has a separate mpv-side binding, `shortcuts.toggleSubtitleSidebar`. The sidebar only opens when SubMiner has parsed the active subtitle file. In the sidebar, `Enter` seeks to the focused line. -Mouse-hover playback behavior is configured separately from shortcuts: `subtitleStyle.autoPauseVideoOnHover` defaults to `true` (pause on subtitle hover, resume on leave). +The subtitle picker (`g` then `s`) is off until you turn it on in **Settings, Behavior, Subtitle Selection**. Press the second key within one second. If `g` already has an action in SubMiner or mpv, the sequence is disabled and a warning is shown. See [subtitle selection](/configuration#subtitle-selection). -## Subtitle and feature shortcuts +## mpv plugin keys -| Shortcut | Action | Config key | -| ------------------ | -------------------------------------------------------- | ------------------------------------------ | -| `Ctrl/Cmd+Shift+V` | Cycle secondary subtitle mode (hidden → visible → hover) | `shortcuts.toggleSecondarySub` | -| `Ctrl/Cmd+D` | Open loaded character dictionary manager | `shortcuts.openCharacterDictionaryManager` | -| `Ctrl/Cmd+Shift+O` | Open runtime options palette | `shortcuts.openRuntimeOptions` | -| `Ctrl/Cmd+/` | Open session help modal | `shortcuts.openSessionHelp` | -| `Ctrl+Shift+J` | Open Jimaku subtitle search modal | `shortcuts.openJimaku` | -| `Ctrl+Shift+G` | Open Japanese subtitle generation modal | `shortcuts.openSubtitleGeneration` | -| `Ctrl+Shift+T` | Open TsukiHime subtitle search modal (EN/JA tabs) | `shortcuts.openTsukihime` | -| `Ctrl/Cmd+N` | Toggle overlay notification history panel | `shortcuts.toggleNotificationHistory` | -| `Ctrl+Alt+C` | Open the manual YouTube subtitle picker | `keybindings` | -| `g` then `s` | Select primary and secondary subtitles, when enabled | `shortcuts.openSubtitleSelection` | -| `Ctrl+Alt+S` | Open subtitle sync (subsync) modal | `shortcuts.triggerSubsync` | -| `Ctrl/Cmd+A` | Append clipboard video path to mpv playlist | `shortcuts.appendClipboardVideoToQueue` | -| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` (overlay) / `shortcuts.toggleSubtitleSidebar` (mpv session binding) | -| `` ` `` | Toggle stats overlay | `stats.toggleKey` | -| `W` | Mark current video watched and advance to next in queue | `stats.markWatchedKey` | +Press `y`, then the second key. -`shortcuts.openAnimetosho` remains accepted as a deprecated alias for `shortcuts.openTsukihime`. The current name takes precedence when both are configured. +| Keys | Action | +| ----- | ------------------------------- | +| `y-y` | Open the SubMiner menu | +| `y-s` | Start the overlay | +| `y-S` | Stop the overlay | +| `y-t` | Toggle the visible overlay | +| `y-o` | Open active dictionary settings | +| `y-r` | Restart the overlay | +| `y-c` | Show overlay status | +| `y-h` | Open session help | +| `v` | Cycle primary subtitle bar | -The stats toggle is handled inside the focused visible overlay window. It is configurable through the top-level `stats.toggleKey` setting and defaults to `Backquote`. +The plugin's `v` replaces mpv's own subtitle visibility toggle. When the overlay has focus, `y` then `d` toggles DevTools. -Enable the subtitle selector in **Settings → Behavior → Subtitle Selection**. Its shortcut overrides mpv subtitle selection only while enabled. In the focused overlay, press the second key within one second. Single-key bindings take priority: if `g` already has an action in SubMiner or mpv, `g-s` is disabled with a conflict warning, and `g` still runs immediately. Remap the sequence or remove the conflicting single-key binding. The existing `y` prefix is reserved for its built-in commands. mpv bindings are checked on connection, configuration changes, and overlay focus; refresh the overlay after changing another script's bindings. See [subtitle selection](/configuration#subtitle-selection). +## Customizing -The subtitle sidebar toggle is overlay-local and only opens when SubMiner has a parsed cue list for the active subtitle source. - -In the sidebar, `Enter` seeks the keyboard-focused cue. `Space` keeps its configured playback action, normally pause/resume, even when a cue has focus. - -## Controller shortcuts - -These overlay-local shortcuts open controller utilities for the Chrome Gamepad API integration. - -| Shortcut | Action | Configurable | -| ------------- | ------------------------------------ | -------------------------------- | -| `Alt+C` | Open controller config + remap modal | `shortcuts.openControllerSelect` | -| `Alt+Shift+C` | Open controller debug modal | `shortcuts.openControllerDebug` | - -Controller input only drives the overlay while keyboard-only mode is enabled. The controller mapping and tuning live under the top-level `controller` config block; keyboard-only mode still works normally without a controller. - -## MPV plugin chords - -When the mpv plugin is installed, all commands use a `y` chord prefix - press `y`, then the second key (the overlay-side chord times out after 1 second; the mpv plugin uses native mpv key sequences). - -| Chord | Action | -| ----- | ---------------------------------------------------------- | -| `y-y` | Open SubMiner menu (OSD) | -| `y-s` | Start overlay | -| `y-S` | Stop overlay | -| `y-t` | Toggle visible overlay | -| `v` | Cycle primary subtitle bar mode (hidden → visible → hover) | -| `y-o` | Open active dictionary settings | -| `y-r` | Restart overlay | -| `y-c` | Check overlay status | -| `y-h` | Open session help | - -The bare `v` plugin binding intentionally overrides mpv's native primary subtitle visibility toggle so it cycles the SubMiner primary subtitle bar (hidden → visible → hover) instead. - -When the overlay has focus, press `y` then `d` to toggle DevTools (debugging helper). - -## Drag-and-drop - -| Gesture | Action | -| ------------------------- | ------------------------------------------------ | -| Drop file(s) onto overlay | Replace current mpv playlist with dropped files | -| `Shift` + drop file(s) | Append all dropped files to current mpv playlist | - -## Customizing shortcuts - -All `shortcuts.*` keys accept [Electron accelerator strings](https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts), for example `"CommandOrControl+D"`. Use `null` to disable a shortcut. +`shortcuts.*` values are [Electron accelerator strings](https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts). ```jsonc { "shortcuts": { "mineSentence": "CommandOrControl+S", - "copySubtitle": "CommandOrControl+C", - "toggleVisibleOverlayGlobal": "Alt+Shift+O", "openJimaku": null, // disabled }, } ``` -The `keybindings` array overrides or extends the overlay's built-in key handling for mpv commands: +`keybindings` entries map a key to an mpv command. They are merged with the defaults above. Set `command` to `null` to disable a default. ```jsonc { "keybindings": [ - { "key": "f", "command": ["cycle", "fullscreen"] }, { "key": "m", "command": ["cycle", "mute"] }, { "key": "MBTN_BACK", "command": ["sub-seek", -1] }, - { "key": "MBTN_FORWARD", "command": ["sub-seek", 1] }, - { "key": "Space", "command": null }, // disable default Space → pause + { "key": "Space", "command": null }, ], } ``` -Mouse keybinding names are `MBTN_LEFT`, `MBTN_MID`, `MBTN_RIGHT`, `MBTN_BACK`, and `MBTN_FORWARD`. +Mouse button names are `MBTN_LEFT`, `MBTN_MID`, `MBTN_RIGHT`, `MBTN_BACK`, and `MBTN_FORWARD`. See [keybindings](/configuration#keybindings) and [shortcuts configuration](/configuration#shortcuts-configuration) in the config reference. -Both `shortcuts`, `keybindings`, and `subtitleSidebar` are [hot-reloadable](/configuration#hot-reload-behavior) - changes take effect without restarting SubMiner. +## Automatic mpv bindings -### Automatic mpv bindings +The overlay reads single-key bindings from the running mpv (`input.conf`, mpv defaults, and scripts). If SubMiner does not handle a key, it passes it to mpv. SubMiner shortcuts and `keybindings` entries win, including ones set to `null`. Keys are not forwarded while you type in a text field, use an overlay menu, or have a Yomitan popup open. -The overlay also discovers supported single-key keyboard bindings from the connected mpv session, -including `input.conf`, mpv defaults, and loaded scripts. When SubMiner does not handle a -key, it forwards the key to mpv to run the current binding. SubMiner shortcuts and -configured bindings take precedence, including entries explicitly disabled with -`"command": null`. Text entry, overlay menus, and Yomitan popups do not forward these -fallback keys. - -Discovery runs in the background at startup, again after a short delay for scripts, -when the overlay regains focus, and when SubMiner's binding configuration reloads. -Bindings added later may require refocusing the overlay. Imported bindings stay in -memory for the session and do not appear in SubMiner's help menu or modify its config. -Supported keys include characters, common navigation keys, and F1 through F24, with -modifiers. Mouse bindings, keypad-specific and media keys, key sequences, and full -navigation of interactive mpv script menus are not imported. If discovery is unavailable, SubMiner's configured controls keep working. +Mouse buttons, keypad and media keys, and key sequences are not imported. Bindings imported this way do not appear in session help. If you add an mpv binding while SubMiner runs, refocus the overlay to pick it up. diff --git a/docs-site/subtitle-annotations.md b/docs-site/subtitle-annotations.md index af9cf737..c8e3718e 100644 --- a/docs-site/subtitle-annotations.md +++ b/docs-site/subtitle-annotations.md @@ -1,190 +1,119 @@ # Subtitle annotations -SubMiner annotates subtitle tokens as they appear in the overlay. There are four layers: **N+1 highlighting**, **character-name highlighting**, **frequency highlighting**, and **JLPT tagging**. +SubMiner can color and underline words in the subtitle overlay: words you already know, the one new word in an N+1 line, common words, JLPT levels, and character names. Each layer is off by default and works on its own, so turn on only the ones you want. -All four are off by default and live under `subtitleStyle`, `ankiConnect.knownWords`, and `ankiConnect.nPlusOne`. They are independent, so any combination works. +Yomitan splits the subtitle into words, so your installed Yomitan dictionaries and their order decide where word boundaries fall. Grammar words such as particles (`は`), auxiliaries (`です`), and endings like `んです` stay hoverable but never get annotation colors. -::: tip Tokenization -Yomitan is the tokenizer, so the dictionaries you installed there decide where word boundaries fall. Piling on large dictionaries adds noise and slows lookups. Be picky about which ones you install and what order you rank them in. -::: +Defaults for every key below are in the [configuration reference](/configuration). -Before any of those layers render, SubMiner strips annotation metadata from tokens that are usually just subtitle glue or annotation noise. Standalone particles, auxiliaries, adnominals, common explanatory endings like `んです` / `のだ`, merged trailing quote-particle forms like `...って`, auxiliary-stem grammar tails like `そうだ` (MeCab POS3 `助動詞語幹`), repeated kana interjections, and similar non-lexical helper tokens remain hoverable in the subtitle text, but they render as plain tokens without known-word, N+1, frequency, JLPT, or name-match annotation styling. +## Known words {#known-words} -Kanji vocabulary that MeCab labels `名詞/非自立`, such as `日` or `以外`, remains content for every annotation layer. The `非自立` exclusion only suppresses kana grammar nouns such as `こと` and `もの`. +Colors every word that already appears in your Anki decks, so you can see how much of a line you know. + +Needs: Anki running with AnkiConnect, and at least one deck in `ankiConnect.knownWords.decks`. + +```jsonc +{ + "ankiConnect": { + "knownWords": { + "highlightEnabled": true, + "decks": { "Kaishi 1.5k": ["Word"] }, + }, + }, +} +``` + +Map each deck to its expression or word field. SubMiner also reads the note's reading field when it has one, so a known word only matches in the reading its card teaches. + +| Key | What it does | +| ------------------------------------------------- | ------------------------------------------------------------------- | +| `ankiConnect.knownWords.highlightEnabled` | Turn known-word coloring on | +| `ankiConnect.knownWords.decks` | Deck name to list of fields to read | +| `ankiConnect.knownWords.matchMode` | `headword` matches the dictionary form, `surface` the text as shown | +| `ankiConnect.knownWords.refreshMinutes` | How often the known-word list is re-read from Anki | +| `ankiConnect.knownWords.addMinedWordsImmediately` | Count a word as known as soon as you mine it | +| `subtitleStyle.knownWordColor` | Color for known words | + +### Known-word maturity highlighting + +Colors known words by how well you know them instead of using one color. Each word gets the tier of its most mature card: + +- `new`: never studied +- `learning`: in the learning or relearning queue +- `young`: in review, interval below the threshold +- `mature`: in review, interval at or above `ankiConnect.knownWords.matureThresholdDays` + +Turn it on with `ankiConnect.knownWords.maturityEnabled` (known-word highlighting must also be on). Set the colors under `subtitleStyle.knownWordMaturityColors` (`new`, `learning`, `young`, `mature`). + +Tiers update when the known-word list refreshes, so a card that turns mature today keeps its old color until the next refresh. If your deck has no relearning steps, lapsed cards go straight back to review and show as `young`. ## N+1 word highlighting -An N+1 sentence is one where you know every word but a single unknown. Those are the best mining targets, because the rest of the sentence gives you the context for free. SubMiner caches your known vocabulary from Anki and marks the lines that qualify. +An N+1 line has exactly one word you don't know. It is the easiest kind of sentence to mine, because the rest of the line gives you context. SubMiner colors that one unknown word. -**How it works:** +Needs: the same Anki setup as [known words](#known-words) (`ankiConnect.knownWords.decks`). Known-word coloring itself can stay off. -1. SubMiner queries your configured Anki decks for expression/word fields such as `Expression` or `Word`. -2. The results are cached locally (`known-words-cache.json`) and refreshed on a configurable interval. -3. When a subtitle line appears, each token is checked against the cache. -4. If exactly one unknown word remains in the sentence, it is highlighted with `subtitleStyle.nPlusOneColor` (default: `#c6a0f6`). -5. Already-known tokens can optionally display in `subtitleStyle.knownWordColor` (default: `#a6da95`). - -**Key settings:** - -| Option | Default | Description | -| ----------------------------------------- | ------------ | -------------------------------------------------------- | -| `ankiConnect.knownWords.highlightEnabled` | `false` | Enable known-word cache lookups used by N+1 highlighting | -| `ankiConnect.knownWords.refreshMinutes` | `1440` | Minutes between Anki cache refreshes | -| `ankiConnect.knownWords.decks` | `{}` | Deck→fields map for known-word cache queries | -| `ankiConnect.knownWords.matchMode` | `"headword"` | `"headword"` (dictionary form) or `"surface"` (raw text) | -| `ankiConnect.nPlusOne.enabled` | `false` | Enable N+1 target highlighting | -| `ankiConnect.nPlusOne.minSentenceWords` | `3` | Minimum tokens in a sentence for N+1 to trigger | -| `subtitleStyle.nPlusOneColor` | `#c6a0f6` | Color for the single unknown target word | -| `subtitleStyle.knownWordColor` | `#a6da95` | Color for already-known tokens | - -Prefer expression/word fields for `ankiConnect.knownWords.decks`. Reading-only fields can mark unrelated homophones as known, so only include them when that tradeoff is intentional. - -::: tip -Set `refreshMinutes` to `1440` (24 hours) for daily sync if your Anki collection is large. -::: - -## Known-word maturity highlighting - -Maturity highlighting tints each known token by the review state of its Anki cards instead of painting every known word the same color, so you can see how much of a line you actually have down. asbplayer does the same thing. - -**How it works:** - -1. During the known-word cache refresh, SubMiner classifies each note with Anki search filters (`prop:ivl`, `is:learn`) - no extra card data is downloaded. -2. Each note gets the tier of its **most mature** card: `mature` (in review, interval ≥ threshold), `young` (in review, interval below the threshold), `learning` (in the learning or relearning queue), or `new` (never studied). The buckets are disjoint, matching Anki's own card counts: a lapsed card in relearning counts as `learning`, not `young`, even though its interval is ≥ 1 day. A note with a mature card plus a relearning card still shows `mature`. -3. A word matched by several notes takes the most mature tier among them, with the same reading-aware matching as regular known-word highlighting. -4. Known tokens render in the tier color instead of `subtitleStyle.knownWordColor`; if tier data is missing for a match, the token falls back to the single known-word color. - -**Key settings:** - -| Option | Default | Description | -| ------------------------------------------------ | --------- | --------------------------------------------------------------------- | -| `ankiConnect.knownWords.maturityEnabled` | `false` | Color known words by card maturity (requires known-word highlighting) | -| `ankiConnect.knownWords.matureThresholdDays` | `21` | Card interval in days at which a word counts as mature | -| `subtitleStyle.knownWordMaturityColors.new` | `#ee99a0` | Tier color for never-reviewed cards | -| `subtitleStyle.knownWordMaturityColors.learning` | `#b7bdf8` | Tier color for cards in the learning/relearning queue | -| `subtitleStyle.knownWordMaturityColors.young` | `#91d7e3` | Tier color for young review cards | -| `subtitleStyle.knownWordMaturityColors.mature` | `#a6da95` | Tier color for mature cards | - -Changing `maturityEnabled` or the threshold triggers a full known-word cache refresh so tiers are refetched, as does upgrading to a build that revises the tier rules. - -How often the `learning` color appears depends on your deck preset: with no relearning steps configured, a lapsed card returns straight to review and shows `young` instead. - -While maturity highlighting is on, the session help color legend replaces its single "Known words" swatch with one row per tier (new, learning, young, mature). - -**Checking the colors you actually see:** - -Tiers are only as fresh as the last known-word cache refresh (`ankiConnect.knownWords.refreshMinutes`), so a card that crosses the mature threshold mid-day keeps its old color until the next refresh. To check a whole episode offline, run the verifier against its subtitle file: - -```sh -bun run verify-known-word-highlights:electron -- --input /path/to/episode.ja.srt --audit -``` - -It tokenizes every cue through the real Yomitan/MeCab pipeline with your live known-word cache, prints each line in your configured tier colors, and summarizes the tier counts. `--audit` re-derives each highlighted tier from live Anki card data (`notesInfo` + `cardsInfo` intervals) and lists any token whose color disagrees, with the note ids and intervals behind it. Electron locks the Yomitan profile, so quit SubMiner first or pass `--profile-copy` to run against a scratch copy. Other useful flags: `--refresh` (refresh the cache first), `--limit <n>`, `--quiet`, `--json`. - -## Character-name highlighting - -Character-name matches are built from the active merged SubMiner character dictionary, which auto-syncs character data from AniList for your recently-watched titles. When the current AniList media ID is known, SubMiner ignores loaded entries from other titles for subtitle name matching and inline portraits. Matching names are highlighted in subtitles and become available for hover-driven Yomitan character profiles - portraits, roles, voice actors, and biographical detail. - -**How it works:** - -1. Subtitles are tokenized, then candidate name tokens are matched against the character dictionary via Yomitan's scanning pipeline. -2. Matching tokens receive a dedicated style distinct from N+1 and frequency layers. -3. This layer can be independently toggled with `subtitleStyle.nameMatchEnabled`. -4. When `subtitleStyle.nameMatchImagesEnabled` is also enabled, SubMiner shows the cached AniList portrait beside matched names. - -**Key settings:** - -| Option | Default | Description | -| -------------------------------------- | --------- | ------------------------------------------------ | -| `subtitleStyle.nameMatchEnabled` | `false` | Enable character-name token highlighting | -| `subtitleStyle.nameMatchImagesEnabled` | `false` | Show small AniList portraits next to name tokens | -| `subtitleStyle.nameMatchColor` | `#f5bde6` | Color used for character-name matches | - -For full details on dictionary generation, name variant expansion, auto-sync lifecycle, and configuration, see the dedicated [Character Dictionary](/character-dictionary) page. +| Key | What it does | +| --------------------------------------- | --------------------------------------- | +| `ankiConnect.nPlusOne.enabled` | Turn N+1 highlighting on | +| `ankiConnect.nPlusOne.minSentenceWords` | Skip lines shorter than this many words | +| `subtitleStyle.nPlusOneColor` | Color for the unknown word | ## Frequency highlighting -Frequency highlighting colors tokens by how common the word is, so a rare word in an otherwise easy line stands out. Ranks come from your installed Yomitan frequency dictionaries, read in priority order. The highest-priority dictionary that has the term wins, lower-priority ones fill in terms it lacks, and occurrence-based dictionaries are skipped. +Colors words by how common they are, so a rare word in an easy line stands out. -**Modes:** +Needs: at least one frequency dictionary installed in Yomitan. When several are installed, SubMiner uses them in your Yomitan priority order. Occurrence-count dictionaries are skipped. You can also point `sourcePath` at a folder of Yomitan-format frequency files as a fallback. -- **Single** - all highlighted tokens share one color (`singleColor`). -- **Banded** - tokens are assigned to five color bands from most common to least common within the `topX` window. - -SubMiner looks up each token's `frequencyRank` from `term_meta_bank_*.json` files. Only tokens with a positive rank at or below `topX` are highlighted. - -**Key settings:** - -| Option | Default | Description | -| ------------------------------------------------ | ------------ | ---------------------------------------------------------------- | -| `subtitleStyle.frequencyDictionary.enabled` | `false` | Enable frequency highlighting | -| `subtitleStyle.frequencyDictionary.topX` | `10000` | Max frequency rank to highlight | -| `subtitleStyle.frequencyDictionary.mode` | `"single"` | `"single"` or `"banded"` | -| `subtitleStyle.frequencyDictionary.matchMode` | `"headword"` | `"headword"` or `"surface"` | -| `subtitleStyle.frequencyDictionary.singleColor` | `#f5a97f` | Color for single mode | -| `subtitleStyle.frequencyDictionary.bandedColors` | 5 colors[^1] | Array of five hex colors for banded mode | -| `subtitleStyle.frequencyDictionary.sourcePath` | `""` | Custom path to frequency dictionary root (empty = auto-discover) | - -[^1]: Default banded palette (most common → least common): `#ed8796`, `#f5a97f`, `#f9e2af`, `#8bd5ca`, `#8aadf4`. - -When `sourcePath` is omitted, SubMiner searches default install/runtime locations for `frequency-dictionary` directories automatically. - -::: info -Frequency highlighting skips tokens that look like non-lexical noise (kana reduplication, short kana endings like `っ`), even when dictionary ranks exist. For merged kana tokens, SubMiner keeps a rank when the dictionary headword reading covers the full token (for example, `かと言って` / `かといって`), while grammar wrapped around a shorter lemma remains unannotated. -::: - -::: info -Frequency, JLPT, and N+1 metadata are only shown for tokens that survive the subtitle-annotation noise filter. Standalone grammar tokens like `は`, `です`, and `この` are intentionally left unannotated even if a dictionary can assign them metadata. -::: +| Key | What it does | +| ------------------------------------------------ | ---------------------------------------------------------------------- | +| `subtitleStyle.frequencyDictionary.enabled` | Turn frequency highlighting on | +| `subtitleStyle.frequencyDictionary.topX` | Only color words whose rank is this number or lower (1 is most common) | +| `subtitleStyle.frequencyDictionary.mode` | `single` uses one color, `banded` splits the range into five colors | +| `subtitleStyle.frequencyDictionary.singleColor` | Color for `single` mode | +| `subtitleStyle.frequencyDictionary.bandedColors` | Five colors for `banded` mode, most common first | +| `subtitleStyle.frequencyDictionary.matchMode` | `headword` or `surface`, as for known words | +| `subtitleStyle.frequencyDictionary.sourcePath` | Optional folder of frequency files | ## JLPT tagging -JLPT tagging underlines each token in a color for its JLPT level (N1–N5), so the difficulty spread of a line is visible without reading it closely. +Underlines each word in a color for its JLPT level, N1 to N5. The JLPT word lists ship with SubMiner, so there is nothing to install. -**How it works:** +| Key | What it does | +| ------------------------------------- | ------------------------------ | +| `subtitleStyle.enableJlpt` | Turn JLPT underlines on | +| `subtitleStyle.jlptColors.N1` to `N5` | Underline color for each level | -SubMiner loads offline `term_meta_bank_*.json` files from `vendor/yomitan-jlpt-vocab` and matches each token's headword against the bank entries. Tokens with a recognized JLPT level receive a colored underline. +## Character names -**Default colors:** +Colors character names from the current show and lets you hover them for a portrait, role, and voice actor. -| Level | Color | Preview | -| ----- | --------- | ------- | -| N1 | `#ed8796` | Red | -| N2 | `#f5a97f` | Peach | -| N3 | `#f9e2af` | Yellow | -| N4 | `#8bd5ca` | Teal | -| N5 | `#8aadf4` | Blue | +Needs: the [character dictionary](/character-dictionary), which SubMiner builds from AniList when you turn this on. -All colors are customizable via the `subtitleStyle.jlptColors` object. +| Key | What it does | +| -------------------------------------- | ----------------------------------------------- | +| `subtitleStyle.nameMatchEnabled` | Build the character dictionary and color names | +| `subtitleStyle.nameMatchImagesEnabled` | Show a small portrait next to each matched name | +| `subtitleStyle.nameMatchColor` | Color for character names | -**Key settings:** +## Toggling during playback -| Option | Default | Description | -| ---------------------------------- | --------- | ----------------------------- | -| `subtitleStyle.enableJlpt` | `false` | Enable JLPT underline styling | -| `subtitleStyle.jlptColors.N1`–`N5` | see above | Per-level underline colors | +Open the runtime options palette (`Ctrl/Cmd+Shift+O`) to switch these without restarting: -## Runtime toggles +- known-word highlighting, maturity colors, and known-word match mode +- N+1 highlighting +- JLPT tagging +- frequency highlighting -These annotation layers can be toggled at runtime via the runtime options palette (`Ctrl/Cmd+Shift+O`) without restarting: +Character names are toggled in the config file or the Settings window. Changes apply from the next subtitle line. -- `ankiConnect.knownWords.highlightEnabled` (`On` / `Off`) -- `ankiConnect.knownWords.maturityEnabled` (`On` / `Off`) -- `ankiConnect.knownWords.matchMode` -- `ankiConnect.nPlusOne.enabled` (`On` / `Off`) -- `subtitleStyle.enableJlpt` (`On` / `Off`) -- `subtitleStyle.frequencyDictionary.enabled` (`On` / `Off`) +## When layers overlap -(Character-name matching, `subtitleStyle.nameMatchEnabled`, is toggled through config or the Settings window, not the runtime palette.) +If one word matches several layers, the first match in this list sets its color: -A toggle takes effect on the next subtitle line. SubMiner does not re-tokenize the line already on screen. +1. Character name (also removes N+1, frequency, and JLPT marks) +2. N+1 target +3. Known word +4. Frequency -## Rendering priority - -When multiple annotations apply to the same token, the visual priority is: - -1. **Character-name match** (highest) - dictionary-driven character-name token styling; it clears the token's N+1, frequency, and JLPT annotations -2. **N+1 target** - the single unknown word in an N+1 sentence -3. **Known-word color** - already-learned token tint (per-tier maturity colors when `maturityEnabled` is on) -4. **Frequency highlight** - common-word coloring (not applied when a higher layer already matched) -5. **JLPT underline** - level-based underline (stacks with N+1/known/frequency since it uses underline rather than text color, but not with a character-name match) +JLPT is an underline, so it shows alongside any of these except a character name. diff --git a/docs-site/subtitle-generation.md b/docs-site/subtitle-generation.md index 7f71a66b..0c2da357 100644 --- a/docs-site/subtitle-generation.md +++ b/docs-site/subtitle-generation.md @@ -1,80 +1,85 @@ # Japanese subtitle generation -Generate Japanese SRT subtitles from a local video's audio using [whisper.cpp](https://github.com/ggml-org/whisper.cpp). The launcher and overlay use the same local generation service. Audio stays on your computer. Model downloads require an internet connection; generation with an installed model does not. +When a video has no Japanese subtitles, SubMiner can transcribe its audio into a Japanese SRT with [whisper.cpp](https://github.com/ggml-org/whisper.cpp). Everything runs on your computer. You only need internet access to download a model. ## Setup -Install whisper.cpp's `whisper-cli` executable and FFmpeg, including `ffprobe`. SubMiner downloads models, not these executables. Leave `whisperPath`, `ffmpegPath`, and `ffprobePath` empty to find the executables on `PATH`. To use a specific installation, set a path override under **Settings → Integrations → Japanese Subtitle Generation**. +1. Install whisper.cpp's `whisper-cli` and FFmpeg (including `ffprobe`). SubMiner downloads models but not these programs. +2. Make sure they are on your `PATH`, or set their paths under **Settings > Integrations > Japanese Subtitle Generation** (`whisperPath`, `ffmpegPath`, `ffprobePath`). +3. Pick a model. Either choose one in the generation modal and click **Download model**, or set `subtitleGeneration.modelPath` to a multilingual whisper.cpp GGML `.bin` file you already have. English-only models and Python Whisper checkpoints do not work. -The generation modal checks for these executables under **Local tools** and keeps **Generate subtitles** disabled until every required one is found, naming the missing executable and its setting. Model downloads stay available in the meantime. After installing a tool or changing a path, click **Check again**. The launcher runs the same check before any model download. Generation also confirms the destination directory grants write and search permissions before extracting audio. +Downloaded models go to `models/whisper/` next to your SubMiner config file. A configured `modelPath` always wins over the modal's choice. -Choose one model source: +The modal's **Local tools** section lists anything missing. After you install a tool or change a path, click **Check again**. -- Set `subtitleGeneration.modelPath` to an existing **multilingual whisper.cpp GGML `.bin` model**. Python Whisper checkpoints and English-only models are not suitable for Japanese transcription. -- Leave that path empty and choose a model directly in the generation modal. Each option shows its download size; the selected model has speed and accuracy guidance. The modal offers **Download model** when that model is missing. Your choice lasts for the current SubMiner session, including closing and reopening the modal. Set `subtitleGeneration.managedModel` in Settings to change the default for future sessions. +## Generating from the overlay -Managed models are stored in `models/whisper/` beside your SubMiner configuration file. Downloads show progress, verify the expected file size and SHA256, and publish the model only after verification. Cancelling or failing a download removes its temporary files. A configured external path always takes precedence; an unreadable path displays an error instead of silently downloading another model. +1. Open a local video in mpv and select its Japanese audio track. +2. Press `Ctrl+Shift+G`. If the subtitle sidebar is empty, its **Generate Japanese subtitles** button opens the same modal. +3. Pick a model and download it if needed. +4. Optionally check **Focus on spoken dialogue** (see below). +5. Click **Generate subtitles**. -See the [generated configuration example](/config.example.jsonc) for current defaults. Changes apply to the next operation. +The modal shows progress. **Cancel** stops the job. Closing the modal lets the job keep running, and reopening it shows the progress. -## Prioritizing spoken dialogue +SubMiner saves `<video>.ja.generated.srt` next to the video and adds a number if that name is taken. If the same file is still playing, it loads the subtitles and resets the subtitle delay. -To focus on dialogue, check the optional **Focus on spoken dialogue** box in the generation modal. If the speech detection model is missing, click **Download speech detection model** to install it. This separate download uses the same progress, cancellation, and integrity checks as Whisper downloads. Checking the box never downloads automatically, and leaving it unchecked lets you generate without the Silero model. +Change the shortcut with `shortcuts.openSubtitleGeneration`. -You also need whisper.cpp's [speech segment detector](https://github.com/ggml-org/whisper.cpp/tree/master/examples/vad-speech-segments). SubMiner downloads the model, not this executable. The detector is found as `whisper-vad-speech-segments` or, for builds from the upstream source, `vad-speech-segments` on `PATH`. Set `vadPath` in **Settings → Integrations → Japanese Subtitle Generation** for any other location. With **Focus on spoken dialogue** checked, the modal's **Local tools** check requires the detector too. +## Generating from the launcher -The checkbox choice lasts for the current SubMiner session, including closing and reopening the modal. To make dialogue mode your default, set `vadModelPath` in Settings to a [Silero GGML VAD model](https://huggingface.co/ggml-org/whisper-vad/tree/main). The modal downloads `ggml-silero-v6.2.0.bin` into the same `models/whisper/` directory as managed Whisper models. An existing configured VAD path takes precedence and checks the box initially. Unchecking it temporarily disables dialogue mode without changing that path. Downloading the model alone does not enable dialogue mode. +```bash +subminer generate-subs # current mpv file and audio track +subminer generate-subs episode.mkv --download-model +subminer generate-subs episode.mkv --model-path /path/to/ggml-small.bin +``` -With speech detection configured, SubMiner keeps detected speech and other audible sections for Whisper to evaluate. A low speech score alone does not discard audio, which helps retain dialogue mixed with music. Only confidently silent gaps outside detected speech are omitted, with extra audio retained around each passage to reduce clipped syllables. +| Flag | What it does | +| ------------------------ | ------------------------------------------------------------- | +| `--model <name>` | Use this managed model, such as `small` or `large-v3-turbo` | +| `--download-model` | Download the managed model if it is missing | +| `--model-path <path>` | Use an existing model file | +| `--audio-stream <index>` | Pick an audio stream by its absolute FFmpeg index | +| `--output <path>` | Write to this SRT path. Existing files are never overwritten. | -Passages that fit within Whisper's 30-second audio window stay intact. Longer passages prefer nearby detected speech starts when choosing cuts, falling back to quiet pauses, with a small overlap to provide context. This reduces early subtitles caused by starting a clip well before its dialogue, while keeping all retained audio covered. Matching overlapping cues are combined even when punctuation differs; repeated dialogue at separate times remains separate. SubMiner runs each passage in a fresh Whisper process so decoder state from earlier audio cannot affect later passages. This reloads the model for each passage and can increase generation time. Subtitle cues stay within the supplied audio and retain each passage's position on the original timeline. Progress reports the current passage. - -This mode favors retaining dialogue over excluding music, so songs and background sounds may also produce subtitles. It can take longer than transcribing only VAD-approved speech. Whisper can still miss or misrecognize dialogue, and its timestamps remain estimates. Uncheck **Focus on spoken dialogue** to disable VAD for the session, or clear `vadModelPath` to change the default. Without a usable subtitle reference, disabling VAD returns to full-audio transcription. A selected detector or model that fails stops generation with an error. Existing subtitles are preserved. - -## Using loaded subtitles as timing references - -When generating for the video currently open in mpv, SubMiner automatically looks for a dialogue subtitle track among its embedded subtitles and loaded external SRT, ASS/SSA, or WebVTT files. It prefers English, then tracks labeled full or dialogue. Forced tracks, image subtitles, generated subtitles, and tracks whose titles or filenames identify signs, songs, lyrics, karaoke, or opening/ending subtitles are skipped. These checks rely on metadata; an unlabeled signs-only file cannot always be identified. - -The selected reference appears in generation progress. SubMiner reads its timestamps, including the active primary or secondary track's subtitle delay, and uses nearby cue starts to guide cuts in long audio passages. Short passages stay intact. The reference works with or without **Focus on spoken dialogue**. With that option enabled, reference starts take priority over VAD starts when choosing a nearby cut; VAD still helps identify speech. Audio outside reference cues remains eligible for transcription, and Whisper still supplies the Japanese text and final timestamps. The reference is assumed to be timed for the playing video; this does not automatically sync a mistimed reference. - -Unreadable or empty references are skipped in favor of another eligible loaded track. If none can be read, generation uses its normal audio timing. The launcher uses loaded references only when its input matches the video currently open in mpv; standalone generation keeps its existing behavior. It captures reference tracks and delays together with the initial audio selection, before checking or downloading a model. When relying on mpv's selected audio, it stops and asks you to retry if the media changes or cannot be verified during capture. +With a file argument, SubMiner uses the audio stream tagged Japanese, or the first stream. `Ctrl+C` cancels. ## Choosing a model -The modal recommends **large-v3-turbo** when it detects an NVIDIA GPU through `nvidia-smi` and the selected `whisper-cli` discovers an available CUDA device. Otherwise it recommends **small** for a balance of Japanese recognition quality and CPU time. The check works before downloading a model and falls back to small if a tool is missing, fails, times out, or reports an unrecognized result. Vulkan, AMD, and Apple GPU support do not qualify for the turbo recommendation. Checks are cached for up to 30 seconds; changing the Whisper executable path triggers a new check. +The modal recommends **large-v3-turbo** if it finds an NVIDIA GPU (`nvidia-smi`) and your `whisper-cli` can use CUDA. Otherwise it recommends **small**. AMD, Vulkan, and Apple GPUs do not trigger the turbo recommendation. The recommendation does not change your settings. -The recommendation labels the model picker and explains the detected support. It does not change your configured model, current selection, external model path, or launcher's model choice. It also does not force a GPU backend during transcription. These are starting recommendations, not hardware benchmarks or guarantees that every model fits in available GPU memory. Tiny and base need less memory and usually finish sooner, with more recognition errors. Medium and large models favor accuracy but need more resources. Large-v3-turbo is optimized for speed compared with large-v3, with some accuracy tradeoff; actual performance depends on your CPU, GPU, whisper.cpp build, and audio. +| Model | Tradeoff | +| ---------------------- | ----------------------------------------------- | +| tiny, base | Fast and small, more recognition errors | +| small | Balanced quality and CPU time | +| medium, large-v1/v2/v3 | More accurate, needs more memory and time | +| large-v3-turbo | Faster than large-v3 with a small accuracy loss | -The picker includes whisper.cpp's official multilingual tiny, base, small, medium, large-v1, large-v2, large-v3, and large-v3-turbo downloads, including their available quantized variants. Quantized models use less disk space and memory, with possible accuracy loss. English-only `.en` models are excluded. See the [upstream model list](https://github.com/ggml-org/whisper.cpp/blob/master/models/download-ggml-model.sh) and [Whisper's model guidance](https://github.com/openai/whisper#available-models-and-languages). +Quantized variants (`-q5_0`, `-q5_1`, `-q8_0`) use less disk and memory, with some accuracy loss. Your pick in the modal lasts for the session. Set `subtitleGeneration.managedModel` to change the default. -A configured external Model Path takes precedence and hides the managed model picker. Clear it in Settings to choose a managed model. Changing the picker never downloads automatically, and it cannot change the model during an active download or generation. +## Prioritizing spoken dialogue -## From the overlay +**Focus on spoken dialogue** uses a speech detection (VAD) model to drop silent stretches before transcription. Long passages are split near detected speech, which reduces subtitles that appear before the line is spoken. -1. Open a local video in mpv and select its Japanese audio track. -2. Press **Ctrl+Shift+G** to open the standalone generation modal. When the subtitle sidebar has no subtitle lines loaded, it also offers a **Generate Japanese subtitles** button. Neither an open sidebar nor an existing subtitle track is required for the shortcut. -3. Choose a model and download it if prompted, or configure your existing model path in Settings and click **Check again**. -4. Optionally check **Focus on spoken dialogue** and click **Download speech detection model** if prompted. -5. Click **Generate subtitles**. +It needs two extra pieces: -The modal adapts to the player window, using a wider layout when space allows and scrolling in smaller windows. It shows audio preparation, transcription, and saving progress. Percentages appear when the underlying tool reports them. **Cancel** stops the current operation. Closing the modal lets the job continue; reopening it shows the current progress or result. +- The Silero VAD model. Click **Download speech detection model** in the modal, or set `vadModelPath` to your own [Silero GGML model](https://huggingface.co/ggml-org/whisper-vad/tree/main). +- whisper.cpp's [speech segment detector](https://github.com/ggml-org/whisper.cpp/tree/master/examples/vad-speech-segments), found as `whisper-vad-speech-segments` or `vad-speech-segments` on `PATH`. Set `vadPath` for any other location. -**Escape** or **Close** closes the modal using the same focus and overlay restoration as other SubMiner modals. Change or disable its shortcut with `shortcuts.openSubtitleGeneration` in Settings. Ctrl+G remains assigned to field grouping. +The checkbox lasts for the session. Setting `vadModelPath` turns it on by default. -SubMiner saves `<video>.ja.generated.srt` beside the media, adding a numeric suffix if that name already exists. It selects the generated Japanese subtitle track and resets the subtitle delay when mpv is still playing the same file. If playback changes, the subtitles remain saved and are not attached to the new video. The result includes the saved path even if mpv cannot load it. +Dialogue mode keeps music and background sound that might contain speech, so songs can still produce subtitles. It can also take longer than a plain run, because each passage is transcribed separately. -## From the launcher +## Using loaded subtitles as timing references -```bash -subminer generate-subs episode.mkv --download-model -subminer generate-subs episode.mkv --model-path /path/to/ggml-small.bin -subminer generate-subs -``` +If the video playing in mpv already has a dialogue subtitle track loaded, SubMiner uses its cue times to decide where to split long audio. This works with or without dialogue mode. Whisper still writes the Japanese text and final timestamps. The launcher uses a reference only when its input is the file open in mpv. -With no file argument, the command uses the current local mpv media and its selected audio track. With an explicit file, it prefers an audio stream tagged Japanese, otherwise the first audio stream. Use `--audio-stream` to choose an absolute FFmpeg stream index. `--output` specifies a new destination SRT; existing output files are never overwritten. See [launcher usage](/usage) for all flags. Ctrl+C cancels the operation. +SubMiner prefers English tracks and tracks labeled full or dialogue. It skips forced, image-based, generated, and signs or songs tracks, based on their titles and file names. An unlabeled signs-only file can slip through. -## Timing and limitations +The reference must be timed correctly for the video. SubMiner does not fix a mistimed reference. -The SRT includes whisper.cpp's timestamps, adjusted for the audio stream's position on the media timeline and, when speech detection is configured, each passage's original start time. No alass step is required to load it. This version uses native Whisper timing; it does not run WhisperX or another forced aligner. Recognition can repeat or invent lines, and timing can be imperfect, especially with music or overlapping speech. Review generated text and audio boundaries when mining. +## Limitations -Generation supports local files and internal audio tracks. Remote URLs, subtitle translation, and transcription of a separately attached mpv audio track are not supported by the modal. Pass a separate local audio file to the launcher if needed. The destination directory needs writable space for subtitles; temporary storage needs enough space for the extracted mono audio. +- Only local files and their internal audio tracks are supported. Not URLs, and not a separate audio file loaded in mpv. Pass a separate local audio file to the launcher instead. +- Whisper can miss, repeat, or invent lines, and its timing is approximate, especially over music or overlapping speech. Check the text and audio when you mine. +- SubMiner does not translate subtitles. diff --git a/docs-site/subtitle-sidebar.md b/docs-site/subtitle-sidebar.md index 4209de90..647b9962 100644 --- a/docs-site/subtitle-sidebar.md +++ b/docs-site/subtitle-sidebar.md @@ -1,98 +1,70 @@ # Subtitle sidebar -The subtitle sidebar puts the whole parsed cue list for the active subtitle file in a scrollable panel next to mpv. Scroll back through lines you already passed, look ahead at what is coming, and click any cue to seek straight to it. The overlay only ever shows the current line; the sidebar shows the rest. +The subtitle sidebar lists every line of the current subtitle file in a scrollable panel next to mpv. Use it to reread lines you missed, look ahead, jump to any line, or copy a stretch of dialogue. -The sidebar is enabled by default. Set `subtitleSidebar.enabled` to `false` if you want to turn it off. +## Using the sidebar -## How it works +Press `\` to open or close it. The sidebar is on by default. Set `subtitleSidebar.enabled` to `false` to turn it off, or `subtitleSidebar.autoOpen` to `true` to open it at startup. -When the sidebar has no subtitle lines loaded, the **Generate Japanese subtitles** button opens [local subtitle generation](/subtitle-generation). The button hides once subtitle lines are loaded and stays hidden between lines. Press **Ctrl+Shift+G** to open generation at any time. +- Click a line to seek to it. With a line focused from the keyboard, `Enter` seeks to it. +- The current line is highlighted and kept in view as playback moves (`autoScroll`). +- Hovering the list pauses playback (`pauseVideoOnHover`). +- Switching media or subtitle track updates the list. -When SubMiner parses the active subtitle source into a cue list, the sidebar becomes available. Toggle it with the `\` key (configurable via `subtitleSidebar.toggleKey`). While open: +The sidebar needs a subtitle file SubMiner can parse. Tracks that mpv renders itself, such as embedded ASS tracks, leave it empty. With no lines loaded, the sidebar shows a **Generate Japanese subtitles** button that opens [subtitle generation](/subtitle-generation). You can also open generation any time with `Ctrl+Shift+G`. -- The active cue is highlighted and kept in view as playback advances (when `autoScroll` is `true`). -- Between subtitle lines, the sidebar follows playback to the next cue without jumping back to a cue at the start of the file. -- Clicking any cue seeks mpv into that line. For overlapping ASS karaoke, SubMiner moves past the previous line's exit animation when the selected cue has enough time remaining. -- Clicking to seek releases row focus. `Enter` seeks a keyboard-focused cue; `Space` keeps its configured playback action, normally pause/resume, without seeking back to a row. -- The sidebar and the overlay share one cue list, so a media change or subtitle source switch updates both at once. +For karaoke and animated ASS subtitles, SubMiner merges the per-frame effect lines into one clean line per cue. -For typeset ASS karaoke and animated signs, SubMiner collapses generated animation frames and repeated full-line color phases before they reach the sidebar. It recovers a clean complete line from a matching timed authoring comment or from full-line events surrounding generated fragments. Ordinary ASS comments, editor notes, alternate lines, repeated dialogue, and separately positioned signs remain distinct. +## Copying dialogue {#selecting-and-copying-dialogue} -The sidebar only opens when a parsed cue list exists. Subtitle sources SubMiner cannot parse, such as embedded ASS tracks that mpv renders itself, leave it empty. +1. Drag across the text to select it. The selection can span several lines, and you can scroll to extend it. +2. Press `Ctrl/Cmd+C` or click **Copy**. -## Selecting and copying dialogue +SubMiner copies the text in subtitle order, without timestamps, with a blank line between cues. Dragging does not seek, and auto-scroll pauses while you have a selection. Press `Escape` to clear it. Changing media or subtitle track, or closing the sidebar, also clears it. -Drag across subtitle text to select an excerpt, including across multiple rows. Scroll to extend a selection through a longer conversation. `Ctrl/Cmd+C` or the **Copy** button copies the highlighted text in subtitle order, without timestamps. Partial first and last lines are preserved, with a blank line between subtitle cues. +## Layout -Dragging to select does not seek playback. Playback-following auto-scroll stops while you drag or have a selection, so the excerpt stays in view. Press `Escape` to clear the selection. An ordinary click with no selection still seeks to that cue. +`subtitleSidebar.layout` has two modes: -Selection survives playback updates and Yomitan popup dismissal. Changing media or subtitle sources, refreshing the cue list, or closing the sidebar clears it. Copying an excerpt does not require creating an Anki card. - -## Layout modes - -Two layout modes are available via `subtitleSidebar.layout`: - -**`overlay`** (default) - The sidebar floats over mpv as a panel. It does not affect the player window size or position. - -**`embedded`** - Reserves space on the right side of the player and shifts the video area over, giving you a split pane. Use this when you want the cue list up without it covering the video. Positioning depends on the compositor, so switch back to `overlay` if the geometry comes out wrong. +- `overlay`: the sidebar floats over mpv and does not change the player window. +- `embedded`: reserves space on the right of the player and moves the video over, so the list doesn't cover it. Placement depends on your compositor. If the geometry comes out wrong, switch back to `overlay`. ## Configuration -Enable and configure the sidebar under `subtitleSidebar` in your config file: +All keys live under `subtitleSidebar`. Defaults are in the [configuration reference](/configuration). -```json +| Key | What it does | +| ------------------- | --------------------------------------------------------------- | +| `enabled` | Turn the sidebar on or off | +| `autoOpen` | Open the sidebar when the overlay starts | +| `layout` | `overlay` or `embedded` | +| `toggleKey` | Toggle key, as a `KeyboardEvent.code` value such as `Backslash` | +| `pauseVideoOnHover` | Pause playback while the pointer is over the list | +| `autoScroll` | Keep the current line in view | +| `css` | Styling, see below | + +`css` takes CSS properties (`font-family`, `font-size`, `color`, `background-color`, `opacity`) and these custom properties: + +| Property | Styles | +| -------------------------------------------- | ------------------------------ | +| `--subtitle-sidebar-max-width` | Maximum sidebar width | +| `--subtitle-sidebar-timestamp-color` | Timestamp text | +| `--subtitle-sidebar-active-line-color` | Current line text | +| `--subtitle-sidebar-active-background-color` | Current line background | +| `--subtitle-sidebar-hover-background-color` | Background of the hovered line | + +```jsonc { "subtitleSidebar": { - "enabled": true, - "autoOpen": false, - "layout": "overlay", - "toggleKey": "Backslash", - "pauseVideoOnHover": true, - "autoScroll": true, + "layout": "embedded", "css": { - "font-family": "Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP", - "color": "#cad3f5", - "background-color": "rgba(73, 77, 100, 0.9)", - "font-size": "16px", - "opacity": "0.95", - "--subtitle-sidebar-max-width": "420px", - "--subtitle-sidebar-timestamp-color": "#a5adcb", - "--subtitle-sidebar-active-line-color": "#f5bde6", - "--subtitle-sidebar-active-background-color": "rgba(138, 173, 244, 0.22)", - "--subtitle-sidebar-hover-background-color": "rgba(54, 58, 79, 0.84)" - } - } + "font-size": "18px", + "--subtitle-sidebar-max-width": "480px", + }, + }, } ``` -Styling lives under the `css` object, using CSS property names and CSS custom properties (the same pattern as `subtitleStyle.css`). +Your `css` object replaces the default one as a whole. To keep a default value, copy it from the configuration reference into your object. -| Option | Type | Default | Description | -| ------------------- | ------- | ------------- | -------------------------------------------------------------------------- | -| `enabled` | boolean | `true` | Enable subtitle sidebar support | -| `autoOpen` | boolean | `false` | Open the sidebar automatically on overlay startup | -| `layout` | string | `"overlay"` | `"overlay"` floats over mpv; `"embedded"` reserves right-side player space | -| `toggleKey` | string | `"Backslash"` | `KeyboardEvent.code` for the toggle shortcut | -| `pauseVideoOnHover` | boolean | `true` | Pause playback while hovering the cue list | -| `autoScroll` | boolean | `true` | Keep the active cue in view during playback | - -| `css` property | Default | Description | -| ------------------------------------------- | --------------------------- | ---------------------------- | -| `font-family` | `Hiragino Sans, M PLUS 1, Source Han Sans JP, Noto Sans CJK JP` | Cue text font family | -| `color` | `#cad3f5` | Default cue text color | -| `background-color` | `rgba(73, 77, 100, 0.9)` | Sidebar shell background color | -| `font-size` | `16px` | Base cue font size | -| `opacity` | `0.95` | Sidebar opacity between `0` and `1` | -| `--subtitle-sidebar-max-width` | `420px` | Maximum sidebar width | -| `--subtitle-sidebar-timestamp-color` | `#a5adcb` | Cue timestamp color | -| `--subtitle-sidebar-active-line-color` | `#f5bde6` | Active cue text color | -| `--subtitle-sidebar-active-background-color`| `rgba(138, 173, 244, 0.22)` | Active cue background color | -| `--subtitle-sidebar-hover-background-color` | `rgba(54, 58, 79, 0.84)` | Hovered cue background color | - -## Keyboard shortcut - -| Key | Action | Config key | -| --- | ----------------------- | ------------------------------ | -| `\` | Toggle subtitle sidebar | `subtitleSidebar.toggleKey` | - -The toggle is overlay-local and only opens when SubMiner has a parsed cue list for the active subtitle source. See [Keyboard Shortcuts](/shortcuts) for the full shortcut reference. +See [keyboard shortcuts](/shortcuts) for all overlay keys. diff --git a/docs-site/troubleshooting.md b/docs-site/troubleshooting.md index f36f642c..34b6f857 100644 --- a/docs-site/troubleshooting.md +++ b/docs-site/troubleshooting.md @@ -1,355 +1,195 @@ # Troubleshooting -Almost everything that goes wrong lands in one of three places. The overlay shows but no subtitles arrive, which is [MPV Connection](#mpv-connection). Cards get created but come out empty, which is [AnkiConnect](#ankiconnect). Or hovering a word does nothing, which is [Yomitan](#yomitan). +Find your symptom below. If you saw an error message, search this page for its text. -If you got an error message on screen, search this page for its exact text. Most headings below are quoted error strings. +## Diagnose first -## MPV connection - -**Overlay starts but shows no subtitles** - -SubMiner connects to mpv via a Unix socket (or named pipe on Windows). If the socket does not exist or the path does not match, the overlay will appear but subtitles will never arrive. - -- Check that mpv is running with `--input-ipc-server=/tmp/subminer-socket`. -- If you use a custom socket path, set it in both your mpv config and SubMiner config (`mpv.socketPath`). -- The `subminer` wrapper script sets the socket automatically when it launches mpv. If you launch mpv yourself, the `--input-ipc-server` flag is required. - -SubMiner retries the connection automatically with increasing delays (200 ms, 500 ms, 1 s, 2 s on first connect; 1 s, 2 s, 5 s, 10 s on reconnect). If mpv exits and restarts, the overlay reconnects without needing a restart. - -If the overlay never appears at all, see [Playback Startup Flow](./architecture#playback-startup-flow) for how a managed launch starts mpv and brings up the overlay. - -**"Failed to parse MPV message"** - -A malformed JSON line arrived from the mpv socket. SubMiner drops the line and keeps going, so a stray one is harmless. A constant stream of them means something else is writing to the same socket path. - -## Updates - -**"Update check failed"** - -Manual update checks show this when GitHub Releases or updater metadata cannot be reached. Check your network connection, then try again from the tray menu or: +Run the launcher's dependency check: ```bash -subminer -u +subminer doctor ``` -Automatic checks log failures quietly so playback is not interrupted. +It reports the app binary, `mpv`, `yt-dlp`, `ffmpeg`, `fzf`, `rofi`, your config file, and the mpv socket path. It exits non-zero when the app binary or `mpv` is missing. -**"SubMiner is up to date" but a prerelease exists** +Logs are written to daily files: -SubMiner uses the configured release channel for update checks. Set `updates.channel` to `"prerelease"` in `config.jsonc` when you want update checks to include beta and RC releases. +| Platform | Log directory | +| ------------- | -------------------------- | +| Linux / macOS | `~/.config/SubMiner/logs/` | +| Windows | `%APPDATA%\SubMiner\logs\` | -**Launcher update shows a sudo command** +Files are named `app-<date>.log`, `launcher-<date>.log`, and `mpv-<date>.log`. The mpv log is off by default. Turn log files on or off and set retention under [`logging`](/configuration#logging). -The detected launcher is installed in a protected path such as `/usr/local/bin/subminer` or `/usr/bin/subminer`. SubMiner does not elevate itself. Run the command shown in the popup to replace the launcher after checksum verification. +For more detail, raise the log level for one run: -**OSD update notification did not appear** +```bash +subminer --log-level debug video.mkv +SubMiner.AppImage --start --log-level debug +``` -`updates.notificationType: "osd"` uses the legacy mpv OSD path. If mpv is disconnected, SubMiner logs the update and does not force-start the overlay. Use `"system"` for OS notifications, `"both"` for overlay + OS notifications, or `"osd-system"` in `config.jsonc` if you want the legacy OSD + OS combination. +The default level is `warn`. `--dev` and `--debug` switch the app into dev mode but do not change log verbosity. To inspect the overlay itself, focus it and press `y` then `d` to open DevTools. -## AnkiConnect +## Overlay starts but shows no subtitles -**"AnkiConnect: unable to connect"** +SubMiner reads subtitles from mpv over an IPC socket (a named pipe on Windows). If the paths do not match, the overlay appears but stays empty. -First confirm you've completed the [Anki Integration prerequisites](/anki-integration#prerequisites) - Anki must be running with the AnkiConnect add-on installed. +- The `subminer` launcher sets the socket for you. If you start mpv yourself, pass `--input-ipc-server=/tmp/subminer-socket`. +- If you changed `mpv.socketPath`, use the same path in your mpv config. -SubMiner connects to the active Anki endpoint: +SubMiner reconnects on its own if mpv restarts. -- `ankiConnect.url` (direct mode, default `http://127.0.0.1:8765`) -- `http://<ankiConnect.proxy.host>:<ankiConnect.proxy.port>` (proxy mode) +## Overlay does not appear -This error means the active endpoint is unavailable, or (in proxy mode) the proxy cannot reach `ankiConnect.proxy.upstreamUrl`. +- Confirm SubMiner is running (`SubMiner.AppImage --start`, or check for the process). +- Linux: Hyprland and Sway work natively. Any other compositor needs mpv and SubMiner under X11 or Xwayland, with `xdotool`, `xprop`, and `xwininfo` installed. See [KDE Plasma and other Wayland compositors](#kde-plasma-and-other-wayland-compositors). +- macOS: grant Accessibility permission in System Settings > Privacy & Security > Accessibility. -- If you changed the AnkiConnect port, update `ankiConnect.url` (or `ankiConnect.proxy.upstreamUrl` if using proxy mode). -- If using external Yomitan/browser clients, confirm they point to your SubMiner proxy URL. +## Overlay is on the wrong monitor or position -SubMiner retries with exponential backoff (up to 5 s) and suppresses repeated error logs after 5 consecutive failures. When Anki comes back, you will see "AnkiConnect connection restored". +SubMiner follows the mpv window. Tracking needs `hyprctl` (Hyprland), `swaymsg` (Sway), or `xdotool` and `xwininfo` (X11) on `PATH`. -**Cards are created but fields are empty** +If the position is only slightly off, right-click and drag the subtitle text to adjust the offset. -Field names in your config must name a field that exists on your Anki note type. Matching is case-insensitive (`sentenceaudio` finds `SentenceAudio`), but the spelling must otherwise match, and unknown fields are skipped silently. Check `ankiConnect.fields` - for example, if your note type uses `SentenceAudio` but your config says `Audio`, the field will not be populated. +## Clicks pass through the overlay -See [Anki Integration](/anki-integration) for the full field mapping reference. +- The overlay only takes input while the cursor is over subtitle text. Hover the text directly. +- Toggle the overlay off and on with `Alt+Shift+O`. +- Linux: if clicks keep failing, toggle the overlay off, click the mpv window, then toggle it back on. -**"Update failed" OSD message** +## Hovering a word shows no popup -Shown when SubMiner tries to update a card that no longer exists, or when AnkiConnect rejects the update. Common causes: +If you have not set up dictionaries yet, start with [Yomitan setup](/usage#yomitan-setup). -- The card was deleted in Anki between creation and enrichment update. -- The note type changed and a mapped field no longer exists. +- Open Yomitan settings (`Alt+Shift+Y` or `SubMiner.AppImage --yomitan`) and confirm at least one dictionary is imported and enabled. +- If `yomitan.externalProfilePath` is set, manage dictionaries in that external profile. SubMiner opens it read-only and has no settings window of its own in that mode. +- Check the log for "Loaded Yomitan extension". -## Overlay +Word boundaries come from Yomitan's parser. Some splits will be wrong, since Japanese has no spaces. -**Overlay does not appear** +## "Yomitan extension not found in any search path" -- Confirm SubMiner is running: `SubMiner.AppImage --start` or check for the process. -- On Linux, the overlay requires a supported window backend. Hyprland and Sway have native Wayland support; all other compositors require both mpv and SubMiner to run under X11 or Xwayland (`xdotool`, `xprop`, and `xwininfo` must be installed). -- On macOS, grant Accessibility permission to SubMiner in System Settings > Privacy & Security > Accessibility. +The bundled Yomitan is missing. Re-download the AppImage, or place an unpacked Yomitan extension in `~/.config/SubMiner/yomitan`. Source builds must run `bun run build` first to produce `build/yomitan`. -**Overlay appears but clicks pass through / cannot interact** +## "MeCab not found on system" -- Hover directly over subtitle text. The overlay only takes pointer input while the cursor is over a subtitle. -- On macOS/Windows: toggle the overlay off and back on (`Alt+Shift+O`) to re-enable pointer events. -- On Linux: mouse event handling is unreliable in some Electron/compositor combinations. If clicks consistently fail, toggle the overlay off, click the underlying mpv window, then toggle it back on. +This is informational. Tokenization uses Yomitan, not MeCab. Install MeCab only if you want to silence the message: -**Overlay briefly freezes after a modal/runtime error** +- Arch: `sudo pacman -S mecab mecab-ipadic` +- Ubuntu/Debian: `sudo apt install mecab libmecab-dev mecab-ipadic-utf8` +- macOS: `brew install mecab mecab-ipadic` -- Renderer errors now trigger an automatic recovery path. You should see a short toast ("Renderer error recovered. Overlay is still running."). -- Recovery closes any open modal and restores click-through/shortcuts automatically without interrupting mpv playback. -- If errors keep recurring, toggle the overlay's DevTools using overlay chord `y` then `d` (`F12` also works in dev builds) and inspect the `renderer overlay recovery` error payload for stack trace + modal/subtitle context. +## "AnkiConnect: unable to connect" -**Overlay is on the wrong monitor or position** +Anki must be running with the AnkiConnect add-on. See [Anki integration prerequisites](/anki-integration#prerequisites). -SubMiner positions the overlay by tracking the mpv window. If tracking fails: +- Direct mode: check that `ankiConnect.url` matches the AnkiConnect port. +- Proxy mode: check `ankiConnect.proxy.upstreamUrl`, and point external Yomitan or browser clients at the SubMiner proxy. -- Hyprland: `hyprctl` must be on `PATH`. -- Sway: `swaymsg` must be on `PATH`. -- X11: `xdotool` and `xwininfo` must be installed. +SubMiner keeps retrying and logs "AnkiConnect connection restored" once Anki is back. -If the overlay position is slightly off, right-click and drag on subtitle text to fine-tune the overlay subtitle offset. +## Cards are created but fields are empty -## Yomitan +Each name in `ankiConnect.fields` must match a field on your note type. Matching is case-insensitive, but otherwise the spelling must match. Unknown fields are skipped without an error. For example, config `Audio` does not fill a note field named `SentenceAudio`. See [Anki integration](/anki-integration). -If you haven't set up dictionaries yet, see [Yomitan setup](/usage#yomitan-setup) first. +## "Update failed" when mining -**"Yomitan extension not found in any search path"** +The card was deleted in Anki before SubMiner finished enriching it, or the note type changed and a mapped field no longer exists. -SubMiner bundles Yomitan and searches for it in these locations (in order): +## "Subtitle timing not found; copy again while playing" -1. `build/yomitan` (local/source build output) -2. `<resources>/yomitan` (Electron resources path) -3. `/usr/share/SubMiner/yomitan` -4. `~/.config/SubMiner/yomitan` (user-data fallback on Linux) +SubMiner has no timing for the current line yet. This happens when paused before any subtitle arrived, after switching subtitle tracks, or while an external subtitle file is still loading. Resume playback, wait for the next line, and mine again. -SubMiner does not load the source tree directly from `vendor/subminer-yomitan`; source builds must produce `build/yomitan` first. +## "FFmpeg not found" -If you installed from the AppImage and see this error, the package may be incomplete. Re-download the AppImage or place the unpacked Yomitan extension manually in `~/.config/SubMiner/yomitan`. +Audio clips and screenshots need FFmpeg. Without it, cards are still created with empty media fields. -**Yomitan lookup popup does not appear when hovering words or triggering lookup** +- Arch: `sudo pacman -S ffmpeg` +- Ubuntu/Debian: `sudo apt install ffmpeg` +- macOS: `brew install ffmpeg` -- Look for "Loaded Yomitan extension" in the terminal output. -- Yomitan requires dictionaries to be installed. Open Yomitan settings (`Alt+Shift+Y` or `SubMiner.AppImage --yomitan`) and confirm at least one dictionary is imported. -- If `yomitan.externalProfilePath` is set, import/check dictionaries in the external app/profile instead. SubMiner treats that profile as read-only and does not open its own Yomitan settings window. -- If the overlay shows subtitles but hover lookup never resolves on tokens, the tokenizer may have failed. See the MeCab section below. +## Audio or screenshot generation is slow or times out -## MeCab / tokenization - -**"MeCab not found on system"** - -This is informational, not an error. SubMiner tokenization is driven by Yomitan's internal parser. MeCab availability checks may still run for auxiliary token metadata, but MeCab is not used as a tokenization fallback path. - -To install MeCab: - -- **Arch Linux**: `sudo pacman -S mecab mecab-ipadic` -- **Ubuntu/Debian**: `sudo apt install mecab libmecab-dev mecab-ipadic-utf8` -- **macOS**: `brew install mecab mecab-ipadic` - -**Words are not segmented correctly** - -Japanese word boundaries depend on Yomitan parser output. If segmentation seems wrong: - -- Check that Yomitan dictionaries are installed and active. -- Japanese text has no spaces, so the parser guesses word boundaries. It gets some of them wrong. - -## Character dictionary - -Character names from AniList are matched and highlighted in subtitles via the bundled Yomitan. See [Character Dictionary](/character-dictionary) for setup and the full troubleshooting list - the most common issues: - -- **Names not highlighting:** Check that `subtitleStyle.nameMatchEnabled` is `true` and that the current media resolved to an AniList entry, since SubMiner needs a media ID to fetch characters. No AniList account or token is needed; character data comes from public GraphQL queries. -- **Inline portraits missing:** Check that `subtitleStyle.nameMatchImagesEnabled` is `true`. AniList also has to return an image, and the download has to succeed while the snapshot is generated. -- **Wrong characters showing:** Open the in-app manager (`Ctrl/Cmd+D`) and use **Override** to pin the correct AniList match for the series. -- **Feature unavailable:** If `yomitan.externalProfilePath` is set, SubMiner runs in read-only external-profile mode and its character-dictionary features are disabled. - -## Media generation - -**"FFmpeg not found"** - -SubMiner uses FFmpeg to extract audio clips and generate screenshots. Install it: - -- **Arch Linux**: `sudo pacman -S ffmpeg` -- **Ubuntu/Debian**: `sudo apt install ffmpeg` -- **macOS**: `brew install ffmpeg` - -Without FFmpeg, card creation still works but audio and image fields will be empty. - -**Audio or screenshot generation hangs** - -Audio extraction has a 2-minute timeout. SubMiner also limits FFmpeg probing when mpv provides the selected audio stream, which avoids scanning unrelated subtitle and font-attachment streams in large MKV files. Screenshots retain a 30-second timeout, and animated AVIF uses 60 seconds. - -If your video file is on a slow or unresponsive network mount, generation may still time out. Try: - -- Using a local copy of the video file. -- Reducing `ankiConnect.media.imageQuality` or switching from `avif` to `static` image type. -- Checking that `ankiConnect.media.maxMediaDuration` is not set too high. - -## Shortcuts - -**"Failed to register global shortcut"** - -This warning refers to the OS-registered shortcut `Alt+Shift+Y` (Yomitan settings), which is fixed and may conflict with other applications or desktop environment keybindings. - -- Check your DE/WM keybinding settings for conflicts and free up `Alt+Shift+Y` there. -- `Alt+Shift+O` (`shortcuts.toggleVisibleOverlayGlobal`) is not OS-registered - it is handled by the overlay window and the mpv plugin, so it does not trigger this warning and only needs those windows focused. -- On Wayland, global shortcut registration has limitations depending on the compositor. Only Hyprland and Sway are supported natively - see the [Hyprland](#hyprland) section below for shortcut passthrough rules. Other Wayland compositors require X11/Xwayland. - -**Overlay keybindings not working** - -Overlay-local shortcuts (Space, arrow keys, etc.) only work when the overlay window has focus. Click on the overlay or use `Alt+Shift+O` (with the overlay or mpv focused) to toggle it and give it focus. - -## Subtitle timing - -**"Subtitle timing not found; copy again while playing"** - -This OSD message appears when you try to mine a sentence but SubMiner has no timing data for the current subtitle. Causes: - -- The video is paused and no subtitle has been received yet. -- The subtitle track changed and timing data was cleared. -- You are using an external subtitle file that mpv has not fully loaded. - -Resume playback and wait for the next subtitle to appear, then try mining again. +- Use a local copy if the video is on a slow network mount. +- Set `ankiConnect.media.imageType` to `"static"`. Animated AVIF is the slowest path. +- Lower `ankiConnect.media.imageQuality` or `ankiConnect.media.maxMediaDuration`. ## Subtitle sync (subsync) -Both **alass** and **ffsubsync** are optional external dependencies. Subtitle syncing requires at least one of them to be installed. +Subtitle sync needs at least one of alass or ffsubsync. Neither ships with SubMiner. -**"Configured alass executable not found"** +**"Configured alass executable not found"**: install it (`paru -S alass` or `cargo install alass-cli`), or set `subsync.alass_path`. -Install alass or configure the path: +**"Configured ffsubsync executable not found"**: install it (`paru -S python-ffsubsync` or `pip install ffsubsync`), or set `subsync.ffsubsync_path`. -- **Arch Linux (AUR)**: `paru -S alass` -- **Cargo**: `cargo install alass-cli` -- Set the path: `subsync.alass_path` in your config. +**"alass synchronization failed" / "ffsubsync synchronization failed"**: -**"Configured ffsubsync executable not found"** +- alass needs a reference: a second subtitle track or the local video file. It cannot use the track being retimed. +- `ffmpeg` must be installed to extract internal subtitle tracks. +- ffsubsync only works on local files, not streams. +- Run the tool by hand to see its full error output. -Install ffsubsync or configure the path: +## "xz binary not found" -- **Arch Linux (AUR)**: `paru -S python-ffsubsync` -- **pip**: `pip install ffsubsync` -- Must be on `PATH` or configured via `subsync.ffsubsync_path` in your config. +TsukiHime subtitles are xz-compressed. Install `xz`: -**"alass synchronization failed" / "ffsubsync synchronization failed"** +- Arch: `sudo pacman -S xz` +- Ubuntu/Debian: `sudo apt install xz-utils` +- Fedora: `sudo dnf install xz` +- macOS: `brew install xz` +- Windows: `scoop install main/xz`, or download XZ Utils from [tukaani.org/xz](https://tukaani.org/xz/) and add the folder with `xz.exe` to `PATH`. Restart SubMiner afterwards. -If subtitle sync fails (the error message is prefixed with the engine name): - -- Select a reference. alass needs either a second subtitle track or the local video file, and it cannot be the track being retimed. -- Check that `ffmpeg` is available, since it extracts the internal subtitle track. -- Try running the sync tool manually to see detailed error output. -- ffsubsync requires local files and cannot handle remote media streams (e.g., streaming URLs). - -## TsukiHime - -**"xz binary not found"** - -TsukiHime serves extracted subtitles xz-compressed, so SubMiner shells out to `xz` to decompress them. Install it: - -- **Arch Linux**: `sudo pacman -S xz` -- **Ubuntu/Debian**: `sudo apt install xz-utils` -- **Fedora**: `sudo dnf install xz` -- **macOS**: `brew install xz` -- **Windows**: neither winget nor Chocolatey packages `xz`. Use `scoop install main/xz`, or download XZ Utils from [tukaani.org/xz](https://tukaani.org/xz/) and add the folder containing `xz.exe` to your `PATH`. Restart SubMiner afterwards. - -Most Linux distributions ship it already. See [TsukiHime Integration](/tsukihime-integration#troubleshooting) for the other TsukiHime error messages. +Other TsukiHime errors are covered in [TsukiHime integration](/tsukihime-integration#troubleshooting). ## Jimaku -**"Jimaku request failed" or HTTP 429** +**"Jimaku request failed" or HTTP 429**: you hit the Jimaku rate limit. Wait for the time shown in the message. Setting `jimaku.apiKey` or `jimaku.apiKeyCommand` gives you a higher limit. -The Jimaku API has rate limits. If you see 429 errors, wait for the retry duration shown in the OSD message and try again. If you have a Jimaku API key, set it in `jimaku.apiKey` or `jimaku.apiKeyCommand` to get higher rate limits. +## Character names are not highlighted -## Logging and app mode +See [Character dictionary](/character-dictionary) for the full list. The common causes: -- Default log output is `warn`. -- Use `--log-level` for more/less output. -- Use `--dev`/`--debug` only to force app/dev mode (for example to get dev behavior from the overlay/app); they do not change log verbosity. -- You can combine both, for example `SubMiner.AppImage --start --dev --log-level debug`, when you need maximum diagnostics. +- `subtitleStyle.nameMatchEnabled` is off, or the media did not resolve to an AniList entry. +- Portraits need `subtitleStyle.nameMatchImagesEnabled`. +- Wrong characters: open the manager (`Ctrl/Cmd+D`) and use **Override** to pick the right AniList entry. +- The feature is disabled when `yomitan.externalProfilePath` is set. -## Performance and resource impact +## "Failed to register global shortcut" -### Where the cost comes from +Another app or your desktop already uses `Alt+Shift+Y` (Yomitan settings). Free it in your desktop or window manager settings. On Hyprland, add a `pass` rule (see [Hyprland](#hyprland)). -Idle playback with the overlay up is cheap. The spikes come from: +## Overlay shortcuts do nothing -- first subtitle parse/tokenization bursts -- media generation (`ffmpeg` audio/image and AVIF paths) -- media sync and subtitle tooling (`alass`, `ffsubsync`) -- `ankiConnect` enrichment (plus polling overhead when proxy mode is disabled) +Overlay shortcuts only work while the overlay has focus. Click the overlay, or press `Alt+Shift+O` with mpv or the overlay focused. -### If playback feels sluggish +## Update checks -1. Reduce overlay workload: +**"Update check failed"**: GitHub could not be reached. Check your connection and retry from the tray menu or with `subminer -u`. -- set secondary subtitles hidden: - - `secondarySub.defaultMode: "hidden"` -- disable optional enrichment: - - `subtitleStyle.enableJlpt: false` - - `subtitleStyle.frequencyDictionary.enabled: false` +**No prerelease offered**: set `updates.channel` to `"prerelease"` to include beta and RC builds. -2. Reduce rendering pressure: +**Launcher update shows a sudo command**: the launcher lives in a protected path such as `/usr/local/bin`. Run the command shown to replace it. -- lower `subtitleStyle.css["font-size"]` +## Playback feels sluggish -3. Reduce media overhead: +Idle playback is cheap. Load comes from the first tokenization burst, media generation, subtitle sync, and Anki enrichment. To cut it: -- keep `ankiConnect.media.imageType` set to `static`, since animated AVIF encoding is the most expensive path -- lower `ankiConnect.media.imageQuality` -- reduce `ankiConnect.media.maxMediaDuration` +- `ankiConnect.media.imageType: "static"`, plus lower `imageQuality` and `maxMediaDuration`. +- `subtitleStyle.enableJlpt: false` and `subtitleStyle.frequencyDictionary.enabled: false`. +- `secondarySub.defaultMode: "hidden"`. +- `immersionTracking.enabled: false` to stop stats logging. -4. Lower integration cost: +Also check that only one SubMiner instance is running, and whether `ffmpeg`, `yt-dlp`, or a sync tool is the process using CPU. -- set `immersionTracking.enabled: false` to stop session logging and its database writes +## Linux -### Practical low-impact profile +### Tray icon missing -```json -{ - "subtitleStyle": { - "css": { - "font-size": "30px" - }, - "enableJlpt": false, - "frequencyDictionary": { - "enabled": false - } - }, - "secondarySub": { - "defaultMode": "hidden" - }, - "ankiConnect": { - "media": { - "imageType": "static", - "imageQuality": 80, - "maxMediaDuration": 12 - } - }, - "immersionTracking": { - "enabled": false - } -} -``` - -### If usage is still high - -- Confirm only one SubMiner instance is running. -- Check whether bottlenecks are `ffmpeg`, `yt-dlp`, or sync tooling in system monitor. -- Keep the default `warn` level for normal use; raise to `info` or `debug` only for targeted diagnosis. -- Reproduce once with `SubMiner.AppImage --start --log-level debug` and open DevTools (`y` then `d`) if freezes recur. - -## Platform-specific - -### Linux - -- **Wayland (Hyprland/Sway only)**: Native Wayland support covers Hyprland and Sway only. Window tracking shells out to `hyprctl` or `swaymsg`; if neither is on `PATH`, tracking fails silently. Other Wayland compositors such as KDE Plasma and GNOME have no native backend - both mpv and SubMiner must run under X11 or Xwayland instead. On those sessions SubMiner forces XWayland automatically for itself and for every mpv it launches (see [KDE Plasma & other Wayland compositors](#kde-plasma-and-other-wayland-compositors)). -- **X11 / Xwayland**: Needs `xdotool`, `xprop`, and `xwininfo`. Without them the overlay cannot track the mpv window position. This is the required backend for any Wayland compositor other than Hyprland or Sway - both mpv and SubMiner must be running under X11/Xwayland for window tracking _and_ for the overlay to stay above mpv (Wayland forbids clients from controlling window stacking). SubMiner uses a managed X11 overlay while mpv is windowed, switches to an override-redirect X11 overlay while tracked mpv is fullscreen, and hides/releases that overlay when another X11/Xwayland app takes focus. The visible overlay stays hidden until SubMiner has tracked mpv geometry, so startup should not create a display-sized fallback overlay while tokenization warms up. -- **Tray icon missing**: SubMiner creates an Electron tray icon in `--background` mode, but Linux trays require a StatusNotifier/AppIndicator host. Hyprland does not provide one by itself; enable a tray in Waybar, Hyprpanel, or another panel. If Electron cannot register the tray, SubMiner logs a warning that mentions the missing tray host. -- **Mouse passthrough**: On Linux X11/Xwayland, SubMiner uses `xdotool` to poll the cursor and only enables overlay input while the cursor is over subtitle or popup regions. Outside those regions, pointer input passes through to mpv. Native Wayland compositors other than Hyprland/Sway cannot provide the stacking control SubMiner needs. +Linux trays need a StatusNotifier/AppIndicator host. Hyprland has none by default. Enable a tray in Waybar, Hyprpanel, or another panel. ### Hyprland -SubMiner's overlay is a transparent, frameless Electron window that must be kept above mpv. SubMiner tries to apply the floating, borderless, no-shadow, and no-blur properties itself each time it places the overlay. It detects Hyprland's active config provider and uses Lua `hl.dsp.window.*` dispatchers for recent Hyprland Lua configs, or the legacy dispatcher syntax for older hyprlang configs. On many configurations that is enough, but if your Hyprland version doesn't honor those runtime dispatches - or a broad rule in your config forces opacity/blur on every window - add explicit window rules so the overlay is exempt. You also need `pass` bindings to forward global shortcuts to SubMiner (see below). - -**Overlay is not transparent or has a visible border** - -Add a window rule matching SubMiner's window class. Recent Hyprland uses the Lua config format: +SubMiner applies float, no-border, and no-blur properties to its window itself. If the overlay still has a border or an opaque background, a global opacity or blur rule is usually overriding it. Add a rule for the `SubMiner` class. Lua config: ```lua hl.window_rule({ @@ -366,7 +206,7 @@ hl.window_rule({ }) ``` -On older Hyprland releases that still use the hyprlang config (`hyprland.conf`), use the equivalent `windowrule` lines: +Older `hyprland.conf` configs: ```ini windowrule = float on, match:class SubMiner @@ -376,82 +216,32 @@ windowrule = no_shadow on, match:class SubMiner windowrule = no_blur on, match:class SubMiner ``` -If you still see a solid background or visual artifacts instead of the mpv video underneath, the culprit is almost always a global opacity/blur rule applying to the overlay - the `opaque`/`opacity` and `no_blur` fields above override it. - -**Application Not Responding dialog covered by the overlay** - -SubMiner keeps visible Hyprland system dialogs above its windows on the same workspace when updating overlay placement. This lets you click the recovery dialog even while the overlay accepts mouse input. If the whole SubMiner process is frozen, use Hyprland's window-focus bindings to reach the dialog; SubMiner cannot update window order until it resumes. - -**Global shortcuts not working** - -On Hyprland, Electron cannot register global shortcuts on its own. You must explicitly pass keybindings to SubMiner using `pass` rules: +Hyprland swallows global shortcuts unless you pass them through. Add a `pass` bind for each one, and update it if you remap the key: ```ini bind = ALT SHIFT, O, pass, class:^(SubMiner)$ bind = ALT SHIFT, Y, pass, class:^(SubMiner)$ ``` -Add a `pass` rule for each global shortcut you configure. The defaults are `Alt+Shift+O` (toggle overlay) and `Alt+Shift+Y` (Yomitan settings). If you remap `shortcuts.toggleVisibleOverlayGlobal` to a different key, update the `pass` rule to match. +If the overlay stays behind fullscreen mpv, check that the mpv socket is connected and that `hyprctl -j clients` works from the environment that launched SubMiner. -Without these rules, Hyprland intercepts the keypresses before they reach SubMiner, and the shortcuts silently do nothing. - -**Overlay stays behind mpv after fullscreen** - -SubMiner watches mpv's `fullscreen` property and refreshes the overlay geometry when it changes. If the overlay still does not move or rise above fullscreen mpv, confirm that the mpv IPC socket is connected and that `hyprctl -j clients` and `hyprctl -j monitors` work from the same environment that launched SubMiner. - -For more details, see the Hyprland docs on [global keybinds](https://wiki.hypr.land/Configuring/Binds/#global-keybinds) and [window rules](https://wiki.hypr.land/Configuring/Window-Rules/). +See the Hyprland wiki on [global keybinds](https://wiki.hypr.land/Configuring/Binds/#global-keybinds) and [window rules](https://wiki.hypr.land/Configuring/Window-Rules/). ### KDE Plasma and other Wayland compositors -On any Wayland session that is not Hyprland or Sway (KDE Plasma, GNOME, and others), the overlay can only stay above mpv when both processes run under **XWayland** - the Wayland protocol forbids clients from controlling window stacking, so the overlay's "always on top" becomes a no-op on a native Wayland surface. +Outside Hyprland and Sway, Wayland does not let the overlay stay on top of mpv, so both must run under Xwayland. SubMiner does this automatically for itself and for every mpv it launches (launcher, tray, Jellyfin, YouTube). Install `xdotool`, `xprop`, and `xwininfo`. -SubMiner handles this automatically: +**Overlay sits behind mpv, and hover or Yomitan stops working**: mpv started as a native Wayland window. This happens when you launch mpv yourself. Launch through SubMiner, or force Xwayland in your own command: -- It launches its own window under XWayland (it sets `--ozone-platform=x11`). -- Every mpv it launches (via the `subminer` launcher, Jellyfin, or YouTube) is pinned to XWayland too - Wayland environment hints are stripped and an X11 GPU context (`--gpu-context=x11vk,x11egl,x11`) is applied. Only the window context is overridden; your `vo`/`gpu-api` and user shaders are left alone. -- Fractional and mixed-monitor display scaling is handled per screen when SubMiner maps XWayland mpv coordinates to the overlay. -- While mpv is windowed, the overlay is a managed X11 window owned by the tracked mpv window (`WM_TRANSIENT_FOR`), so it stays above mpv while other foreground X11/Xwayland apps can still cover both windows. -- While tracked mpv is fullscreen, SubMiner swaps the visible overlay to a focusable-false X11 override-redirect window. That path can stay above the active fullscreen mpv window without requiring a KDE/KWin-specific rule, and SubMiner hides/releases it when mpv is no longer the active X11/Xwayland window. -- The visible overlay is shown inactive on Linux, so normal hover should not steal keyboard focus from mpv. -- During startup and fullscreen transitions, SubMiner waits for tracked mpv geometry before showing the visible overlay and skips the fullscreen restack hide/show path after mpv leaves fullscreen. That avoids a temporary full-screen overlay or black window while the subtitle tokenizer and Yomitan warmups finish. -- If the subtitle sidebar is open during a windowed/fullscreen transition, SubMiner restores it on the replacement overlay window. Subtitle hit regions are also refreshed as soon as the first measured subtitle line is reported, so hover and Yomitan lookup should work on the first visible line. +```bash +mpv --gpu-context=x11vk,x11egl,x11 video.mkv +``` -Requirements: `xdotool`, `xprop`, and `xwininfo` must be installed. SubMiner uses root `_NET_ACTIVE_WINDOW` from `xprop` for focus detection and falls back to `xdotool getactivewindow` when that signal is unavailable. +`WAYLAND_DISPLAY= mpv video.mkv` also works, as does `gpu-context=x11vk` (or `x11egl`) in `mpv.conf`. To check, `xdotool search --class mpv` should print a window id. -**Overlay sits behind mpv / pause-on-hover and Yomitan stop working** +**Overlay stays above an unrelated app**: SubMiner can only see X11/Xwayland windows in this mode. Run that app under Xwayland too. -This almost always means mpv came up as a **native Wayland** window that the XWayland overlay cannot cover. It happens when mpv is launched **manually** (your own command), because SubMiner can only force XWayland on the mpv processes it launches itself. Fix it one of these ways: +## macOS -- Launch playback through SubMiner (the `subminer` launcher or the tray), which forces XWayland for you, or -- Force XWayland in your own mpv command, for example `mpv --gpu-context=x11vk,x11egl,x11 <file>`. Launching with `WAYLAND_DISPLAY= mpv <file>` works too, as does setting `gpu-context=x11vk` (Vulkan) or `gpu-context=x11egl` (OpenGL) in your `mpv.conf`. - -To confirm mpv is on XWayland, `xdotool search --class mpv` should return a window id (a native Wayland mpv returns nothing). - -**Overlay stays above an unrelated foreground app** - -SubMiner can only detect focus for X11/Xwayland windows in this mode. If a native Wayland app covers mpv but the overlay stays visible, run that app under Xwayland too or use Hyprland/Sway native support. Generic X11 cannot observe native Wayland foreground windows. - -### macOS - -- **Accessibility permission**: Required for window tracking. Grant it in System Settings > Privacy & Security > Accessibility. -- **Gatekeeper**: If macOS blocks SubMiner, right-click the app and select "Open" to bypass the warning, or remove the quarantine attribute: `xattr -d com.apple.quarantine /path/to/SubMiner.app` - -## See also - -Feature-specific issues are covered in each feature's own page: - -- [Anki Integration](/anki-integration) - card creation, field mapping, and AnkiConnect setup -- [AniList Integration](/anilist-integration) - watch-progress sync and authentication -- [Character Dictionary](/character-dictionary) - AniList character name matching and inline portraits -- [Jellyfin Integration](/jellyfin-integration) - remote playback and library connection -- [Jimaku Integration](/jimaku-integration) - subtitle fetching and API rate limits -- [TsukiHime Integration](/tsukihime-integration) - multi-language subtitle download and `xz` decompression -- [YouTube Integration](/youtube-integration) - subtitle generation and playback -- [Immersion Tracking](/immersion-tracking) - telemetry, session logging, and the stats dashboard -- [Launcher Script](/launcher-script) - `subminer` commands, pickers, watch history, and cross-machine sync -- [MPV Plugin](/mpv-plugin) - in-player chords, script-opts, and binary auto-detection -- [WebSocket / Texthooker API](/websocket-texthooker-api) - external texthooker clients -- [Subtitle Annotations](/subtitle-annotations) - N+1, frequency, JLPT, and name-match layers -- [Subtitle Sidebar](/subtitle-sidebar) - sidebar navigation and behavior -- [Configuration Reference](/configuration) - full config options -- [Shortcuts](/shortcuts) - keybinding reference +- Accessibility permission is required for window tracking: System Settings > Privacy & Security > Accessibility. +- If Gatekeeper blocks the app, right-click it and choose Open, or run `xattr -d com.apple.quarantine /path/to/SubMiner.app`. diff --git a/docs-site/tsukihime-integration.md b/docs-site/tsukihime-integration.md index 24a4a19c..7477ac71 100644 --- a/docs-site/tsukihime-integration.md +++ b/docs-site/tsukihime-integration.md @@ -1,82 +1,48 @@ # TsukiHime integration -[TsukiHime](https://tsukihime.org) indexes anime torrent releases and pulls every attachment out of the release files, embedded subtitle tracks included, then hosts them for direct download. SubMiner talks to the TsukiHime API, so you can grab subtitles for the episode you are watching from the overlay without a torrent client. The download is decompressed, saved next to the video, and loaded into mpv straight away. +[TsukiHime](https://tsukihime.org) extracts the subtitle tracks from anime torrent releases and hosts them for download. SubMiner searches it from the overlay, so you can grab Japanese or secondary-language subtitles for the current episode without a torrent client. Most releases carry only English subtitles, so [Jimaku](/jimaku-integration) is usually the better source for Japanese. -This is the multi-language companion to the [Jimaku integration](/jimaku-integration). Releases that ship multiple languages (e.g. Netflix `[MultiSub]` rips) expose them all; the modal's tabs pick which ones you see, and each download is saved with its own language suffix. +## Setup -::: tip Successor to Animetosho -TsukiHime replaces [Animetosho](https://animetosho.org), which stops processing new releases in May 2026. TsukiHime imported the Animetosho index and mirrors its attachment storage, so older releases stay reachable alongside new ones. -::: +TsukiHime needs no account or API key. SubMiner needs the `xz` binary on your `PATH` to unpack downloads. Most Linux distributions ship it (package `xz` or `xz-utils`). -::: tip No API key required -Unlike Jimaku, TsukiHime needs no account or API key. The only requirement is the `xz` binary on your `PATH` - TsukiHime serves extracted subtitles xz-compressed, and SubMiner shells out to `xz` to decompress them. Most Linux distributions ship it by default (package `xz` or `xz-utils`). -::: +## Usage -## How it works +1. Press `Ctrl+Shift+T` during playback. +2. SubMiner fills in the title and episode from the file name and searches right away when it finds both. Otherwise, fix the fields and press `Enter`. +3. Pick a tab. The first tab shows your secondary language (`secondarySub.secondarySubLanguages`, or English if unset). The second tab shows Japanese. Each tab lists only releases that carry that language. +4. Select a release, then a subtitle track. -The integration runs through an in-overlay modal opened with `Ctrl+Shift+T` by default. The modal has two tabs that filter both the release list and the subtitle tracks of the selected release by role: the first follows `secondarySub.secondarySubLanguages` (English when unset), and the second is always **Japanese**, the currently supported primary subtitle language. Each tab lists only the releases whose reported subtitle languages include the tab's language, so the Japanese tab hides the many releases that ship English subtitles only. Releases and tracks with no language tag stay visible on the secondary tab. If nothing on the active tab qualifies, the status line says so and points at the other tab. +The track is saved next to the video with a language suffix, such as `<video>.ja.ass` or `<video>.en.ass` (a temp directory is used for streams). A Japanese track becomes mpv's primary subtitle. A track from the secondary tab loads as the secondary subtitle and leaves the primary alone. -When you open the modal, SubMiner parses the current video filename to extract a title and episode number (same parser as Jimaku - `S01E03`, `1x03`, `E03`, and dash-separated numbers all work). If the filename yields a high-confidence match, SubMiner auto-searches immediately. +Pick the release that matches your video file, same group and same version, and the timing will line up. With any other release, fix the offset with subtitle sync (`Ctrl+Alt+S`). -From there: +| Key | Action | +| ---------------- | -------------------------------------- | +| `Enter` | Search, or select the highlighted item | +| `Up` / `Down` | Move through releases or tracks | +| `Left` / `Right` | Switch tabs | +| `Escape` | Close | -1. **Search** - SubMiner queries TsukiHime with `<title> <episode>`. Results appear as a list of releases (e.g. `[SubsPlease] ... - 28 (1080p)`), each showing size, file count, and the subtitle languages the release carries. -2. **Browse releases** - Select a release to list the text subtitle tracks extracted from its files. English tracks sort first; image-based tracks (PGS/VobSub) are filtered out. -3. **Download** - Selecting a track downloads the xz-compressed subtitle from TsukiHime's storage, decompresses it, saves it next to the video (or a temp directory for remote/streamed media), and loads it into mpv. Japanese tracks are selected as mpv's **primary** subtitle. Tracks from the configured secondary tab are assigned to mpv's **secondary** subtitle slot without replacing the primary. The filename carries the track's language - `<video basename>.en.<ext>` for English, `.ja` for Japanese, and so on - so mpv and media servers detect the language correctly. +You can also open the modal with `subminer app --open-tsukihime`, bind a key to `["__tsukihime-open"]` in `keybindings`, or change the shortcut with `shortcuts.openTsukihime`. -TsukiHime's releases are the same files that circulate as torrents. Pick the release matching your local file, same group and same version, and the timing lines up exactly with no resync. For a raw or a different group's encode, take any release of the episode and fix the offset with the [subtitle sync tools](/troubleshooting#subtitle-sync-subsync) (`Ctrl+Alt+S`). +## Options -### Modal keyboard shortcuts +| Key | What it does | +| ---------------------------- | ------------------------------------------------------ | +| `tsukihime.maxSearchResults` | Maximum releases per search. The API caps this at 100. | +| `tsukihime.apiBaseUrl` | API address. Change only for a mirror. | -| Key | Action | -| ---------------------------- | ------------------------------- | -| `Enter` (in text field) | Search | -| `Enter` (in list) | Select release / download track | -| `Arrow Up` / `Arrow Down` | Navigate releases or tracks | -| `Arrow Left` / `Arrow Right` | Switch English / Japanese tab | -| `Escape` | Close modal | - -## Configuration - -There is nothing to configure to get started. An optional `tsukihime` section in `config.jsonc` tunes it: - -```jsonc -{ - "tsukihime": { - "apiBaseUrl": "https://api.tsukihime.org/v1", - "maxSearchResults": 10, - }, -} -``` - -| Option | Type | Default | Description | -| ---------------------------- | -------- | -------------------------------- | -------------------------------------------------------------------------- | -| `tsukihime.apiBaseUrl` | `string` | `"https://api.tsukihime.org/v1"` | Base URL of the TsukiHime API. Only change this if using a mirror. | -| `tsukihime.maxSearchResults` | `number` | `10` | Maximum number of releases returned per search (the API caps this at 100). | - -The keyboard shortcut is configured separately under `shortcuts`: - -```jsonc -{ - "shortcuts": { - "openTsukihime": "Ctrl+Shift+T", // default; set to null to disable - }, -} -``` - -Existing Animetosho configuration remains compatible. SubMiner treats the old `animetosho` section and `shortcuts.openAnimetosho` setting as deprecated aliases. When old and current names are both present, `tsukihime` and `shortcuts.openTsukihime` take precedence. - -## Other ways to open it - -- CLI: `subminer --open-tsukihime` -- Keybinding command: bind any key to `["__tsukihime-open"]` in the `keybindings` array - -The previous `--open-animetosho` flag and `__animetosho-open` keybinding command remain accepted as deprecated aliases. +See [Configuration](/configuration#tsukihime) for defaults. ## Troubleshooting -- **"xz binary not found"** - install `xz`/`xz-utils` with your package manager. -- **"No releases with Japanese subtitles"** - none of the search results carry a Japanese track. Most releases only ship English subtitles; try another search, or use the [Jimaku integration](/jimaku-integration) for Japanese subtitles. -- **"Batch releases are not supported"** - TsukiHime only exposes extracted attachments for single-file torrents. Pick the single-episode release for your episode instead of a season batch. -- **"No text subtitle tracks in this release"** - the release only carries image-based subtitles (PGS/VobSub) or none at all; try a different release (fansub and SubsPlease-style releases almost always carry ASS tracks). -- **Timing is off** - the subtitle came from a different release than your video file. Use the subtitle sync modal (`Ctrl+Alt+S`) or pick the release matching your file exactly. +**"xz binary not found."** Install `xz` or `xz-utils` with your package manager. + +**"No releases with Japanese subtitles."** None of the results carry a Japanese track. Try another search, or use Jimaku. + +**"Batch releases are not supported."** TsukiHime only has extracted tracks for single-file torrents. Pick the single-episode release. + +**"No text subtitle tracks in this release."** The release has only image-based subtitles (PGS or VobSub) or none. Try another release. + +**Timing is off.** The subtitle came from a different release than your video. Use subtitle sync (`Ctrl+Alt+S`) or pick the matching release. diff --git a/docs-site/usage.md b/docs-site/usage.md index 1c5c379a..f8480ee4 100644 --- a/docs-site/usage.md +++ b/docs-site/usage.md @@ -1,454 +1,182 @@ # Usage -## Quick start +This page covers everyday use: starting playback, working with the overlay, and the commands you will reach for most. For every `subminer` subcommand and flag, see [Launcher script](/launcher-script). -Play a video with SubMiner: +## Play a video ```bash subminer video.mkv ``` -On **Windows**, use the **SubMiner mpv** shortcut created during first-run setup - double-click it, or drag a video file onto it. +On Windows, double-click the **SubMiner mpv** shortcut or drag a video onto it. -That is the whole setup. The `subminer` launcher starts mpv, opens the IPC socket, and brings up the overlay. +SubMiner starts mpv, connects to it, and opens the overlay. Subtitle lines appear as hoverable words. Hover a word to look it up, then mine it into Anki. [Mining workflow](/mining-workflow) covers lookup and card creation in detail. -Every current launcher wrapper uses the Bun runtime included with the SubMiner app. This includes setup installs, release downloads, `make install`, and the AUR package. You only need the wrapper directory on your terminal `PATH`. Building SubMiner from source still requires Bun on the development machine. - -> [!IMPORTANT] -> SubMiner requires at least one dictionary in the selected lookup backend. -> See [Yomitan setup](#yomitan-setup) or [Hachidori setup](#hachidori-setup). - -::: tip Anki card enrichment -If you want sentence, audio, and screenshot fields on your Anki cards, add this to your config: - -```jsonc -{ - "ankiConnect": { - "enabled": true, - "deck": "Mining", - "fields": { - "sentence": "Sentence", - "audio": "SentenceAudio", - "image": "Picture", - }, - }, -} -``` - -Field names must match a field on your Anki note type. Matching is case-insensitive (an exact match wins, then a lowercase comparison), but the spelling must otherwise match. See [Anki Integration](/anki-integration) for the full reference. -::: - -## How it works - -Launching SubMiner wires up mpv and the overlay for you: - -1. SubMiner starts the overlay app in the background -2. mpv runs with an **IPC socket** at `/tmp/subminer-socket` - a small local channel two programs use to talk to each other, so the overlay can ask mpv what subtitle is on screen right now -3. The overlay connects and subscribes to subtitle changes - -Subtitles then render as hoverable word spans, and you mine cards straight from the overlay. [Mining Workflow](/mining-workflow) covers the overlay layout, word lookup, card creation, and annotations. - -### Ways to launch - -| Approach | Use when | How | -| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | -| **`subminer` launcher** | You want SubMiner to handle everything - launch mpv, set up the socket, start the overlay. **Recommended for most users.** | `subminer video.mkv` | -| **SubMiner mpv shortcut** (Windows) | The recommended Windows entry point. Created during first-run setup, launches mpv with SubMiner's defaults. | Double-click, drag a file onto it, or run `SubMiner.exe --launch-mpv` | -| **mpv plugin** (all platforms) | Bundled and injected at runtime. Provides `y` chord keybindings for controlling the overlay from within mpv. No manual install needed. | Automatic when using the launcher or shortcut | - -The mpv plugin is always available, because SubMiner bundles it and injects it at runtime. On Linux, normal `subminer` playback auto-installs the launcher-managed runtime plugin copy from the bundled app if that managed copy is missing, so no separate plugin install is needed for standard launcher usage. If you launch mpv yourself (without the launcher), pass `--input-ipc-server=/tmp/subminer-socket` in your mpv config for the overlay to connect. - -## Commands - -These are the ones you will use day to day. [Launcher Script](/launcher-script#subcommands) has every subcommand and flag. - -```bash -subminer video.mkv # Play a specific file -subminer # Browse the current directory (fzf picker) -subminer -R # Browse with the rofi picker instead -subminer -d ~/Anime -r # Browse a specific directory, recursively -subminer -H # Browse watch history, then replay/next/previous -subminer https://youtu.be/... # Play a YouTube URL -subminer stats # Open the immersion stats dashboard -subminer doctor # Check dependencies, config, and the mpv socket -subminer settings # Open the SubMiner settings window -subminer generate-subs video.mkv # Generate Japanese subtitles from local audio -subminer app --setup # Re-open first-run setup -subminer -u # Check for updates -``` - -On **Windows**, first-run setup can install the optional `subminer` terminal wrapper. Use the **SubMiner mpv** shortcut for playback (see [Windows mpv Shortcut](#windows-mpv-shortcut)), or use `subminer` and `SubMiner.exe` from a terminal. - -Two flags are worth knowing early: - -- `-a/--args` passes extra arguments straight to mpv, for example `subminer --args "--ao=alsa --volume=80" video.mkv`. -- `--log-level debug` turns on verbose logging when something is not working. - -### Generate Japanese subtitles locally - -`generate-subs` transcribes local audio with whisper.cpp, saves a timed Japanese SRT file, -and loads it into mpv if that same media file is still playing, clearing the previous subtitle -delay. It also works with no running -SubMiner app or mpv instance when you provide a file path. Omit the path to use the current -mpv file and selected audio track. - -When the input matches the current mpv file, generation automatically uses an eligible embedded -or loaded external subtitle track as a timing reference, preferring English dialogue and skipping -tracks marked as signs, songs, or forced. See [timing references](/subtitle-generation#using-loaded-subtitles-as-timing-references). - -```bash -subminer generate-subs video.mkv --download-model -subminer generate-subs video.mkv --model-path ~/models/ggml-medium.bin -subminer generate-subs --model medium --download-model -subminer generate-subs video.mkv --audio-stream 2 --output ~/Subs/video.ja.srt -``` - -Install `whisper-cli` from whisper.cpp, `ffmpeg`, and `ffprobe`, or configure their paths in -`subtitleGeneration.whisperPath`, `subtitleGeneration.ffmpegPath`, and `subtitleGeneration.ffprobePath`. -Set `subtitleGeneration.modelPath` in settings to reuse an existing whisper.cpp model. -With no external path, SubMiner uses `subtitleGeneration.managedModel` and stores downloaded -models under `models/whisper` beside its config file. `--model` selects an official multilingual model, including available quantized variants, for -this invocation and overrides a configured external model path. Run `subminer generate-subs --help` -for accepted names. See [model selection](/subtitle-generation#choosing-a-model) for accuracy and speed guidance. - -Downloads only happen when you pass `--download-model` or choose the download action in the -generation modal. The launcher reports each stage and percentages when available. Press Ctrl+C -to cancel. `--audio-stream` takes an absolute ffprobe stream index. When you provide a file -path without that flag, generation uses a Japanese audio track when tagged, falling back -to the first audio track. With no file path, mpv must have an identifiable selected audio -track, or you must provide `--audio-stream`. - -Generated files include Whisper's native timing. Speech recognition can make mistakes, -especially over music or overlapping dialogue, so check the wording before mining. Existing -output files are preserved. See [configuration](/configuration) for the generation settings. - -<details> -<summary><b>Less common launcher commands</b></summary> - -```bash -subminer --start video.mkv # Explicit overlay start (when mpv.autoStartSubMiner is false) -subminer -S video.mkv # Also force the visible overlay on start -subminer -T video.mkv # Disable the texthooker server -subminer -b x11 video.mkv # Force a window backend -subminer -p gpu-hq video.mkv # Use a specific mpv profile -subminer ytsearch:"jp news" # Play the first YouTube search result -subminer texthooker # Texthooker-only mode (-o also opens the browser) -subminer stats -b # Start/reuse the background stats daemon -subminer stats -s # Stop the background stats daemon -subminer stats cleanup # Backfill vocabulary metadata, prune stale rows -subminer stats cleanup -d --dry-run # Preview cleanup of repeated typeset subtitle lines -subminer stats cleanup -d --lookback-days 30 # Clean only lines recorded in the last 30 days -subminer stats rebuild # Rebuild rollup data -subminer doctor --refresh-known-words # Refresh the known-word cache -subminer logs -e # Export a sanitized log ZIP and print its path -subminer config path # Print the active config path -subminer config show # Print the active config contents -subminer mpv socket # Print the active mpv socket path -subminer mpv status # Exit 0 if the socket is ready, else exit 1 -subminer mpv idle # Launch a detached idle mpv with SubMiner defaults -subminer app --stop # Stop the background app -subminer --version # Print the launcher's version -``` - -`stats cleanup` runs one mode per invocation: `-v`/`--vocab` (the default), `-l`/`--lifetime`, or `-d`/`--duplicate-lines`; explicitly selected modes cannot be combined. `--dry-run` and `--lookback-days <days>` apply to `--duplicate-lines` only and are rejected without it; `--lookback-days` must be at least one day, and leaving it off scans all history. - -Jellyfin, cross-machine sync, and character-dictionary commands have their own sections: [Jellyfin](/jellyfin-integration), [Sync Between Machines](/launcher-script#sync-between-machines), and [Character Dictionary](/character-dictionary). - -</details> - -<details> -<summary><b>Direct packaged-app flags (advanced)</b></summary> - -These call the app binary directly rather than going through the launcher. On Windows, replace `SubMiner.AppImage` with `SubMiner.exe`. - -```bash -SubMiner.AppImage --background # Start in background (tray + IPC wait, minimal logs) -SubMiner.AppImage --start --texthooker # Start overlay with texthooker -SubMiner.AppImage --texthooker # Texthooker only (no overlay window) -SubMiner.AppImage --setup # Open first-run setup -SubMiner.AppImage --stop # Stop overlay -SubMiner.AppImage --start --toggle # Start mpv IPC + toggle visibility -SubMiner.AppImage --show-visible-overlay # Force show the visible overlay -SubMiner.AppImage --hide-visible-overlay # Force hide the visible overlay -SubMiner.AppImage --toggle-primary-subtitle-bar # Toggle the primary subtitle bar -SubMiner.AppImage --toggle-subtitle-sidebar # Toggle the subtitle sidebar -SubMiner.AppImage --open-tsukihime # Open TsukiHime subtitle search -SubMiner.AppImage --yomitan # Open Yomitan settings -SubMiner.AppImage --hachidori # Open Hachidori settings -SubMiner.AppImage --settings # Open the SubMiner settings window -SubMiner.AppImage --jellyfin # Open the Jellyfin setup window -SubMiner.AppImage --dictionary # Generate a character dictionary ZIP -SubMiner.AppImage --start --dev # Enable app/dev mode -SubMiner.AppImage --start --log-level debug # Verbose logging without dev mode -SubMiner.AppImage --help # Show all options -``` - -The remaining flags are internal or scripting-only surfaces: the `--jellyfin-*` family (login, library listing, item playback, cast announce), `--sync-cli` (the app's headless sync entrypoint that `subminer sync` proxies to), the `--stats-cleanup-*` family that `subminer stats cleanup` forwards (`--stats-cleanup-vocab`, `--stats-cleanup-lifetime`, `--stats-cleanup-duplicate-lines`, and its `--stats-cleanup-dry-run` / `--stats-cleanup-lookback-days <days>` modifiers), `--dictionary-candidates` / `--dictionary-select`, and `--playback-feedback <text>`. Run `SubMiner.AppImage --help` for the complete list. The previous `--open-animetosho` flag is still accepted as a deprecated alias for `--open-tsukihime`. - -</details> - -The tray menu includes `Export Logs`, which creates the same sanitized local-date log ZIP as `subminer logs -e` and shows the archive path when complete. Export sanitization masks common PII and secrets, including home-directory usernames, IP addresses, emails, auth/cookie headers, yt-dlp cookie arguments, URL credentials, token/key/password fields, and signed YouTube media URL query strings. The exported copy is sanitized; source log files remain unredacted on disk. - -Once Jellyfin is configured, the tray menu includes `Jellyfin Discovery` for starting or stopping cast discovery in the current app session without changing config. - -The tray menu also includes `View Changelog`, which opens the in-app changelog modal. It fetches the changelog from the newest published release, so you see release notes for versions newer than the one you run; if the download fails it falls back to the changelog bundled with your install and says so. Versions in the current `0.x` line are expanded by default and older lines are folded, matching this site's [Changelog](/changelog). A badge marks the version you have installed, and newer versions are tagged `New`. The same modal opens from the `What's New` button on the update-available overlay notification. - -### Logging and app mode - -- `--log-level` controls logger verbosity. -- `--dev` and `--debug` are app/dev-mode switches; they are not log-level aliases. -- `--background` starts at the default quieter logging level (`warn`), then follows `logging.level` after config loads. An explicit `--log-level` remains the override. -- `--background` launched from a terminal detaches and returns the prompt; stop it with tray Quit or `SubMiner.AppImage --stop` (`SubMiner.exe --stop` on Windows). -- Linux desktop launcher starts SubMiner with `--background` by default (via electron-builder `linux.executableArgs`). -- On Hyprland and other Wayland compositors, the tray icon appears only when your panel provides a StatusNotifier/AppIndicator tray host. -- On Linux, the app now defaults `safeStorage` to `gnome-libsecret` for encrypted token persistence. - Launcher pass-through commands also support `--password-store=<backend>` and forward it to the app when present. - Override with e.g. `--password-store=basic_text`. -- Use both when needed, for example `SubMiner.AppImage --start --dev --log-level debug` (or `SubMiner.exe --start --dev --log-level debug` on Windows). -- `--playback-feedback <text>` (also `--playback-feedback=<text>`) sends a non-empty text string through the playback-feedback route used for recording/playback prompts. For example: `SubMiner.AppImage --playback-feedback "your feedback"`. - -### Windows mpv shortcut - -First-run setup creates the config file, then requires dictionaries in the selected backend before it can finish. - -If you enabled the optional Windows shortcut during install, SubMiner creates a `SubMiner mpv` shortcut in the Start menu and/or on the desktop. On Windows, that shortcut is the recommended way to launch local files with SubMiner because it starts `mpv.exe` with the right defaults directly. -After setup completes, the shortcut is the normal Windows playback entry point. - -You can use it three ways: - -- Double-click `SubMiner mpv` to open `mpv` with SubMiner's default socket/subtitle args. -- Drag a video file onto `SubMiner mpv` to launch that file with the same defaults. -- Run it directly from Command Prompt or PowerShell with `--launch-mpv`. - -```powershell -& "C:\Program Files\SubMiner\SubMiner.exe" --launch-mpv -& "C:\Program Files\SubMiner\SubMiner.exe" --launch-mpv "C:\Videos\episode 01.mkv" -``` - -This flow requires `mpv.exe` to be discoverable. Leave `mpv.executablePath` blank to auto-discover from `PATH`, or set it to the full `mpv.exe` path if mpv is installed elsewhere. `SUBMINER_MPV_PATH` is still honored as a fallback. - -### Launcher subcommands - -The launcher groups related work under subcommands: `jellyfin` (aliased `jf`), `stats`, `sync`, `dictionary` (aliased `dict`), `texthooker`, `doctor`, `settings`, `config`, `mpv`, `logs`, and `app` (aliased `bin`) for passing arguments straight to the SubMiner binary. - -Every subcommand has its own help page, for example `subminer jellyfin -h`. See [Launcher Script - Subcommands](/launcher-script#subcommands) for the full table, and [Sync Between Machines](/launcher-script#sync-between-machines) for the SSH stats/history sync. - -Sync selects compressed transfers automatically and reuses cached snapshots when rsync is available. Its `--transfer-cache <key>` option belongs to the internal `--make-temp` / `--remove-temp` helpers; normal `subminer sync <host>` commands manage it for you. See [Sync Between Machines](/launcher-script#sync-between-machines) for cache storage and compatibility details. - -A _texthooker_ is a web page that displays the current subtitle line as selectable text, so browser-based dictionary extensions and other tools can read along with playback. - -### First-run setup - -The setup window opens on first launch and on any later launch where setup never finished. - -You can also open it manually: - -```bash -subminer app --setup -SubMiner.AppImage --setup -``` - -Setup flow: - -- config file: create the default config directory and prefer `config.jsonc` -- legacy plugin cleanup: remove detected older global SubMiner mpv plugin files if present (the bundled plugin is injected at runtime automatically) -- Yomitan shortcut: open bundled Yomitan settings directly from the setup window -- dictionary check: confirm at least one bundled Yomitan dictionary is present, unless an external Yomitan profile is configured -- command line launcher: optionally install or reinstall the managed `subminer` wrapper. Reinstall it to migrate an older launcher or after moving a macOS or Windows app install. -- Windows: optionally create or remove `SubMiner mpv` Start Menu/Desktop shortcuts (`SubMiner.exe --launch-mpv`) -- Windows: optionally set `mpv.executablePath` if `mpv.exe` is not on `PATH` -- refresh: re-check dictionary state without restarting -- `Finish setup` stays disabled until the config and dictionary gates are satisfied -- finish action writes setup completion state and suppresses future auto-open prompts - -AniList character dictionary auto-sync (optional): - -- Enable with `subtitleStyle.nameMatchEnabled=true` in config or **Name Match Enabled** in Settings. -- SubMiner syncs the currently watched AniList media into a per-media snapshot, then rebuilds one merged `SubMiner Character Dictionary` from the most recently used snapshots. -- Rotation limit defaults to 3 recent media snapshots in that merged dictionary (`maxLoaded`). - -Use subcommands for Jellyfin workflows (`subminer jellyfin ...`). -Top-level launcher flags like `--jellyfin-*` are intentionally rejected. - -### MPV profile example (mpv.conf) - -`subminer` passes the following MPV options directly on launch by default: - -- `--input-ipc-server=/tmp/subminer-socket` (or your configured socket path) -- `--alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us` -- `--slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us` -- `--sub-auto=fuzzy` -- `--sub-file-paths=.;subs;subtitles` -- `--sid=auto` -- `--secondary-sid=auto` -- `--sub-visibility=no` (the overlay renders subtitles instead of mpv) -- `--secondary-sub-visibility=no` - -You can append additional MPV arguments with launcher `-a/--args`, for example `--args "--ao=alsa --volume=80"`. - -You can define a matching profile in `~/.config/mpv/mpv.conf` for consistency when launching `mpv` manually or from other tools. The Windows `SubMiner.exe --launch-mpv` shortcut path uses equivalent args directly, but skips the extra current-directory subtitle scan to avoid duplicate sidecar detection when you drag a video onto the shortcut; the optional profile remains useful for manual mpv launches. The `subminer` wrapper passes no mpv profile by default; set one with `subminer -p <profile> ...` or with `mpv.profile` in your config (for example `"profile": "subminer"` to use the `[subminer]` profile below): - -```ini -[subminer] -# IPC socket (must match SubMiner config) -input-ipc-server=/tmp/subminer-socket - -# Prefer JP/EN audio + subtitle language variants -alang=ja,jp,jpn,japanese,en,eng,english,enus,en-us -slang=ja,jp,jpn,japanese,en,eng,english,enus,en-us - -# Auto-load external subtitles -sub-auto=fuzzy -sub-file-paths=.;subs;subtitles - -# Select primary + secondary subtitle tracks automatically -sid=auto -secondary-sid=auto -secondary-sub-visibility=no -``` +Run `subminer` with no file to pick one from the current directory instead. See [Picking files](#picking-files). ### Yomitan setup -SubMiner bundles its own Yomitan extension for overlay lookups. It is a separate install from any Yomitan you run in a browser, with its own dictionaries and settings. +Lookups need at least one dictionary in SubMiner's bundled Yomitan (or in Hachidori, if you [switched backends](#hachidori-setup)). First-run setup asks you to import one. To add more later, open Yomitan settings with `Alt+Shift+Y` or `subminer app --yomitan`. -For SubMiner overlay lookups to work, open Yomitan settings (`subminer app --yomitan` or `SubMiner.AppImage --yomitan`) and import at least one dictionary in the bundled Yomitan instance. - -If you also use Yomitan in a browser, set that profile up separately. It inherits nothing from the bundled instance. +The bundled Yomitan is separate from any Yomitan in your browser. It has its own dictionaries and settings. ### Hachidori setup -Set `dictionaryBackend` to `"hachidori"` in SubMiner settings or `config.jsonc`, then restart SubMiner. The tray's dictionary settings entry changes to **Open Hachidori Settings**. Switching to `"yomitan"` restores the Yomitan entry after restarting. +Hachidori is an alternative lookup backend. Set `dictionaryBackend` to `"hachidori"` in settings or `config.jsonc`, then restart SubMiner. Set it back to `"yomitan"` and restart to switch back. -Open Hachidori settings with `subminer app --hachidori` or `SubMiner.AppImage --hachidori`. Import your dictionary ZIPs or use Hachidori's recommended dictionary installer, then configure its Anki templates. Yomitan and Hachidori keep separate dictionaries and settings. Yomitan profiles, custom Handlebars templates, and `yomitan.externalProfilePath` do not transfer to Hachidori. +Open Hachidori settings with `Alt+Shift+Y`, the tray's **Open Hachidori Settings**, or `subminer app --hachidori`. Import dictionary ZIPs or use Hachidori's recommended dictionary installer, then set up its Anki template (SubMiner [fills in what it can](/anki-integration#hachidori-settings-from-subminer)). Yomitan and Hachidori keep separate dictionaries and settings. Yomitan profiles, custom Handlebars templates, and `yomitan.externalProfilePath` do not carry over. -First-run setup also offers **Dictionary source → Use an external dictionary host → Link host**. Enable sharing in the other Hachidori app or browser, or start a compatible Docker dictionary host, then enter its sharing address, such as `127.0.0.1:8771` or `ws://host:8771/link`. Use the WebSocket sharing port, not the management page or HTTP API port. The external host section is collapsed until you expand it or a host is linked. Browser hosts need the browser, Hachidori extension, and relay running. Electron hosts need the host app and any required relay running. Docker hosts need the container running; no browser needs to stay open. +Hachidori uses SubMiner's subtitle scanning, popup pause, controller commands, character dictionaries, and Anki media. Keep the [Anki proxy](/anki-integration#proxy-mode-setup-yomitan-texthooker) on for screenshots and sentence audio. Hachidori's own screen recorder and screenshot capture are off inside SubMiner. `startupWarmups.yomitanExtension` and `subtitleStyle.autoPauseVideoOnYomitanPopup` apply to whichever backend is selected. -Setup checks the host connection and dictionary inventory before enabling Finish. Import at least one dictionary on the host and refresh status. The link persists across restarts. **Unlink and use local dictionaries** restores SubMiner's local library. Anki templates, pronunciation sources, custom buttons, and SubMiner's audio/image processing remain local while linked. Dictionary settings and dictionary edits use the host. Frequency annotations use the frequencies returned with Hachidori dictionary entries. SubMiner keeps ranks found during scanning and queries the existing term-entry API for missing ranks. Words without a matching definition entry may remain unranked, even if a frequency dictionary contains them. +Switching backends: -Both named settings flags work independently of the selected backend. Opening settings does not switch the overlay backend. The global dictionary-settings shortcut opens the selected backend. +- First-run setup asks for dictionaries the first time you switch to a backend. Switching back to a backend that already finished setup skips it. +- Until you restart, SubMiner keeps running the backend it started with. The launcher waits for that backend before playback and logs a restart reminder. +- `--yomitan` and `--hachidori` both work whichever backend is selected. Opening settings does not switch backends. +- When `yomitan.externalProfilePath` is set, `--yomitan` is disabled to keep the external profile read-only. Hachidori settings still open. -Hachidori uses SubMiner's subtitle scanning, lookup counter, popup pause behavior, controller commands, character dictionaries, and Anki media enrichment. Keep SubMiner's AnkiConnect proxy enabled for screenshots and sentence audio. SubMiner routes Hachidori to that proxy when it is active; Hachidori's own screen recorder and screenshot capture are disabled in the embedded app. +#### External dictionary host -For automatic character dictionary sync with a Docker host, set `hachidori.externalHostManagementUrl` to that same host's management origin, for example `"http://127.0.0.1:8780"`. This is separate from the WebSocket sharing address. SubMiner uploads the generated ZIP directly and replaces its previous dictionary after a successful import; busy imports are retried. Keep this URL pointed at the currently linked Docker host if you change hosts. An empty value disables external uploads and reports a configuration error when sync is attempted. Local Hachidori dictionaries do not need this setting. External browser/app hosts without the Docker management API do not support this automatic upload path. +First-run setup can link a Hachidori host instead of using local dictionaries: **Dictionary source → Use an external dictionary host → Link host**. Turn on sharing in the other Hachidori app or browser, or start a compatible Docker host, then enter its sharing address, for example `127.0.0.1:8771` or `ws://host:8771/link`. Use the WebSocket sharing port, not the management page or HTTP API port. -Existing controls such as `startupWarmups.yomitanExtension` and `subtitleStyle.autoPauseVideoOnYomitanPopup` apply to the selected backend. Hachidori has one dictionary configuration, so character-dictionary profile scope applies to that configuration. +| Host | Must be running | +| -------- | ------------------------------------------- | +| Browser | The browser, the Hachidori extension, relay | +| Electron | The host app and any relay it needs | +| Docker | The container only | -First-run setup remembers each backend that finished it, including when setup is reopened for legacy plugin cleanup. Switching to a backend for the first time asks for that backend's dictionaries; switching back to one that already finished does not repeat setup. Until SubMiner restarts, it keeps running the backend it started with, and the launcher gates playback on that running backend and logs a restart reminder. A running Yomitan session continues using its external profile until the restart. When `yomitan.externalProfilePath` is configured, `--yomitan` is disabled to preserve read-only external-profile mode, including while Hachidori is active. Hachidori settings remain available. +Setup checks the connection and the host's dictionaries before **Finish** unlocks, so import at least one dictionary on the host and refresh. The link survives restarts. **Unlink and use local dictionaries** goes back to local. -Hachidori's own duplicate handling differs from Yomitan's. Choosing **Overwrite** in the Hachidori popup updates the existing note and SubMiner enriches its media, while **Add anyway** creates a new note and runs SubMiner's Kiku/Senren [field grouping](./anki-integration.md#field-grouping-kiku-senren). Mining from the stats dashboard uses the selected backend as well. +While linked, dictionaries and dictionary settings come from the host. Anki templates, pronunciation sources, custom buttons, and SubMiner's audio and image processing stay local. Frequency annotations use ranks returned with dictionary entries, and SubMiner asks the host for missing ones. Words with no matching definition entry may stay unranked even if a frequency dictionary lists them. -### YouTube playback +To sync [character dictionaries](/character-dictionary) to a Docker host, set `hachidori.externalHostManagementUrl` to the same host's management origin, for example `"http://127.0.0.1:8780"`. This is not the WebSocket sharing address. SubMiner uploads the ZIP and replaces its previous dictionary once the import succeeds, retrying while the host is busy. Keep the URL pointed at the linked host. Leaving it empty turns off uploads and reports a config error when sync runs. Browser and app hosts have no management API, so automatic upload does not work with them. Local Hachidori does not need this setting. -`subminer` accepts direct URLs (for example, YouTube links) and `ytsearch:` targets. -For YouTube playback, SubMiner resolves subtitle selection during startup while mpv is paused: it auto-selects the default primary subtitle track plus a best-effort secondary track, then resumes when primary subtitles are ready. +## Picking files -Notes: +```bash +subminer # fzf picker for the current directory +subminer -d ~/Anime -r # pick from a directory, searching subfolders +subminer -R # rofi picker instead of fzf (Linux) +subminer -H # watch history: replay, next, or previous episode +``` -- Install `yt-dlp` so mpv can resolve YouTube streams and subtitle tracks reliably. -- For YouTube URLs, startup no longer requires opening the picker first; SubMiner loads subtitles and keeps the overlay available for retries. -- Press `Ctrl+Alt+C` during active YouTube playback to open the manual YouTube subtitle picker and retry track selection. -- For YouTube URLs, `subminer` probes available YouTube subtitle tracks, reuses existing authoritative tracks when available, and downloads only missing sides. -- Native mpv secondary subtitle rendering stays hidden so the overlay remains the visible secondary subtitle surface. -- YouTube auto-selection always targets a Japanese primary track and an English secondary track (manual uploads preferred over auto-generated captions). `youtube.primarySubLanguages` (defaults to `["ja","jpn"]`) defines which loaded track counts as a satisfactory primary for the missing-subtitle notification and for managed local/playlist selection. -- When multiple matching secondary tracks exist, SubMiner prefers a non-Signs/Songs track. -- Configure defaults in `$XDG_CONFIG_HOME/SubMiner/config.jsonc` (or `~/.config/SubMiner/config.jsonc`) under `youtube` and `secondarySub`. +See [Launcher script](/launcher-script#video-picker) for picker and history details. -For local video files, SubMiner uses the same config-driven language priorities to auto-select the primary and secondary subtitle tracks from internal and external subtitle sources. +## Overlay basics -## Live config reload +| Key | Action | +| ------------- | ---------------------------------------------------------------------------- | +| `Alt+Shift+O` | Show or hide the overlay (works while the overlay or mpv has focus) | +| `Alt+Shift+Y` | Open Yomitan or Hachidori settings (works from any window, not configurable) | +| `V` | Cycle the subtitle bar through hidden, visible, and hover-only | +| `Ctrl+Alt+P` | Open the playlist browser to queue, reorder, or jump between episodes | +| `Ctrl/Cmd+/` | Show every overlay and mpv keybinding for this session | -While SubMiner is running, it watches your active config file and applies safe updates automatically. +Hovering subtitle text pauses mpv, and moving away resumes it. An open dictionary popup also keeps playback paused. Turn these off with `subtitleStyle.autoPauseVideoOnHover` and `subtitleStyle.autoPauseVideoOnYomitanPopup`. -Live-updated settings include: +You can drop files onto the overlay: -- `subtitleStyle` -- `keybindings` -- `shortcuts` -- `secondarySub.defaultMode` -- `subtitleSidebar` -- `notifications` -- `logging` -- `jimaku`, `subsync` -- `mpv.aniskipEnabled`, `mpv.aniskipButtonKey` -- `stats.toggleKey`, `stats.markWatchedKey` -- `youtube.primarySubLanguages` -- most `ankiConnect.*` settings +- A video replaces what is playing. Hold `Shift` to add it to the playlist instead. +- A subtitle file loads as a new subtitle track. -Invalid config edits are rejected; SubMiner keeps the previous valid runtime config and shows an error notification. -For restart-required sections, SubMiner shows a restart-needed notification. +The full list is in [Keyboard shortcuts](/shortcuts). The in-player `y` key chords are in [mpv plugin](/mpv-plugin). -## Controller support +## YouTube playback -SubMiner reads gamepads through the Chrome Gamepad API, so you can mine from the couch. The controller drives the overlay while keyboard-only mode is on. +Pass a URL or a search. Install `yt-dlp` first. -### Getting started +```bash +subminer https://youtu.be/... +subminer ytsearch:"jp news" # play the first search result +``` -1. Connect a controller before or after launching SubMiner. -2. Set `controller.enabled` to `true` in your config. -3. Press `Alt+C` in the overlay by default to pick the controller you want to save and remap any action inline. -4. Enable keyboard-only mode - press `Y` on the controller (default binding) or use the overlay keybinding. -5. Click the binding badge, edit pencil, or `Learn` on the overlay action you want, then press the matching button, trigger, or stick direction on the controller. -6. Use the left stick to navigate subtitle tokens and scroll the popup; use the right stick vertically for popup page jumps. -7. Press `A` to look up the selected word, `X` to mine a card, `B` to close the popup. +SubMiner picks subtitles during startup while mpv is paused. It selects a Japanese primary track and an English secondary track, downloads whatever is missing, and resumes once the primary subtitles are ready. If the choice is wrong, press `Ctrl+Alt+C` to open the YouTube subtitle picker and choose again. -By default SubMiner uses the first connected controller after controller support is enabled. `Alt+C` opens the controller config modal, where you can save the preferred controller and remap bindings inline per controller. The reset button beside each edit pencil restores that binding to its built-in default for the selected controller. `Alt+Shift+C` opens the live debug modal with raw axes/button values for non-standard pads. Both modals stay closed while `controller.enabled` is false, and both shortcuts can be changed through `shortcuts.openControllerSelect` and `shortcuts.openControllerDebug`. +Language preferences live under `youtube` and `secondarySub` in the config. See [YouTube integration](/youtube-integration). -### Default button mapping +## Common commands -| Button | Action | -| ----------------------- | --------------------------------------- | -| `A` (South) | Toggle lookup | -| `B` (East) | Close lookup | -| `Y` (North) | Toggle keyboard-only mode | -| `X` (West) | Mine card | -| `L1` | Play current Yomitan audio | -| `R1` | Next Yomitan audio track | -| `L3` (left stick press) | Toggle mpv pause | -| `Select` / `Minus` | Quit mpv | -| `L2` / `R2` | Unbound (available for custom bindings) | +```bash +subminer stats # start the immersion stats dashboard +subminer settings # open the settings window +subminer doctor # check dependencies, config, and the mpv socket +subminer generate-subs video.mkv # make Japanese subtitles from the audio +subminer logs -e # export a log ZIP for bug reports +subminer app --setup # reopen first-run setup +subminer -u # update SubMiner +``` -The default quit binding uses gamepad button index 6. Pads that follow the W3C standard layout report L2 as index 6 and Select as index 8, so on those controllers quit fires on L2 instead. Remap it with `Alt+C` learn mode. +Two flags help early on: -### Analog controls +- `-a/--args` passes options to mpv, for example `subminer --args "--volume=80" video.mkv`. +- `--log-level debug` turns on verbose logs when something is wrong. -| Input | Action | -| --------------------- | --------------------------------------------- | -| Left stick horizontal | Move token selection left/right | -| Left stick vertical | Scroll Yomitan popup | -| Right stick vertical | Jump through Yomitan popup | -| D-pad | Fallback for stick navigation when configured | +[Launcher script](/launcher-script) lists every command. Jellyfin, sync, and character dictionary commands are covered in [Jellyfin](/jellyfin-integration), [Sync between machines](/launcher-script#sync-between-machines), and [Character dictionary](/character-dictionary). -Learn mode ignores inputs you are already holding and waits for the next fresh press or axis push, so opening the modal mid-input does not capture whatever your thumb was on. +### Generate Japanese subtitles locally -All button and axis mappings are configurable under the `controller` config block. Learned remaps are saved under `controller.profiles` for the selected controller id. See [Configuration - Controller Support](/configuration#controller-support) for the full options. +`subminer generate-subs` transcribes audio with whisper.cpp and writes a Japanese SRT file. If that file is playing in mpv, it loads the new subtitles right away. Leave out the path to use the file mpv is playing. -## Keybindings +```bash +subminer generate-subs video.mkv --download-model # download a model on first use +subminer generate-subs video.mkv --model-path ~/models/ggml-medium.bin +``` -See [Keyboard Shortcuts](/shortcuts) for the full reference, including mining shortcuts, overlay controls, and customization. +You need `whisper-cli`, `ffmpeg`, and `ffprobe`. Check the output before mining, since speech recognition makes mistakes over music and overlapping voices. See [Subtitle generation](/subtitle-generation) for models, timing references, and settings. -**App-wide shortcuts:** +## Windows mpv shortcut -| Keybind | Action | Scope | -| ------------- | ---------------------- | -------------------------------------------------------------------------------------------------- | -| `Alt+Shift+O` | Toggle visible overlay | Works while the overlay or mpv has focus (configurable via `shortcuts.toggleVisibleOverlayGlobal`) | -| `Alt+Shift+Y` | Open active dictionary settings | OS-global - registered with the system, works from any window | +First-run setup can create a **SubMiner mpv** shortcut in the Start menu and on the desktop. It is the easiest way to play local files on Windows: -`Alt+Shift+Y` is fixed and not configurable. All other shortcuts can be changed under `shortcuts` in your config. +- Double-click it to open mpv with SubMiner attached. +- Drag a video onto it to play that file. +- Run it from a terminal: -Useful overlay-local default keybinding: `Ctrl+Alt+P` opens the playlist browser for the current video's parent directory and the live mpv queue so you can append, reorder, remove, or jump between episodes without leaving playback. +```powershell +& "C:\Program Files\SubMiner\SubMiner.exe" --launch-mpv "C:\Videos\episode 01.mkv" +``` -Press `V` to cycle the primary SubMiner subtitle bar through hidden → visible → hover modes. The bundled mpv plugin also binds bare `v` to the same action (injected at runtime). +mpv must be on `PATH`, or `mpv.executablePath` must point to `mpv.exe`. The `subminer` terminal command also works on Windows if you installed it during setup. -`Ctrl/Cmd+/` opens the session help modal with the current overlay and mpv keybindings. The same help view is also available through the `y-h` chord in mpv. +## Tray menu -The changelog modal (tray > `View Changelog`) works the same way: it renders over mpv when a video is playing and in its own window otherwise. Use `J`/`K` or the arrow keys to move between versions, `Enter` to fold or unfold one, `R` to refetch, and `Esc` to close. +The tray icon gives you: -Hovering over subtitle text pauses mpv by default; leaving resumes it. Yomitan popups also pause playback by default. Set `subtitleStyle.autoPauseVideoOnHover: false` or `subtitleStyle.autoPauseVideoOnYomitanPopup: false` to disable either behavior. +- **Export Logs**: saves a log ZIP and shows its path. Usernames, IP addresses, emails, tokens, passwords, and cookies are masked in the exported copy. Your log files on disk stay unchanged. +- **View Changelog**: release notes, including versions newer than yours. Use `J`/`K` to move between versions, `Enter` to expand one, and `Esc` to close. +- **Sync Stats & History**: opens the [sync window](/launcher-script#sync-between-machines). +- **Jellyfin Discovery**: turns cast discovery on or off for this session, once [Jellyfin](/jellyfin-integration) is set up. -### Drag-and-drop +On Wayland, the tray icon only appears if your panel provides a StatusNotifier (AppIndicator) tray. -- Drop video files onto the overlay to replace current playback. -- Hold `Shift` while dropping to append to the playlist instead. -- Drop subtitle files onto the overlay to load them as a new subtitle track. +## Controller support {#controller-support} -Next: [Mining Workflow](/mining-workflow) - word lookup, card creation, and the full mining loop. +You can drive the overlay with a gamepad. + +1. Set `controller.enabled` to `true` in your config. +2. Connect a controller. SubMiner uses the first one it sees. +3. Press `Y` on the controller to turn on keyboard-only mode. The controller only works in this mode. +4. Move between words with the left stick, press `A` to look one up, and `X` to mine it. + +Press `Alt+C` to choose a controller and remap buttons. Click an action's **Learn** button, then press the button you want. `Alt+Shift+C` shows raw input values for unusual pads. + +| Button | Action | +| --------------------- | ------------------------------------ | +| `A` (South) | Look up the selected word | +| `B` (East) | Close the lookup | +| `X` (West) | Mine a card | +| `Y` (North) | Toggle keyboard-only mode | +| `L1` | Play the current Yomitan audio | +| `R1` | Next Yomitan audio source | +| `L3` | Pause or resume mpv | +| `Select` / `Minus` | Quit mpv | +| Left stick | Move between words, scroll the popup | +| Right stick (up/down) | Jump through the popup | + +On controllers that report the W3C standard layout, the default quit button lands on `L2` instead of `Select`. Remap it with `Alt+C`. All options are in [Configuration](/configuration#controller-support). + +## Changing settings while you watch + +SubMiner watches your config file and applies most changes without a restart, including subtitle style, keybindings, and most Anki settings. If a change needs a restart, SubMiner tells you. If the file has an error, it keeps the last working config and shows a notification. See [Configuration](/configuration). + +Next: [Mining workflow](/mining-workflow). diff --git a/docs-site/websocket-texthooker-api.md b/docs-site/websocket-texthooker-api.md index 852748e4..133e3bbc 100644 --- a/docs-site/websocket-texthooker-api.md +++ b/docs-site/websocket-texthooker-api.md @@ -1,72 +1,49 @@ # WebSocket and texthooker API -This page is for people wiring SubMiner's live subtitle stream into their own tools: a browser tab, an automation script, another mpv plugin. If you only want subtitles in a browser tab for Yomitan, jump to [Texthooker Integration Guide](#texthooker-integration-guide). Everything else here is reference for building a client. +SubMiner streams the current subtitle over local WebSockets and serves a texthooker page, so browser tools and your own scripts can follow along. This page is the reference for building a client. If you only want subtitles in a browser tab for Yomitan, see [Texthooker page](#texthooker-integration-guide). -A *texthooker* is a page/tool that receives the text currently on screen so a dictionary extension (like Yomitan) can look words up. SubMiner ships its own texthooker UI and also broadcasts subtitle text over local WebSockets that any client can connect to. +| Surface | Default | Purpose | +| --------------------- | --------------------------- | ----------------------------------------------------- | +| `websocket` | `ws://127.0.0.1:6677` | Plain subtitle text | +| `annotationWebsocket` | `ws://127.0.0.1:6678` | Subtitle text plus token metadata and rendered HTML | +| `texthooker` | `http://127.0.0.1:5174` | Bundled texthooker page, preconfigured for your setup | +| mpv plugin | `script-message subminer-*` | Start, stop, toggle, and status automation inside mpv | -SubMiner opens four local integration points: +All servers bind to `127.0.0.1` only. There is no authentication. -- **Subtitle WebSocket** at `ws://127.0.0.1:6677` by default for plain subtitle pushes. -- **Annotation WebSocket** at `ws://127.0.0.1:6678` by default for token-aware clients. -- **Texthooker HTTP UI** at `http://127.0.0.1:5174` by default for browser-based subtitle consumption. -- **mpv plugin script messages** for in-player automation and extension. +## Enable the services -The rest of this page documents each one and shows how to build a consumer for it. - -## Quick reference - -| Surface | Default | Purpose | -| --- | --- | --- | -| `websocket` | `ws://127.0.0.1:6677` | Basic subtitle broadcast stream | -| `annotationWebsocket` | `ws://127.0.0.1:6678` | Structured stream with token metadata | -| `texthooker` | `http://127.0.0.1:5174` | Local texthooker UI with injected websocket config | -| mpv plugin | `script-message subminer-*` | Start/stop/toggle/status automation inside mpv | - -## Enable and configure the services - -SubMiner's integration ports are configured in `config.jsonc`. All three services are **off by default** - the block below shows the values to set to turn them on. +All three services are off by default. Turn on the ones you need in `config.jsonc`: ```jsonc { "websocket": { "enabled": "auto", - "port": 6677 + "port": 6677, }, "annotationWebsocket": { "enabled": true, - "port": 6678 + "port": 6678, }, "texthooker": { "launchAtStartup": true, - "openBrowser": false - } + "openBrowser": false, + }, } ``` -### How startup behaves +- `websocket.enabled`: `true` always starts the plain stream. `"auto"` starts it unless the external `mpv_websocket` plugin is installed at `~/.config/mpv/mpv_websocket`. +- `annotationWebsocket.enabled`: starts the annotated stream. It is independent of `websocket`. +- `texthooker.launchAtStartup`: starts the texthooker page with the app. +- `texthooker.openBrowser`: opens the page in your browser when it starts. -- `websocket.enabled` defaults to `false`. Set it to `"auto"` to start the basic subtitle websocket unless SubMiner detects the external `mpv_websocket` plugin, or `true` to always start it. -- `annotationWebsocket.enabled` defaults to `false` and is independent from `websocket`. Set it to `true` to start the annotated stream. -- `texthooker.launchAtStartup` defaults to `false`. Set it to `true` to start the local HTTP UI automatically. -- `texthooker.openBrowser` controls whether SubMiner opens the texthooker page in your browser when it starts. +See [Configuration](/configuration) for all related options. -If you use the [mpv plugin](/mpv-plugin), it can also start a texthooker-only helper process. The launcher derives the plugin's texthooker setting from your SubMiner config (`texthooker.launchAtStartup`) and injects it at runtime - there is no plugin config file to edit. +## Subtitle WebSocket -## Developer API documentation +`ws://127.0.0.1:6677`. Use it when you only need the current line as text. -### 1. subtitle WebSocket - -Use the basic subtitle websocket when you only need the current subtitle line as plain text. - -- **Default URL:** `ws://127.0.0.1:6677` -- **Transport:** local WebSocket server bound to `127.0.0.1` -- **Direction:** server push only -- **Client auth:** none -- **Reconnects:** client-managed - -When a client connects, SubMiner immediately sends the latest subtitle payload if one is available. After that, it pushes a new message each time the current subtitle changes. Annotation-only upgrades do not repeat the same line on this basic stream. - -#### Message shape +The server pushes only; it ignores client messages. On connect it sends the latest subtitle if there is one, then a new message each time the subtitle changes. Reconnecting is up to the client. ```json { @@ -77,28 +54,18 @@ When a client connects, SubMiner immediately sends the latest subtitle payload i } ``` -#### Field reference +| Field | Type | Notes | +| ---------- | ------ | ------------------------------------------------------------------ | +| `version` | number | Payload version, currently `1` | +| `text` | string | Raw subtitle text | +| `sentence` | string | HTML-escaped text with line breaks as `<br>`, no annotation markup | +| `tokens` | array | Always empty on this stream | -| Field | Type | Notes | -| --- | --- | --- | -| `version` | number | Current websocket payload version. Today this is `1`. | -| `text` | string | Raw subtitle text. | -| `sentence` | string | Plain subtitle text with line breaks represented as `<br>`. No annotation spans or attributes. | -| `tokens` | array | Always empty on the basic subtitle websocket. | +## Annotation WebSocket -### 2. annotation WebSocket +`ws://127.0.0.1:6678`. The same token data the bundled texthooker uses. Prefer this stream for new clients. It keeps running when the plain stream is auto-disabled by `mpv_websocket`. -Use the annotation websocket for custom clients that want the same structured token payload the bundled texthooker UI consumes. - -- **Default URL:** `ws://127.0.0.1:6678` -- **Payload shape:** JSON payload with `text`, rendered `sentence` HTML, and token metadata -- **Primary difference:** this stream is intended to stay on even when the basic websocket auto-disables because `mpv_websocket` is installed - -In practice, if you are building a new client, prefer `annotationWebsocket` unless you specifically need compatibility with an existing `websocket` consumer. - -On a tokenization cache miss, this stream first sends the cue as plain text with an empty `tokens` array, then sends the annotated replacement when tokenization finishes. Treat each message as the complete current state, replacing the previous payload. - -#### Message shape +When a line is not yet tokenized, the stream first sends it with an empty `tokens` array, then sends the annotated version when tokenization finishes. Treat each message as the complete current state and replace the previous one. The plain stream does not repeat the line for this upgrade. ```json { @@ -127,79 +94,48 @@ On a tokenization cache miss, this stream first sends the cue as plain text with } ``` -Each annotation token may include: +| Token field | Type | Notes | +| --------------------- | ---------------- | ------------------------------------------------------------------------------ | +| `surface` | string | Display text | +| `reading` | string | Kana reading when available | +| `headword` | string | Dictionary headword when available | +| `startPos` / `endPos` | number | Character offsets in `text` | +| `partOfSpeech` | string | SubMiner part-of-speech label | +| `isMerged` | boolean | Token was merged from several parser tokens | +| `isKnown` | boolean | Word is known | +| `isNPlusOneTarget` | boolean | Token is the line's N+1 target | +| `isNameMatch` | boolean | Token matched a character name | +| `frequencyRank` | number | Frequency rank; omitted when unavailable or a name match | +| `jlptLevel` | string | JLPT level; omitted when unavailable or a name match | +| `className` | string | CSS class list for the token | +| `frequencyRankLabel` | string or `null` | Rank label, set only when the rank is within your frequency highlight settings | +| `jlptLevelLabel` | string or `null` | JLPT label for display | -| Token field | Type | Notes | -| --- | --- | --- | -| `surface` | string | Display text for the token | -| `reading` | string | Kana reading when available | -| `headword` | string | Dictionary headword when available | -| `startPos` / `endPos` | number | Character offsets in the subtitle text | -| `partOfSpeech` | string | SubMiner token POS label | -| `isMerged` | boolean | Whether this token represents merged content | -| `isKnown` | boolean | Marked known by SubMiner's known-word logic | -| `isNPlusOneTarget` | boolean | True when the token is the sentence's N+1 target | -| `isNameMatch` | boolean | True for prioritized character-name matches | -| `frequencyRank` | number | Frequency rank when available | -| `jlptLevel` | string | JLPT level when available | -| `className` | string | CSS-ready class list derived from token state | -| `frequencyRankLabel` | string or `null` | Preformatted rank label for UIs | -| `jlptLevelLabel` | string or `null` | Preformatted JLPT label for UIs | +### HTML markup -### 3. HTML markup conventions +`sentence` is HTML rendered by SubMiner. Each token is a `<span>` with these classes as they apply: -The `sentence` field is pre-rendered HTML generated by SubMiner. Depending on token state, it can include classes such as: - -- `word` -- `word-known` -- `word-n-plus-one` -- `word-name-match` +- `word` on every token +- one of `word-name-match`, `word-n-plus-one`, or `word-known` - `word-jlpt-n1` through `word-jlpt-n5` -- `word-frequency-single` -- `word-frequency-band-1` through `word-frequency-band-5` +- `word-frequency-single`, or `word-frequency-band-1` through `word-frequency-band-5`, on words that are not known, N+1, or names -SubMiner also adds tooltip-friendly data attributes when available: +Spans also carry `data-reading`, `data-headword`, `data-frequency-rank`, and `data-jlpt-level` when available. For a fully custom UI, ignore `sentence` and render from `tokens`. -- `data-reading` -- `data-headword` -- `data-frequency-rank` -- `data-jlpt-level` +## Texthooker page {#texthooker-integration-guide} -If you need a fully custom UI, ignore `sentence` and render from `tokens` instead. - -## Texthooker integration guide - -### When to use the bundled texthooker page - -Use texthooker when you want a browser tab that: - -- updates live from current subtitles -- works well with browser-based Yomitan setups -- inherits SubMiner's coloring preferences and websocket URL automatically - -Start it with either: +The bundled texthooker is a browser tab that updates live with the current subtitle, works with browser Yomitan, and uses SubMiner's colors. Start it with the app (`texthooker.launchAtStartup`) or from the launcher: ```bash -subminer texthooker -# or open the page immediately -subminer texthooker -o +subminer texthooker # start the texthooker +subminer texthooker -o # start it and open the browser ``` -or by leaving `texthooker.launchAtStartup` enabled. +SubMiner injects the page's settings into `window.localStorage` when it serves it: the WebSocket URL (`bannou-texthooker-websocketUrl`), the known, N+1, name, frequency, and JLPT coloring toggles, and CSS custom properties for the token colors. The page connects to the annotation stream if it is enabled, otherwise to the plain stream. With neither running, it has nothing to connect to. -### What SubMiner injects into the page +## Build a client -When SubMiner serves the local texthooker UI, it injects bootstrap values into `window.localStorage`, including: - -- `bannou-texthooker-websocketUrl` -- coloring toggles for known/N+1/name/frequency/JLPT styling -- CSS custom properties for SubMiner's token colors - -That means the bundled page already knows which websocket to connect to and which color palette to use. - -### Build a custom websocket client - -Here is a minimal browser client for the annotation stream: +A minimal browser client for the annotation stream: ```html <!doctype html> @@ -221,7 +157,7 @@ Here is a minimal browser client for the annotation stream: </script> ``` -### Build a custom node client +A Node client: ```js import WebSocket from 'ws'; @@ -238,112 +174,15 @@ ws.on('message', (raw) => { }); ``` -### Integration tips +Tips: -- Bind only to `127.0.0.1`; these services are local-only by design. -- Handle empty `tokens` arrays gracefully because subtitle text can arrive before tokenization completes. -- Reconnect on disconnect; SubMiner does not manage client reconnects for you. -- Prefer `payload.text` for logging/automation and `payload.sentence` or `payload.tokens` for UI rendering. +- Handle empty `tokens` arrays. Text can arrive before tokenization finishes. +- Reconnect on disconnect yourself. +- Use `text` for logging and automation, and `sentence` or `tokens` for display. -## Plugin development +### Forward lines to a webhook -SubMiner does **not** currently expose a general-purpose third-party plugin SDK inside the app itself. Today, the supported extension surfaces are: - -1. the local websocket streams -2. the local texthooker UI -3. the mpv Lua plugin's script-message API -4. the launcher CLI - -### mpv script messages - -The mpv plugin accepts these script messages: - -```text -script-message subminer-start -script-message subminer-stop -script-message subminer-toggle -script-message subminer-menu -script-message subminer-options -script-message subminer-restart -script-message subminer-status -script-message subminer-autoplay-ready -script-message subminer-stats-toggle -script-message subminer-visible-overlay-shown -script-message subminer-visible-overlay-hidden -script-message subminer-managed-subtitles-loading -script-message subminer-overlay-loading-ready -script-message subminer-reload-session-bindings -``` - -The overlay/loading/session-binding messages are primarily sent by the SubMiner app to keep the plugin's state in sync. The AniSkip messages (`subminer-skip-intro`, `subminer-aniskip-refresh`) are handled by the SubMiner app over the mpv IPC socket while it is connected. - -The start command also accepts inline overrides: - -```text -script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug -``` - -### Practical extension patterns - -#### Add another mpv script that coordinates with SubMiner - -Examples: - -- send `subminer-start` after your own media-selection script chooses a file -- send `subminer-status` before running follow-up automation -- send `subminer-aniskip-refresh` after you update title/episode metadata (handled by the SubMiner app) - -#### Build a launcher wrapper - -Examples: - -- open a media picker, then call `subminer /path/to/file.mkv` -- launch browser-only subtitle tooling with `subminer texthooker -o` -- disable the helper UI for a session with `subminer --no-texthooker video.mkv` - -#### Build an overlay-adjacent client - -Examples: - -- browser widget showing current subtitle + token breakdown -- local vocabulary capture helper that writes interesting lines to a file -- bridge service that forwards websocket events into your own workflow engine - -## Webhook examples - -SubMiner does **not** currently send outbound webhooks by itself. The supported pattern is to consume the websocket locally and relay events into another system. - -That still makes webhook-style automation straightforward. - -### Example: forward subtitle lines to a local webhook receiver - -```js -import WebSocket from 'ws'; - -const ws = new WebSocket('ws://127.0.0.1:6678'); - -ws.on('message', async (raw) => { - const payload = JSON.parse(String(raw)); - - await fetch('http://127.0.0.1:5678/subminer/subtitle', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - text: payload.text, - tokens: payload.tokens, - receivedAt: new Date().toISOString(), - }), - }); -}); -``` - -### Automation ideas - -- **n8n / Make / Zapier relay:** send each subtitle line into an automation workflow for logging, translation, or summarization. -- **Discord / Slack notifier:** post only lines that contain unknown words or N+1 targets. -- **Obsidian / Markdown capture:** append subtitle lines plus token metadata to a daily immersion note. - -### Filtering example: only forward N+1 lines +SubMiner does not send webhooks itself. Relay the stream to your own endpoint instead. This example forwards only lines that contain an N+1 target: ```js import WebSocket from 'ws'; @@ -353,7 +192,6 @@ const ws = new WebSocket('ws://127.0.0.1:6678'); ws.on('message', async (raw) => { const payload = JSON.parse(String(raw)); const hasNPlusOne = payload.tokens.some((token) => token.isNPlusOneTarget); - if (!hasNPlusOne) return; await fetch('http://127.0.0.1:5678/subminer/n-plus-one', { @@ -364,18 +202,39 @@ ws.on('message', async (raw) => { }); ``` -## Recommended integration combinations +The same pattern works for n8n or Zapier workflows, Discord notifiers, or appending lines to a notes file. -- **Browser Yomitan client:** `texthooker` + `annotationWebsocket` -- **Custom dashboard:** `annotationWebsocket` only -- **Lightweight subtitle mirror:** `websocket` only -- **mpv-side automation:** mpv plugin script messages + optional websocket relay -- **Webhook-style workflows:** `annotationWebsocket` + your own local relay service +## mpv script messages + +SubMiner has no in-app plugin SDK. Besides the streams above, you can drive it from other mpv scripts and from the [launcher CLI](/launcher-script). + +The mpv plugin accepts these script messages: + +| Message | Action | +| ----------------------- | ------------------------------------------ | +| `subminer-start` | Start the overlay | +| `subminer-stop` | Stop the overlay | +| `subminer-toggle` | Toggle the visible overlay | +| `subminer-menu` | Open the plugin menu | +| `subminer-options` | Open the SubMiner settings window | +| `subminer-restart` | Restart the overlay | +| `subminer-status` | Show overlay status on the mpv OSD | +| `subminer-stats-toggle` | Show an OSD hint for the overlay stats key | + +`subminer-start` accepts overrides for `backend` (`auto`, `hyprland`, `sway`, `x11`, `macos`), `socket`, `texthooker`, and `log-level`: + +```text +script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug +``` + +The plugin also registers `subminer-autoplay-ready`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts. + +While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro, and `subminer-aniskip-refresh` reloads intro data, for example after your script changes title or episode metadata. ## Related pages -- [Configuration](/configuration#websocket-server) -- [Mining Workflow - Texthooker](/mining-workflow#texthooker) -- [MPV Plugin](/mpv-plugin) -- [Launcher Script](/launcher-script) -- [Anki Integration](/anki-integration#proxy-mode-setup-yomitan-texthooker) +- [Configuration](/configuration) +- [Mining workflow](/mining-workflow) +- [mpv plugin](/mpv-plugin) +- [Launcher script](/launcher-script) +- [Anki integration](/anki-integration) diff --git a/docs-site/youtube-integration.md b/docs-site/youtube-integration.md index a9c48df6..8017cccb 100644 --- a/docs-site/youtube-integration.md +++ b/docs-site/youtube-integration.md @@ -1,162 +1,63 @@ # YouTube integration -Play a YouTube URL and SubMiner loads Japanese subtitles for it, so mining works the same as it does on a local file. It probes the available tracks with `yt-dlp`, picks a primary and a secondary, downloads both, and loads them into mpv before playback resumes. +Play a YouTube URL and SubMiner downloads its Japanese subtitles and loads them into mpv, so you can mine from it like a local file. -## Requirements +## Setup -- **[yt-dlp](https://github.com/yt-dlp/yt-dlp)** must be installed and on your `PATH`. yt-dlp is a free command-line tool that reads YouTube video and subtitle info; SubMiner calls it behind the scenes. (`PATH` is the list of folders your system searches for programs - most installers add yt-dlp to it automatically. If yours did not, set `SUBMINER_YTDLP_BIN` to the full path of the yt-dlp binary.) -- mpv with `--input-ipc-server` configured (handled automatically when you launch playback through the `subminer` launcher - no manual setup needed). +Install [yt-dlp](https://github.com/yt-dlp/yt-dlp) and make sure it is on your `PATH`. If it is somewhere else, set `SUBMINER_YTDLP_BIN` to the full path of the binary. -## How it works +## Usage -When SubMiner detects a YouTube URL (or `ytsearch:` target), it pauses mpv at startup and runs a subtitle pipeline before resuming playback: - -1. **Probe** - `yt-dlp --dump-single-json` extracts all available subtitle tracks (manual uploads and auto-generated captions) along with video metadata. Every yt-dlp call passes `--no-playlist`, so playlist links (for example a Watch Later URL with `list=`/`index=`) resolve to the single video instead of the whole playlist. -2. **Discover** - Each track is normalized into a `YoutubeTrackOption` with language code, kind (`manual` or `auto`), display label, and direct download URL. -3. **Select** - SubMiner picks the best primary track (Japanese, preferring manual over auto) and secondary track (English, preferring manual over auto). -4. **Download** - Selected tracks are fetched via direct URL when available, falling back to `yt-dlp --write-subs` / `--write-auto-subs`. YouTube TimedText XML formats (`srv1`/`srv2`/`srv3`) are converted to VTT on the fly. Auto-generated VTT captions are normalized to remove rolling-caption duplication. -5. **Load** - Subtitle files are injected into mpv via `sub-add`. Playback resumes once the primary track is ready; secondary failures do not block. - -## Pipeline diagram - -```mermaid -flowchart TD - classDef step fill:#c6a0f6,stroke:#494d64,color:#24273a - classDef action fill:#8aadf4,stroke:#494d64,color:#24273a - classDef result fill:#a6da95,stroke:#494d64,color:#24273a - classDef enrich fill:#8bd5ca,stroke:#494d64,color:#24273a - classDef ext fill:#eed49f,stroke:#494d64,color:#24273a - - A[YouTube URL detected]:::step - B[yt-dlp probe]:::ext - C[Track discovery]:::action - D{Auto or manual selection?}:::step - E[Auto-select best tracks]:::action - F[Manual picker - Ctrl+Alt+C]:::action - G[Download subtitle files]:::action - H[Convert TimedText to VTT]:::enrich - I[Normalize auto-caption duplicates]:::enrich - K[sub-add into mpv]:::action - L[Overlay renders subtitles]:::result - - A --> B - B --> C - C --> D - D - startup --> E - D - user request --> F - E --> G - F --> G - G --> H - H --> I - I --> K - K --> L +```bash +subminer https://www.youtube.com/watch?v=VIDEO_ID +subminer ytsearch:"keyword" # plays the first search result ``` -## Auto-load flow +mpv starts paused while SubMiner fetches the subtitle list. It picks a primary and a secondary track, loads them, and resumes playback once the primary track is ready. A playlist link plays only the linked video. -On startup with a YouTube URL: +SubMiner picks tracks in this order. Manual (uploaded) tracks win over auto-generated captions. -1. mpv launches paused. -2. SubMiner calls `yt-dlp --dump-single-json` to probe all subtitle tracks. -3. Tracks are split into **manual** (human-uploaded) and **auto** (machine-generated) categories. -4. The selection algorithm picks: - - **Primary**: first Japanese manual track, then Japanese auto track, then any manual track, then first available track. - - **Secondary**: first English manual track, then English auto track (excluding the primary). -5. If mpv already exposes an authoritative matching track, SubMiner reuses it instead of downloading again. -6. Missing tracks are downloaded to a temp directory and loaded via `sub-add`. -7. Playback unpauses once the primary subtitle is ready. +| Track | Choice | +| --------- | -------------------------------------------------------------------------------- | +| Primary | Japanese manual, then Japanese auto, then any manual track, then the first track | +| Secondary | English manual, then English auto. Skipped if none exists. | -## Manual subtitle picker +Press `Ctrl+Alt+C` during playback to open the subtitle picker. It lists every track with its language and kind, and lets you choose different primary and secondary tracks or retry a failed load. -Press **Ctrl+Alt+C** during YouTube playback to open the subtitle picker overlay. This lets you: +## Secondary subtitle languages -- Browse all discovered tracks (manual and auto-generated) -- Select different primary and secondary tracks -- Retry track loading if the auto-load failed or picked the wrong track +YouTube secondary selection is fixed to English. `secondarySub.secondarySubLanguages` and `secondarySub.autoLoadSecondarySub` apply only to local files and Jellyfin. `secondarySub.defaultMode` still controls how the secondary bar is shown. Use the picker to load a different secondary language. -SubMiner shows an "Opening YouTube subtitle picker..." status through your configured notification -surface while it probes tracks and prepares the modal, then updates the subtitle download progress -card to a success notification after the selected tracks load. +Likewise, `youtube.primarySubLanguages` does not change which YouTube track is picked. It sets which languages count as a primary subtitle for local and playlist subtitle selection and for the "primary subtitle missing" notification. -The picker displays each track with its language, kind (manual/auto), and title when available. +## Card media -## Subtitle format handling - -SubMiner handles several YouTube subtitle formats transparently: - -| Format | Handling | -| ---------------------- | -------------------------------------------------------- | -| `srt`, `vtt` | Used directly (preferred for manual tracks) | -| `srv1`, `srv2`, `srv3` | YouTube TimedText XML - converted to VTT automatically | -| Auto-generated VTT | Normalized to remove rolling-caption text duplication | - -For auto-generated tracks, SubMiner prefers `srv3` > `srv2` > `srv1` > `vtt` (TimedText XML produces cleaner output). For manual tracks, `srt` > `vtt` is preferred. - -## Card media cache - -By default, YouTube card audio and screenshots are extracted directly from mpv's active stream URLs. If generated card media fails with YouTube `403` errors, set `youtube.mediaCache.mode` to `"background"`. Background mode starts a separate `yt-dlp` media download after playback loads, including YouTube URLs opened directly in mpv and resolved stream URLs when mpv still exposes the original YouTube playlist entry. It creates text fields immediately, queues audio/image work for mined notes, and fills those fields once the local cache file is ready. - -Background cache downloads are capped at 720p by default (`youtube.mediaCache.maxHeight`; set `0` for unlimited) and use IPv4 and retry flags to reduce YouTube throttling failures. If the background download still fails, SubMiner shows a cache failure notification, shows queued-card failure notifications, and clears those pending updates so cards are not left waiting silently. - -## Configuration reference - -### Primary subtitle languages +By default, card audio and screenshots are cut from mpv's live YouTube stream. If card media fails with `403` errors, switch to the background cache: ```jsonc { "youtube": { - "primarySubLanguages": ["ja", "jpn"], + "mediaCache": { "mode": "background" }, }, } ``` -| Option | Type | Description | -| --------------------- | ---------- | ------------------------------------------------------------------------------------- | -| `primarySubLanguages` | `string[]` | Languages that count as a satisfactory primary subtitle (default `["ja", "jpn"]`). Used by the "primary subtitle missing" notification and by managed local/playlist subtitle selection. | +In background mode, SubMiner downloads the video with yt-dlp after playback starts. Cards you mine get their text fields right away, and audio and images are added once the download finishes. `youtube.mediaCache.maxHeight` caps the download resolution (`0` for no limit). If the download fails, SubMiner tells you and drops the pending media updates. -YouTube auto-selection itself always picks a Japanese track first (manual over auto), then falls back to any manual track. `primarySubLanguages` does not change which YouTube track is auto-picked. +See [Configuration](/configuration#youtube-playback-settings) for all `youtube` options and defaults. -### Secondary subtitle languages +## Troubleshooting -YouTube secondary selection is fixed: SubMiner always tries an English track (manual over auto) and loads it when found. The shared `secondarySub` config does not change YouTube track selection. `secondarySubLanguages` and `autoLoadSecondarySub` apply only to local and Jellyfin sidecar selection. `defaultMode` still controls how the loaded secondary bar is displayed: +**No Japanese subtitles.** The video may not have any. Open the picker with `Ctrl+Alt+C` to see what is available. -```jsonc -{ - "secondarySub": { - "secondarySubLanguages": [], - "autoLoadSecondarySub": false, - "defaultMode": "hover", - }, -} -``` +**yt-dlp not found.** Install it and put it on `PATH`, or set `SUBMINER_YTDLP_BIN`. -| Option | Type | Description | -| ----------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `secondarySubLanguages` | `string[]` | Extra language codes (e.g. `["eng", "en"]`) used when auto-selecting a secondary track for local/Jellyfin sidecar files. Default is empty (`[]`). Not used for YouTube. | -| `autoLoadSecondarySub` | `boolean` | Auto-detect and load a matching secondary sidecar track for local files (default: `false`). Not used for YouTube. | -| `defaultMode` | `"hidden"` / `"visible"` / `"hover"` | Initial display mode for secondary subtitles (default: `"hover"`) | +**Timeouts.** Each yt-dlp call times out after 15 seconds. Slow or rate-limited connections can hit this. Retry, or update yt-dlp. -These settings come from `config.jsonc` (or built-in defaults); there are no CLI flags or environment variables for subtitle language selection. +**Poor subtitle quality.** Auto-generated captions are often inaccurate. SubMiner uses a manual track when one exists. -## Limitations and troubleshooting +A missing or failed secondary track never blocks playback. -- **No subtitles found**: The video may not have Japanese subtitles. Open the picker with `Ctrl+Alt+C` to see all available tracks. -- **yt-dlp not found**: Install `yt-dlp` and put it on `PATH`, or set `SUBMINER_YTDLP_BIN` to the binary path. -- **Probe timeout**: `yt-dlp` has a 15-second timeout per operation. Slow connections or rate-limited IPs may hit this. Retry or update `yt-dlp`. -- **Card media `403` errors**: Switch `youtube.mediaCache.mode` from `"direct"` to `"background"` so card media is generated from a local `yt-dlp` cache instead of ffmpeg reading an expiring YouTube stream URL. -- **Auto-caption quality**: YouTube auto-generated captions vary in quality. Manual subtitles (when available) are always preferred. -- **`ytsearch:` targets**: `subminer ytsearch:"keyword"` plays the first search result. Subtitle availability depends on the matched video. -- **Secondary subtitle fails**: Secondary track failures never block playback. The primary subtitle loads independently. -- **Native mpv secondary rendering**: Stays hidden during YouTube flows so the SubMiner overlay remains the visible secondary subtitle surface. +## Stats -## Viewing stats - -The stats Library groups tracked YouTube videos by channel when channel metadata is available. Select **YouTube** in the Library filter to see those channels separately from anime. Each channel page lists its videos, watch time, vocabulary, and mined cards. See [Immersion Tracking](/immersion-tracking#library). - -## Related pages - -- [Usage - YouTube Playback](/usage#youtube-playback) -- [Configuration - YouTube Playback Settings](/configuration#youtube-playback-settings) -- [Configuration - Secondary Subtitles](/configuration#secondary-subtitles) -- [Keyboard Shortcuts](/shortcuts) -- [Jellyfin Integration](/jellyfin-integration) +The stats Library groups YouTube videos by channel. Choose **YouTube** in the Library filter to see them. See [Immersion tracking](/immersion-tracking). diff --git a/scripts/build-versioned-docs.ts b/scripts/build-versioned-docs.ts index 012de33f..a6bbf24f 100644 --- a/scripts/build-versioned-docs.ts +++ b/scripts/build-versioned-docs.ts @@ -1,49 +1,52 @@ import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; import { cpSync, existsSync, lstatSync, mkdirSync, - readFileSync, readdirSync, - readlinkSync, rmSync, symlinkSync, writeFileSync, } from 'node:fs'; import { join, resolve } from 'node:path'; import { - collectSharedAssetPaths, - dedupeVersionedPublicAssets, - pruneArchiveCacheGenerations, -} from './docs-versioned-assets'; + archiveStoreEnvFromProcess, + createArchiveStore, + type DocsArchiveStore, +} from './docs-archive-store'; +import { collectSharedAssetPaths, dedupeVersionedPublicAssets } from './docs-versioned-assets'; import { buildVersionManifest, + renderVersionsPage, stableTagsWithDocs, - versionArchiveCacheKey, - versionArchiveCacheName, versionOutputPath, versionPath, } from './docs-versioning'; +// Assembles the Cloudflare Pages deployment: latest stable at `/` and development docs +// at `/main/`. Stable archives under `/v/<version>/` are built once, uploaded to R2, and +// never rebuilt unless requested; this script only fills in archives R2 is missing. +// +// Flags: +// --require-archives fail instead of skipping archive sync without R2 credentials +// --rebuild-archives=<list> comma-separated tags (or `all`) to rebuild even if present + const repoRoot = resolve(__dirname, '..'); const currentDocsSite = join(repoRoot, 'docs-site'); const buildRoot = join(repoRoot, '.tmp/docs-versioned-build'); const aggregateOutDir = join(repoRoot, '.tmp/docs-versioned-site'); -const archiveCacheRoot = join(repoRoot, '.tmp/docs-versioned-archive-cache'); +const archiveOutRoot = join(repoRoot, '.tmp/docs-versioned-archives'); const maxCloudflareFiles = 20_000; const maxCloudflareFileBytes = 25 * 1024 * 1024; -// Cloudflare Pages header rules for the whole deployment. Mirrors the `noindex,follow` -// meta tag the non-root channels emit, so the duplicate trees stay out of the index -// even for responses a crawler takes without parsing the HTML. +// Cloudflare Pages header rules for the static deployment. Mirrors the `noindex,follow` +// meta tag the `main` channel emits, so the duplicate tree stays out of the index even +// for responses a crawler takes without parsing the HTML. `/v/*` is served by the +// archive Pages Function, which sets the same header itself. const deployHeaders = `# Generated by scripts/build-versioned-docs.ts. Do not edit by hand. /main/* X-Robots-Tag: noindex, follow - -/v/* - X-Robots-Tag: noindex, follow `; function run( @@ -103,8 +106,7 @@ function copyCurrentDocsSite(targetDir: string) { recursive: true, dereference: false, filter: (source) => - !/[\\/]node_modules([\\/]|$)/.test(source) && - !/[\\/]\\.vitepress[\\/]dist([\\/]|$)/.test(source), + !/[\\/]node_modules([\\/]|$)/.test(source) && !isGeneratedVitePressPath(source), }); } @@ -173,8 +175,6 @@ function buildDocs(options: { outDir: string; channel: string; version?: string; - latestStable: string; - manifestJson: string; }) { console.info(`[docs] building ${options.version ?? options.channel} -> ${options.base}`); run('bun', ['run', '--cwd', currentDocsSite, 'vitepress', 'build', options.snapshotDocsSite], { @@ -187,98 +187,13 @@ function buildDocs(options: { SUBMINER_DOCS_REPO_DIR: currentDocsSite, SUBMINER_DOCS_CHANNEL: options.channel, SUBMINER_DOCS_VERSION: options.version ?? '', - SUBMINER_DOCS_LATEST_STABLE: options.latestStable, - SUBMINER_DOCS_VERSION_MANIFEST: options.manifestJson, VITE_EXTRA_EXTENSIONS: 'jsonc', }, }); } -function updateHashWithPath(hash: ReturnType<typeof createHash>, path: string) { - if (isSharedInternalsHashIgnoredPath(path)) { - return; - } - - const stat = lstatSync(path); - const relativePath = path.replace(repoRoot, ''); - - if (stat.isSymbolicLink()) { - hash.update(`symlink:${relativePath}`); - hash.update(readlinkSync(path)); - return; - } - - if (stat.isDirectory()) { - hash.update(`dir:${relativePath}`); - for (const entry of readdirSync(path).sort()) { - updateHashWithPath(hash, join(path, entry)); - } - return; - } - - hash.update(`file:${relativePath}`); - hash.update(readFileSync(path)); -} - function isGeneratedVitePressPath(path: string): boolean { - return /[\\/]\\.vitepress[\\/](cache|dist)([\\/]|$)/.test(path); -} - -function isSharedInternalsHashIgnoredPath(path: string): boolean { - return isGeneratedVitePressPath(path) || /\.test\.[cm]?[jt]s$/.test(path); -} - -function computeSharedInternalsHash(): string { - const hash = createHash('sha256'); - hash.update( - `version-link-origin:${process.env.SUBMINER_DOCS_VERSION_LINK_ORIGIN === 'local' ? 'local' : 'production'}`, - ); - const paths = [ - join(currentDocsSite, '.vitepress'), - join(currentDocsSite, 'public/assets/fonts'), - join(currentDocsSite, 'package.json'), - join(currentDocsSite, 'bun.lock'), - join(repoRoot, 'scripts/build-versioned-docs.ts'), - join(repoRoot, 'scripts/docs-versioning.ts'), - ]; - - for (const path of paths) { - if (existsSync(path)) { - updateHashWithPath(hash, path); - } - } - - return hash.digest('hex'); -} - -function archiveCachePath(version: string, sharedInternalsHash: string): string { - return join(archiveCacheRoot, versionArchiveCacheName(version, sharedInternalsHash)); -} - -function restoreCachedArchive(version: string, sharedInternalsHash: string): boolean { - const cachedArchive = archiveCachePath(version, sharedInternalsHash); - if (!existsSync(cachedArchive)) { - return false; - } - - console.info(`[docs] cache hit ${version}`); - cpSync(cachedArchive, join(aggregateOutDir, versionOutputPath(version)), { - recursive: true, - force: true, - }); - return true; -} - -function saveArchiveCache(version: string, sharedInternalsHash: string) { - const outputPath = join(aggregateOutDir, versionOutputPath(version)); - if (!existsSync(outputPath)) { - return; - } - - const cachedArchive = archiveCachePath(version, sharedInternalsHash); - rmSync(cachedArchive, { recursive: true, force: true }); - mkdirSync(archiveCacheRoot, { recursive: true }); - cpSync(outputPath, cachedArchive, { recursive: true, force: true }); + return /[\\/]\.vitepress[\\/](cache|dist)([\\/]|$)/.test(path); } function assertCloudflarePagesLimits(root: string) { @@ -317,7 +232,66 @@ function assertCloudflarePagesLimits(root: string) { } } +function currentCommit(): string { + return capture('git', ['rev-parse', 'HEAD']).trim(); +} + +function parseArgs(argv: string[]): { requireArchives: boolean; rebuild: Set<string> | 'all' } { + let requireArchives = false; + let rebuild: Set<string> | 'all' = new Set(); + for (const arg of argv) { + if (arg === '--require-archives') { + requireArchives = true; + } else if (arg.startsWith('--rebuild-archives=')) { + const value = arg.slice('--rebuild-archives='.length).trim(); + rebuild = + value === 'all' + ? 'all' + : new Set( + value + .split(',') + .map((tag) => tag.trim()) + .filter(Boolean), + ); + } else { + throw new Error(`Unknown argument: ${arg}`); + } + } + return { requireArchives, rebuild }; +} + +// Builds and uploads every stable archive that R2 does not already hold (or that was +// explicitly requested). Old tags are rendered with the current `.vitepress` overlay. +function syncArchives(options: { + store: DocsArchiveStore; + stableVersions: string[]; + rebuild: Set<string> | 'all'; +}) { + const builtFrom = currentCommit(); + for (const version of options.stableVersions) { + const forced = options.rebuild === 'all' || options.rebuild.has(version); + if (!forced && options.store.has(version)) { + continue; + } + + console.info(`[docs] building archive ${version}`); + const outDir = join(archiveOutRoot, versionOutputPath(version)); + rmSync(outDir, { recursive: true, force: true }); + buildDocs({ + snapshotDocsSite: prepareSnapshot(version, version), + base: versionPath(version), + outDir, + channel: 'stable-archive', + version, + }); + console.info(`[docs] uploading archive ${version}`); + options.store.upload(version, outDir, builtFrom); + rmSync(outDir, { recursive: true, force: true }); + } +} + function main() { + const { requireArchives, rebuild } = parseArgs(process.argv.slice(2)); const stableVersions = getStableVersions(); const latestStable = stableVersions[0]; @@ -325,54 +299,42 @@ function main() { throw new Error('No stable release tags with docs-site/package.json found.'); } + if (rebuild !== 'all') { + const unknown = [...rebuild].filter((tag) => !stableVersions.includes(tag)); + if (unknown.length > 0) { + throw new Error(`Cannot rebuild unknown stable docs versions: ${unknown.join(', ')}`); + } + } + const manifest = buildVersionManifest({ latestStable, stableVersions }); - const manifestJson = JSON.stringify(manifest); - const sharedInternalsHash = computeSharedInternalsHash(); - const archiveCacheKey = versionArchiveCacheKey({ sharedInternalsHash, manifestJson }); const sharedAssetPaths = collectSharedAssetPaths(join(currentDocsSite, 'public/assets')); - console.info(`[docs] archive cache key ${archiveCacheKey.slice(0, 12)}`); rmSync(buildRoot, { recursive: true, force: true }); rmSync(aggregateOutDir, { recursive: true, force: true }); mkdirSync(buildRoot, { recursive: true }); mkdirSync(aggregateOutDir, { recursive: true }); + const store = createArchiveStore(archiveStoreEnvFromProcess(process.env)); + if (store) { + syncArchives({ store, stableVersions, rebuild }); + } else if (requireArchives) { + throw new Error( + 'Docs archive R2 credentials are missing (CLOUDFLARE_ACCOUNT_ID, DOCS_ARCHIVE_R2_ACCESS_KEY_ID, DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY, DOCS_ARCHIVE_R2_BUCKET).', + ); + } else { + console.warn('[docs] R2 credentials not set; skipping /v/<version>/ archive sync'); + } + const latestStableSnapshot = prepareSnapshot(latestStable, latestStable); + writeFileSync(join(latestStableSnapshot, 'versions.md'), renderVersionsPage(manifest)); buildDocs({ snapshotDocsSite: latestStableSnapshot, base: '/', outDir: aggregateOutDir, channel: 'stable-root', version: latestStable, - latestStable, - manifestJson, }); - for (const version of stableVersions) { - if (restoreCachedArchive(version, archiveCacheKey)) { - continue; - } - - console.info(`[docs] rebuilding archive ${version}`); - const snapshot = - version === latestStable ? latestStableSnapshot : prepareSnapshot(version, version); - buildDocs({ - snapshotDocsSite: snapshot, - base: versionPath(version), - outDir: join(aggregateOutDir, versionOutputPath(version)), - channel: 'stable-archive', - version, - latestStable, - manifestJson, - }); - dedupeVersionedPublicAssets({ - outDir: join(aggregateOutDir, versionOutputPath(version)), - base: versionPath(version), - sharedAssetPaths, - }); - saveArchiveCache(version, archiveCacheKey); - } - const mainSnapshot = prepareSnapshot('main'); buildDocs({ snapshotDocsSite: mainSnapshot, @@ -380,8 +342,6 @@ function main() { outDir: join(aggregateOutDir, 'main'), channel: 'main', version: 'main', - latestStable, - manifestJson, }); dedupeVersionedPublicAssets({ outDir: join(aggregateOutDir, 'main'), @@ -392,13 +352,6 @@ function main() { writeFileSync(join(aggregateOutDir, 'versions.json'), `${JSON.stringify(manifest, null, 2)}\n`); writeFileSync(join(aggregateOutDir, '_headers'), deployHeaders); assertCloudflarePagesLimits(aggregateOutDir); - const prunedArchives = pruneArchiveCacheGenerations({ - cacheRoot: archiveCacheRoot, - activeCacheKey: archiveCacheKey, - }); - if (prunedArchives.length > 0) { - console.info(`[docs] pruned ${prunedArchives.length} stale archive cache directories`); - } rmSync(buildRoot, { recursive: true, force: true }); } diff --git a/scripts/docs-archive-store.ts b/scripts/docs-archive-store.ts new file mode 100644 index 00000000..bc8966f6 --- /dev/null +++ b/scripts/docs-archive-store.ts @@ -0,0 +1,107 @@ +import { spawnSync } from 'node:child_process'; +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { versionOutputPath } from './docs-versioning'; + +// Frozen `/v/<version>/` doc builds live in an R2 bucket and are served by the Pages +// Function in `docs-site/functions/v/[[path]].ts`, so they never count toward the Pages +// deployment. Transfers go through the AWS CLI's S3 API (preinstalled on GitHub runners). + +// Written last on upload; an archive without it is treated as missing and rebuilt. +export const ARCHIVE_MARKER = '_archive.json'; + +export type DocsArchiveStore = { + has(version: string): boolean; + upload(version: string, dir: string, builtFrom: string): void; +}; + +export type DocsArchiveStoreEnv = { + accountId?: string; + accessKeyId?: string; + secretAccessKey?: string; + bucket?: string; +}; + +export function archiveStoreEnvFromProcess(env: NodeJS.ProcessEnv): DocsArchiveStoreEnv { + return { + accountId: env.CLOUDFLARE_ACCOUNT_ID, + accessKeyId: env.DOCS_ARCHIVE_R2_ACCESS_KEY_ID, + secretAccessKey: env.DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY, + bucket: env.DOCS_ARCHIVE_R2_BUCKET, + }; +} + +export function archiveKeyPrefix(version: string): string { + return `${versionOutputPath(version)}/`; +} + +// Returns null when credentials are absent so local builds can skip archive sync. +export function createArchiveStore(config: DocsArchiveStoreEnv): DocsArchiveStore | null { + const { accountId, accessKeyId, secretAccessKey, bucket } = config; + if (!accountId || !accessKeyId || !secretAccessKey || !bucket) { + return null; + } + + const endpoint = `https://${accountId}.r2.cloudflarestorage.com`; + const env: NodeJS.ProcessEnv = { + ...process.env, + AWS_ACCESS_KEY_ID: accessKeyId, + AWS_SECRET_ACCESS_KEY: secretAccessKey, + AWS_DEFAULT_REGION: 'auto', + // AWS CLI >= 2.23 sends CRC checksums by default, which R2 does not fully support. + AWS_REQUEST_CHECKSUM_CALCULATION: 'when_required', + AWS_RESPONSE_CHECKSUM_VALIDATION: 'when_required', + }; + + function aws(args: string[]) { + return spawnSync('aws', [...args, '--endpoint-url', endpoint], { + env, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + } + + return { + has(version) { + const result = aws([ + 's3api', + 'head-object', + '--bucket', + bucket, + '--key', + `${archiveKeyPrefix(version)}${ARCHIVE_MARKER}`, + ]); + if (result.error) throw result.error; + if (result.status === 0) return true; + if (/\b404\b|Not Found/i.test(result.stderr)) return false; + throw new Error(`Unable to check docs archive ${version}: ${result.stderr.trim()}`); + }, + + upload(version, dir, builtFrom) { + const target = `s3://${bucket}/${archiveKeyPrefix(version)}`; + // Unmark first so a rebuild that fails partway is retried by the next deploy + // instead of being skipped as complete. Deleting a missing key succeeds. + const unmark = aws(['s3', 'rm', `${target}${ARCHIVE_MARKER}`, '--only-show-errors']); + if (unmark.error) throw unmark.error; + if (unmark.status !== 0) { + throw new Error(`Unable to unmark docs archive ${version}: ${unmark.stderr.trim()}`); + } + + const sync = aws(['s3', 'sync', dir, target, '--only-show-errors']); + if (sync.error) throw sync.error; + if (sync.status !== 0) { + throw new Error(`Unable to upload docs archive ${version}: ${sync.stderr.trim()}`); + } + + const markerPath = join(dir, ARCHIVE_MARKER); + writeFileSync( + markerPath, + `${JSON.stringify({ version, builtFrom, builtAt: new Date().toISOString() }, null, 2)}\n`, + ); + const marker = aws(['s3', 'cp', markerPath, `${target}${ARCHIVE_MARKER}`]); + if (marker.status !== 0) { + throw new Error(`Unable to mark docs archive ${version}: ${marker.stderr.trim()}`); + } + }, + }; +} diff --git a/scripts/docs-versioned-assets.test.ts b/scripts/docs-versioned-assets.test.ts index 27e27c00..aa44b35a 100644 --- a/scripts/docs-versioned-assets.test.ts +++ b/scripts/docs-versioned-assets.test.ts @@ -3,11 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from import { rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { - dedupeVersionedPublicAssets, - pruneArchiveCacheGenerations, - rewriteSharedAssetReferences, -} from './docs-versioned-assets'; +import { dedupeVersionedPublicAssets, rewriteSharedAssetReferences } from './docs-versioned-assets'; function tempDir() { return mkdtempSync(join(tmpdir(), 'subminer-docs-versioned-assets-')); @@ -97,28 +93,3 @@ describe('docs versioned asset dedupe', () => { } }); }); - -describe('docs archive cache pruning', () => { - test('removes stale cache generations while keeping the active generation', async () => { - const dir = tempDir(); - try { - mkdirSync(join(dir, 'active123456-v0.14.0'), { recursive: true }); - mkdirSync(join(dir, 'stale654321-v0.14.0'), { recursive: true }); - mkdirSync(join(dir, 'stale654321-v0.13.0'), { recursive: true }); - - const removed = pruneArchiveCacheGenerations({ - cacheRoot: dir, - activeCacheKey: 'active123456abcdef', - }); - - expect(removed.sort()).toEqual([ - join(dir, 'stale654321-v0.13.0'), - join(dir, 'stale654321-v0.14.0'), - ]); - expect(existsSync(join(dir, 'active123456-v0.14.0'))).toBe(true); - expect(existsSync(join(dir, 'stale654321-v0.14.0'))).toBe(false); - } finally { - await rm(dir, { recursive: true, force: true }); - } - }); -}); diff --git a/scripts/docs-versioned-assets.ts b/scripts/docs-versioned-assets.ts index 38e1f988..da9f5deb 100644 --- a/scripts/docs-versioned-assets.ts +++ b/scripts/docs-versioned-assets.ts @@ -119,30 +119,3 @@ function removeEmptyDirectories(root: string) { rmSync(root, { recursive: true, force: true }); } } - -export function pruneArchiveCacheGenerations(options: { - cacheRoot: string; - activeCacheKey: string; -}): string[] { - if (!existsSync(options.cacheRoot)) { - return []; - } - - const activePrefix = options.activeCacheKey.slice(0, 12); - const removed: string[] = []; - - for (const entry of readdirSync(options.cacheRoot)) { - const path = join(options.cacheRoot, entry); - if (!lstatSync(path).isDirectory()) { - continue; - } - if (entry.startsWith(`${activePrefix}-`)) { - continue; - } - - rmSync(path, { recursive: true, force: true }); - removed.push(path); - } - - return removed; -} diff --git a/scripts/docs-versioning.test.ts b/scripts/docs-versioning.test.ts index 379f0b54..e9afdf5a 100644 --- a/scripts/docs-versioning.test.ts +++ b/scripts/docs-versioning.test.ts @@ -2,10 +2,9 @@ import { describe, expect, test } from 'bun:test'; import { buildVersionManifest, compareStableVersionsDesc, - versionArchiveCacheKey, isStableReleaseTag, + renderVersionsPage, stableTagsWithDocs, - versionArchiveCacheName, versionOutputPath, versionPath, } from './docs-versioning'; @@ -47,21 +46,16 @@ describe('docs versioning helpers', () => { }); }); - test('archive cache names are normalized by version and shared internals hash', () => { - expect(versionArchiveCacheName('v0.14.0', 'abcdef1234567890')).toBe('abcdef123456-v0.14.0'); - }); + test('versions page links every build with full page loads', () => { + const page = renderVersionsPage( + buildVersionManifest({ latestStable: 'v0.14.0', stableVersions: ['v0.14.0', 'v0.13.0'] }), + ); - test('archive cache keys change when manifest contents change', () => { - const firstKey = versionArchiveCacheKey({ - sharedInternalsHash: 'abcdef1234567890', - manifestJson: '{"latestStable":"v0.14.0"}', - }); - const secondKey = versionArchiveCacheKey({ - sharedInternalsHash: 'abcdef1234567890', - manifestJson: '{"latestStable":"v0.15.0"}', - }); - - expect(firstKey).not.toBe(secondKey); + expect(page).toContain('<a href="/" target="_self">Latest stable (v0.14.0)</a>'); + expect(page).toContain('<a href="/main/" target="_self">main</a>'); + expect(page).toContain('<a href="/v/0.14.0/" target="_self">v0.14.0</a>'); + expect(page.indexOf('/v/0.14.0/')).toBeLessThan(page.indexOf('/v/0.13.0/')); + expect(page).toContain('<a href="/v/0.13.0/" target="_self">v0.13.0</a>'); }); test('archive output paths stay relative for filesystem joins', () => { diff --git a/scripts/docs-versioning.ts b/scripts/docs-versioning.ts index 517871b2..c3a50627 100644 --- a/scripts/docs-versioning.ts +++ b/scripts/docs-versioning.ts @@ -1,5 +1,3 @@ -import { createHash } from 'node:crypto'; - export type DocsVersionEntry = { version: string; path: string; @@ -55,22 +53,6 @@ export function versionOutputPath(version: string): string { return `v/${version.replace(/^v/, '')}`; } -export function versionArchiveCacheName(version: string, sharedInternalsHash: string): string { - return `${sharedInternalsHash.slice(0, 12)}-${version}`; -} - -export function versionArchiveCacheKey(options: { - sharedInternalsHash: string; - manifestJson: string; -}): string { - const hash = createHash('sha256'); - hash.update('shared-internals:'); - hash.update(options.sharedInternalsHash); - hash.update('\nmanifest:'); - hash.update(options.manifestJson); - return hash.digest('hex'); -} - export function stableTagsWithDocs( tags: string[], hasDocsSite: (tag: string) => boolean, @@ -94,3 +76,27 @@ export function buildVersionManifest(options: { })), }; } + +// Markdown for the root-only `/versions` page. Archives link here instead of baking the +// release list into their nav, so an archive never needs a rebuild when a new tag ships. +// Raw anchors with `target="_self"` keep VitePress from treating the other builds as +// dead links or routing to them client-side. +export function renderVersionsPage(manifest: DocsVersionManifest): string { + const link = (path: string, text: string) => `<a href="${path}" target="_self">${text}</a>`; + return [ + '---', + 'title: Documentation versions', + 'description: Every published version of the SubMiner documentation.', + '---', + '', + '# Documentation versions', + '', + `- ${link('/', `Latest stable (${manifest.latestStable})`)}`, + `- ${link('/main/', 'main')}: development docs, may describe unreleased behavior`, + '', + '## Stable releases', + '', + ...manifest.versions.map((entry) => `- ${link(entry.path, entry.version)}`), + '', + ].join('\n'); +} diff --git a/scripts/print-docs-version-manifest.ts b/scripts/print-docs-version-manifest.ts deleted file mode 100644 index e6fc107e..00000000 --- a/scripts/print-docs-version-manifest.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { spawnSync } from 'node:child_process'; -import { resolve } from 'node:path'; -import { buildVersionManifest, stableTagsWithDocs } from './docs-versioning'; - -const repoRoot = resolve(__dirname, '..'); - -function capture(command: string, args: string[]): string { - const result = spawnSync(command, args, { - cwd: repoRoot, - encoding: 'utf8', - }); - - if (result.status !== 0) { - throw new Error(result.stderr || `Command failed: ${command} ${args.join(' ')}`); - } - - return result.stdout; -} - -function tagHasDocsSite(tag: string): boolean { - const result = spawnSync('git', ['cat-file', '-e', `${tag}:docs-site/package.json`], { - cwd: repoRoot, - }); - return result.status === 0; -} - -const stableVersions = stableTagsWithDocs( - capture('git', ['tag', '--list', 'v*']) - .split('\n') - .map((tag) => tag.trim()) - .filter(Boolean), - tagHasDocsSite, -); - -const latestStable = stableVersions[0]; - -if (!latestStable) { - throw new Error('No stable release tags with docs-site/package.json found.'); -} - -process.stdout.write(JSON.stringify(buildVersionManifest({ latestStable, stableVersions }))); diff --git a/src/ci-workflow.test.ts b/src/ci-workflow.test.ts index ce153430..db4895c1 100644 --- a/src/ci-workflow.test.ts +++ b/src/ci-workflow.test.ts @@ -53,15 +53,17 @@ test('main docs deploy exists, serializes deploys, and uses Cloudflare credentia assert.match(docsPagesWorkflow, /CLOUDFLARE_API_TOKEN/); assert.match(docsPagesWorkflow, /CLOUDFLARE_ACCOUNT_ID/); assert.match(docsPagesWorkflow, /CLOUDFLARE_PAGES_PROJECT_NAME/); - assert.match(docsPagesWorkflow, /pages deploy \.tmp\/docs-versioned-site/); + assert.match(docsPagesWorkflow, /pages deploy \.\.\/\.tmp\/docs-versioned-site/); assert.match(docsPagesWorkflow, /--branch main/); }); -test('docs deploy caches stable archive builds between runs', () => { - assert.match(docsPagesWorkflow, /actions\/cache@v4/); - assert.match(docsPagesWorkflow, /\.tmp\/docs-versioned-archive-cache/); - assert.match(docsPagesWorkflow, /docs-versioned-archives-/); - assert.match(docsPagesWorkflow, /docs-site\/\.vitepress\/\*\*/); +test('docs deploy syncs frozen archives to R2 and ships the archive Pages Function', () => { + assert.doesNotMatch(docsPagesWorkflow, /actions\/cache@/); + assert.match(docsPagesWorkflow, /DOCS_ARCHIVE_R2_ACCESS_KEY_ID/); + assert.match(docsPagesWorkflow, /DOCS_ARCHIVE_R2_SECRET_ACCESS_KEY/); + assert.match(docsPagesWorkflow, /--require-archives/); + assert.match(docsPagesWorkflow, /--rebuild-archives=\$\{REBUILD_ARCHIVES\}/); + assert.match(docsPagesWorkflow, /workingDirectory: docs-site/); }); test('docs deploy skips invalid release tags without failing the workflow', () => { diff --git a/src/release-workflow.test.ts b/src/release-workflow.test.ts index 55d4ee9b..9946d1de 100644 --- a/src/release-workflow.test.ts +++ b/src/release-workflow.test.ts @@ -72,7 +72,7 @@ test('stable release tags publish docs and prereleases do not update stable docs assert.match(docsPagesWorkflow, /tags:\s*\n\s*-\s*'v\*'/); assert.match(docsPagesWorkflow, /github\.ref_name/); assert.match(docsPagesWorkflow, /\^v\[0-9\]\+\\\.\[0-9\]\+\\\.\[0-9\]\+\$/); - assert.match(docsPagesWorkflow, /bun run docs:build:versioned/); + assert.match(docsPagesWorkflow, /bun run scripts\/build-versioned-docs\.ts/); assert.doesNotMatch(docsPagesWorkflow, /beta/); });