// PREPARING THE WALK: what the clip bench makes lazily on a clip's first open, // made ahead of time, in the background, politely. // // Opening a clip whose source is a long recording (a saved whole stream; any // window longer than EXCERPT_OVER_S) used to stall on "decoding the audio…" // for 30 s and more: the bench's routes cut the excerpt on first read // (serve.mjs, "A RECORDING IS NOT A WINDOW"), then the waveform decoded it -- // all of it while a person waited. This makes the same files beforehand: // // - the EXCERPT, through serve.mjs's own excerptOf + ensureWindowFile, so the // name, the rounding, the padding and the encode are the bench's, and the // bench finds it (cut from its source as it is now = done); // - the WAVEFORM, through lib/analyse.mjs, the same disk cache // /api/report/peaks reads (keyed by the file's path, mtime and size). // // NOT the decoded audio. /api/report/audio decodes the bench's first span // (decodeSpan: the whole excerpt, or the clip ± DECODE_MARGIN) from the // excerpt in ~0.15 s once the excerpt is on disk (measured 2026-10-26, a 63 s // span of a 2-minute excerpt), and the browser keeps the answer // (`immutable`). A cached WAV would be ~12 MB a clip to save a sixth of a // second, so the route stays as it is. // // HOW IT RUNS: one runner process per project (`umtool prep --run`), // detached from whoever asked, so a writer is never held and a restart of the // app does not lose the work. Not lib/jobs.ts: that runner is one job at a // time for the whole app, so a prep waiting behind a 40-minute render for the // heavy slot would refuse every fetch, build and take the bench asks for // meanwhile, and it is in memory, where the CLI's triggers (`umtool window`, // `umtool timeline insert`, `umtool fetch`) cannot reach it. Its progress is a // status file the app reads (prep-status.json), as fetch-runs.json is for a // fetch. // // - ONE CLIP AT A TIME, each in the machine's HEAVY SLOT with a declared // estimate (PREP_ESTIMATE_MB: an excerpt cut measured at 234 MB RSS, plus // the node runner): beside a render while MemAvailable minus the running // estimates stays >= the floor, waiting otherwise, and released between // clips so a render queued behind it waits one clip at most. The floor is // never bypassed here (HEAVY=0 is the operator's own switch). // - `nice -n 19` and `ionice -c3`: the runner is started under both, so its // ffmpeg children inherit the lowest CPU priority and the idle I/O class. // - Requests are a queue file (`.prep-pending`, one JSON line each) beside a // run lock (`.prep-run.lock`, the runner's pid): a trigger appends and // starts a runner only when none is alive; the runner drains the queue // until it is empty, then looks once more after letting go of the lock. // // A clip somebody opens before the prep reaches it is cut by the bench, as // before; the prep then finds it fresh and skips it. A cut in flight in either // process is waited for by the other (serve.mjs, `.cutting`). import { spawn } from "node:child_process"; import { closeSync, existsSync, openSync, readFileSync, statSync, unlinkSync, writeSync } from "node:fs"; import { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { MIX_CACHE, REPORTS_ROOT, inside } from "../paths.mjs"; import { analysisCacheFile } from "../analyse.mjs"; import { clipsOf, readManifest } from "../projects/report.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; import { isTakeId } from "./takes.mjs"; import { absOf, ensureWindowFile, projectCache, windowFileFresh, windowsFor } from "./serve.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** An excerpt cut's resident set (234 MB, measured: a 2-minute 720p excerpt of a 1080p stream) plus the runner. */ export const PREP_ESTIMATE_MB = 400; /** Where the prep keeps its state: beside the excerpts it makes. */ export const prepDirOf = (projectDir) => path.join(/* turbopackIgnore: true */ projectDir, "out", "bench-excerpts"); // A TAKE'S PREP (`umtool prep

