commit a7a48b349b170ac7a05a6b41faa920a1adb16655
parent 8ca9345d5dbb2547e96928a5548c7bbb7c660ca3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 27 Oct 2026 14:36:22 -0400
Merge lane/bench-prep: the clip bench's first-open work (a long recording's excerpt, the waveform) made before the walk, as a queued, polite job
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
21 files changed, 1694 insertions(+), 143 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -10,6 +10,7 @@
- **A report video's trailer can be cut from the finished video, so it shows the whole timeline.** The Huck trailer was a short take of its own: 14 clips with their own rail, so the on-screen timeline, dates and tallies said the video was two minutes long. `umtool trailer <project> --take <take> --beats beats.json --intro --finale 8` now cuts the trailer from the take's finished master instead. Each beat is a clip's source seconds (or master seconds), and the take's own build records find where those seconds play in the master. The rail on screen is the full video's, so a viewer can see there is more. Nothing is rendered again: it is one ffmpeg pass, crossfaded and encoded with the take's own settings. It writes `<slug>.trailer.mp4` beside the master and a `.trailer.json` record of what was cut. A beat that reaches into one of the master's own crossfades is moved in, and the command says so. A beat that runs into the next piece (the intro into the first clip, the last beat into the finale) plays straight on, so no moment is shown twice. Unknown clips, beats outside what was cut, and takes with no build are refused by name.
- **A twin of a finished report-video take renders in a fraction of the time.** A full build of the Huck cut took about 1 h 45 m, and its uncensored twin — the same cut with `render.blur` off — took as long again, because every build encoded all 66 clips again (about 8 minutes), which in turn redid every crossfade batch, and captured the on-screen chrome again (about 47 minutes) once the first build had pruned its frames. Now a clip's segment is encoded again only when something that makes its picture or sound changed (its cut, snap, room, blur, framing, captions, loudness, encode settings or source file); otherwise the one on disk is reused untouched, and so are the crossfade batches over it. `umtool take <project> --id <id> --from <other take> …` starts a take from another take's render: it hard-links that take's clip segments, chrome frames and crossfade batches in (no copies, and the other take's files never change) and renders, rebuilding only what differs — for the uncensored twin, the blurred clip and the batch it sits in, then the final overlay. Make the first take with `--keep-frames` so its chrome frames are still there for the twin (they are 1–3 GB a layer; without it they are pruned after the render as before). `--from` refuses a take that does not exist, the take itself, or a take never rendered. Needs a restart of umtool for the Takes page's jobs; the CLI has it at once.
- **A report video's brand intro can turn into the cited site's on the chime.** With `render.intro.site: "auto"` the "ARCHILYZER" intro becomes, on its second chime, the archive the video cites: "Archi" swipes down out of its line as the site's name swipes in from above ("Jera" for the Huck cut, which cites jeralyzer.pages.dev), "lyzer" stays, the word re-centres, and the letters, MEDIA and the mark's lit line turn the site's colour (brass for Jeralyzer), while jeralyzer.pages.dev and archilyzer.pages.dev rise in under MEDIA. `"site"` also takes a site id (`"hasanalyzer"`) or the site spelled out (`{"name": "Jeralyzer", "accent": "brass", "url": "jeralyzer.pages.dev"}`). `"swap"` picks the change: `swipe-down` (the default), `roll` (letter by letter, like a split-flap board) or `wipe` (a line of the site's colour sweeps down the name). `"url"` picks the URLs (`both`, `site`, `project`, or `false` for none) and `"urlPlace"` where they go (`under` MEDIA in one row, or `replace`, one line each in MEDIA's place). An intro without `site` is exactly as before, and its cached render is reused. A site id with no site, or a bad value, is refused by name. Set it in a take (`--set render.intro.site=auto`) or in the manifest; variants to compare are in ~/reports/archilyzer-intro/variants/site. Needs a restart of umtool and a rebuild of the video.
+- **Opening a clip on umtool's walk no longer waits on ffmpeg.** A clip cut from a long recording (a saved whole stream) opened on "decoding the audio…" for 30 s or more, because the bench cut its 2-minute excerpt and decoded its waveform the first time it was opened. That work is now done before the walk, in the background: the Cut tab's **Prepare clips for the walk** (beside it, how many clips are ready to open and what it is on while it runs), `umtool prep <project>` (`--wait` to run it in the terminal, `--status` to see what is left), and by itself after a fetch lands a window and after an edit moves a clip's edges or adds a clip. It makes exactly the files the bench would, so the bench finds them, and skips a clip already prepared. It is polite to the machine: one clip at a time, each through the heavy slot with a small memory estimate (it runs beside a render while memory allows and waits when it does not), at the lowest CPU and disk priority. A clip opened before the prep gets to it is prepared by the bench as before. On a copy of the Huck cut, a clip on a saved stream took 51 s to answer the bench's first audio request unprepared; prepared (raw-only, on a 3-hour stream), it answered in 0.3–0.8 s and its waveform in 0.08 s. `UMTOOL_BENCH_PREP=0` turns the queueing off. Needs a restart of umtool.
- **A report video's fact-check counter can stay off screen until it first counts.** The deck's tally drew every verdict's cell from the first frame, so in the Huck cut the "Huck's Blend pitches" cell read 0 for about 23 of its 29 minutes. With `render.chrome.factcheck.tally.showAt: "first"` a cell is hidden until the stamp that gives it its first count lands; then it pops in already reading that count, flashes, and stays to the end. `{ "PARTLY": "first" }` sets it for one verdict's cell only. The default, `"always"`, is the tally as before. A hidden cell keeps its place in the row, and the finale's totals still show every verdict. Set it in the On-screen tab's fact-check labels (**pop in**, per verdict), with `umtool look <project> factcheck.tally.showAt=first` (or `factcheck.tally.showAt.PARTLY=first`; `factcheck.tally.showAt=` clears it), or in a take (`--set render.chrome.factcheck.tally.showAt=first`). An unknown value is refused by name. The clip editor's live preview and the Play view show the same deck page as the render, so the cell pops in at the same moment there. Needs a restart of umtool and a rebuild of the video.
- **A report video's finale timeline no longer prints words over words.** In the Huck cut's finale the claim checks' words all stood on one line over the rail (`“less than ten” a year`, `19 seizures on camera`, `12 in a day · 4 in a week`, both pill-test goalposts), the `12 IN A DAY`/`4 IN A WEEK` labels ran into the markers' flags, and the turned dates under the rail overlapped. Now the claim checks take turns (`deck.finale.claims`: `rotate`, the default — one claim at a time for an even share of the finale's time, at least 6 s each, with a short crossfade; `all` stacks them), every claim's words, span label and marker label is laid in its own place in rows over the rail, with its stick kept inside its bracket and clear of the words under it, and a crowded rail says each date once and fans the turned labels out on thin leaders so no two meet. The timeline takes the height its rows need (`deck.finale.timelineShare`: `auto`, up to just over half the frame, its words set larger when there is room; or a share 0.38–0.6), and the clip, the totals and the stats shrink to fit under it. A finale without claim checks and with room for its labels renders as before. Re-render a take to see it.
- **An assistant can finish a report video from umtool's command line without hand fixes.** `umtool variants <project> --take <take>` now makes the delivery ladder (master, 1080p, 720p, fit24) of a finished take, and so does the Deliver tab's **Make variants** with a take picked. A take used to be refused with "has no build to make variants of" because its render was moved to `takes/<take>/preview.mp4`; the take maker now also leaves it in the take's `out/` under the build's name (a hard link, so no extra disk), and a take made before this is encoded from its `preview.mp4`. `umtool timeline <project> insert` writes a clip the way the rest of the cut is written: in a cut with the on-screen deck, `--title` sets the deck's title (`onscreen.title`; `--stream-title` sets the stream's), a cut whose deck titles are dates gets `--date` as one in the same format (`9 Dec 2024`), the clip takes the section of the clip it goes after unless `--section N` says otherwise, and `--lock` and `--lock-end` lock its edges. `umtool check` now says how to fix a clip with no cue file: `pnpm ops build-cues --json '{"slug":"<channel>","ids":["<video>"]}' --wait` when the video is in the archive, and the Rumble two-ids check when it is not. A take of part of a cut says in its log what timed the window: the last build's schedule, or the clips' own lengths when there is no schedule or it does not time clips inserted since the build.
diff --git a/umtool/app/api/report/fetch-windows/route.ts b/umtool/app/api/report/fetch-windows/route.ts
@@ -9,7 +9,9 @@ import {
readFetchRuns,
recordFetchRun,
summarizeAnswer,
+ TERMINAL,
} from "@/lib/report/fetchWindows.mjs";
+import { benchPrepAfterWrite } from "@/lib/report/benchPrepTrigger.mjs";
export const dynamic = "force-dynamic";
@@ -63,6 +65,11 @@ export async function POST(request: Request) {
const run = lastStartedRun(await readFetchRuns(project.dir));
if (!run) return Response.json({ error: "no fetch run has started jobs yet" }, { status: 404, headers });
const jobs = await followRun(cfg, project.dir, run);
+ // A run that has ended landed what it landed: the bench's prep for it,
+ // in the background (lib/report/benchPrep.mjs).
+ if (jobs.length && jobs.every((j: { status: string }) => TERMINAL.has(j.status)) && jobs.some((j: { status: string }) => j.status === "done")) {
+ benchPrepAfterWrite(project.dir, null, { excerptsOnly: false });
+ }
return Response.json({ run: { at: run.at, jobIds: run.jobIds, summary: run.summary }, jobs }, { headers });
}
if (action !== "dry-run" && action !== "start") {
diff --git a/umtool/app/api/report/fetch/route.ts b/umtool/app/api/report/fetch/route.ts
@@ -7,6 +7,7 @@ import {
localFetch,
} from "@/lib/report/driver.mjs";
import { projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs";
+import { benchPrepAfterWrite } from "@/lib/report/benchPrepTrigger.mjs";
export const dynamic = "force-dynamic";
@@ -149,6 +150,9 @@ export async function POST(request: Request) {
steps,
{
project: r.project.id,
+ // The window it landed, prepared for the bench (a long recording's
+ // excerpt, the waveform) in the background: lib/report/benchPrep.mjs.
+ onDone: () => benchPrepAfterWrite(r.project.dir, [clipId], { excerptsOnly: false }),
},
);
// Which side this run is growing, so the caller can say so rather than
diff --git a/umtool/app/api/report/prep/route.ts b/umtool/app/api/report/prep/route.ts
@@ -0,0 +1,45 @@
+import { projectRef } from "@/lib/projects";
+import { benchPrepState, queueBenchPrep } from "@/lib/report/benchPrep.mjs";
+
+export const dynamic = "force-dynamic";
+
+// PREPARING THE WALK (lib/report/benchPrep.mjs): what the clip bench makes on a
+// clip's first open -- a long recording's excerpt, the waveform -- made ahead,
+// by a runner in the background (`umtool prep <project> --run`), one clip at a
+// time in the machine's heavy slot. The Cut tab's "Prepare clips for the walk".
+//
+// GET ?project=<id> ready / to prepare / failed / not fetched, and the runner when one is alive
+// POST { project, clips? } queue them (all when none are named); returns at once
+const headers = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(url.searchParams.get("project") ?? "");
+ if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
+ try {
+ const s = await benchPrepState({ id: project.id, dir: project.dir });
+ return Response.json({ ...s, items: undefined }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers });
+ }
+}
+
+export async function POST(request: Request) {
+ const b = (await request.json().catch(() => null)) as { project?: unknown; clips?: unknown } | null;
+ if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const project = await projectRef(String(b.project ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
+ const clips = Array.isArray(b.clips) ? b.clips.map(String).filter(Boolean) : null;
+ const ref = { id: project.id, dir: project.dir };
+ try {
+ const q = await queueBenchPrep(ref, clips, { retry: true });
+ const s = await benchPrepState(ref);
+ // A runner just started may not hold its lock yet: it is running all the same.
+ return Response.json(
+ { ...s, running: s.running || q.started, items: undefined, queued: q.queued.length, started: q.started, off: !!q.off },
+ { headers },
+ );
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -63,6 +63,8 @@
// the clip deck's montage rulings (release 34)
// umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of
// the editor as one fetch-windows batch (release 35)
+// umtool prep <project> [--clips a,b] [--wait | --status] [--json] the bench's excerpts and waveforms,
+// made before the walk (one clip at a time, in the heavy slot)
// umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] stand-ins for refused windows
// umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex]
// [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass)
@@ -781,6 +783,10 @@ function usage() {
" umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]",
" the clip windows asked of the editor as one fetch-windows batch (one paced job per platform);",
" each run recorded in <project>/fetch-runs.json",
+ " umtool prep <project> [--clips a,b] [--wait | --status] [--json]",
+ " what the clip bench makes on a clip's first open (a long recording's excerpt, the waveform),",
+ " made before the walk: queued and run in the background, one clip at a time, in the heavy slot",
+ " (a small declared estimate), under nice/ionice; --wait runs it here; a write or a fetch queues it too",
" umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] [--json]",
" stand-ins for refused montage windows: the instance's public alternate (YouTube first), on the clip",
" umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]",
@@ -819,6 +825,15 @@ function usage() {
);
}
+// A write that queued the bench's prep (lib/report/benchPrepTrigger.mjs) has
+// a plan to finish before process.exit cuts it off: a few stats, at most a
+// detached runner started. Never the prep itself.
+async function settled(code) {
+ const { settleBenchPrepTriggers } = await import("../lib/report/benchPrepTrigger.mjs");
+ await settleBenchPrepTriggers();
+ return code;
+}
+
const COMMANDS = {
ls: cmdLs,
window: cmdWindow,
@@ -851,7 +866,9 @@ const COMMANDS = {
// The clip deck's rulings (release 34): lib/report/rulingsCli.mjs.
rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))),
// Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs.
- fetch: async () => process.exit(await (await import("../lib/report/fetchCli.mjs")).fetchCommand(argv.slice(argv.indexOf("fetch") + 1))),
+ fetch: async () => process.exit(await settled(await (await import("../lib/report/fetchCli.mjs")).fetchCommand(argv.slice(argv.indexOf("fetch") + 1)))),
+ // The clip bench's first-open work, ahead of the walk: lib/report/prepCli.mjs.
+ prep: async () => process.exit(await (await import("../lib/report/prepCli.mjs")).prepCommand(argv.slice(argv.indexOf("prep") + 1))),
fallback: async () => process.exit(await (await import("../lib/report/standInsCli.mjs")).fallbackCommand(argv.slice(argv.indexOf("fallback") + 1))),
// The phrase finder (release 34): lib/phrase-finder/cli.mjs.
phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))),
@@ -861,7 +878,7 @@ const COMMANDS = {
clips: async () => process.exit(await (await import("../lib/report/reactions.mjs")).clipsCommand(argv.slice(argv.indexOf("clips") + 1))),
// The cut's structure, scene cuts, posts from the archive (2026-10-25): lib/report/timelineCli.mjs,
// scenesCli.mjs, postsCli.mjs.
- timeline: async () => process.exit(await (await import("../lib/report/timelineCli.mjs")).timelineCommand(argv.slice(argv.indexOf("timeline") + 1))),
+ timeline: async () => process.exit(await settled(await (await import("../lib/report/timelineCli.mjs")).timelineCommand(argv.slice(argv.indexOf("timeline") + 1)))),
scenes: async () => process.exit(await (await import("../lib/report/scenesCli.mjs")).scenesCommand(argv.slice(argv.indexOf("scenes") + 1))),
posts: async () => process.exit(await (await import("../lib/report/postsCli.mjs")).postsCommand(argv.slice(argv.indexOf("posts") + 1))),
inbox: cmdInbox,
diff --git a/umtool/components/projects/report/BenchPrepPanel.tsx b/umtool/components/projects/report/BenchPrepPanel.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+
+// "Prepare clips for the walk" (lib/report/benchPrep.mjs): the clip bench's
+// first-open work -- a long recording's excerpt, the waveform -- made by a
+// runner in the background, one clip at a time in the heavy slot, so opening
+// a clip on the walk does not wait on ffmpeg. A status line and one button.
+
+type PrepState = {
+ counts: { clips: number; ready: number; todo: number; failed: number; noWindow: number; excerpts: number };
+ running: boolean;
+ runner: { pid: number | null; done: number; total: number; current: { id: string; step: string } | null } | null;
+ last: { state: string; endedAt: string | null; done: number; total: number } | null;
+ off?: boolean;
+ error?: string;
+};
+
+const POLL_MS = 2500;
+
+export default function BenchPrepPanel({ project }: { project: string }) {
+ const [s, setS] = useState<PrepState | null>(null);
+ const [asking, setAsking] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/prep?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as PrepState;
+ if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
+ else {
+ setErr(null);
+ setS(j);
+ }
+ }, [project]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useEffect(() => {
+ if (!s?.running) return;
+ const id = window.setTimeout(() => void load(), POLL_MS);
+ return () => window.clearTimeout(id);
+ }, [s, load]);
+
+ if (!s && !err) return null;
+ const c = s?.counts;
+ const fetched = c ? c.clips - c.noWindow : 0;
+ if (c && fetched === 0) return null;
+ const left = c ? c.todo + c.failed : 0;
+
+ async function prepare() {
+ setAsking(true);
+ setErr(null);
+ try {
+ const r = await fetch("/api/report/prep", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project }),
+ });
+ const j = (await r.json().catch(() => ({}))) as PrepState;
+ if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
+ else setS(j);
+ if (j.off) setErr("prep is switched off here (UMTOOL_BENCH_PREP=0)");
+ } finally {
+ setAsking(false);
+ }
+ }
+
+ const run = s?.runner;
+ return (
+ <div className="flex flex-wrap items-center gap-2" data-bench-prep="" data-bench-prep-state={s?.running ? "running" : left ? "todo" : "ready"}>
+ {left > 0 && !s?.running && (
+ <button
+ type="button"
+ data-action="bench-prep"
+ disabled={asking}
+ className={buttonVariants({ variant: "quiet", size: "sm" })}
+ onClick={() => void prepare()}
+ >
+ Prepare clips for the walk
+ </button>
+ )}
+ {c && (
+ <span className="text-[11px] text-[var(--color-dim)]" data-bench-prep-status="">
+ {c.ready} of {fetched} ready to open
+ {s?.running && run
+ ? ` · preparing ${Math.min(run.done + 1, Math.max(run.total, 1))} of ${run.total}${
+ run.current ? ` — ${run.current.id}, ${run.current.step === "waiting" ? "waiting for the heavy slot" : run.current.step}` : ""
+ }`
+ : left
+ ? ` · ${c.todo} to prepare${c.failed ? ` · ${c.failed} failed` : ""}`
+ : ""}
+ </span>
+ )}
+ {err && (
+ <span className="text-[11px] text-[var(--color-bad)]" data-bench-prep-error="">
+ {err}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -16,6 +16,7 @@ import { RowControls, RowNotes, TimelineList } from "../TimelineEditor";
import { Pill, TONE, hms, type ReportTabProps } from "./shared";
import VoiceMatchPanel from "./VoiceMatchPanel";
import FetchWindowsPanel from "./FetchWindowsPanel";
+import BenchPrepPanel from "./BenchPrepPanel";
import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs";
import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
@@ -155,6 +156,9 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
ready {readiness.ready} of {readiness.needing} needing judgement
</span>
</span>
+ {/* The bench's first-open work (a long recording's excerpt, the
+ waveform), made ahead in the background (lib/report/benchPrep.mjs). */}
+ <BenchPrepPanel project={project.id} />
</div>
)}
{/* The whole cut played in the browser in its final look, no render (the Play view). */}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -50,6 +50,7 @@ Inbox cannot disagree about what is wrong with one.
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. Every run is recorded in `<project>/fetch-runs.json`. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
+| `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). **Exit 1** when a clip failed (`--wait`) |
| `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in |
| `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase |
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
@@ -86,6 +87,7 @@ whatever directory it is run from — `umtool notes --all` from a report workspa
`REPORTS_DIR` reads the corpus's sites. The app (`next dev`/`start`) finds it by walking up
from its cwd to `pnpm-workspace.yaml`.
| `VIDEO_ROOT` (`song/spec.mjs`, `song/video-dir.mjs`) | `~/reports/quartering-uh-song/videos` |
+| `UMTOOL_BENCH_PREP` | unset = a fetch that lands and a write that moves or adds a clip queue the bench's prep (`prep`); `0` queues nothing (the triggers, `umtool prep` and the Cut tab's button; `prep --wait` still runs) |
## `check` is the one to run before every build
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -261,6 +261,34 @@ verdict, `N` the ones among them that can be judged today. The gap between the
two is what is waiting on a download rather than on you — every row the project
page marks **not fetched yet**.
+### Prepared before you open it
+
+A clip whose source is a long recording (a saved whole stream, any window over
+10 minutes) is opened on an **excerpt**: the clip and 45 s either side, edges
+rounded out to 15 s, cut once into `out/bench-excerpts/<video>/<from>-<to>.excerpt.mp4`
+(`lib/report/serve.mjs`). Cut on first open, that is 10–35 s of ffmpeg with the
+bench saying "decoding the audio…", and then the waveform is decoded.
+
+So the walk is prepared ahead: **Prepare clips for the walk** under the Cut
+tab's walk button (with `N of M ready to open` beside it, and what it is on while
+it runs), `umtool prep <project>`, and on their own after a fetch lands a window
+and after a write that moves a clip's extent or adds one (an excerpt is cut
+only then; a waveform is made too after a fetch). It makes exactly what the
+first open would: the excerpt, by the same name, and the waveform in the cache
+`/api/report/peaks` reads. A clip already prepared is skipped (its excerpt newer
+than its recording, its waveform cached). Not the decoded audio: once the
+excerpt exists `/api/report/audio` decodes the first span in a fraction of a
+second.
+
+It runs as a background runner per project (`umtool prep <project> --run`), one
+clip at a time, each in the machine's **heavy slot** with a declared estimate
+of 400 MB (so it runs beside a render while the memory floor holds, and waits
+when it does not), under `nice -n 19` and `ionice -c3`. Its progress is
+`out/bench-excerpts/prep-status.json`, its log `prep.log` beside it. A clip you
+open before it gets there is cut by the bench as before; a cut already running
+in the other process is waited for, not repeated. `UMTOOL_BENCH_PREP=0` queues
+nothing (`umtool prep --wait` still runs).
+
### Is this accurate?
A clip is a **claim** — the report said somebody said this, here — so the right
diff --git a/umtool/e2e/bench-prep.spec.ts b/umtool/e2e/bench-prep.spec.ts
@@ -0,0 +1,71 @@
+import { test, expect } from "@playwright/test";
+import { copyFileSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// Preparing the walk (lib/report/benchPrep.mjs): the Cut tab's "Prepare clips
+// for the walk" runs, in the background, what the clip bench would do on a
+// clip's first open -- a long recording's excerpt, the waveform -- and the
+// bench then opens on the prepared files.
+//
+// Its own project, made here and removed after (the suite runs one spec file
+// at a time, so no other spec's project count sees it): r01 sits on a
+// "recording", a cached window whose NAME says 0–700 s (longer than the
+// bench's EXCERPT_OVER_S, so the bench is given an excerpt of it), and r02 on
+// an ordinary window. The bytes are report-fixture's nine seconds of tone.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/prep-fixture";
+const DIR = path.join(FIXTURE, "reports", "prep-fixture");
+const TONE = path.join(FIXTURE, "reports", "report-fixture", "out", "clips-raw", "vid1_0.00-9.00.mp4");
+const EXCERPT = path.join(DIR, "out", "bench-excerpts", "vidp", "0.00-60.00.excerpt.mp4");
+
+test.beforeAll(() => {
+ rmSync(DIR, { recursive: true, force: true });
+ mkdirSync(path.join(DIR, "out", "clips-raw"), { recursive: true });
+ const clip = (id: string, video: string) => ({ type: "clip", id, video, start: 3, end: 6, cite: 3, section: 0, lock: true, quote: "and because" });
+ writeFileSync(
+ path.join(DIR, "video.manifest.json"),
+ `${JSON.stringify({ slug: "prep-fixture", title: "The Prep Fixture", provenance: { siteOrigin: "https://archive.example" }, timeline: [clip("r01", "vidp"), clip("r02", "vid1")] }, null, 2)}\n`,
+ );
+ copyFileSync(TONE, path.join(DIR, "out", "clips-raw", "vidp_0.00-700.00.mp4"));
+ copyFileSync(TONE, path.join(DIR, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+});
+
+test.afterAll(() => {
+ rmSync(DIR, { recursive: true, force: true });
+});
+
+test("Prepare clips for the walk makes the excerpt and the waveforms, and the bench opens on them", async ({ page, request }) => {
+ await page.goto(urls.section(PROJECT, "timeline"));
+ const panel = page.locator("[data-bench-prep]");
+ await expect(panel.locator("[data-bench-prep-status]")).toHaveText("0 of 2 ready to open · 2 to prepare");
+ expect(existsSync(EXCERPT)).toBe(false);
+
+ await panel.locator("[data-action=bench-prep]").click();
+ // The runner is its own process; the line follows it to the end.
+ await expect(panel.locator("[data-bench-prep-status]")).toHaveText("2 of 2 ready to open", { timeout: 60_000 });
+ await expect(panel.locator("[data-action=bench-prep]")).toHaveCount(0);
+ await expect(panel).toHaveAttribute("data-bench-prep-state", "ready");
+ // The excerpt the bench's excerptOf names: the clip ± 45 s, rounded out to 15 s.
+ expect(existsSync(EXCERPT)).toBe(true);
+
+ // The bench's own routes take it: the clip's window is the excerpt, and its
+ // audio answers from it.
+ const clip = await (await request.get(`/api/report/clip?project=${encodeURIComponent(PROJECT)}&clip=r01`)).json();
+ expect(clip.windows[0].name).toBe("0.00-60.00.excerpt.mp4");
+ const audio = await request.get(
+ `/api/report/audio?project=${encodeURIComponent(PROJECT)}&clip=r01&file=0.00-60.00.excerpt.mp4&from=0&to=9`,
+ );
+ expect(audio.status()).toBe(200);
+ expect(audio.headers()["content-type"]).toBe("audio/wav");
+
+ // And the API says so too: nothing left, no runner.
+ const state = await (await request.get(`/api/report/prep?project=${encodeURIComponent(PROJECT)}`)).json();
+ expect(state.counts).toMatchObject({ clips: 2, ready: 2, todo: 0, failed: 0 });
+ expect(state.running).toBe(false);
+});
diff --git a/umtool/lib/analyse.mjs b/umtool/lib/analyse.mjs
@@ -0,0 +1,160 @@
+// One file's analysis -- the bench's waveform, the mix bench's envelope and
+// brightness -- and the disk cache it lives in.
+//
+// Plain ESM, so a plain node process makes the very file the app reads: the
+// bench's prep (lib/report/benchPrep.mjs, `umtool prep`) analyses a clip's
+// window ahead of the walk, and /api/report/peaks (through lib/media.ts
+// analyseMedia, which keeps the type and an in-memory memo) then finds it.
+// The key is spelled once, here.
+//
+// One decode per file gives everything the bench draws:
+//
+// peak a plain envelope, for the shape of the track
+// ratio high-band over low-band energy -- WHERE A CUE STARTS
+// firstSound the first sustained sound, matched to ffmpeg's own
+// silencedetect so the number on screen equals the number the
+// command line would print
+import { spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync } from "node:fs";
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { MIX_CACHE, labelFor } from "./paths.mjs";
+import { brightnessCurve, brightnessSteps } from "../song/flatness.mjs";
+
+/** Analysis sample rate. 16 kHz resolves the whole band the ratio looks at. */
+const ANALYSIS_SR = 16000;
+/** Envelope frames per second. */
+export const ENV_RATE = 100;
+/** Brightness frames per second. */
+export const RATIO_RATE = 50;
+/** -45 dBFS, held for 150ms: the same test `silencedetect=n=-45dB:d=0.15` makes. */
+const SILENCE_FLOOR = 10 ** (-45 / 20);
+const SILENCE_HOLD = 0.15;
+/** Refuse to decode something absurd rather than sitting on it. */
+const MAX_ANALYSIS_SECONDS = 3600;
+
+/** The key: the file's absolute path, its mtime and its size. */
+export const analysisCacheKey = (abs, mtimeMs, size) =>
+ createHash("sha1").update(`${abs}|${Math.round(mtimeMs)}|${size}|v3`).digest("hex").slice(0, 16);
+
+/**
+ * The cache file for `abs` as it is now (`st` is its stat).
+ * @param {string} abs
+ * @param {{ mtimeMs: number, size: number }} st
+ * @param {string} [dir]
+ */
+export const analysisCacheFile = (abs, st, dir = MIX_CACHE) =>
+ path.join(/* turbopackIgnore: true */ dir, `${analysisCacheKey(abs, st.mtimeMs, st.size)}.json`);
+
+/** @param {string} abs */
+async function decodeMono(abs) {
+ /** @type {Buffer[]} */
+ const chunks = [];
+ await new Promise((resolve, reject) => {
+ const ff = spawn("ffmpeg", [
+ "-nostdin", "-v", "error",
+ "-i", abs,
+ "-map", "a:0?",
+ "-ac", "1", "-ar", String(ANALYSIS_SR),
+ "-f", "f32le", "-",
+ ]);
+ let err = "";
+ ff.stdout.on("data", (b) => chunks.push(b));
+ ff.stderr.on("data", (b) => {
+ err += b.toString();
+ });
+ ff.on("error", reject);
+ ff.on("close", (code) => (code === 0 ? resolve(undefined) : reject(new Error(err.trim() || `ffmpeg exited ${code}`))));
+ });
+ const buf = Buffer.concat(chunks);
+ // Buffer.concat may hand back a view into a larger pool, so honour the offset
+ // -- reading from byteOffset 0 would silently analyse the wrong bytes.
+ const usable = buf.length - (buf.length % 4);
+ return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + usable));
+}
+
+/**
+ * Envelope + brightness for a whole track, from the disk cache when it is
+ * there, else decoded and written to it.
+ *
+ * @param {string} abs
+ * @param {{ st?: { mtimeMs: number, size: number }, cacheDir?: string }} [opts]
+ */
+export async function analyseFile(abs, { st = undefined, cacheDir = MIX_CACHE } = {}) {
+ const s = st ?? (await stat(abs));
+ const file = analysisCacheFile(abs, s, cacheDir);
+ if (existsSync(/* turbopackIgnore: true */ file)) {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ /* rewrite it below */
+ }
+ }
+
+ const x = await decodeMono(abs);
+ const duration = x.length / ANALYSIS_SR;
+ if (duration > MAX_ANALYSIS_SECONDS) {
+ throw new Error(`${labelFor(abs)} is ${Math.round(duration)}s; the bench analyses up to ${MAX_ANALYSIS_SECONDS}s`);
+ }
+
+ const envHop = Math.round(ANALYSIS_SR / ENV_RATE);
+ const peak = [];
+ for (let i = 0; i + envHop <= x.length; i += envHop) {
+ let p = 0;
+ for (let k = 0; k < envHop; k += 1) {
+ const v = x[i + k] < 0 ? -x[i + k] : x[i + k];
+ if (v > p) p = v;
+ }
+ peak.push(+p.toFixed(5));
+ }
+
+ const holdFrames = Math.max(1, Math.round(SILENCE_HOLD * ENV_RATE));
+ let firstSound = null;
+ for (let i = 0; i + holdFrames <= peak.length; i += 1) {
+ if (peak[i] < SILENCE_FLOOR) continue;
+ let ok = true;
+ for (let k = 0; k < holdFrames; k += 1) {
+ if (peak[i + k] < SILENCE_FLOOR) {
+ ok = false;
+ break;
+ }
+ }
+ if (ok) {
+ firstSound = +(i / ENV_RATE).toFixed(3);
+ break;
+ }
+ }
+
+ const curve = brightnessCurve(x, ANALYSIS_SR, { N: 512, hop: Math.round(ANALYSIS_SR / RATIO_RATE) });
+ // Keep a GENEROUS list, in time order, and let the caller choose by locality.
+ //
+ // Ranking these globally by strength and keeping the top handful is wrong for
+ // the job: over a 150s background the Pokemon encounter alarm at 3.96s is a
+ // perfectly clear 3.6x step, and it still ranked below eight louder cues
+ // elsewhere in the file -- so the one onset the whole exercise was about
+ // never reached the screen. The strongest cue in a file is rarely the one you
+ // are working next to.
+ const steps = brightnessSteps(curve, { hold: 0.4, rise: 1.8 })
+ .map((/** @type {{ at: number, gain: number }} */ s) => ({ at: s.at, gain: s.gain }))
+ .sort((/** @type {{ at: number }} */ a, /** @type {{ at: number }} */ b) => a.at - b.at)
+ .slice(0, 60);
+
+ const out = {
+ label: labelFor(abs),
+ duration: +duration.toFixed(3),
+ envRate: ENV_RATE,
+ peak,
+ ratioRate: RATIO_RATE,
+ ratio: /** @type {number[]} */ (curve.ratio).map((v) => +v.toFixed(3)),
+ flux: /** @type {number[]} */ (curve.flux).map((v) => +v.toFixed(2)),
+ firstSound,
+ steps,
+ };
+
+ await mkdir(cacheDir, { recursive: true });
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, JSON.stringify(out));
+ await rename(tmp, file).catch(() => {});
+ return out;
+}
diff --git a/umtool/lib/jobs.ts b/umtool/lib/jobs.ts
@@ -187,7 +187,17 @@ function killGroup(pid: number | undefined) {
}, KILL_GRACE_MS);
}
-export function startJob(kind: string, steps: Step[], { project = null }: { project?: string | null } = {}): Job {
+/**
+ * `onDone` runs once the job has finished every step (state `done`), after
+ * the runner has let go of it -- a fetch's follow-up (the bench's prep for
+ * the window it landed) is never part of the job and never holds the runner.
+ * An error in it is swallowed: the job is done either way.
+ */
+export function startJob(
+ kind: string,
+ steps: Step[],
+ { project = null, onDone }: { project?: string | null; onDone?: (job: Job) => unknown } = {},
+): Job {
const running = runningJob();
if (running) throw new Error(`a job is already running (${running.id})`);
@@ -229,6 +239,13 @@ export function startJob(kind: string, steps: Step[], { project = null }: { proj
job.endedAt = Date.now();
if (reg.current === job) reg.current = null;
}
+ if (job.state === "done" && onDone) {
+ try {
+ await onDone(job);
+ } catch {
+ /* the job is done either way */
+ }
+ }
})();
return job;
diff --git a/umtool/lib/media.ts b/umtool/lib/media.ts
@@ -1,13 +1,10 @@
-import { createHash } from "node:crypto";
-import { spawn } from "node:child_process";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
-import { mkdir, readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
-import { existsSync } from "node:fs";
+import { readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
import { MEDIA_ROOT, MEDIA_ROOTS, MEDIA_TIERED, MIX_CACHE, REPORTS_ROOT, SONG_REPORTS, inside, labelFor } from "./paths";
-import { brightnessCurve, brightnessSteps } from "../song/flatness.mjs";
import { fileSig, pathCache } from "./pathCache.mjs";
+import { analyseFile } from "./analyse.mjs";
const run = promisify(execFile);
@@ -220,17 +217,12 @@ export async function listMedia(limit = 400): Promise<MediaRow[]> {
// game's alarm instead of on top of it. On screen it is unmissable.
// ---------------------------------------------------------------------------
-/** Analysis sample rate. 16 kHz resolves the whole band the ratio looks at. */
-const ANALYSIS_SR = 16000;
-/** Envelope frames per second. */
-export const ENV_RATE = 100;
-/** Brightness frames per second. */
-export const RATIO_RATE = 50;
-/** -45 dBFS, held for 150ms: the same test `silencedetect=n=-45dB:d=0.15` makes. */
-const SILENCE_FLOOR = 10 ** (-45 / 20);
-const SILENCE_HOLD = 0.15;
-/** Refuse to decode something absurd rather than sitting on it. */
-const MAX_ANALYSIS_SECONDS = 3600;
+// The pass itself is lib/analyse.mjs (plain ESM), so the bench's prep
+// (lib/report/benchPrep.mjs, `umtool prep`) makes the very file the bench's
+// /api/report/peaks then reads, from a plain node process. This keeps the
+// type and the in-memory memo.
+
+export { ENV_RATE, RATIO_RATE } from "./analyse.mjs";
export type Analysis = {
label: string;
@@ -246,34 +238,6 @@ export type Analysis = {
steps: { at: number; gain: number }[];
};
-async function decodeMono(abs: string): Promise<Float32Array> {
- const chunks: Buffer[] = [];
- await new Promise<void>((resolve, reject) => {
- const ff = spawn("ffmpeg", [
- "-nostdin", "-v", "error",
- "-i", abs,
- "-map", "a:0?",
- "-ac", "1", "-ar", String(ANALYSIS_SR),
- "-f", "f32le", "-",
- ]);
- let err = "";
- ff.stdout.on("data", (b: Buffer) => chunks.push(b));
- ff.stderr.on("data", (b: Buffer) => {
- err += b.toString();
- });
- ff.on("error", reject);
- ff.on("close", (code) => (code === 0 ? resolve() : reject(new Error(err.trim() || `ffmpeg exited ${code}`))));
- });
- const buf = Buffer.concat(chunks);
- // Buffer.concat may hand back a view into a larger pool, so honour the offset
- // -- reading from byteOffset 0 would silently analyse the wrong bytes.
- const usable = buf.length - (buf.length % 4);
- return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + usable));
-}
-
-const cacheKey = (abs: string, mtimeMs: number, size: number) =>
- createHash("sha1").update(`${abs}|${Math.round(mtimeMs)}|${size}|v3`).digest("hex").slice(0, 16);
-
// In memory: ONE analysis per file (lib/pathCache.mjs), its signature the
// file's mtime and size -- a re-rendered track replaces its old analysis
// rather than keeping it beside the new one -- and at most 64 MB of curves (a
@@ -284,86 +248,10 @@ const memo = pathCache<Analysis>({ max: 64, maxBytes: 64 * 1024 * 1024, sizeOf:
/** Envelope + brightness for a whole track. Cached on disk, keyed by mtime. */
export async function analyseMedia(abs: string): Promise<Analysis> {
const st = await stat(abs);
- const key = cacheKey(abs, st.mtimeMs, st.size);
const sig = fileSig(st);
const hit = memo.get(abs, sig);
if (hit) return hit;
-
- const file = path.join(MIX_CACHE, `${key}.json`);
- if (existsSync(file)) {
- try {
- const cached = JSON.parse(await readFile(file, "utf8")) as Analysis;
- memo.set(abs, sig, cached);
- return cached;
- } catch {
- /* rewrite it below */
- }
- }
-
- const x = await decodeMono(abs);
- const duration = x.length / ANALYSIS_SR;
- if (duration > MAX_ANALYSIS_SECONDS) {
- throw new Error(`${labelFor(abs)} is ${Math.round(duration)}s; the bench analyses up to ${MAX_ANALYSIS_SECONDS}s`);
- }
-
- const envHop = Math.round(ANALYSIS_SR / ENV_RATE);
- const peak: number[] = [];
- for (let i = 0; i + envHop <= x.length; i += envHop) {
- let p = 0;
- for (let k = 0; k < envHop; k += 1) {
- const v = x[i + k] < 0 ? -x[i + k] : x[i + k];
- if (v > p) p = v;
- }
- peak.push(+p.toFixed(5));
- }
-
- const holdFrames = Math.max(1, Math.round(SILENCE_HOLD * ENV_RATE));
- let firstSound: number | null = null;
- for (let i = 0; i + holdFrames <= peak.length; i += 1) {
- if (peak[i] < SILENCE_FLOOR) continue;
- let ok = true;
- for (let k = 0; k < holdFrames; k += 1) {
- if (peak[i + k] < SILENCE_FLOOR) {
- ok = false;
- break;
- }
- }
- if (ok) {
- firstSound = +(i / ENV_RATE).toFixed(3);
- break;
- }
- }
-
- const curve = brightnessCurve(x, ANALYSIS_SR, { N: 512, hop: Math.round(ANALYSIS_SR / RATIO_RATE) });
- // Keep a GENEROUS list, in time order, and let the caller choose by locality.
- //
- // Ranking these globally by strength and keeping the top handful is wrong for
- // the job: over a 150s background the Pokemon encounter alarm at 3.96s is a
- // perfectly clear 3.6x step, and it still ranked below eight louder cues
- // elsewhere in the file -- so the one onset the whole exercise was about
- // never reached the screen. The strongest cue in a file is rarely the one you
- // are working next to.
- const steps = brightnessSteps(curve, { hold: 0.4, rise: 1.8 })
- .map((s: { at: number; gain: number }) => ({ at: s.at, gain: s.gain }))
- .sort((a: { at: number }, b: { at: number }) => a.at - b.at)
- .slice(0, 60);
-
- const out: Analysis = {
- label: labelFor(abs),
- duration: +duration.toFixed(3),
- envRate: ENV_RATE,
- peak,
- ratioRate: RATIO_RATE,
- ratio: (curve.ratio as number[]).map((v: number) => +v.toFixed(3)),
- flux: (curve.flux as number[]).map((v: number) => +v.toFixed(2)),
- firstSound,
- steps,
- };
-
- await mkdir(MIX_CACHE, { recursive: true });
- const tmp = `${file}.tmp-${process.pid}`;
- await writeFile(tmp, JSON.stringify(out));
- await rename(tmp, file).catch(() => {});
+ const out = (await analyseFile(abs, { st, cacheDir: MIX_CACHE })) as Analysis;
memo.set(abs, sig, out);
return out;
}
diff --git a/umtool/lib/report/benchPrep.mjs b/umtool/lib/report/benchPrep.mjs
@@ -0,0 +1,573 @@
+// 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 ("newer than its source = 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 <project> --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 { absOf, ensureWindowFile, projectCache, windowFileFresh, windowsFor } from "./serve.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");
+const statusFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), "prep-status.json");
+const pendingFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), ".prep-pending");
+const lockFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), ".prep-run.lock");
+/** The runner's stdout and stderr (the heavy slot's waiting lines land here). */
+export const prepLogOf = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), "prep.log");
+
+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 newer than its recording (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).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {any} [manifest]
+ * @param {{ clips?: string[] | null, cache?: any, mixCache?: string }} [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 } = {}) {
+ const m = manifest ?? (await readManifest(project.dir));
+ 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))?.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<string, { window: string, error: string, at: string }>,
+ * }} PrepStatus
+ */
+
+/** @param {string} dir @returns {Promise<PrepStatus | null>} */
+export async function readPrepStatus(dir) {
+ try {
+ return JSON.parse(await readFile(statusFile(dir), "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+/** @param {string} dir @param {PrepStatus} st */
+async function writePrepStatus(dir, st) {
+ await mkdir(prepDirOf(dir), { recursive: true });
+ const tmp = `${statusFile(dir)}.tmp-${process.pid}`;
+ await writeFile(tmp, `${JSON.stringify(st, null, 1)}\n`);
+ await rename(tmp, statusFile(dir));
+}
+
+/**
+ * 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<ReturnType<typeof benchPrepPlan>> }} [opts]
+ */
+export async function benchPrepState(project, { clips = null, plan = null } = {}) {
+ const p = plan ?? (await benchPrepPlan(project, null, { clips }));
+ const st = await readPrepStatus(project.dir);
+ const holder = lockHolder(project.dir);
+ const running = !!holder || (st?.state === "running" && alive(Number(st.pid)));
+ return {
+ project: project.id,
+ 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<void>) => Promise<void>,
+ * ensure?: (win: any) => Promise<void>,
+ * analyse?: (abs: string) => Promise<unknown>,
+ * onEvent?: (ev: Record<string, unknown>) => void,
+ * mixCache?: string,
+ * }} [opts]
+ * @returns {Promise<{ done: string[], failed: string[], skipped: number }>}
+ */
+export async function runBenchPrep(project, {
+ clips = null,
+ retry = false,
+ 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 });
+ const todo = plan.items.filter((i) => i.state === "todo" || (retry && i.state === "failed"));
+ const prev = await readPrepStatus(project.dir);
+ /** @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 writePrepStatus(project.dir, status);
+ onEvent({ ev: "start", project: project.id, 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 writePrepStatus(project.dir, 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, it.id], async () => {
+ if (!it.cut) {
+ status.current = { id: it.id, step: "cutting" };
+ await writePrepStatus(project.dir, 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 writePrepStatus(project.dir, 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 writePrepStatus(project.dir, status);
+ }
+ status.current = null;
+ status.state = failed.length ? "failed" : "done";
+ status.endedAt = new Date().toISOString();
+ await writePrepStatus(project.dir, 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 */
+export function lockHolder(dir) {
+ let raw;
+ try {
+ raw = readFileSync(/* turbopackIgnore: true */ lockFile(dir), "utf8");
+ } catch {
+ return null;
+ }
+ const pid = Number(String(raw).trim());
+ if (alive(pid)) return pid;
+ try {
+ unlinkSync(/* turbopackIgnore: true */ lockFile(dir));
+ } catch {
+ /* somebody else dropped it */
+ }
+ return null;
+}
+
+/** Take the run lock, or false when a live runner holds it. @param {string} dir */
+export function tryLock(dir) {
+ for (let i = 0; i < 2; i += 1) {
+ try {
+ const fd = openSync(/* turbopackIgnore: true */ lockFile(dir), "wx");
+ writeSync(fd, `${process.pid}\n`);
+ closeSync(fd);
+ return true;
+ } catch (e) {
+ if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e;
+ if (lockHolder(dir)) return false;
+ }
+ }
+ return false;
+}
+
+/** @param {string} dir */
+export function unlock(dir) {
+ try {
+ if (Number(readFileSync(/* turbopackIgnore: true */ lockFile(dir), "utf8").trim()) === process.pid) {
+ unlinkSync(/* turbopackIgnore: true */ lockFile(dir));
+ }
+ } 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
+ */
+export async function appendPrepRequest(dir, req) {
+ await mkdir(prepDirOf(dir), { recursive: true });
+ await appendFile(pendingFile(dir), `${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
+ * @returns {Promise<{ clips: string[] | null, retry: boolean } | null>}
+ */
+export async function takePrepRequests(dir) {
+ const taking = `${pendingFile(dir)}.${process.pid}`;
+ try {
+ await rename(pendingFile(dir), 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
+ * @param {Parameters<typeof runBenchPrep>[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 } = {}) {
+ await mkdir(prepDirOf(project.dir), { recursive: true });
+ const done = [];
+ const failed = [];
+ let runs = 0;
+ let own = initial;
+ for (;;) {
+ if (!tryLock(project.dir)) {
+ if (!wait) return { runs, done, failed, held: true };
+ await sleep(pollMs);
+ continue;
+ }
+ try {
+ for (;;) {
+ const queued = await takePrepRequests(project.dir);
+ 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);
+ }
+ // 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))) 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 <project> --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, has?: (name: string) => boolean }} [opts]
+ */
+export function runnerArgv(projectId, { wait = false, clips = null, retry = false, ndjson = false, 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,
+ "--run",
+ ...(wait ? ["--wait"] : []),
+ ...(clips && clips.length ? ["--clips", clips.join(",")] : []),
+ ...(retry ? ["--retry"] : []),
+ ...(ndjson ? ["--ndjson"] : []),
+ ];
+}
+
+/** Start a detached runner, its output appended to prep.log. @param {{ id: string, dir: string }} project */
+export function spawnPrepRunner(project) {
+ const argv = runnerArgv(project.id);
+ // 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)).size > 1024 * 1024;
+ } catch {
+ return false;
+ }
+ })();
+ const fd = openSync(/* turbopackIgnore: true */ prepLogOf(project.dir), 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).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string[] | null} [clips]
+ * @param {{ excerptsOnly?: boolean, retry?: boolean, start?: (project: { id: string, dir: string }) => 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, 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 }));
+ 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) };
+ await appendPrepRequest(project.dir, { clips: queued, retry });
+ const holder = lockHolder(project.dir);
+ if (holder) return { queued, started: false, pid: holder };
+ return { queued, started: true, pid: start(project) };
+}
+
+/**
+ * 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 };
+}
diff --git a/umtool/lib/report/benchPrep.test.mjs b/umtool/lib/report/benchPrep.test.mjs
@@ -0,0 +1,303 @@
+// Preparing the walk ahead of time (benchPrep.mjs): the same excerpt the bench
+// would cut on first open, at the same path; fresh work skipped; the bench's
+// serve path taking the prepared file; the triggers queueing without holding a
+// writer.
+//
+// Run with: node --test lib/report/benchPrep.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+import path from "node:path";
+import os from "node:os";
+import { execFileSync, spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
+
+const root = await mkdtemp(path.join(os.tmpdir(), "bench-prep-"));
+// The roots are read when paths.mjs loads.
+process.env.MIX_ROOTS = root;
+process.env.REPORTS_DIR = path.join(root, "reports");
+process.env.CHANNELS_DIR = path.join(root, "channels");
+process.env.SAVED_VIDEOS_DIR = path.join(root, "saved");
+process.env.UMTOOL_CACHE_DIR = path.join(root, "cache");
+delete process.env.UMTOOL_BENCH_PREP;
+
+const serve = await import("./serve.mjs");
+const prep = await import("./benchPrep.mjs");
+const trigger = await import("./benchPrepTrigger.mjs");
+const { updateClip, insertEntry } = await import("./manifest.mjs");
+const { analysisCacheFile, analyseFile } = await import("../analyse.mjs");
+const { MIX_CACHE } = await import("../paths.mjs");
+
+test.after(() => rm(root, { recursive: true, force: true }));
+
+const dir = path.join(root, "reports", "p");
+const project = { id: "p", dir };
+const raw = path.join(dir, "out", "clips-raw");
+
+/** A clip on a "recording" (its window is 700 s by its name: longer than EXCERPT_OVER_S), one on a short window, one with nothing fetched. */
+const MANIFEST = {
+ slug: "p",
+ timeline: [
+ { type: "clip", id: "long", video: "vid", start: 18, end: 22 },
+ { type: "clip", id: "short", video: "vs", start: 2, end: 5 },
+ { type: "clip", id: "none", video: "zzz", start: 1, end: 2 },
+ ],
+};
+
+const media = (file, seconds) =>
+ execFileSync("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `testsrc2=size=160x120:rate=10:duration=${seconds}`,
+ "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`,
+ "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", file,
+ ]);
+
+async function fresh() {
+ await rm(dir, { recursive: true, force: true });
+ await rm(MIX_CACHE, { recursive: true, force: true });
+ await mkdir(raw, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(MANIFEST, null, 2)}\n`);
+ // A file whose NAME says 0–700: the window listing reads windows from names.
+ media(path.join(raw, "vid_0.00-700.00.mp4"), 40);
+ media(path.join(raw, "vs_0.00-10.00.mp4"), 10);
+}
+
+/** What the bench opens for a clip: the clip route's own windowsFor, first. */
+async function benchWindow(id) {
+ const clip = MANIFEST.timeline.find((e) => e.id === id);
+ return (await serve.windowsFor(project, clip, await serve.projectCache(project)))[0] ?? null;
+}
+
+test("the plan: the long window is an excerpt to cut, the short one a waveform to make, the unfetched one nothing", async () => {
+ await fresh();
+ const plan = await prep.benchPrepPlan(project);
+ const by = Object.fromEntries(plan.items.map((i) => [i.id, i]));
+ assert.equal(by.long.state, "todo");
+ assert.equal(by.long.excerpt, true);
+ assert.equal(by.long.cut, false);
+ assert.equal(by.short.state, "todo");
+ assert.equal(by.short.excerpt, false);
+ assert.equal(by.short.cut, true);
+ assert.equal(by.short.peaks, false);
+ assert.equal(by.none.state, "no-window");
+ assert.deepEqual(plan.counts, { clips: 3, ready: 0, todo: 2, failed: 0, noWindow: 1, excerpts: 1 });
+});
+
+test("prep makes the excerpt at the path the bench's excerptOf names, and the waveform the peaks route reads; a second run skips both", async () => {
+ await fresh();
+ const events = [];
+ const slots = [];
+ const r = await prep.runBenchPrep(project, {
+ slot: async (cmd, fn) => {
+ slots.push(cmd);
+ return fn();
+ },
+ onEvent: (e) => events.push(e),
+ });
+ assert.deepEqual(r.done.sort(), ["long", "short"]);
+ assert.deepEqual(r.failed, []);
+ // One clip per slot, in the plan's order.
+ assert.deepEqual(slots, [["umtool-prep", "p", "long"], ["umtool-prep", "p", "short"]]);
+
+ const win = await benchWindow("long");
+ assert.ok(win.excerptOf, "the bench's window for a recording is an excerpt");
+ const named = serve.excerptOf(
+ { name: "vid_0.00-700.00.mp4", path: path.join(raw, "vid_0.00-700.00.mp4"), from: 0, to: 700 },
+ MANIFEST.timeline[0],
+ dir,
+ );
+ assert.equal(win.path, named.path);
+ assert.equal(win.path, path.join(dir, "out", "bench-excerpts", "vid", "0.00-75.00.excerpt.mp4"));
+ const st = await stat(win.path);
+ assert.ok(st.size > 0);
+ assert.equal(await serve.windowFileFresh(win), true);
+ for (const id of ["long", "short"]) {
+ const w = await benchWindow(id);
+ const abs = serve.absOf(w);
+ assert.ok(existsSync(analysisCacheFile(abs, await stat(abs))), `${id}: the waveform is cached`);
+ }
+
+ const plan = await prep.benchPrepPlan(project);
+ assert.equal(plan.counts.ready, 2);
+ assert.equal(plan.counts.todo, 0);
+ const again = await prep.runBenchPrep(project, { slot: () => assert.fail("nothing to do takes no slot") });
+ assert.deepEqual(again.done, []);
+ assert.equal(again.skipped, 3);
+ assert.equal((await stat(win.path)).mtimeMs, st.mtimeMs, "not cut again");
+
+ const status = await prep.readPrepStatus(dir);
+ assert.equal(status.state, "done");
+ assert.equal(status.pid, process.pid);
+ assert.deepEqual(events.map((e) => e.ev).filter((e) => e !== "clip"), ["start", "clip-done", "clip-done", "end"]);
+});
+
+test("the bench's serve path takes a prepared file: no cut, and the cached waveform", async () => {
+ // Continues from the run above: everything is prepared.
+ const win = await benchWindow("long");
+ // An ffmpeg that cannot run: a cut would throw.
+ await serve.ensureWindowFile(win, { ffmpeg: "/nonexistent/ffmpeg" });
+ const abs = serve.absOf(win);
+ const file = analysisCacheFile(abs, await stat(abs));
+ const cached = JSON.parse(await readFile(file, "utf8"));
+ await writeFile(file, JSON.stringify({ ...cached, label: "from-the-cache" }));
+ assert.equal((await analyseFile(abs)).label, "from-the-cache", "the peaks route's analysis reads the prepared file");
+});
+
+test("a recording newer than its excerpt is prepared again; a cut in flight in another process is waited for, not repeated", async () => {
+ const win = await benchWindow("long");
+ const src = path.join(raw, "vid_0.00-700.00.mp4");
+ const later = new Date(Date.now() + 5000);
+ await utimes(src, later, later);
+ const plan = await prep.benchPrepPlan(project, null, { clips: ["long"] });
+ assert.equal(plan.items[0].state, "todo");
+ assert.equal(plan.items[0].cut, false);
+
+ // Another process (a live pid) has marked the cut; it lands 300 ms later.
+ const other = spawn(process.execPath, ["-e", "setTimeout(() => {}, 5000)"]);
+ try {
+ await writeFile(serve.cutMarkOf(win.path), JSON.stringify({ pid: other.pid, at: Date.now() }));
+ const done = (async () => {
+ await new Promise((r) => setTimeout(r, 300));
+ const t = new Date(Date.now() + 10_000);
+ await utimes(win.path, t, t);
+ await rm(serve.cutMarkOf(win.path));
+ })();
+ // A real cut would need ffmpeg: this one must wait for the other process instead.
+ await serve.ensureWindowFile(win, { ffmpeg: "/nonexistent/ffmpeg", pollMs: 50 });
+ await done;
+ assert.equal(await serve.windowFileFresh(win), true);
+ } finally {
+ other.kill();
+ }
+});
+
+test("a manifest write queues prep for the clips it moved or added, and returns without waiting for it", async () => {
+ await fresh();
+ const calls = [];
+ let release;
+ const held = new Promise((r) => {
+ release = r;
+ });
+ trigger.setBenchPrepQueue(async (p, clips, opts) => {
+ calls.push({ p, clips, opts });
+ await held; // a queue that never finishes on its own
+ });
+ try {
+ const t0 = Date.now();
+ const res = await updateClip(dir, "long", { start: 100, end: 104 });
+ assert.equal(res.entry.start, 100);
+ assert.ok(Date.now() - t0 < 2000, "the writer did not wait");
+ await new Promise((r) => setTimeout(r, 50));
+ assert.equal(calls.length, 1);
+ assert.deepEqual(calls[0].p, { id: "p", dir });
+ assert.deepEqual(calls[0].clips, ["long"]);
+ assert.deepEqual(calls[0].opts, { excerptsOnly: true });
+
+ // Only the cut moved: the extent (and so any excerpt) is where it was.
+ await updateClip(dir, "long", { cutStart: 101, cutEnd: 103 });
+ await new Promise((r) => setTimeout(r, 50));
+ assert.equal(calls.length, 1, "a cut inside the extent needs no new excerpt");
+
+ const ins = await insertEntry(dir, "long", "chan/vid@300-310");
+ await new Promise((r) => setTimeout(r, 50));
+ assert.equal(calls.length, 2);
+ assert.deepEqual(calls[1].clips, [ins.id]);
+ } finally {
+ release();
+ await trigger.settleBenchPrepTriggers();
+ trigger.setBenchPrepQueue(null);
+ }
+});
+
+test("queueing: only the clips that need it, a runner started once, none while one is alive; off with UMTOOL_BENCH_PREP=0", async () => {
+ await fresh();
+ const started = [];
+ const start = (p) => {
+ started.push(p.id);
+ return 4242;
+ };
+ const excerpts = await prep.queueBenchPrep(project, null, { excerptsOnly: true, start });
+ assert.deepEqual(excerpts.queued, ["long"], "a trigger queues the excerpt, not a short window's waveform");
+ assert.equal(excerpts.started, true);
+ const all = await prep.queueBenchPrep(project, null, { start });
+ assert.deepEqual(all.queued.sort(), ["long", "short"]);
+ assert.deepEqual(started, ["p", "p"]);
+
+ // A live runner holds the lock: the request is queued, no second runner.
+ assert.equal(prep.tryLock(dir), true);
+ try {
+ const q = await prep.queueBenchPrep(project, ["short"], { start });
+ assert.deepEqual(q.queued, ["short"]);
+ assert.equal(q.started, false);
+ assert.equal(q.pid, process.pid);
+ assert.equal(started.length, 2);
+ } finally {
+ prep.unlock(dir);
+ }
+ const reqs = await prep.takePrepRequests(dir);
+ // The clips each ask resolved to, merged into one request.
+ assert.deepEqual({ ...reqs, clips: [...reqs.clips].sort() }, { clips: ["long", "short"], retry: false });
+ assert.deepEqual(prep.mergeRequests([{ clips: ["a"] }, { clips: null, retry: true }]), { clips: null, retry: true }, "one ask for all is all");
+ assert.equal(await prep.takePrepRequests(dir), null);
+
+ process.env.UMTOOL_BENCH_PREP = "0";
+ try {
+ const off = await prep.queueBenchPrep(project, null, { start });
+ assert.equal(off.off, true);
+ assert.equal(started.length, 2);
+ } finally {
+ delete process.env.UMTOOL_BENCH_PREP;
+ }
+});
+
+test("the runner drains the queue under its lock, and lets go", async () => {
+ await fresh();
+ await prep.appendPrepRequest(dir, { clips: ["short"] });
+ const r = await prep.drainPrepQueue(project, { slot: (_c, fn) => fn() });
+ assert.deepEqual(r.done, ["short"]);
+ assert.equal(r.held, false);
+ assert.equal(prep.lockHolder(dir), null, "the lock is released");
+ // A busy lock: a background runner leaves the queue to its holder.
+ assert.equal(prep.tryLock(dir), true);
+ try {
+ await prep.appendPrepRequest(dir, { clips: ["long"] });
+ const held = await prep.drainPrepQueue(project, { slot: (_c, fn) => fn() });
+ assert.equal(held.held, true);
+ assert.deepEqual(held.done, []);
+ } finally {
+ prep.unlock(dir);
+ }
+});
+
+test("a failed clip reads failed until its window changes; an explicit ask tries it again", async () => {
+ await fresh();
+ const r = await prep.runBenchPrep(project, { clips: ["short"], analyse: async () => { throw new Error("no audio"); } });
+ assert.deepEqual(r.failed, ["short"]);
+ let plan = await prep.benchPrepPlan(project, null, { clips: ["short"] });
+ assert.equal(plan.items[0].state, "failed");
+ assert.match(plan.items[0].error, /no audio/);
+ const trig = await prep.queueBenchPrep(project, ["short"], { start: () => 1 });
+ assert.deepEqual(trig.queued, [], "a trigger leaves a failed clip alone");
+ await prep.takePrepRequests(dir);
+ const again = await prep.runBenchPrep(project, { clips: ["short"], retry: true });
+ assert.deepEqual(again.done, ["short"]);
+ plan = await prep.benchPrepPlan(project, null, { clips: ["short"] });
+ assert.equal(plan.items[0].state, "ready");
+});
+
+test("the runner's command: niced and idle-I/O when the tools are there", () => {
+ const argv = prep.runnerArgv("folder/p", { has: () => true });
+ assert.deepEqual(argv.slice(0, 5), ["nice", "-n", "19", "ionice", "-c3"]);
+ assert.equal(argv[5], process.execPath);
+ assert.ok(argv[6].endsWith(path.join("bin", "umtool.mjs")));
+ assert.deepEqual(argv.slice(7), ["prep", "folder/p", "--run"]);
+ const bare = prep.runnerArgv("p", { has: () => false, wait: true, clips: ["a", "b"], retry: true });
+ assert.deepEqual(bare.slice(2), ["prep", "p", "--run", "--wait", "--clips", "a,b", "--retry"]);
+ assert.equal(bare[0], process.execPath);
+});
+
+test("a project directory is one of REPORTS_ROOT's, or not one at all", () => {
+ assert.deepEqual(prep.projectOfDir(path.join(root, "reports", "a", "b")), { id: "a/b", dir: path.join(root, "reports", "a", "b") });
+ assert.equal(prep.projectOfDir(path.join(root, "elsewhere")), null);
+ assert.equal(prep.projectOfDir(path.join(root, "reports")), null);
+});
diff --git a/umtool/lib/report/benchPrepTrigger.mjs b/umtool/lib/report/benchPrepTrigger.mjs
@@ -0,0 +1,57 @@
+// The bench prep's TRIGGER: after a write that may need a new excerpt (a
+// window moved, a clip inserted, split, merged, duplicated, restored) and
+// after a fetch lands, queue prep for the clips it touched (benchPrep.mjs).
+//
+// Never holds the writer: the writer has already written when this is called,
+// it returns at once, and the work -- a plan of a few stats, then at most a
+// detached runner started -- happens after. benchPrep.mjs is loaded lazily, so
+// manifest.mjs (which calls this) gains no import graph and no cycle.
+//
+// A CLI process that exits with process.exit right after its write would cut
+// that work off, so the CLI awaits `settleBenchPrepTriggers()` first.
+// UMTOOL_BENCH_PREP=0 turns every trigger off.
+
+/** @type {Set<Promise<unknown>>} */
+const inFlight = new Set();
+
+/**
+ * @typedef {(project: { id: string, dir: string }, clips: string[] | null, opts: { excerptsOnly: boolean }) => Promise<unknown>} QueueFn
+ */
+/** @type {QueueFn | null} a test's stand-in for queueBenchPrep */
+let queueOverride = null;
+
+/** For tests: replace the queue (null restores it). @param {QueueFn | null} fn */
+export function setBenchPrepQueue(fn) {
+ queueOverride = fn;
+}
+
+/**
+ * Queue prep for `clips` of the project at `dir`, without waiting for it.
+ *
+ * `excerptsOnly` (the default, for a manifest write: they come by the dozen
+ * in a walk) starts a runner only when an excerpt is missing; a FETCH that
+ * landed passes false, so the new windows' waveforms are made too.
+ *
+ * @param {string} dir the project directory (the manifest's)
+ * @param {string[] | null} clips null: every clip
+ * @param {{ excerptsOnly?: boolean }} [opts]
+ */
+export function benchPrepAfterWrite(dir, clips, { excerptsOnly = true } = {}) {
+ if (process.env.UMTOOL_BENCH_PREP === "0") return;
+ const p = (async () => {
+ const m = await import("./benchPrep.mjs");
+ const project = m.projectOfDir(dir);
+ if (!project) return;
+ const queue = queueOverride ?? m.queueBenchPrep;
+ await queue(project, clips, { excerptsOnly });
+ })().catch(() => {
+ /* a trigger never fails a write */
+ });
+ inFlight.add(p);
+ void p.finally(() => inFlight.delete(p));
+}
+
+/** Every trigger started so far, settled. */
+export async function settleBenchPrepTriggers() {
+ await Promise.allSettled([...inFlight]);
+}
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -22,6 +22,7 @@ import {
recordFetchRun,
summarizeAnswer,
} from "./fetchWindows.mjs";
+import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
export const FETCH_USAGE = [
"usage: umtool fetch <project> --body the editor's fetch-windows body for the manifest, printed",
@@ -87,6 +88,10 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
const run = lastStartedRun(await readFetchRuns(project.dir));
if (!run) throw new CliError(`${project.id} has no started fetch run in ${FETCH_RUNS_FILE}`);
const states = await followRun(cfg, project.dir, run);
+ // A run that has ended landed what it landed: the bench's prep for it.
+ if (states.length && states.every((st) => TERMINAL.has(st.status)) && states.some((st) => st.status === "done")) {
+ benchPrepAfterWrite(project.dir, null, { excerptsOnly: false });
+ }
if (json) out(JSON.stringify({ project: project.id, run: { at: run.at, jobIds: run.jobIds }, jobs: states }, null, 2));
else {
out(`${project.id}: the run of ${run.at}`);
@@ -144,6 +149,8 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (states.every((st) => TERMINAL.has(st.status))) break;
await sleep(pollMs);
}
+ // What landed, prepared for the walk (a runner in the background; bin/umtool.mjs waits for the queueing only).
+ if (states.some((st) => st.status === "done")) benchPrepAfterWrite(project.dir, null, { excerptsOnly: false });
const failed = states.flatMap((st) => st.failed ?? []);
if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary, jobsEnded: states }, null, 2));
else {
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -52,6 +52,7 @@ import { validateNarration } from "umtool-report-to-video/narration";
import { parseMuteFrom } from "./playback.mjs";
import { DELIVERABLES_MODES } from "./storage.mjs";
import { createSnapshot, listSnapshots } from "./snapshots.mjs";
+import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
import {
DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish,
} from "yt-dlp-transcript-common/lib/report/drafted.mjs";
@@ -539,6 +540,8 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri
if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant";
const nextToken = await writeManifestAtomic(dir, manifest);
+ // A moved extent may need a new bench excerpt: queued, never waited for.
+ if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]);
return { entry, before, token: nextToken };
});
}
@@ -615,7 +618,7 @@ const textOr = (v, fallback) => (v === undefined ? fallback : String(v ?? "").tr
* @param {{ token?: string | null, quotes?: { first?: string, second?: string }, now?: string | null }} [opts]
*/
export async function splitClip(dir, clipId, at, { token = null, quotes = {}, now = null } = {}) {
- return structural(dir, "split", token, (m) => {
+ return prepAfter(dir, (r) => [r.id, r.second], structural(dir, "split", token, (m) => {
const { i, e } = clipAt(m.timeline, clipId);
const t = round2(Number(at));
const { cutStart, cutEnd } = cutOf(e);
@@ -652,7 +655,7 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no
}
m.timeline.splice(i + 1, 0, b);
return { id: e.id, second: b.id, entries: [e, b] };
- });
+ }));
}
const pick = (o, keys) => Object.fromEntries(keys.filter((k) => o[k] !== undefined).map((k) => [k, o[k]]));
@@ -668,7 +671,7 @@ const pick = (o, keys) => Object.fromEntries(keys.filter((k) => o[k] !== undefin
* @param {{ token?: string | null, quote?: string, now?: string | null }} [opts]
*/
export async function mergeClips(dir, clipId, { token = null, quote, now = null } = {}) {
- return structural(dir, "merge", token, (m) => {
+ return prepAfter(dir, (r) => [r.id], structural(dir, "merge", token, (m) => {
const { i, e } = clipAt(m.timeline, clipId);
const j = m.timeline.findIndex((x, k) => k > i && x?.type === "clip");
if (j < 0) throw new Error(`${clipId} is the last clip: nothing to merge it with`);
@@ -695,7 +698,7 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null
noteAssistEdit(e, "merge", from, stamp);
m.timeline.splice(j, 1);
return { id: e.id, absorbed: b.id, entry: e };
- });
+ }));
}
/**
@@ -710,7 +713,7 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null
* @param {{ token?: string | null, now?: string | null }} [opts]
*/
export async function addClip(dir, spec, { token = null, now = null } = {}) {
- return structural(dir, "add", token, (m) => {
+ return prepAfter(dir, (r) => [r.id], structural(dir, "add", token, (m) => {
if (!isObj(spec)) throw new Error("a clip to add is { video, cutStart, cutEnd }");
if (typeof spec.video !== "string" || !/^[\w.-]+$/.test(spec.video)) throw new Error("a clip needs its video id");
const num = (k, v) => {
@@ -749,7 +752,7 @@ export async function addClip(dir, spec, { token = null, now = null } = {}) {
}
m.timeline.splice(at, 0, entry);
return { id: entry.id, at, entry };
- });
+ }));
}
@@ -1440,6 +1443,26 @@ export class StructureRefused extends Error {
}
/**
+ * After a structural write that put a clip in (insert, duplicate, add, split,
+ * merge): queue the bench's prep for it (benchPrepTrigger.mjs). The write has
+ * landed when this runs, and nothing waits for the prep.
+ *
+ * @template T
+ * @param {string} dir
+ * @param {(r: T) => (string | null | undefined)[]} ids
+ * @param {Promise<T>} write
+ * @returns {Promise<T>}
+ */
+async function prepAfter(dir, ids, write) {
+ const r = await write;
+ const clips = ids(r).filter((x) => typeof x === "string" && x);
+ if (clips.length) benchPrepAfterWrite(dir, clips);
+ return r;
+}
+/** A structural result's entry id, when the entry is a clip. */
+const clipIdOf = (r) => [r?.entry?.type === "clip" ? r.id : null];
+
+/**
* One structural write: token, read, `mutate` (which throws to refuse), the
* build's checks, the auto snapshot of the file as it still is, then the write.
*/
@@ -1509,7 +1532,7 @@ export async function removeEntry(dir, id, { token = null, at = null } = {}) {
* @param {{ token?: string | null, at?: number | null }} [opts]
*/
export async function duplicateEntry(dir, id, { token = null, at = null } = {}) {
- return structural(dir, "duplicate", token, (m) => {
+ return prepAfter(dir, clipIdOf, structural(dir, "duplicate", token, (m) => {
const i = entryIndex(m.timeline, id, at);
const copy = JSON.parse(JSON.stringify(m.timeline[i]));
copy.id = freshEntryId(m.timeline, `${id}-copy`);
@@ -1517,7 +1540,7 @@ export async function duplicateEntry(dir, id, { token = null, at = null } = {})
delete copy.claims;
m.timeline.splice(i + 1, 0, copy);
return { id: copy.id, at: i + 1, entry: copy };
- });
+ }));
}
// `<channel>/<video>@<start>-<end>`, in seconds: clipEditorModel.mjs's
@@ -1572,12 +1595,12 @@ function clipEntry(timeline, e) {
* @param {{ token?: string | null, at?: number | null }} [opts] `at` is afterId's index
*/
export async function insertEntry(dir, afterId, spec, { token = null, at = null } = {}) {
- return structural(dir, "insert", token, (m) => {
+ return prepAfter(dir, clipIdOf, structural(dir, "insert", token, (m) => {
const i = afterId ? entryIndex(m.timeline, afterId, at) + 1 : 0;
const entry = entryFromSpec(m.timeline, spec);
m.timeline.splice(i, 0, entry);
return { id: entry.id, at: i, entry };
- });
+ }));
}
const TEASER_PATCH_KEYS = ["lines", "beat", "dip", "tail", "tailWait"];
diff --git a/umtool/lib/report/prepCli.mjs b/umtool/lib/report/prepCli.mjs
@@ -0,0 +1,156 @@
+// `umtool prep`: the clip bench's first-open work for a project, made ahead
+// of the walk (lib/report/benchPrep.mjs says what and why).
+//
+// umtool prep <project> [--clips a,b] [--json] queue it; a runner starts in the background
+// umtool prep <project> [--clips a,b] --wait run it here and wait (the same runner, niced)
+// umtool prep <project> --status [--json] what is ready, what is not, the runner if one is alive
+//
+// `--run` is the runner itself (what the queue starts): it takes the
+// project's run lock and drains the queue, one clip at a time, each in the
+// machine's heavy slot with PREP_ESTIMATE_MB declared. Plain ESM: the CLI runs
+// under bare node. Imported by bin/umtool.mjs only -- never by the app, which
+// reaches the heavy gate through the runner process.
+import { spawn } from "node:child_process";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import {
+ PREP_ESTIMATE_MB,
+ benchPrepState,
+ drainPrepQueue,
+ queueBenchPrep,
+ runnerArgv,
+} from "./benchPrep.mjs";
+import { UMTOOL_DIR } from "./driver.mjs";
+
+export const PREP_USAGE = [
+ "usage: umtool prep <project> [--clips a,b] [--json] queue the clips' excerpts and waveforms for the walk; returns at once",
+ " umtool prep <project> [--clips a,b] --wait the same, here, until it is done",
+ " umtool prep <project> --status [--json] ready / to prepare / not fetched, and the runner",
+ "",
+ "One clip at a time, each in the heavy slot (estimate " + PREP_ESTIMATE_MB + " MB), under nice -n 19 and ionice -c3.",
+ "A clip already prepared (its excerpt newer than its recording, its waveform cached) is skipped.",
+].join("\n");
+
+/** @param {Awaited<ReturnType<typeof benchPrepState>>} s */
+export function stateLine(s) {
+ const c = s.counts;
+ const fetched = c.clips - c.noWindow;
+ const parts = [`${c.ready} of ${fetched} fetched clip${fetched === 1 ? "" : "s"} ready for the walk`];
+ if (c.todo) parts.push(`${c.todo} to prepare${c.excerpts ? ` (${c.excerpts} excerpt${c.excerpts === 1 ? "" : "s"} to cut)` : ""}`);
+ if (c.failed) parts.push(`${c.failed} failed`);
+ if (c.noWindow) parts.push(`${c.noWindow} not fetched`);
+ if (s.runner) {
+ const cur = s.runner.current;
+ parts.push(`preparing ${Math.min(s.runner.done + 1, s.runner.total)} of ${s.runner.total}${cur ? ` — ${cur.id}, ${cur.step === "waiting" ? "waiting for the heavy slot" : cur.step}` : ""} (pid ${s.runner.pid})`);
+ }
+ return `${s.project}: ${parts.join(" · ")}`;
+}
+
+const stamp = () => new Date().toISOString().slice(11, 19);
+
+/** The runner's progress as lines (stderr, and prep.log when it runs detached). */
+export function eventLine(project, ev) {
+ switch (ev.ev) {
+ case "start":
+ return `${stamp()} prep ${project}: ${ev.total} to prepare (${ev.ready} ready${ev.noWindow ? `, ${ev.noWindow} not fetched` : ""})`;
+ case "clip":
+ return ev.step === "waiting"
+ ? `${stamp()} ${ev.id} (${ev.n}/${ev.total}): waiting for the heavy slot`
+ : `${stamp()} ${ev.id}: ${ev.step}${ev.window ? ` ${ev.window}` : ""}`;
+ case "clip-done":
+ return `${stamp()} ${ev.id}: ready (${(Number(ev.ms) / 1000).toFixed(1)} s)`;
+ case "clip-failed":
+ return `${stamp()} ${ev.id}: FAILED — ${String(ev.error).split("\n").pop()}`;
+ case "end":
+ return `${stamp()} prep ${project}: ${ev.done} prepared, ${ev.failed} failed, ${ev.skipped} already ready`;
+ default:
+ return null;
+ }
+}
+
+/**
+ * @param {string[]} args the words after `prep`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ const json = args.includes("--json");
+ const words = [];
+ let clips = null;
+ for (let i = 0; i < args.length; i += 1) {
+ if (args[i] === "--clips") {
+ clips = String(args[i + 1] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
+ i += 1;
+ } else if (!args[i].startsWith("--")) words.push(args[i]);
+ }
+ const [projectArg] = words;
+ if (!projectArg || args.includes("--help")) {
+ err(PREP_USAGE);
+ return 2;
+ }
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) {
+ err(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ return 1;
+ }
+ if (!r.project) {
+ err(`no project matches "${projectArg}"`);
+ return 1;
+ }
+ const project = { id: r.project.id, dir: r.project.dir };
+
+ // ---- the runner ----------------------------------------------------------
+ if (args.includes("--run")) {
+ const ndjson = args.includes("--ndjson");
+ const { withRenderSlot } = await import("../../report-to-video/heavy-gate.mjs");
+ const res = await drainPrepQueue(project, {
+ initial: args.includes("--wait") ? { clips, retry: args.includes("--retry") } : null,
+ wait: args.includes("--wait"),
+ slot: (cmd, fn) => withRenderSlot(cmd, fn, { estimateMb: PREP_ESTIMATE_MB }),
+ onEvent: (ev) => {
+ const line = ndjson ? JSON.stringify(ev) : eventLine(project.id, ev);
+ if (line) process.stderr.write(`${line}\n`);
+ },
+ });
+ return res.failed.length ? 1 : 0;
+ }
+
+ if (args.includes("--status")) {
+ const s = await benchPrepState(project, { clips });
+ if (json) out(JSON.stringify(s, null, 2));
+ else {
+ out(stateLine(s));
+ for (const it of s.items) if (it.state === "failed") out(` ✗ ${it.id}: ${it.error ?? "failed"}`);
+ }
+ return 0;
+ }
+
+ // ---- --wait: the runner, here --------------------------------------------
+ if (args.includes("--wait")) {
+ const argv = runnerArgv(project.id, { wait: true, clips, retry: true });
+ const code = await new Promise((resolve) => {
+ const child = spawn(argv[0], argv.slice(1), { cwd: UMTOOL_DIR, stdio: ["ignore", "inherit", "inherit"], env: process.env });
+ child.on("error", (e) => {
+ err(String(e));
+ resolve(1);
+ });
+ child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1)));
+ });
+ const s = await benchPrepState(project, { clips });
+ if (json) out(JSON.stringify(s, null, 2));
+ else out(stateLine(s));
+ return Number(code) === 0 ? 0 : 1;
+ }
+
+ // ---- queue it --------------------------------------------------------------
+ const q = await queueBenchPrep(project, clips, { retry: true });
+ const s = await benchPrepState(project, { clips });
+ if (json) out(JSON.stringify({ ...s, queued: q.queued, started: q.started, pid: q.pid, ...(q.off ? { off: true } : {}) }, null, 2));
+ else {
+ out(stateLine(s));
+ if (q.off) out(" UMTOOL_BENCH_PREP=0: nothing queued");
+ else if (q.queued.length) out(` queued ${q.queued.length}: ${q.started ? `runner started (pid ${q.pid})` : `the runner already going takes them (pid ${q.pid})`}; its log is out/bench-excerpts/prep.log`);
+ else out(" nothing to prepare");
+ }
+ return 0;
+}
+
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -7,7 +7,7 @@
// membership check and once on resolveInRoots.
import path from "node:path";
import { createReadStream } from "node:fs";
-import { mkdir, realpath, rename, rm, stat } from "node:fs/promises";
+import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { Readable } from "node:stream";
@@ -153,6 +153,11 @@ export async function windowsFor(project, clip, cache = null) {
// excerpt of a 1080p recording on a platter is 10-30 s of ffmpeg on a busy
// machine). The render never comes through here; it cuts the clip from the
// whole recording itself.
+//
+// AND BEFORE ANYBODY OPENS IT: the bench's prep (lib/report/benchPrep.mjs,
+// `umtool prep`, the Cut tab's "Prepare clips for the walk", and a write or a
+// fetch that needs one) cuts the same excerpts in a background runner, through
+// excerptOf and ensureWindowFile here, so the walk finds them made.
// ---------------------------------------------------------------------------
/** A window longer than this (seconds) is a recording, and the bench is given an excerpt of it. */
@@ -189,25 +194,96 @@ export function excerptOf(win, clip, projectDir, { over = EXCERPT_OVER_S, pad =
const execFileP = promisify(execFile);
const cutting = new Map();
+let cutSeq = 0;
+
+/** Where an excerpt's cut says who is making it: `<excerpt>.cutting`, `{pid, at}`. */
+export const cutMarkOf = (file) => `${file}.cutting`;
+/** How long a request waits for ANOTHER process's cut of the same excerpt before cutting it itself. */
+export const CUT_WAIT_MS = 180_000;
+/** A mark older than this is a cut that died without cleaning up. */
+const CUT_MARK_STALE_MS = 15 * 60_000;
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const alive = (pid) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return /** @type {NodeJS.ErrnoException} */ (e).code === "EPERM";
+ }
+};
+
+/**
+ * The live mark another process left on this excerpt, or null.
+ * @param {string} file
+ * @param {{ now?: number, self?: number }} [opts]
+ * @returns {Promise<{ pid: number, at: number } | null>}
+ */
+export async function foreignCut(file, { now = Date.now(), self = process.pid } = {}) {
+ const raw = await readFile(cutMarkOf(file), "utf8").catch(() => null);
+ if (!raw) return null;
+ let m;
+ try {
+ m = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ const pid = Number(m?.pid);
+ const at = Number(m?.at);
+ if (!Number.isInteger(pid) || pid <= 0 || pid === self) return null;
+ if (!Number.isFinite(at) || now - at > CUT_MARK_STALE_MS) return null;
+ return alive(pid) ? { pid, at } : null;
+}
+
+/**
+ * Is a window's file on disk and current? A real window always is (nothing
+ * here makes one). An excerpt is when it is NEWER THAN ITS SOURCE: a
+ * re-fetched recording invalidates every excerpt cut from it.
+ *
+ * @param {{path: string, excerptOf?: {path: string}}} win
+ */
+export async function windowFileFresh(win) {
+ if (!win?.excerptOf) return true;
+ const src = resolveInRoots(win.excerptOf.path);
+ if (!src) throw new Error("the recording is outside the roots");
+ const srcSt = await stat(src);
+ const have = await stat(win.path).catch(() => null);
+ return !!(have && have.size > 0 && have.mtimeMs >= srcSt.mtimeMs);
+}
/**
* Make sure a window's file is on disk: a no-op for a real window; for an
* excerpt, cut it once (newer than its source = done) and share the cut with
* every request that asks meanwhile.
*
+ * ACROSS PROCESSES too: the bench's prep (lib/report/benchPrep.mjs, `umtool
+ * prep`) cuts the same files ahead of the walk, in a process of its own. Each
+ * cut leaves `<excerpt>.cutting` naming its pid while it runs; a request that
+ * finds a live one waits for that cut (up to `waitMs`) rather than starting a
+ * second encode of the same seconds, and every cut writes its own temporary
+ * name, so two that do overlap cannot write into one file.
+ *
* @param {{path: string, from: number, to: number, excerptOf?: {path: string, from: number}}} win
+ * @param {{ ffmpeg?: string, waitMs?: number, pollMs?: number }} [opts]
*/
-export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN } = {}) {
+export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN, waitMs = CUT_WAIT_MS, pollMs = 250 } = {}) {
if (!win?.excerptOf) return;
const src = resolveInRoots(win.excerptOf.path);
if (!src) throw new Error("the recording is outside the roots");
- const srcSt = await stat(src);
- const have = await stat(win.path).catch(() => null);
- if (have && have.size > 0 && have.mtimeMs >= srcSt.mtimeMs) return;
+ if (await windowFileFresh(win)) return;
if (!cutting.has(win.path)) {
const job = (async () => {
+ const until = Date.now() + waitMs;
+ while (await foreignCut(win.path)) {
+ if (Date.now() > until) break;
+ await sleep(pollMs);
+ }
+ if (await windowFileFresh(win)) return;
await mkdir(path.dirname(win.path), { recursive: true });
- const tmp = `${win.path}.part.mp4`;
+ const mark = cutMarkOf(win.path);
+ await writeFile(mark, JSON.stringify({ pid: process.pid, at: Date.now() })).catch(() => {});
+ cutSeq += 1;
+ const tmp = `${win.path}.part-${process.pid}-${cutSeq}.mp4`;
try {
await execFileP(ffmpeg, [
"-v", "error", "-y",
@@ -225,6 +301,10 @@ export async function ensureWindowFile(win, { ffmpeg = FFMPEG_BIN } = {}) {
} catch (e) {
await rm(tmp, { force: true });
throw e;
+ } finally {
+ // Only our own mark: another process may have written one since.
+ const m = await readFile(mark, "utf8").then((t) => JSON.parse(t), () => null);
+ if (Number(m?.pid) === process.pid) await rm(mark, { force: true });
}
})().finally(() => cutting.delete(win.path));
cutting.set(win.path, job);
diff --git a/umtool/report-to-video/heavy-gate.mjs b/umtool/report-to-video/heavy-gate.mjs
@@ -45,13 +45,18 @@ export function heavyLockFile(root = checkoutRoot()) {
* it. With no gate to load (a copy of the directory without the checkout's
* scripts/), says so and runs: the slot is a safety net, not a correctness lock.
*
+ * `estimateMb` declares the job's memory (queue-lock's weighted admission): it
+ * then runs BESIDE others while MemAvailable minus every running estimate stays
+ * at or above the floor, and waits otherwise. Without one it runs alone, as a
+ * render does. The bench's prep (lib/report/benchPrep.mjs) declares one.
+ *
* @template T
* @param {string[]} cmd
* @param {() => Promise<T>} fn
- * @param {{ env?: NodeJS.ProcessEnv, root?: string, say?: (line: string) => void }} [opts]
+ * @param {{ env?: NodeJS.ProcessEnv, root?: string, say?: (line: string) => void, estimateMb?: number }} [opts]
* @returns {Promise<T>}
*/
-export async function withRenderSlot(cmd, fn, { env = process.env, root = checkoutRoot(), say } = {}) {
+export async function withRenderSlot(cmd, fn, { env = process.env, root = checkoutRoot(), say, estimateMb } = {}) {
const note = say ?? ((line) => process.stderr.write(`${line}\n`));
if (env.HEAVY === "0" || env.HEAVY_HELD) return fn();
let gate;
@@ -66,5 +71,5 @@ export async function withRenderSlot(cmd, fn, { env = process.env, root = checko
const lock = heavyLockFile(root);
if (lock) env.HEAVY_LOCK_FILE = lock;
}
- return gate.withHeavy({ cmd }, fn);
+ return gate.withHeavy({ cmd, ...(Number(estimateMb) > 0 ? { estimateMb: Number(estimateMb) } : {}) }, fn);
}