feat(setup): download FFmpeg from first-run setup when none is usable (#333)

This commit is contained in:
sudacode authored and GitHub committed 2026-11-22 02:09:06 -08:00
1 parent 0ae70b4ab2
commit ee52664655
14 files changed
+571 -11

No files matched your search

+1 -1
View File
@@ -121,7 +121,7 @@ SubMiner runs on Linux, macOS 11+, and Windows 10+. Only **mpv** is required to
| mpv | Required | The video player SubMiner draws over | | mpv | Required | The video player SubMiner draws over |
| fuse2 | Required (Linux) | Running the AppImage | | fuse2 | Required (Linux) | Running the AppImage |
| Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup | | Anki + AnkiConnect | Required to mine | Card creation from the Yomitan popup |
| ffmpeg | Recommended | Audio clips and screenshots on cards | | ffmpeg | Recommended | Card audio and screenshots (first-run setup can download it) |
| MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting | | MeCab + mecab-ipadic | Recommended | More accurate N+1, JLPT, and frequency highlighting |
| xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway | | xdotool + xwininfo | Required (X11) | Window tracking on desktops other than Hyprland or Sway |
| yt-dlp | Optional | YouTube playback | | yt-dlp | Optional | YouTube playback |
+4
View File
@@ -0,0 +1,4 @@
type: added
area: setup
- First-run setup now shows whether FFmpeg and FFprobe are usable. When they are missing from `PATH`, **Download FFmpeg** saves a verified static build next to your config, and SubMiner and the `subminer` command use it whenever no system FFmpeg is found.
+1 -1
View File
@@ -8,7 +8,7 @@ For the day-to-day flow, see [Mining workflow](/mining-workflow). Every key on t
1. Install [Anki](https://apps.ankiweb.net/). 1. Install [Anki](https://apps.ankiweb.net/).
2. Install AnkiConnect (add-on code `2055492159`). 2. Install AnkiConnect (add-on code `2055492159`).
3. Install FFmpeg and make sure it is on your `PATH`. SubMiner uses it for audio and images. 3. Install FFmpeg and make sure it is on your `PATH`, or download it from first-run setup. SubMiner uses it for audio and images.
4. Keep Anki running while you mine. 4. Keep Anki running while you mine.
If you changed AnkiConnect's port, set `ankiConnect.url` to match. If you changed AnkiConnect's port, set `ankiConnect.url` to match.
+5 -4
View File
@@ -12,7 +12,7 @@ Getting started takes three steps:
## 1. Install requirements ## 1. Install requirements
Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. Only mpv is required. Install ffmpeg too unless you are fine with cards that have no audio or screenshot. If you skip it, first-run setup can download a copy for SubMiner.
| Dependency | Needed for | Platforms | | Dependency | Needed for | Platforms |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ | | ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------ |
@@ -124,7 +124,7 @@ mpv --version
ffmpeg -version ffmpeg -version
``` ```
ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`). ffmpeg must be on `PATH`, because SubMiner runs it by name to make card audio and screenshots. Otherwise, use the FFmpeg download in first-run setup. mpv does not have to be. If `mpv --version` says `not recognized`, find `mpv.exe` (usually in `%LOCALAPPDATA%\Programs\mpv`) and either add that folder to `PATH` or enter the full path to `mpv.exe` during first-run setup (`mpv.executablePath`).
<details> <details>
<summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary> <summary><b>Alternative: Scoop (no admin rights, includes xz)</b></summary>
@@ -262,8 +262,9 @@ Setup walks you through:
1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows). 1. **Config file.** Created at `~/.config/SubMiner/config.jsonc` (Linux and macOS) or `%APPDATA%\SubMiner\config.jsonc` (Windows).
2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser. 2. **Yomitan dictionaries.** Import at least one dictionary, or lookups will not work. SubMiner's Yomitan is separate from any Yomitan in your browser.
3. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`. 3. **FFmpeg** (optional). If `ffmpeg` and `ffprobe` are on your `PATH` and run, there is nothing to do. Otherwise **Download FFmpeg** saves a static build to `tools/ffmpeg/` next to your config file. SubMiner and the `subminer` command use it only when FFmpeg is missing from `PATH`, so a system install always takes priority.
4. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached. 4. **The `subminer` command** (optional). Setup installs it into a folder already on your `PATH`. If there is none on Linux or macOS, it uses `~/.local/bin` and shows the `export PATH=...` line to add to your shell config. On Windows it adds `%LOCALAPPDATA%\SubMiner\bin` to your user `PATH`.
5. **SubMiner mpv shortcut** (Windows only). A Start menu or desktop shortcut that opens mpv with SubMiner attached.
**Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`. **Finish setup** unlocks once the config exists and at least one dictionary is imported. To reopen setup later, run `subminer app --setup`.
+7
View File
@@ -1,6 +1,11 @@
import path from 'node:path'; import path from 'node:path';
import packageJson from '../package.json'; import packageJson from '../package.json';
import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js'; import { applyLogFileTogglesToEnv } from '../src/shared/log-files.js';
import { getDefaultConfigDir } from '../src/shared/setup-state.js';
import {
appendManagedFfmpegToPath,
getManagedFfmpegDir,
} from '../src/core/services/managed-ffmpeg.js';
import { import {
loadLauncherJellyfinConfig, loadLauncherJellyfinConfig,
loadLauncherLoggingConfig, loadLauncherLoggingConfig,
@@ -65,6 +70,8 @@ function ensureAppPath(context: LauncherCommandContext): string {
async function main(): Promise<void> { async function main(): Promise<void> {
const scriptPath = process.argv[1] || 'subminer'; const scriptPath = process.argv[1] || 'subminer';
const scriptName = path.basename(scriptPath); const scriptName = path.basename(scriptPath);
// Same PATH rule as the app: dependency checks and spawned tools see a setup-page FFmpeg.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(getDefaultConfigDir()));
const launcherConfig = loadLauncherYoutubeSubgenConfig(); const launcherConfig = loadLauncherYoutubeSubgenConfig();
const launcherMpvConfig = loadLauncherMpvConfig(); const launcherMpvConfig = loadLauncherMpvConfig();
const launcherLoggingConfig = loadLauncherLoggingConfig(); const launcherLoggingConfig = loadLauncherLoggingConfig();
+154
View File
@@ -0,0 +1,154 @@
import assert from 'node:assert/strict';
import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import test from 'node:test';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from './managed-ffmpeg';
async function withTempDirs(run: (dirs: { system: string; managed: string }) => Promise<void>) {
const root = await mkdtemp(path.join(tmpdir(), 'managed-ffmpeg-'));
const dirs = { system: path.join(root, 'bin'), managed: getManagedFfmpegDir(root) };
await mkdir(dirs.system, { recursive: true });
await mkdir(dirs.managed, { recursive: true });
try {
await run(dirs);
} finally {
await rm(root, { recursive: true, force: true });
}
}
async function writeExecutable(directory: string, name: string): Promise<void> {
const filePath = path.join(directory, name);
await writeFile(filePath, '#!/bin/sh\n');
await chmod(filePath, 0o755);
}
const passVersionCheck = async () => undefined;
test('managed FFmpeg is appended to PATH once, behind system entries, only when downloaded', async () => {
await withTempDirs(async ({ system, managed }) => {
const env: NodeJS.ProcessEnv = { Path: system };
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
await writeExecutable(managed, 'ffmpeg');
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), true);
assert.equal(appendManagedFfmpegToPath(env, managed, 'linux'), false);
// Writes the existing key (Windows spells it Path) instead of adding a second one.
assert.deepEqual(env, { Path: [system, managed].join(path.delimiter) });
});
});
test('detectFfmpeg prefers system tools and fills gaps from the managed copy', async () => {
await withTempDirs(async ({ system, managed }) => {
const env = { PATH: [system, managed].join(path.delimiter) };
const detect = () =>
detectFfmpeg({
managedDir: managed,
env,
platform: 'linux',
arch: 'x64',
runVersionCheck: passVersionCheck,
});
assert.deepEqual(await detect(), {
kind: 'missing',
missing: ['ffmpeg', 'ffprobe'],
downloadable: true,
});
await writeExecutable(system, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
assert.deepEqual(await detect(), {
kind: 'ready',
source: 'managed',
ffmpegPath: path.join(system, 'ffmpeg'),
ffprobePath: path.join(managed, 'ffprobe'),
});
await writeExecutable(system, 'ffprobe');
const status = await detect();
assert.equal(status.kind === 'ready' ? status.source : status.kind, 'system');
});
});
test('detectFfmpeg reports a tool that is found but fails to run', async () => {
await withTempDirs(async ({ managed }) => {
await writeExecutable(managed, 'ffmpeg');
await writeExecutable(managed, 'ffprobe');
const status = await detectFfmpeg({
managedDir: managed,
env: { PATH: managed },
platform: 'freebsd',
arch: 'x64',
runVersionCheck: async () => {
throw new Error('Killed: 9');
},
});
assert.deepEqual(status, {
kind: 'broken',
path: path.join(managed, 'ffmpeg'),
message: 'Killed: 9',
managed: true,
downloadable: false,
});
});
});
test('detectFfmpeg reports a broken system tool before offering a download for its companion', async () => {
await withTempDirs(async ({ system, managed }) => {
await writeExecutable(system, 'ffmpeg');
const detect = (runVersionCheck: (executablePath: string) => Promise<void>) =>
detectFfmpeg({
managedDir: managed,
env: { PATH: system },
platform: 'linux',
arch: 'x64',
runVersionCheck,
});
// A download would only add ffprobe; the broken system ffmpeg would still shadow it.
assert.deepEqual(
await detect(async () => {
throw new Error('exit 127');
}),
{
kind: 'broken',
path: path.join(system, 'ffmpeg'),
message: 'exit 127',
managed: false,
downloadable: true,
},
);
assert.deepEqual(await detect(passVersionCheck), {
kind: 'missing',
missing: ['ffprobe'],
downloadable: true,
});
});
});
test('installManagedFfmpeg rejects unsupported platforms and never publishes a failed download', async () => {
await withTempDirs(async ({ managed }) => {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'freebsd', arch: 'x64' }),
/no FFmpeg download for freebsd-x64/,
);
const originalFetch = globalThis.fetch;
globalThis.fetch = Object.assign(async () => new Response('not ffmpeg'), originalFetch);
try {
await assert.rejects(
installManagedFfmpeg({ managedDir: managed, platform: 'linux', arch: 'x64' }),
/FFmpeg failed integrity verification/,
);
} finally {
globalThis.fetch = originalFetch;
}
assert.deepEqual(await readdir(managed), []);
});
});
+222
View File
@@ -0,0 +1,222 @@
import { execFile } from 'node:child_process';
import { createReadStream, createWriteStream, existsSync } from 'node:fs';
import { chmod, mkdir, mkdtemp, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { createGunzip } from 'node:zlib';
import { downloadSubtitleGenerationArtifact } from './subtitle-generation-download';
import { findOnPath } from './subtitle-generation-tools';
/**
* SubMiner can download its own FFmpeg when none is usable on PATH. The copy lives in
* `<configDir>/tools/ffmpeg` and is appended to PATH at startup, so a system FFmpeg always
* wins and every bare `ffmpeg`/`ffprobe` spawn picks up the download otherwise.
*/
export type FfmpegTool = 'ffmpeg' | 'ffprobe';
const FFMPEG_TOOLS: readonly FfmpegTool[] = ['ffmpeg', 'ffprobe'];
/** Pinned ffmpeg-static release: single gzipped static binaries per platform. */
const MANAGED_FFMPEG_RELEASE_URL =
'https://github.com/eugeneware/ffmpeg-static/releases/download/b6.1.1';
type ManagedAsset = { size: number; sha256: string };
const MANAGED_FFMPEG_ASSETS = {
'linux-x64': {
ffmpeg: {
size: 29354986,
sha256: 'bfe8a8fc511530457b528c48d77b5737527b504a3797a9bc4866aeca69c2dffa',
},
ffprobe: {
size: 29276839,
sha256: '25d9b6ccb05e3d9de9e04e31e2506d8dd7f9f0418981965ac6df12e8d3afd067',
},
},
'linux-arm64': {
ffmpeg: {
size: 25568691,
sha256: '754a678672298bc68156adff58aa7385a592c2b30b1d0ae8750c45c915c4bac0',
},
ffprobe: {
size: 25493573,
sha256: '2ab6aba60ee84412dff9188720703376cb4e7aaf7e0b5e43aa8249f2acae5bf8',
},
},
'darwin-x64': {
ffmpeg: {
size: 25296431,
sha256: '929b375c1182d956c51f7ac25e0b2b0411fb01f6f407aa15c9758efeb4242106',
},
ffprobe: {
size: 25239438,
sha256: 'd4da574d6e2e197bd259b47d69cf262df9e312af24ad960444f6d806d3d4c186',
},
},
'darwin-arm64': {
ffmpeg: {
size: 19246198,
sha256: '8923876afa8db5585022d7860ec7e589af192f441c56793971276d450ed3bbfa',
},
ffprobe: {
size: 19207077,
sha256: 'd986a8ec7b030899fe66a8a288ed809a3543338705a3ce178cfb85869c5d80be',
},
},
'win32-x64': {
ffmpeg: {
size: 29581307,
sha256: '8883a3dffbd0a16cf4ef95206ea05283f78908dbfb118f73c83f4951dcc06d77',
},
ffprobe: {
size: 29521644,
sha256: 'f309e6223ad89d2fe54bccd420a7709b66fd27540674e92309578ed491a43c8d',
},
},
} as const satisfies Record<string, Record<FfmpegTool, ManagedAsset>>;
type ManagedFfmpegTarget = keyof typeof MANAGED_FFMPEG_ASSETS;
function getManagedFfmpegTarget(
platform: NodeJS.Platform,
arch: string,
): ManagedFfmpegTarget | null {
// Windows on ARM runs the x64 build through emulation; there is no native arm64 build.
const key = platform === 'win32' && arch === 'arm64' ? 'win32-x64' : `${platform}-${arch}`;
return key in MANAGED_FFMPEG_ASSETS ? (key as ManagedFfmpegTarget) : null;
}
export function getManagedFfmpegDir(configDir: string): string {
return path.join(configDir, 'tools', 'ffmpeg');
}
function managedBinaryPath(
managedDir: string,
tool: FfmpegTool,
platform: NodeJS.Platform,
): string {
return path.join(managedDir, platform === 'win32' ? `${tool}.exe` : tool);
}
function pathKey(env: NodeJS.ProcessEnv): string {
return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';
}
/**
* Appends the managed FFmpeg directory to `env`'s PATH when a download exists there.
* Appending keeps a system FFmpeg in front. Returns whether PATH changed.
*/
export function appendManagedFfmpegToPath(
env: NodeJS.ProcessEnv,
managedDir: string,
platform: NodeJS.Platform = process.platform,
): boolean {
if (!existsSync(managedBinaryPath(managedDir, 'ffmpeg', platform))) return false;
const key = pathKey(env);
const entries = (env[key] ?? '').split(path.delimiter).filter(Boolean);
if (entries.some((entry) => path.resolve(entry) === path.resolve(managedDir))) return false;
env[key] = [...entries, managedDir].join(path.delimiter);
return true;
}
export type FfmpegSetupStatus =
| { kind: 'ready'; source: 'system' | 'managed'; ffmpegPath: string; ffprobePath: string }
| { kind: 'missing'; missing: FfmpegTool[]; downloadable: boolean }
/** Found on PATH but `-version` failed. Only a broken managed copy is fixed by downloading. */
| { kind: 'broken'; path: string; message: string; managed: boolean; downloadable: boolean };
export type RunVersionCheck = (executablePath: string) => Promise<void>;
const runVersionCheckDefault: RunVersionCheck = (executablePath) =>
new Promise((resolve, reject) => {
// Generous timeout: Windows Defender scans a fresh 80 MB exe on first launch.
execFile(executablePath, ['-version'], { timeout: 15_000 }, (error) =>
error ? reject(error) : resolve(),
);
});
/** Whether SubMiner can run FFmpeg and FFprobe from the current PATH, and where they come from. */
export async function detectFfmpeg(options: {
managedDir: string;
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
arch?: string;
runVersionCheck?: RunVersionCheck;
}): Promise<FfmpegSetupStatus> {
const env = options.env ?? process.env;
const platform = options.platform ?? process.platform;
const runVersionCheck = options.runVersionCheck ?? runVersionCheckDefault;
const downloadable = getManagedFfmpegTarget(platform, options.arch ?? process.arch) !== null;
const isManaged = (filePath: string) =>
path.resolve(path.dirname(filePath)) === path.resolve(options.managedDir);
const found = await Promise.all(FFMPEG_TOOLS.map((tool) => findOnPath([tool], env)));
// Check what was found before reporting gaps: a broken system tool shadows any download.
for (const executablePath of found.filter(Boolean)) {
try {
await runVersionCheck(executablePath);
} catch (error) {
return {
kind: 'broken',
path: executablePath,
message: error instanceof Error ? error.message : String(error),
managed: isManaged(executablePath),
downloadable,
};
}
}
const missing = FFMPEG_TOOLS.filter((_, index) => !found[index]);
if (missing.length > 0) return { kind: 'missing', missing, downloadable };
const [ffmpegPath, ffprobePath] = found as [string, string];
return {
kind: 'ready',
source: isManaged(ffmpegPath) || isManaged(ffprobePath) ? 'managed' : 'system',
ffmpegPath,
ffprobePath,
};
}
/**
* Downloads, verifies, and unpacks FFmpeg and FFprobe into `managedDir`, replacing any
* earlier download. Callers append `managedDir` to PATH afterwards.
*/
export async function installManagedFfmpeg(options: {
managedDir: string;
platform?: NodeJS.Platform;
arch?: string;
}): Promise<void> {
const platform = options.platform ?? process.platform;
const arch = options.arch ?? process.arch;
const target = getManagedFfmpegTarget(platform, arch);
if (!target) {
throw new Error(
`SubMiner has no FFmpeg download for ${platform}-${arch}. Install FFmpeg yourself.`,
);
}
await mkdir(options.managedDir, { recursive: true });
const staging = await mkdtemp(path.join(options.managedDir, '.install-'));
try {
const unpacked: Array<[string, string]> = [];
for (const tool of FFMPEG_TOOLS) {
const asset = MANAGED_FFMPEG_ASSETS[target][tool];
const archivePath = path.join(staging, `${tool}.gz`);
await downloadSubtitleGenerationArtifact({
url: `${MANAGED_FFMPEG_RELEASE_URL}/${tool}-${target}.gz`,
size: asset.size,
sha256: asset.sha256,
destination: archivePath,
label: tool === 'ffmpeg' ? 'FFmpeg' : 'FFprobe',
});
const binaryPath = managedBinaryPath(staging, tool, platform);
await pipeline(createReadStream(archivePath), createGunzip(), createWriteStream(binaryPath));
await chmod(binaryPath, 0o755);
unpacked.push([binaryPath, managedBinaryPath(options.managedDir, tool, platform)]);
}
// Publish only after both tools verified, so a failed download never leaves half a pair.
for (const [from, to] of unpacked) await rename(from, to);
} finally {
await rm(staging, { recursive: true, force: true });
}
}
@@ -18,12 +18,12 @@ export async function downloadSubtitleGenerationArtifact(input: {
const temporaryDirectory = await mkdtemp( const temporaryDirectory = await mkdtemp(
path.join(path.dirname(input.destination), '.download-'), path.join(path.dirname(input.destination), '.download-'),
); );
const temporaryPath = path.join(temporaryDirectory, 'model.bin'); const temporaryPath = path.join(temporaryDirectory, 'artifact.bin');
input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` }); input.onProgress?.({ stage: 'download', percent: 0, message: `Downloading ${input.label}...` });
try { try {
const response = await fetch(input.url, { signal: input.signal }); const response = await fetch(input.url, { signal: input.signal });
if (!response.ok || !response.body) { if (!response.ok || !response.body) {
throw new Error(`Model download failed: HTTP ${response.status}`); throw new Error(`${input.label} download failed: HTTP ${response.status}`);
} }
const file = await open(temporaryPath, 'wx'); const file = await open(temporaryPath, 'wx');
const reader = response.body.getReader(); const reader = response.body.getReader();
@@ -36,7 +36,8 @@ export async function downloadSubtitleGenerationArtifact(input: {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
if (done) break; if (done) break;
received += value.byteLength; received += value.byteLength;
if (received > input.size) throw new Error('Downloaded model exceeds expected size.'); if (received > input.size)
throw new Error(`Downloaded ${input.label} exceeds expected size.`);
digest.update(value); digest.update(value);
await file.writeFile(value); await file.writeFile(value);
const percent = Math.min(99, Math.floor((received / input.size) * 100)); const percent = Math.min(99, Math.floor((received / input.size) * 100));
@@ -50,7 +51,9 @@ export async function downloadSubtitleGenerationArtifact(input: {
} }
} }
if (received !== input.size || digest.digest('hex') !== input.sha256) { if (received !== input.size || digest.digest('hex') !== input.sha256) {
throw new Error('Downloaded model failed integrity verification. Try downloading again.'); throw new Error(
`Downloaded ${input.label} failed integrity verification. Try downloading again.`,
);
} }
await file.sync(); await file.sync();
} finally { } finally {
@@ -46,7 +46,11 @@ function executableNames(name: string, env: NodeJS.ProcessEnv): string[] {
return [name, ...extensions.map((extension) => `${name}${extension}`)]; return [name, ...extensions.map((extension) => `${name}${extension}`)];
} }
async function findOnPath(names: readonly string[], env: NodeJS.ProcessEnv): Promise<string> { /** First executable on `env.PATH` matching any of `names` (PATHEXT-aware on Windows), or ''. */
export async function findOnPath(
names: readonly string[],
env: NodeJS.ProcessEnv,
): Promise<string> {
const directories = (env.PATH ?? '') const directories = (env.PATH ?? '')
.split(path.delimiter) .split(path.delimiter)
.map((entry) => entry.trim()) .map((entry) => entry.trim())
+4
View File
@@ -155,6 +155,7 @@ import { createSyncAssembly } from './main/assemblies/sync';
import { createYoutubeAssembly } from './main/assemblies/youtube'; import { createYoutubeAssembly } from './main/assemblies/youtube';
import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals'; import { createOverlayModalsAssembly } from './main/assemblies/overlay-modals';
import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup'; import { createFirstRunSetupAssembly } from './main/assemblies/first-run-setup';
import { appendManagedFfmpegToPath, getManagedFfmpegDir } from './core/services/managed-ffmpeg';
import { createOverlayAssembly } from './main/assemblies/overlay'; import { createOverlayAssembly } from './main/assemblies/overlay';
import { createYomitanAssembly } from './main/assemblies/yomitan'; import { createYomitanAssembly } from './main/assemblies/yomitan';
import { createStatsAssembly } from './main/assemblies/stats'; import { createStatsAssembly } from './main/assemblies/stats';
@@ -428,6 +429,8 @@ const {
appState, appState,
appLifecycleApp, appLifecycleApp,
} = bootServices; } = bootServices;
// Before any ffmpeg/ffprobe spawn: a system FFmpeg stays first, the setup-page download fills in.
appendManagedFfmpegToPath(process.env, getManagedFfmpegDir(CONFIG_DIR));
// Backend changes take effect on restart; windows and parser must share one session. // Backend changes take effect on restart; windows and parser must share one session.
const activeDictionaryBackend = configService.getConfig().dictionaryBackend; const activeDictionaryBackend = configService.getConfig().dictionaryBackend;
const yomitan = createYomitanAssembly({ const yomitan = createYomitanAssembly({
@@ -688,6 +691,7 @@ const firstRunSetup = createFirstRunSetupAssembly({
ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(), ensureYomitanExtensionLoaded: () => yomitan.ensureExtensionLoaded(),
getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(), getYomitanParserRuntimeDeps: () => yomitan.getParserRuntimeDeps(),
createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(), createCommandLineLauncherRuntimeOptions: () => createCommandLineLauncherRuntimeOptions(),
waitForLoginShellPath: () => loginShellPathReady,
getAppPath: (name) => app.getPath(name), getAppPath: (name) => app.getPath(name),
trashItem: (targetPath) => shell.trashItem(targetPath), trashItem: (targetPath) => shell.trashItem(targetPath),
writeShortcutLink: (shortcutPath, operation, details) => writeShortcutLink: (shortcutPath, operation, details) =>
@@ -30,6 +30,7 @@ function makeDeps(configDir: string): FirstRunSetupAssemblyDeps {
ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'), ensureYomitanExtensionLoaded: lazy('ensureYomitanExtensionLoaded'),
getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'), getYomitanParserRuntimeDeps: lazy('getYomitanParserRuntimeDeps'),
createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'), createCommandLineLauncherRuntimeOptions: lazy('createCommandLineLauncherRuntimeOptions'),
waitForLoginShellPath: lazy('waitForLoginShellPath'),
getAppPath: lazy('getAppPath'), getAppPath: lazy('getAppPath'),
trashItem: lazy('trashItem'), trashItem: lazy('trashItem'),
writeShortcutLink: lazy('writeShortcutLink'), writeShortcutLink: lazy('writeShortcutLink'),
+32
View File
@@ -1,6 +1,12 @@
import os from 'node:os'; import os from 'node:os';
import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron'; import type { BrowserWindow, BrowserWindowConstructorOptions } from 'electron';
import type { ConfigService } from '../../config/service'; import type { ConfigService } from '../../config/service';
import {
appendManagedFfmpegToPath,
detectFfmpeg,
getManagedFfmpegDir,
installManagedFfmpeg,
} from '../../core/services/managed-ffmpeg';
import { getYomitanDictionaryInfo } from '../../core/services'; import { getYomitanDictionaryInfo } from '../../core/services';
import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime'; import { requestHachidoriSharing } from '../../core/services/tokenizer/yomitan-parser-runtime';
import type { Logger } from '../../logger'; import type { Logger } from '../../logger';
@@ -62,6 +68,8 @@ export interface FirstRunSetupAssemblyDeps {
getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps; getYomitanParserRuntimeDeps: () => YomitanParserRuntimeDeps;
/** Resolves the launcher options after the login-shell PATH is applied. */ /** Resolves the launcher options after the login-shell PATH is applied. */
createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>; createCommandLineLauncherRuntimeOptions: () => Promise<CommandLineLauncherRuntimeOptions>;
/** Resolves once the macOS login-shell PATH is merged, so FFmpeg detection sees it. */
waitForLoginShellPath: () => Promise<void>;
getAppPath: (name: 'appData' | 'desktop') => string; getAppPath: (name: 'appData' | 'desktop') => string;
trashItem: (targetPath: string) => Promise<void>; trashItem: (targetPath: string) => Promise<void>;
writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink']; writeShortcutLink: Parameters<typeof applyWindowsMpvShortcuts>[0]['writeShortcutLink'];
@@ -83,6 +91,23 @@ export type FirstRunSetupAssembly = ReturnType<typeof createFirstRunSetupAssembl
export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) { export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
const { appState, configService, logger } = deps; const { appState, configService, logger } = deps;
let firstRunSetupMessage: string | null = null; let firstRunSetupMessage: string | null = null;
const managedFfmpegDir = getManagedFfmpegDir(deps.configDir);
// Shared by repeat clicks so a second press never starts a parallel download.
let ffmpegInstall: Promise<string> | null = null;
const installFfmpeg = (): Promise<string> =>
(ffmpegInstall ??= installManagedFfmpeg({ managedDir: managedFfmpegDir })
.then(() => {
appendManagedFfmpegToPath(process.env, managedFfmpegDir);
logger.info(`[ffmpeg] Downloaded FFmpeg to ${managedFfmpegDir}`);
return 'FFmpeg downloaded. SubMiner uses it whenever FFmpeg is not on PATH.';
})
.catch((error: unknown) => {
logger.error('[ffmpeg] FFmpeg download failed', error);
return `FFmpeg download failed: ${error instanceof Error ? error.message : String(error)}`;
})
.finally(() => {
ffmpegInstall = null;
}));
const resolveWindowsMpvShortcutRuntimePaths = () => const resolveWindowsMpvShortcutRuntimePaths = () =>
resolveWindowsMpvShortcutPaths({ resolveWindowsMpvShortcutPaths({
appDataDir: deps.getAppPath('appData'), appDataDir: deps.getAppPath('appData'),
@@ -232,6 +257,9 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath), mpvExecutablePathStatus: getConfiguredWindowsMpvPathStatus(mpvExecutablePath),
windowsMpvShortcuts: snapshot.windowsMpvShortcuts, windowsMpvShortcuts: snapshot.windowsMpvShortcuts,
commandLineLauncher: snapshot.commandLineLauncher, commandLineLauncher: snapshot.commandLineLauncher,
ffmpeg: await deps
.waitForLoginShellPath()
.then(() => detectFfmpeg({ managedDir: managedFfmpegDir })),
message: firstRunSetupMessage, message: firstRunSetupMessage,
}; };
}, },
@@ -304,6 +332,10 @@ export function createFirstRunSetupAssembly(deps: FirstRunSetupAssemblyDeps) {
firstRunSetupMessage = snapshot.message; firstRunSetupMessage = snapshot.message;
return; return;
} }
if (submission.action === 'install-ffmpeg') {
firstRunSetupMessage = await installFfmpeg();
return;
}
if (submission.action === 'open-yomitan-settings') { if (submission.action === 'open-yomitan-settings') {
firstRunSetupMessage = deps.openDictionarySettings() firstRunSetupMessage = deps.openDictionarySettings()
? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.` ? `Opened ${deps.dictionaryBackend === 'hachidori' ? 'Hachidori' : 'Yomitan'} settings. Install dictionaries, then refresh status.`
@@ -7,6 +7,14 @@ import {
parseFirstRunSetupSubmissionUrl, parseFirstRunSetupSubmissionUrl,
} from './first-run-setup-window'; } from './first-run-setup-window';
import type { CommandLineLauncherSnapshot } from './command-line-launcher'; import type { CommandLineLauncherSnapshot } from './command-line-launcher';
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
const READY_FFMPEG: FfmpegSetupStatus = {
kind: 'ready',
source: 'system',
ffmpegPath: '/usr/bin/ffmpeg',
ffprobePath: '/usr/bin/ffprobe',
};
function createCommandLineLauncherSnapshot( function createCommandLineLauncherSnapshot(
overrides: Partial<CommandLineLauncherSnapshot> = {}, overrides: Partial<CommandLineLauncherSnapshot> = {},
@@ -52,6 +60,7 @@ test('buildFirstRunSetupHtml shows legacy mpv plugin removal action with confirm
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -90,6 +99,7 @@ test('buildFirstRunSetupHtml marks an invalid configured mpv path as invalid', (
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -117,6 +127,7 @@ test('buildFirstRunSetupHtml explains the config blocker when setup is missing c
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -146,6 +157,7 @@ test('buildFirstRunSetupHtml explains external yomitan mode and keeps finish ena
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -221,6 +233,7 @@ test('buildFirstRunSetupHtml reports a broken included runtime in the optional l
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'failed', status: 'failed',
@@ -275,6 +288,7 @@ test('buildFirstRunSetupHtml labels a missing launcher without error-message wor
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
bun: { bun: {
status: 'ready', status: 'ready',
@@ -310,6 +324,7 @@ test('buildFirstRunSetupHtml disables launcher install when no target is install
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot({ commandLineLauncher: createCommandLineLauncherSnapshot({
launcher: { launcher: {
status: 'not_installable', status: 'not_installable',
@@ -403,6 +418,7 @@ test('opening first-run setup shows and focuses window after content loads', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -469,6 +485,7 @@ test('opening first-run setup skips rendering if window is destroyed after snaps
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}; };
@@ -538,6 +555,7 @@ test('first-run setup action can skip rerender after launching another window',
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -620,6 +638,7 @@ test('closing incomplete first-run setup quits app outside background mode', asy
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -692,6 +711,7 @@ test('closing completed first-run setup quits app when completion policy allows
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}), }),
@@ -747,6 +767,7 @@ test('Hachidori setup names the active dictionary backend', () => {
desktopInstalled: false, desktopInstalled: false,
status: 'optional', status: 'optional',
}, },
ffmpeg: READY_FFMPEG,
commandLineLauncher: createCommandLineLauncherSnapshot(), commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null, message: null,
}); });
@@ -775,3 +796,55 @@ test('setup parses link and unlink actions without losing the host address', ()
{ action: 'unlink-hachidori-host' }, { action: 'unlink-hachidori-host' },
); );
}); });
test('FFmpeg card offers a download only when one would be used', () => {
const render = (ffmpeg: FfmpegSetupStatus) =>
buildFirstRunSetupHtml({
configReady: true,
dictionaryCount: 1,
canFinish: true,
externalYomitanConfigured: false,
pluginStatus: 'installed',
pluginInstallPathSummary: null,
mpvExecutablePath: '',
mpvExecutablePathStatus: 'blank',
windowsMpvShortcuts: {
supported: false,
startMenuEnabled: false,
desktopEnabled: false,
startMenuInstalled: false,
desktopInstalled: false,
status: 'optional',
},
ffmpeg,
commandLineLauncher: createCommandLineLauncherSnapshot(),
message: null,
});
const system = render(READY_FFMPEG);
assert.match(system, /Found on your system\. Nothing to do\./);
assert.match(system, /\/usr\/bin\/ffprobe/);
assert.doesNotMatch(system, /action=install-ffmpeg/);
const missing = render({ kind: 'missing', missing: ['ffprobe'], downloadable: true });
assert.match(missing, /Not found on PATH: ffprobe\./);
assert.match(missing, /action=install-ffmpeg/);
const unsupported = render({ kind: 'missing', missing: ['ffmpeg'], downloadable: false });
assert.match(unsupported, /No download is available for this platform/);
assert.doesNotMatch(unsupported, /action=install-ffmpeg/);
const broken = {
kind: 'broken',
path: '/x/ffmpeg',
message: 'exit 127',
downloadable: true,
} as const;
assert.doesNotMatch(render({ ...broken, managed: false }), /action=install-ffmpeg/);
assert.match(render({ ...broken, managed: true }), /Download FFmpeg again/);
assert.deepEqual(
parseFirstRunSetupSubmissionUrl('subminer://first-run-setup?action=install-ffmpeg'),
{ action: 'install-ffmpeg' },
);
});
@@ -1,3 +1,4 @@
import type { FfmpegSetupStatus } from '../../core/services/managed-ffmpeg';
import type { HachidoriHostStatus } from '../../shared/hachidori-sharing'; import type { HachidoriHostStatus } from '../../shared/hachidori-sharing';
import type { DictionaryBackend } from '../../types/config'; import type { DictionaryBackend } from '../../types/config';
import { getFirstRunSetupCompletionMessage } from './first-run-setup-service'; import { getFirstRunSetupCompletionMessage } from './first-run-setup-service';
@@ -34,6 +35,7 @@ export type FirstRunSetupSubmission =
| 'remove-legacy-plugin' | 'remove-legacy-plugin'
| 'install-bun' | 'install-bun'
| 'install-command-line-launcher' | 'install-command-line-launcher'
| 'install-ffmpeg'
| 'open-yomitan-settings' | 'open-yomitan-settings'
| 'open-config-settings' | 'open-config-settings'
| 'refresh' | 'refresh'
@@ -63,6 +65,7 @@ export interface FirstRunSetupHtmlModel {
status: 'installed' | 'optional' | 'skipped' | 'failed'; status: 'installed' | 'optional' | 'skipped' | 'failed';
}; };
commandLineLauncher: CommandLineLauncherSnapshot; commandLineLauncher: CommandLineLauncherSnapshot;
ffmpeg: FfmpegSetupStatus;
message: string | null; message: string | null;
} }
@@ -154,6 +157,56 @@ function renderCommandLineLauncherSection(
</section>`; </section>`;
} }
function renderFfmpegCard(ffmpeg: FfmpegSetupStatus): string {
const lines: string[] = [];
let badge: string;
let showDownload = false;
if (ffmpeg.kind === 'ready') {
lines.push(
ffmpeg.source === 'system'
? 'Found on your system. Nothing to do.'
: 'Using the copy SubMiner downloaded. Nothing to do.',
`FFmpeg: ${ffmpeg.ffmpegPath}`,
`FFprobe: ${ffmpeg.ffprobePath}`,
);
badge = renderStatusBadge(ffmpeg.source === 'system' ? 'Detected' : 'Downloaded', 'ready');
} else if (ffmpeg.kind === 'missing') {
lines.push(`Not found on PATH: ${ffmpeg.missing.join(', ')}.`);
lines.push(
ffmpeg.downloadable
? 'Download a copy for SubMiner (under 60 MB), or install FFmpeg yourself and refresh.'
: 'No download is available for this platform. Install FFmpeg, then refresh.',
);
badge = renderStatusBadge('Missing', 'warn');
showDownload = ffmpeg.downloadable;
} else {
lines.push(`${ffmpeg.path} failed to run: ${ffmpeg.message}`);
lines.push(
ffmpeg.managed
? 'Download it again to repair the copy SubMiner downloaded.'
: 'Repair or remove that FFmpeg install, then refresh.',
);
badge = renderStatusBadge('Not working', 'danger');
showDownload = ffmpeg.managed && ffmpeg.downloadable;
}
// The button relabels itself because the page only re-renders once the download finishes.
const downloadButton = showDownload
? `<div class="inline-actions"><button onclick="this.disabled = true; this.textContent = 'Downloading FFmpeg...'; window.location.href='subminer://first-run-setup?action=install-ffmpeg'">${ffmpeg.kind === 'broken' ? 'Download FFmpeg again' : 'Download FFmpeg'}</button></div>`
: '';
return `
<div class="card block">
<div class="card-head">
<div>
<strong>FFmpeg</strong>
<div class="meta">Used for card audio and screenshots, and subtitle generation.</div>
${lines.map((line) => `<div class="meta">${escapeHtml(line)}</div>`).join('')}
</div>
${badge}
</div>
${downloadButton}
</div>`;
}
export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string { export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? []; const legacyMpvPluginPaths = model.legacyMpvPluginPaths ?? [];
const finishButtonLabel = const finishButtonLabel =
@@ -535,6 +588,7 @@ export function buildFirstRunSetupHtml(model: FirstRunSetupHtmlModel): string {
${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)} ${renderStatusBadge(yomitanBadgeLabel, yomitanBadgeTone)}
</div> </div>
${hostCard} ${hostCard}
${renderFfmpegCard(model.ffmpeg)}
${mpvExecutablePathCard} ${mpvExecutablePathCard}
${windowsShortcutCard} ${windowsShortcutCard}
${renderCommandLineLauncherSection(model.commandLineLauncher)} ${renderCommandLineLauncherSection(model.commandLineLauncher)}
@@ -566,6 +620,7 @@ export function parseFirstRunSetupSubmissionUrl(rawUrl: string): FirstRunSetupSu
action !== 'configure-windows-mpv-shortcuts' && action !== 'configure-windows-mpv-shortcuts' &&
action !== 'install-bun' && action !== 'install-bun' &&
action !== 'install-command-line-launcher' && action !== 'install-command-line-launcher' &&
action !== 'install-ffmpeg' &&
action !== 'open-yomitan-settings' && action !== 'open-yomitan-settings' &&
action !== 'open-config-settings' && action !== 'open-config-settings' &&
action !== 'refresh' && action !== 'refresh' &&