--take `, the take's walk) keeps its own // status, queue, lock and log, under out/bench-excerpts/takes//: a take's // clip may carry the cut's id with other bounds (a widened kf3), and a // failure, a queued request or a runner of one must never read as the // other's. The excerpts themselves are shared -- named by their seconds of the // source, so one cut serves every clip that opens the same seconds. /** * The directory a prep's state lives in: the project's, or a take's. * @param {string} projectDir * @param {string | null} [take] */ export function prepStateDirOf(projectDir, take = null) { if (!take) return prepDirOf(projectDir); if (!isTakeId(take)) throw new Error(`"${take}" is not a take id`); return path.join(/* turbopackIgnore: true */ prepDirOf(projectDir), "takes", take); } const statusFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), "prep-status.json"); const pendingFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), ".prep-pending"); const lockFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), ".prep-run.lock"); /** The runner's stdout and stderr (the heavy slot's waiting lines land here). */ export const prepLogOf = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), "prep.log"); /** * The manifest a prep reads: the project's, or -- with `take` -- the take's as * its walk reads it (takeManifest.mjs resolveTakeManifest: the project's * manifest now, the style's patch, then the take's, merged). A DRAFT take * (recorded, nothing rendered) has one too: nothing here waits for a render, * and the windows prepared are the ones the take's bench will open. * * @param {{ dir: string }} project * @param {string | null} [take] */ export async function prepManifestOf(project, take = null) { if (!take) return readManifest(project.dir); const { resolveTakeManifest } = await import("./takeManifest.mjs"); return (await resolveTakeManifest(project.dir, take)).manifest; } const alive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return /** @type {NodeJS.ErrnoException} */ (e).code === "EPERM"; } }; // --------------------------------------------------------------------------- // What the bench would make, per clip. // --------------------------------------------------------------------------- /** * @typedef {{ * id: string, * video: string, * state: "ready" | "todo" | "no-window" | "failed", * window: { name: string, from: number, to: number } | null, * excerpt: boolean, * cut: boolean, * peaks: boolean, * error?: string, * win?: any, * }} PrepItem */ /** * Per clip: the window the bench would open (windowsFor's first, the same * listing the clip route and the bench page read) and what of it is on disk. * * `cut`: the excerpt is there and was cut from its recording as it is now (a real window is * always "cut"). `peaks`: its analysis is in the cache. A clip whose last prep * of THIS window failed reads `failed` until the window changes (an explicit * prep tries it again; a trigger does not). * * `take`: the take's clips (prepManifestOf), its failures from its own status. * * @param {{ id: string, dir: string }} project * @param {any} [manifest] * @param {{ clips?: string[] | null, cache?: any, mixCache?: string, take?: string | null }} [opts] * @returns {Promise<{ items: PrepItem[], counts: { clips: number, ready: number, todo: number, failed: number, noWindow: number, excerpts: number } }>} */ export async function benchPrepPlan(project, manifest = null, { clips = null, cache = null, mixCache = MIX_CACHE, take = null } = {}) { const m = manifest ?? (await prepManifestOf(project, take)); const want = clips && clips.length ? new Set(clips) : null; const all = clipsOf(m).filter((c) => !want || want.has(c.id)); const c = cache ?? (await projectCache(project, m)); const failures = (await readPrepStatus(project.dir, take))?.failed ?? {}; /** @type {PrepItem[]} */ const items = []; for (const clip of all) { const wins = await windowsFor(project, clip, c); const win = wins[0] ?? null; if (!win) { items.push({ id: clip.id, video: String(clip.video), state: "no-window", window: null, excerpt: false, cut: false, peaks: false }); continue; } const excerpt = !!win.excerptOf; let cut = true; let peaks = false; let error; try { cut = await windowFileFresh(win); const abs = absOf(win); const st = cut && abs ? await stat(abs).catch(() => null) : null; peaks = !!(st && abs && existsSync(/* turbopackIgnore: true */ analysisCacheFile(abs, st, mixCache))); } catch (e) { error = e instanceof Error ? e.message : String(e); } const f = failures[clip.id]; const failedHere = !!(f && f.window === win.name); const state = cut && peaks ? "ready" : failedHere || error ? "failed" : "todo"; items.push({ id: clip.id, video: String(clip.video), state, window: { name: win.name, from: win.from, to: win.to }, excerpt, cut, peaks, ...(error || failedHere ? { error: error ?? f.error } : {}), win, }); } const n = (s) => items.filter((i) => i.state === s).length; return { items, counts: { clips: items.length, ready: n("ready"), todo: n("todo"), failed: n("failed"), noWindow: n("no-window"), excerpts: items.filter((i) => i.excerpt && i.state !== "ready").length, }, }; } /** A plan item without its window's internals: what a status line or --json shows. */ export const publicItem = ({ win, ...rest }) => rest; // --------------------------------------------------------------------------- // The status file. // --------------------------------------------------------------------------- /** * @typedef {{ * pid: number | null, * state: "running" | "done" | "failed", * startedAt: string, * endedAt: string | null, * total: number, * done: number, * current: { id: string, step: "waiting" | "cutting" | "analysing" } | null, * failed: Record, * }} PrepStatus */ /** @param {string} dir @param {string | null} [take] @returns {Promise} */ export async function readPrepStatus(dir, take = null) { try { return JSON.parse(await readFile(statusFile(dir, take), "utf8")); } catch { return null; } } /** @param {string} dir @param {PrepStatus} st @param {string | null} [take] */ async function writePrepStatus(dir, st, take = null) { await mkdir(prepStateDirOf(dir, take), { recursive: true }); const tmp = tmpPathFor(statusFile(dir, take)); await writeFile(tmp, `${JSON.stringify(st, null, 1)}\n`); await rename(tmp, statusFile(dir, take)); } /** * What the app and `umtool prep --status` show: the plan's counts, and the * runner when one is alive (a status file naming a dead pid as `running` is a * runner that was killed: it reads as stopped). * * @param {{ id: string, dir: string }} project * @param {{ clips?: string[] | null, plan?: Awaited>, take?: string | null }} [opts] */ export async function benchPrepState(project, { clips = null, plan = null, take = null } = {}) { const p = plan ?? (await benchPrepPlan(project, null, { clips, take })); const st = await readPrepStatus(project.dir, take); const holder = lockHolder(project.dir, take); const running = !!holder || (st?.state === "running" && alive(Number(st.pid))); return { project: project.id, take, counts: p.counts, running, runner: running ? { pid: holder ?? st?.pid ?? null, done: st?.done ?? 0, total: st?.total ?? 0, current: st?.current ?? null } : null, last: st && !running ? { state: st.state === "running" ? "stopped" : st.state, endedAt: st.endedAt, done: st.done, total: st.total } : null, items: p.items.map(publicItem), }; } // --------------------------------------------------------------------------- // Doing it: one clip at a time. // --------------------------------------------------------------------------- /** * Prepare the clips that need it, sequentially, each inside `slot` (the heavy * slot; the CLI passes heavy-gate's withRenderSlot with PREP_ESTIMATE_MB). * * @param {{ id: string, dir: string }} project * @param {{ * clips?: string[] | null, * retry?: boolean, * slot?: (cmd: string[], fn: () => Promise) => Promise, * ensure?: (win: any) => Promise, * analyse?: (abs: string) => Promise, * onEvent?: (ev: Record) => void, * mixCache?: string, * take?: string | null, * }} [opts] * @returns {Promise<{ done: string[], failed: string[], skipped: number }>} */ export async function runBenchPrep(project, { clips = null, retry = false, take = null, slot = (_cmd, fn) => fn(), ensure = (win) => ensureWindowFile(win), analyse = null, onEvent = () => {}, mixCache = MIX_CACHE, } = {}) { const analyseOne = analyse ?? (async (abs) => (await import("../analyse.mjs")).analyseFile(abs, { cacheDir: mixCache })); const plan = await benchPrepPlan(project, null, { clips, mixCache, take }); const todo = plan.items.filter((i) => i.state === "todo" || (retry && i.state === "failed")); const prev = await readPrepStatus(project.dir, take); const put = (st) => writePrepStatus(project.dir, st, take); /** @type {PrepStatus} */ const status = { pid: process.pid, state: "running", startedAt: new Date().toISOString(), endedAt: null, total: todo.length, done: 0, current: null, failed: { ...(prev?.failed ?? {}) }, }; // A failure of a window no longer in the plan is history, not a state. for (const id of Object.keys(status.failed)) { const it = plan.items.find((i) => i.id === id); if (it && it.window?.name !== status.failed[id].window) delete status.failed[id]; } await put(status); onEvent({ ev: "start", project: project.id, ...(take ? { take } : {}), total: todo.length, ready: plan.counts.ready, noWindow: plan.counts.noWindow }); const done = []; const failed = []; for (const it of todo) { const t0 = Date.now(); status.current = { id: it.id, step: "waiting" }; await put(status); onEvent({ ev: "clip", id: it.id, step: "waiting", n: done.length + failed.length + 1, total: todo.length }); try { await slot(["umtool-prep", project.id, ...(take ? ["--take", take] : []), it.id], async () => { if (!it.cut) { status.current = { id: it.id, step: "cutting" }; await put(status); onEvent({ ev: "clip", id: it.id, step: "cutting", window: it.window?.name }); await ensure(it.win); } if (!it.peaks) { status.current = { id: it.id, step: "analysing" }; await put(status); onEvent({ ev: "clip", id: it.id, step: "analysing" }); const abs = absOf(it.win); if (!abs) throw new Error("the window is outside the roots"); await analyseOne(abs); } }); delete status.failed[it.id]; done.push(it.id); onEvent({ ev: "clip-done", id: it.id, ms: Date.now() - t0 }); } catch (e) { const error = e instanceof Error ? e.message : String(e); status.failed[it.id] = { window: it.window?.name ?? "", error: error.split("\n").slice(-3).join(" ").slice(0, 400), at: new Date().toISOString() }; failed.push(it.id); onEvent({ ev: "clip-failed", id: it.id, error }); } status.done = done.length + failed.length; await put(status); } status.current = null; status.state = failed.length ? "failed" : "done"; status.endedAt = new Date().toISOString(); await put(status); onEvent({ ev: "end", done: done.length, failed: failed.length, skipped: plan.items.length - todo.length }); return { done, failed, skipped: plan.items.length - todo.length }; } // --------------------------------------------------------------------------- // The queue and the run lock. // --------------------------------------------------------------------------- /** The live runner's pid, or null (a lock naming a dead pid is dropped). @param {string} dir @param {string | null} [take] */ export function lockHolder(dir, take = null) { let raw; try { raw = readFileSync(/* turbopackIgnore: true */ lockFile(dir, take), "utf8"); } catch { return null; } const pid = Number(String(raw).trim()); if (alive(pid)) return pid; try { unlinkSync(/* turbopackIgnore: true */ lockFile(dir, take)); } catch { /* somebody else dropped it */ } return null; } /** Take the run lock, or false when a live runner holds it. @param {string} dir @param {string | null} [take] */ export function tryLock(dir, take = null) { for (let i = 0; i < 2; i += 1) { try { const fd = openSync(/* turbopackIgnore: true */ lockFile(dir, take), "wx"); writeSync(fd, `${process.pid}\n`); closeSync(fd); return true; } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e; if (lockHolder(dir, take)) return false; } } return false; } /** @param {string} dir @param {string | null} [take] */ export function unlock(dir, take = null) { try { if (Number(readFileSync(/* turbopackIgnore: true */ lockFile(dir, take), "utf8").trim()) === process.pid) { unlinkSync(/* turbopackIgnore: true */ lockFile(dir, take)); } } catch { /* not ours, or gone */ } } /** * Add a request to the project's queue. `clips: null` is every clip. * @param {string} dir * @param {{ clips: string[] | null, retry?: boolean }} req * @param {string | null} [take] */ export async function appendPrepRequest(dir, req, take = null) { await mkdir(prepStateDirOf(dir, take), { recursive: true }); await appendFile(pendingFile(dir, take), `${JSON.stringify({ clips: req.clips ?? null, retry: !!req.retry, at: Date.now() })}\n`); } /** * Take every queued request at once (a rename, so a trigger appending * meanwhile starts a new file), merged: the union of the clips (`null` if any * asks for all), `retry` if any does. Null when the queue is empty. * * @param {string} dir * @param {string | null} [take] * @returns {Promise<{ clips: string[] | null, retry: boolean } | null>} */ export async function takePrepRequests(dir, take = null) { const taking = `${pendingFile(dir, take)}.${process.pid}`; try { await rename(pendingFile(dir, take), taking); } catch { return null; } const text = await readFile(taking, "utf8").catch(() => ""); await rm(taking, { force: true }); return mergeRequests(text.split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean)); } /** @param {{ clips?: string[] | null, retry?: boolean }[]} reqs */ export function mergeRequests(reqs) { if (!reqs.length) return null; let all = false; const ids = new Set(); let retry = false; for (const r of reqs) { if (!Array.isArray(r.clips)) all = true; else for (const id of r.clips) ids.add(String(id)); if (r.retry) retry = true; } return { clips: all ? null : [...ids], retry }; } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** * The runner: hold the project's lock and drain its queue. `initial` is this * run's own request (`umtool prep --wait`); `wait` waits for a busy lock * instead of leaving the queue to the runner that holds it. * * @param {{ id: string, dir: string }} project * `take`: the take's queue, under the take's lock (prepStateDirOf). * * @param {{ id: string, dir: string }} project * @param {Parameters[1] & { initial?: { clips: string[] | null, retry?: boolean } | null, wait?: boolean, pollMs?: number }} [opts] * @returns {Promise<{ runs: number, done: string[], failed: string[], held: boolean }>} */ export async function drainPrepQueue(project, { initial = null, wait = false, pollMs = 2000, ...run } = {}) { const take = run.take ?? null; await mkdir(prepStateDirOf(project.dir, take), { recursive: true }); const done = []; const failed = []; let runs = 0; let own = initial; for (;;) { if (!tryLock(project.dir, take)) { if (!wait) return { runs, done, failed, held: true }; await sleep(pollMs); continue; } try { for (;;) { const queued = await takePrepRequests(project.dir, take); const req = own && queued ? mergeRequests([own, queued]) : own ?? queued; own = null; if (!req) break; runs += 1; const r = await runBenchPrep(project, { ...run, clips: req.clips, retry: !!req.retry }); done.push(...r.done); failed.push(...r.failed); } } finally { unlock(project.dir, take); } // A request appended after the last look and before the unlock saw a live // runner and started none: look once more, now that the lock is free. if (!existsSync(/* turbopackIgnore: true */ pendingFile(project.dir, take))) return { runs, done, failed, held: false }; wait = false; } } // --------------------------------------------------------------------------- // Asking for it: the triggers and the button. // --------------------------------------------------------------------------- /** @param {string} name */ function onPath(name) { for (const d of String(process.env.PATH ?? "").split(path.delimiter)) { if (d && existsSync(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ d, name))) return true; } return false; } /** * The runner's argv: `umtool prep --run` under `nice -n 19` and * `ionice -c3` (each when it is installed), so every ffmpeg it starts inherits * both. Pure apart from the PATH probe. * * @param {string} projectId * @param {{ wait?: boolean, clips?: string[] | null, retry?: boolean, ndjson?: boolean, take?: string | null, has?: (name: string) => boolean }} [opts] */ export function runnerArgv(projectId, { wait = false, clips = null, retry = false, ndjson = false, take = null, has = onPath } = {}) { const prefix = [ ...(has("nice") ? ["nice", "-n", "19"] : []), ...(has("ionice") ? ["ionice", "-c3"] : []), ]; return [ ...prefix, process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "prep", projectId, ...(take ? ["--take", take] : []), "--run", ...(wait ? ["--wait"] : []), ...(clips && clips.length ? ["--clips", clips.join(",")] : []), ...(retry ? ["--retry"] : []), ...(ndjson ? ["--ndjson"] : []), ]; } /** * Start a detached runner, its output appended to prep.log (the take's, for a take). * @param {{ id: string, dir: string }} project * @param {{ take?: string | null }} [opts] */ export function spawnPrepRunner(project, { take = null } = {}) { const argv = runnerArgv(project.id, { take }); // The log is the last runs', not a history: past 1 MB it starts again. const big = (() => { try { return statSync(/* turbopackIgnore: true */ prepLogOf(project.dir, take)).size > 1024 * 1024; } catch { return false; } })(); const fd = openSync(/* turbopackIgnore: true */ prepLogOf(project.dir, take), big ? "w" : "a"); try { const child = spawn(argv[0], argv.slice(1), { cwd: UMTOOL_DIR, detached: true, stdio: ["ignore", fd, fd], env: process.env, }); child.on("error", () => {}); child.unref(); return child.pid ?? null; } finally { closeSync(fd); } } /** * Queue prep for some clips of a project (all when `clips` is null) and start * a runner when none is alive. Returns at once: nothing here cuts or waits. * * `excerptsOnly` (the triggers): queue only when a clip needs an EXCERPT -- * the slow part, and the only reason to start a process after a write; a * short window's waveform is a fraction of a second on first open. The runner * then prepares each queued clip whole. `retry` also takes clips whose last * prep failed (an explicit ask; a trigger leaves them). * * `take`: the take's clips, queued for the take's own runner (`umtool prep

--take --run`). * * @param {{ id: string, dir: string }} project * @param {string[] | null} [clips] * @param {{ excerptsOnly?: boolean, retry?: boolean, take?: string | null, start?: (project: { id: string, dir: string }, opts: { take: string | null }) => number | null, plan?: any }} [opts] * @returns {Promise<{ queued: string[], started: boolean, pid: number | null, off?: boolean }>} */ export async function queueBenchPrep(project, clips = null, { excerptsOnly = false, retry = false, take = null, start = spawnPrepRunner, plan = null } = {}) { if (process.env.UMTOOL_BENCH_PREP === "0") return { queued: [], started: false, pid: null, off: true }; const p = plan ?? (await benchPrepPlan(project, null, { clips, take })); const queued = p.items .filter((i) => i.state === "todo" || (retry && i.state === "failed")) .filter((i) => !excerptsOnly || (i.excerpt && !i.cut)) .map((i) => i.id); if (!queued.length) return { queued, started: false, pid: lockHolder(project.dir, take) }; await appendPrepRequest(project.dir, { clips: queued, retry }, take); const holder = lockHolder(project.dir, take); if (holder) return { queued, started: false, pid: holder }; return { queued, started: true, pid: start(project, { take }) }; } /** * The project a manifest directory is, when it is one of REPORTS_ROOT's (ids * are paths relative to it). A directory elsewhere -- a test's temp dir -- is * not a project anything here prepares for. * @param {string} dir */ export function projectOfDir(dir, root = REPORTS_ROOT) { const abs = path.resolve(/* turbopackIgnore: true */ dir); if (!inside(root, abs) || abs === root) return null; return { id: path.relative(root, abs).split(path.sep).join("/"), dir: abs }; }