commit e19d52d2df9a19661605fcf04dceb8140f2f83c8
parent df511d6b05c2d07e15cee64ad9f664de8394ffae
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 29 Oct 2026 19:45:26 -0400
Merge lane/render-speed: each distinct chrome frame captured once, the frame-list page seeks exactly (fixes take --from marker drift), layers captured side by side with workers sized to the machine
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 580 insertions(+), 125 deletions(-)
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -306,13 +306,16 @@ its chrome capture, with about 20 % on top:
joins (a window's, a whole cut's), at most a batch (`REPORT_VIDEO_XFADE_BATCH` /
`render.xfadeBatch`, default 24), one when nothing is crossfaded (`--no-xfade`, a
transition of 0) or the run is one clip (`--clip-preview`, `--short`): **6020 MB** for a
- whole cut, 2420 MB for a 4-entry window, 1880 MB for one clip;
-- the chrome capture: 400 MB + 320 MB per `UMTOOL_CHROME_WORKERS` (default 4): 1680 MB, 2640
- at 7, 5520 at 16;
+ whole cut, 2420 MB for a 4-entry window, 1880 MB for one clip (a short run's chrome capture
+ is the larger, below);
+- the chrome capture: 400 MB per render at once (`UMTOOL_CHROME_LAYERS`, default 3) + 320 MB
+ per worker of the capture pool's budget (1.5 a core, at most 12; or
+ `UMTOOL_CHROME_WORKERS`): 5040 MB on 8 cores, 6320 at 16 (measured: 12 workers peaked at
+ 3.4 GB PSS);
- the ladder: 1000 MB.
So a capped 5 GB build joins a whole-cut render only while `MemAvailable − 6020 ≥ 6000`, and
-a window take while `MemAvailable − 2420 ≥ 6000`; under that it waits for the render, as
+a window take while `MemAvailable − 5040 ≥ 6000` (on 8 cores); under that it waits for the render, as
before. On a 16 GB machine a whole cut and a build together is rare — the 23-segment batch
alone took MemAvailable to about 450 MB here, with the desktop and the live apps running.
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -511,8 +511,9 @@ nothing and ran alone. `report-to-video/render-estimate.mjs` holds the numbers,
180 MB per segment, the run's segments (a window's entries, a whole cut's; the brand intro
is one) capped at the batch size (`REPORT_VIDEO_XFADE_BATCH` / `render.xfadeBatch`, 24),
one under `--no-xfade`, a transition of 0, `--clip-preview` or `--short`. The capture is
- 400 MB + 320 MB per `UMTOOL_CHROME_WORKERS` (4). A whole cut declares 6020 MB, a 4-entry
- window 2420 MB, one clip 1880 MB;
+ 400 MB per render at once (`UMTOOL_CHROME_LAYERS`, 3) + 320 MB per worker (the capture
+ pool's budget: 1.5 a core, or `UMTOOL_CHROME_WORKERS`) -- 5040 MB on 8 cores. A whole
+ cut declares 6020 MB, a 4-entry window or one clip 5040 MB on 8 cores;
- **the encode ladder** (`umtool variants`, Deliver's **Make variants**): 1000 MB (it peaked at 0.76 GB).
Measured on the Huck cut (WORKTREES.md, "A render's estimate"): a 23-segment crossfade batch
@@ -1016,6 +1017,37 @@ changed or added recaptures from its moment on, and with the rail at a fixed pit
(`deck.pip.spacing: "pitch"`) a clip appended keeps every frame before the marker reaches the clip
before it. A render keyed before then (frame-key version 1) is captured once more, then reused.
+A layer's FIRST render is keyed the same way: each DISTINCT frame is captured once and every frame
+of its key is a hard link to that capture. A layer draws a still stretch for most of a cut, so this
+is most of its frames -- measured on Ember's 26-minute cut (47,041 frames a layer): the status card
+39 distinct frames, the pair strip 176, the stamps ~1,300, each chapter card 29 of 91, the deck
+~11,500 (its fuse moves the whole cut). The distinct frames are counted before the render, and a
+layer whose new keys are nearly all its frames (over 90 %) renders whole as before.
+`UMTOOL_FRAME_DEDUP=0` turns the first-render dedup off. Measured on that cut (draft 4, uncached
+chrome, 8 cores): every layer captured whole, one after another, took 1,143 s (deck 461, pair 260,
+status 382, ten chapter cards ~40); by their distinct frames, side by side, 169 s -- and the final
+it encodes to matched main's frame for frame in 46,367 of 47,041 frames (the rest at least 52.9 dB
+PSNR, the renderer's worker-to-worker noise below), its sound bit for bit. A preview's window of the cut
+(`--chrome-preview`, `--clip-preview`) is keyed too: each frame at its cut time.
+
+The layers then CAPTURE SIDE BY SIDE (report-to-video `capture-pool.mjs`): every layer of a build
+starts at once, and each asks one pool of renderer workers for its share right before its renderer
+runs -- a worker per 120 frames it will capture, the largest first, one left for each layer beside
+it, at most `UMTOOL_CHROME_LAYERS` (3) renders at once. The pool's budget is one and a half
+workers per core (at least 2, at most 12, within 6 GB of the heavy scope's 8 GB cap;
+`render-estimate.mjs` `chromeWorkers`): 12 on 8 cores. `UMTOOL_CHROME_WORKERS` sets it outright.
+A worker spends much of each frame waiting on its browser, so more workers than cores pay: Ember's
+deck (10,689 distinct frames) captured in 114 s at 8 workers (machine 66 % busy), 98 s at 12,
+92 s at 16, 100 s at 24.
+
+The frame-list page (the one capture of only the frames a render needs) seeks the page's own
+timeline at exactly `cutFrame / fps`, the time a whole render seeks, finding the frame's run by
+binary search. It used to nest a tween per run, which drifted: on Ember's deck 13,542 of 47,041
+frames came out unlike the whole render (a marker and its label a pixel over); now 45,959 are
+byte-identical to it and the other 1,082 differ by the renderer's own worker-to-worker noise (at
+most 47 levels on at most 128 pixels; main's own renders at 6 and 7 workers differ in 2.4 % of
+frames the same way).
+
`--quick` (a recipe's or a take's `quick: true`) is that quick render. A take that exists is skipped unless forced (**make it again if it exists**, `--force`).
**Rebuild** on a card (`--rebuild`) makes it again from its own take.json against the project's
manifest as it is now. A recipe is `{ group, window, quick?, takes: [{ id, label, style?, patch?,
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -244,21 +244,20 @@ import {
validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, levelFilters, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords,
} from "./montage.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
-import { chromeWorkers, manifestEstimateMb } from "./render-estimate.mjs";
+import { chromeLayers, chromeWorkers, manifestEstimateMb } from "./render-estimate.mjs";
+import { createCapturePool, runLimited } from "./capture-pool.mjs";
const execFileP = promisify(execFile);
const YTDLP = process.env.YTDLP_BIN ?? "yt-dlp";
const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg";
-// Chromium workers for the 4-worker chrome regions (deck, feed, teaser): a
-// render on an idle 8-core machine is capture-bound, and 4 leaves cores idle.
-// UMTOOL_CHROME_WORKERS raises it for one run; absent, 4 as before.
-// (render-estimate.mjs reads it the same way: a render's memory estimate scales
-// with it.)
+// The chrome capture's worker budget, shared by every layer of a build
+// (capture-pool.mjs): a worker per core, within the heavy scope's memory, or
+// UMTOOL_CHROME_WORKERS for one run (render-estimate.mjs chromeWorkers --
+// a render's memory estimate is read the same way). CHROME_LAYERS renders at
+// once (UMTOOL_CHROME_LAYERS; 1 is one layer after another).
const CHROME_WORKERS = chromeWorkers(process.env);
-// The 2-worker regions (posts, finale, stamps, stats, threads, flips): the same
-// knob raises them too when it is set; absent, 2 as before.
-const CHROME_WORKERS_SMALL = process.env.UMTOOL_CHROME_WORKERS ? CHROME_WORKERS : 2;
+const CHROME_LAYERS = chromeLayers(process.env);
const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe";
const QRENCODE = process.env.QRENCODE_BIN ?? "qrencode";
@@ -2517,6 +2516,8 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir,
const r = await composeChrome({
manifestPath, outDir, variant, region: "teaser", segment: entry.id, doRender: true,
fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence", transition,
+ // Workers by the frames it captures (its distinct ones), up to the budget.
+ lease: createCapturePool({ budget: CHROME_WORKERS }).lease,
});
EMIT("chrome", {
phase: r.cached ? "cached" : "render", region: "teaser", segment: entry.id,
@@ -5061,62 +5062,92 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro
// covers every region under it while it is up. A whole-cut module is one
// sequence for the whole cut -- or the deck's window -- laid from frame 1;
// a window module is a short sequence per window, laid at its own second.
+ //
+ // Every layer is its own render, and they CAPTURE SIDE BY SIDE: each is a
+ // job here, they all start at once, and each asks the build's one capture
+ // pool (capture-pool.mjs) for its workers when it knows how many frames it
+ // will capture -- the overlay order is the jobs' order, whatever order
+ // they finish in.
+ const jobs = [];
for (const mod of deckOverlays()) {
if (!mod.on(schedule, render)) continue;
- const workers = mod.workers === "wide" ? CHROME_WORKERS : CHROME_WORKERS_SMALL;
// The shell's events name no region (the deck's, as they always have).
const named = mod.region === "deck" ? {} : { region: mod.region };
if (mod.kind === "overlay-whole") {
- EMIT("chrome", { phase: "compose", ...named, ...win });
- const t1 = Date.now();
- const r = await composeChrome({
- manifestPath, outDir, variant, region: mod.region, doRender: true,
- fps: render.fps, workers, quality: "high", format: "png-sequence", ...win,
- });
- if (r.frameCount !== want) {
- throw new Error(
- mod.region === "deck"
- ? `the deck's sequence is ${r.frameCount} frames but the ${duration != null ? "window" : "cut"} ` +
- `is ${want} (${(duration ?? schedule.total).toFixed(3)}s at ${render.fps} fps)`
- : `${mod.noun} sequence is ${r.frameCount} frames but the deck's is ${want}`,
- );
- }
- emitChrome({
- phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", ...named,
- ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}),
- frames: r.frameCount, key: r.key, dir: r.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ jobs.push(async (lease) => {
+ EMIT("chrome", { phase: "compose", ...named, ...win });
+ const t1 = Date.now();
+ const r = await composeChrome({
+ manifestPath, outDir, variant, region: mod.region, doRender: true,
+ fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence", ...win,
+ });
+ if (r.frameCount !== want) {
+ throw new Error(
+ mod.region === "deck"
+ ? `the deck's sequence is ${r.frameCount} frames but the ${duration != null ? "window" : "cut"} ` +
+ `is ${want} (${(duration ?? schedule.total).toFixed(3)}s at ${render.fps} fps)`
+ : `${mod.noun} sequence is ${r.frameCount} frames but the deck's is ${want}`,
+ );
+ }
+ emitChrome({
+ phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", ...named,
+ ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}),
+ frames: r.frameCount, key: r.key, dir: r.frames,
+ seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ });
+ return mod.regions(schedule, { render, outDir, frames: r.frames });
});
- regions.push(...mod.regions(schedule, { render, outDir, frames: r.frames }));
continue;
}
for (const pr of mod.regions(schedule, { render, outDir, shift: clip ? clip.at : 0, clip })) {
- EMIT("chrome", { phase: "compose", region: mod.region, ...(pr.segment !== undefined ? { segment: pr.segment } : {}) });
- const t1 = Date.now();
- const p = await composeChrome({
- manifestPath, outDir, variant, region: mod.region, ...(pr.segment !== undefined ? { window: pr.window } : {}), doRender: true,
- fps: render.fps, workers, quality: "high", format: "png-sequence",
- });
- if (p.frames !== pr.frames || p.frameCount !== pr.frameCount) {
- throw new Error(
- pr.segment !== undefined
- ? `the posts window for ${pr.segment} rendered ${p.frameCount} frames to ${p.frames}; ` +
- `the overlay expects ${pr.frameCount} at ${pr.frames}`
- : `the ${mod.region} rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${pr.frameCount} at ${pr.frames}`,
- );
- }
- emitChrome({
- phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: mod.region,
- ...(pr.segment !== undefined ? { segment: pr.segment } : {}),
- ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}),
- frames: p.frameCount, key: p.key, dir: p.frames,
- seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ jobs.push(async (lease) => {
+ EMIT("chrome", { phase: "compose", region: mod.region, ...(pr.segment !== undefined ? { segment: pr.segment } : {}) });
+ const t1 = Date.now();
+ const p = await composeChrome({
+ manifestPath, outDir, variant, region: mod.region, ...(pr.segment !== undefined ? { window: pr.window } : {}), doRender: true,
+ fps: render.fps, workers: CHROME_WORKERS, lease, quality: "high", format: "png-sequence",
+ });
+ if (p.frames !== pr.frames || p.frameCount !== pr.frameCount) {
+ throw new Error(
+ pr.segment !== undefined
+ ? `the posts window for ${pr.segment} rendered ${p.frameCount} frames to ${p.frames}; ` +
+ `the overlay expects ${pr.frameCount} at ${pr.frames}`
+ : `the ${mod.region} rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${pr.frameCount} at ${pr.frames}`,
+ );
+ }
+ emitChrome({
+ phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: mod.region,
+ ...(pr.segment !== undefined ? { segment: pr.segment } : {}),
+ ...(p.reused != null ? { reused: p.reused, captured: p.captured } : {}),
+ frames: p.frameCount, key: p.key, dir: p.frames,
+ seconds: Number(((Date.now() - t1) / 1000).toFixed(1)),
+ });
+ const { window: _w, ...region } = pr;
+ return [region];
});
- const { window: _w, ...region } = pr;
- regions.push(region);
}
}
- if (duration == null && layers.length) await logRebuild(outDir, { phase: "chrome", layers });
+ const pool = createCapturePool({ budget: CHROME_WORKERS, maxActive: CHROME_LAYERS });
+ const tAll = Date.now();
+ // Composing is cheap and most of a job's time is its lease: a few more
+ // jobs in flight than renders, so the next is composed and asking when one ends.
+ const placed = await runLimited(jobs.map((job) => async () => {
+ const m = pool.member();
+ try {
+ return await job(m.lease);
+ } finally {
+ m.done();
+ }
+ }), CHROME_LAYERS + 3);
+ for (const rs of placed) regions.push(...rs);
+ if (jobs.length > 1) {
+ EMIT("chrome", { phase: "captured", layers: jobs.length, workers: pool.budget, peakWorkers: pool.stats.peakWorkers,
+ peakRenders: pool.stats.peakActive, seconds: Number(((Date.now() - tAll) / 1000).toFixed(1)) });
+ }
+ if (duration == null && layers.length) {
+ await logRebuild(outDir, { phase: "chrome", seconds: Number(((Date.now() - tAll) / 1000).toFixed(1)), workers: pool.budget,
+ renders: CHROME_LAYERS, layers });
+ }
return { regions, outLabel: "[hfout]" };
}
diff --git a/umtool/report-to-video/capture-pool.mjs b/umtool/report-to-video/capture-pool.mjs
@@ -0,0 +1,134 @@
+// THE CHROME CAPTURE POOL: one budget of renderer workers that a build's
+// chrome layers share, so the layers capture side by side instead of one
+// after another.
+//
+// Every layer (the deck, the pair strip, the stamps, each chapter card's
+// window …) is a HyperFrames render of its own, and each pays a fixed start
+// (the CLI, a browser, a page load per worker) before its first frame. One at
+// a time, a cut with fifteen small layers paid fifteen starts in a row while
+// most of the machine's cores sat idle behind a 2-worker render. Now
+// build-video starts the layers together (`member()` each) and each asks this
+// pool for workers right before its renderer runs (`lease(frames)`), sized by
+// the frames it will actually capture -- compose-chrome's frame keys: its
+// DISTINCT frames, not its length:
+//
+// - a lease wants one worker per FRAMES_PER_WORKER frames, at least one,
+// at most the budget;
+// - nothing is granted while a started layer is still composing (its frame
+// count unknown): the deck, composed first but slowest to key, is never
+// starved by the small layers that asked before it;
+// - then the largest asks are served first, each leaving one worker for
+// every other ask that could start beside it, so the small layers run
+// beside the big one instead of after it;
+// - at most `maxActive` renders run at once (each is a browser of its own:
+// memory, render-estimate.mjs).
+//
+// Pure: no I/O, no timers. build-video makes one per renderDeck.
+
+/** Frames a worker should have to itself before another is worth its start. */
+export const FRAMES_PER_WORKER = 120;
+
+/**
+ * @param {{ budget: number, maxActive?: number, perWorker?: number }} o
+ * `budget` the workers in all; `maxActive` the renders at once.
+ */
+export function createCapturePool({ budget, maxActive = Infinity, perWorker = FRAMES_PER_WORKER }) {
+ const B = Math.max(1, Math.floor(budget));
+ let free = B;
+ let active = 0;
+ let composing = 0;
+ let seq = 0;
+ const queue = [];
+ const stats = { peakWorkers: 0, peakActive: 0, leases: [] };
+
+ const want = (count) => Math.max(1, Math.min(B, Math.ceil(Number(count || 0) / perWorker)));
+
+ const pump = () => {
+ if (composing > 0) return;
+ // Largest first; ties in the order asked.
+ queue.sort((x, y) => y.count - x.count || x.seq - y.seq);
+ for (let i = 0; i < queue.length && free > 0 && active < maxActive; ) {
+ const q = queue[i];
+ // The others that could start beside this one now: one worker each.
+ const others = Math.min(queue.length - 1, maxActive - active - 1);
+ const n = Math.max(1, Math.min(want(q.count), free - others));
+ queue.splice(i, 1);
+ free -= n;
+ active += 1;
+ stats.peakWorkers = Math.max(stats.peakWorkers, B - free);
+ stats.peakActive = Math.max(stats.peakActive, active);
+ stats.leases.push({ count: q.count, workers: n });
+ let released = false;
+ q.resolve({
+ workers: n,
+ release() {
+ if (released) return;
+ released = true;
+ free += n;
+ active -= 1;
+ pump();
+ },
+ });
+ }
+ };
+
+ const ask = (count) =>
+ new Promise((resolve) => {
+ queue.push({ count: Number(count) || 0, seq: seq++, resolve });
+ pump();
+ });
+
+ return {
+ budget: B,
+ stats,
+ /** Workers for a capture of `count` frames, for a caller that is no member: `{ workers, release }`. */
+ lease: ask,
+ /**
+ * A layer that has started: until it asks (`lease`) or is finished
+ * (`done`, leased or not), no lease is granted.
+ */
+ member() {
+ composing += 1;
+ let state = "composing";
+ const settle = () => {
+ if (state === "composing") composing -= 1;
+ };
+ return {
+ lease(count) {
+ settle();
+ state = "asked";
+ return ask(count);
+ },
+ done() {
+ settle();
+ state = "done";
+ pump();
+ },
+ };
+ },
+ };
+}
+
+/**
+ * Run `jobs` (functions returning promises) with at most `limit` running at
+ * once; results in the jobs' order. A failure rejects once every started
+ * job has settled.
+ */
+export async function runLimited(jobs, limit = Infinity) {
+ const out = new Array(jobs.length);
+ let next = 0;
+ let failed = null;
+ const width = Math.max(1, Math.min(jobs.length, limit));
+ await Promise.all(Array.from({ length: width }, async () => {
+ while (next < jobs.length && !failed) {
+ const i = next++;
+ try {
+ out[i] = await jobs[i]();
+ } catch (e) {
+ failed = failed ?? { e };
+ }
+ }
+ }));
+ if (failed) throw failed.e;
+ return out;
+}
diff --git a/umtool/report-to-video/capture-pool.test.mjs b/umtool/report-to-video/capture-pool.test.mjs
@@ -0,0 +1,102 @@
+// The chrome capture pool (capture-pool.mjs): one worker budget the layers share.
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createCapturePool, FRAMES_PER_WORKER, runLimited } from "./capture-pool.mjs";
+
+const tick = () => new Promise((r) => setImmediate(r));
+
+test("a lease wants a worker per FRAMES_PER_WORKER frames, at least one, at most the budget", async () => {
+ const pool = createCapturePool({ budget: 8 });
+ const a = await pool.lease(10);
+ assert.equal(a.workers, 1, "a few frames: one worker");
+ a.release();
+ const b = await pool.lease(FRAMES_PER_WORKER * 3 + 1);
+ assert.equal(b.workers, 4);
+ b.release();
+ const c = await pool.lease(1e6);
+ assert.equal(c.workers, 8, "never more than the budget");
+ c.release();
+ const d = await pool.lease(0);
+ assert.equal(d.workers, 1, "nothing to capture still renders with one");
+ d.release();
+});
+
+test("nothing is granted while a layer is still composing; then the largest first, one worker left for each other", async () => {
+ const pool = createCapturePool({ budget: 8, maxActive: 3 });
+ const deck = pool.member();
+ const pair = pool.member();
+ const status = pool.member();
+ const chapter = pool.member();
+ const got = {};
+ // The small ones ask first (they key fast); the deck is still composing.
+ pair.lease(176).then((l) => (got.pair = l));
+ status.lease(39).then((l) => (got.status = l));
+ await tick();
+ assert.deepEqual(got, {}, "the deck has not asked: nothing granted");
+ chapter.done(); // cached: never asks
+ await tick();
+ assert.deepEqual(got, {});
+ deck.lease(10207).then((l) => (got.deck = l));
+ await tick();
+ // Three may run: the deck leaves one worker for each of the two beside it.
+ assert.equal(got.deck.workers, 6);
+ assert.equal(got.pair.workers, 1);
+ assert.equal(got.status.workers, 1);
+ assert.equal(pool.stats.peakWorkers, 8);
+ assert.equal(pool.stats.peakActive, 3);
+ for (const l of Object.values(got)) l.release();
+});
+
+test("a lease waits for a free worker, and takes what its size wants once others are done", async () => {
+ const pool = createCapturePool({ budget: 4, maxActive: 4 });
+ const a = await pool.lease(1e6);
+ assert.equal(a.workers, 4, "alone: the whole budget");
+ let b = null;
+ pool.lease(FRAMES_PER_WORKER * 2).then((l) => (b = l));
+ await tick();
+ assert.equal(b, null, "nothing free");
+ a.release();
+ await tick();
+ assert.equal(b.workers, 2);
+ b.release();
+});
+
+test("at most maxActive renders at once", async () => {
+ const pool = createCapturePool({ budget: 16, maxActive: 2 });
+ const got = [];
+ for (let i = 0; i < 5; i += 1) pool.lease(10).then((l) => got.push(l));
+ await tick();
+ assert.equal(got.length, 2);
+ got[0].release();
+ await tick();
+ assert.equal(got.length, 3);
+ got[0].release(); // twice: once
+ await tick();
+ assert.equal(got.length, 3, "a second release of one lease frees nothing");
+ for (const l of got.slice(1)) l.release();
+ await tick();
+ await tick();
+ assert.equal(got.length, 5);
+ assert.equal(pool.stats.peakActive, 2);
+});
+
+test("runLimited: the jobs' order, at most `limit` at once, a failure after the started ones settle", async () => {
+ let running = 0;
+ let peak = 0;
+ const job = (v, ms) => async () => {
+ running += 1;
+ peak = Math.max(peak, running);
+ await new Promise((r) => setTimeout(r, ms));
+ running -= 1;
+ return v;
+ };
+ assert.deepEqual(await runLimited([job("a", 20), job("b", 1), job("c", 5), job("d", 1)], 2), ["a", "b", "c", "d"]);
+ assert.equal(peak, 2);
+ let settled = 0;
+ await assert.rejects(
+ runLimited([async () => { throw new Error("boom"); }, async () => { await new Promise((r) => setTimeout(r, 10)); settled += 1; }], 4),
+ /boom/,
+ );
+ assert.equal(settled, 1, "the other job finished before the rejection");
+});
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -866,6 +866,7 @@ export async function composeChrome({
schedule = null, preview = false, doRender = false,
fps = null, workers = null, quality = "high", format = "png-sequence",
still = null, png = null, from = 0, duration = null, window = null, segment = null, transition = null,
+ lease = null,
}) {
// The variant's view, and its own out directory. Handed the whole manifest
// the band would draw claims this cut never makes, and the deck would name
@@ -984,7 +985,7 @@ export async function composeChrome({
// A page the model cannot read (an ease it does not know, a cue it cannot
// place) renders whole, as a page without frame keys always has.
let fk = null;
- if (keyed && sequence && ((wholeCut && !windowed) || mod.kind === "overlay-window" || mod.kind === "segment") && !preview && mod.frameKeys) {
+ if (keyed && sequence && (wholeCut || mod.kind === "overlay-window" || mod.kind === "segment") && !preview && mod.frameKeys) {
try {
fk = frameKeys({ html, region, assets, fps: rate, frames, version: hf.version, items: pageItems });
} catch (e) {
@@ -992,6 +993,18 @@ export async function composeChrome({
fk = null;
}
}
+ // The renderer's workers for a capture of `count` frames: `workers`, or as
+ // many as the build's capture pool (`lease`, capture-pool.mjs) grants --
+ // held only while the renderer runs.
+ const withWorkers = async (count, fn) => {
+ if (!lease) return fn(workers);
+ const l = await lease(count);
+ try {
+ return await fn(l.workers);
+ } finally {
+ l.release();
+ }
+ };
if (keyed && sequence) {
const onDisk = await readFile(keyFile, "utf8").then((s) => s.trim(), () => null);
if (onDisk === key && (await framesOnDisk(target)) === frames) {
@@ -1004,7 +1017,7 @@ export async function composeChrome({
}
if (fk) {
const r = await reuseFrames({
- base, target, stem, fk, key, html, region, rate, hf, workers, quality, assetsDir,
+ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup: frameDedupOn(),
});
if (r) return { ...result, frames: target, ...r };
}
@@ -1012,17 +1025,16 @@ export async function composeChrome({
await rm(target, { recursive: true, force: true });
}
- const args = [
+ await withWorkers(frames ?? 0, (w) => runRenderer(hf.cmd, [
...hf.args, "render",
"--format", format, "--quality", quality,
"--fps", String(rate),
- ...(workers != null ? ["-w", String(workers)] : []),
+ ...(w != null ? ["-w", String(w)] : []),
// The deck is flat colour and text: software GL is deterministic and the
// GPU probe is a second per worker for nothing.
...(keyed ? ["--no-browser-gpu"] : []),
"--output", target, projDir,
- ];
- await runRenderer(hf.cmd, args);
+ ]));
if (keyed && sequence) {
const got = await framesOnDisk(target);
@@ -1064,10 +1076,14 @@ export function frameRuns(list) {
/**
* The page that renders only some of the cut's frames: its timeline is swapped,
- * where the page registers it, for one that plays each run of `runs`
- * (frameRuns') as a piece of the cut's timeline in turn -- the windowed
- * render's own tween, once per run -- and the page declares their length.
- * null when the page does not register its timeline the one way this knows.
+ * where the page registers it, for one whose frame f is the cut's frame
+ * `n + (f - j)` of the run `[j, n, len]` of `runs` (frameRuns') holding it --
+ * one tween on a clock whose setter seeks the page's own timeline there, at
+ * exactly the cut time a whole render seeks (`cutFrame / fps`) -- and the
+ * page declares their length. The run is found by binary search: a deck's
+ * first render lists ~10,000 one-frame runs, and a timeline of one child per
+ * run cost every seek a walk over all of them. null when the page does not
+ * register its timeline the one way this knows.
*/
export function frameListHtml(html, region, runs, fps) {
const reg = `window.__timelines["${region}"] = tl;`;
@@ -1079,9 +1095,21 @@ export function frameListHtml(html, region, runs, fps) {
const count = runs.reduce((n, r) => n + r[2], 0);
const helper =
`<script>window.__hfFrames = function (inner) {\n` +
- ` const R = ${JSON.stringify(runs)}, fps = ${Number(fps)};\n` +
+ ` const R = ${JSON.stringify(runs)}, fps = ${Number(fps)}, count = ${count};\n` +
+ ` const cutAt = (f) => {\n` +
+ ` let lo = 0, hi = R.length - 1;\n` +
+ ` while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (R[mid][0] <= f) lo = mid; else hi = mid - 1; }\n` +
+ ` return (R[lo][1] + Math.min(f - R[lo][0], R[lo][2] - 1)) / fps;\n` +
+ ` };\n` +
+ ` let now = 0;\n` +
+ ` const clock = {};\n` +
+ ` Object.defineProperty(clock, "t", { get() { return now; }, set(v) {\n` +
+ ` now = v;\n` +
+ ` inner.seek(cutAt(Math.max(0, Math.min(count - 1, Math.round(v * fps)))), false);\n` +
+ ` } });\n` +
+ ` clock.t = 0;\n` +
` const tl = gsap.timeline({ paused: true });\n` +
- ` for (const [j, n, len] of R) tl.add(inner.tweenFromTo(n / fps, (n + len) / fps, { duration: len / fps, ease: "none" }), j / fps);\n` +
+ ` tl.to(clock, { t: count / fps, duration: count / fps, ease: "none" }, 0);\n` +
` return tl;\n` +
`};</script>\n `;
return html
@@ -1091,15 +1119,32 @@ export function frameListHtml(html, region, runs, fps) {
}
/**
- * A layer re-rendered by its frames: every frame whose key a render on disk
+ * Is a layer's FIRST render captured by its distinct frames? `UMTOOL_FRAME_DEDUP=0`
+ * says no: a layer with nothing on disk is then rendered whole, frame by
+ * frame, as before (reuse from a render on disk is not affected).
+ */
+export function frameDedupOn(env = process.env) {
+ return env.UMTOOL_FRAME_DEDUP !== "0";
+}
+
+/**
+ * A layer rendered by its frames' keys: every frame whose key a render on disk
* has (this layer's last, or the ones `take --from` linked beside it,
* `work-from[-own]-<stem>-frames`) is that frame, hard-linked; the others are
- * captured in ONE render of the frame-list page (each new key once) and the
- * sequence is assembled beside, then swapped in with its `.frame-keys` and,
- * last, its `.key`. null when nothing on disk has frame keys or nearly every
- * frame is new (the whole render is the cheaper one then).
+ * captured in ONE render of the frame-list page -- each new key ONCE, however
+ * many frames draw it -- and the sequence is assembled beside, then swapped in
+ * with its `.frame-keys` and, last, its `.key`.
+ *
+ * With nothing on disk (a first render) the same: each distinct key is
+ * captured once and every frame of it is a link to that capture (`dedup`; a
+ * static strip over a whole cut is one capture, not 49,000). A layer draws a
+ * still stretch for most of a cut, so this is most of its frames.
+ *
+ * null when the distinct new keys are nearly every frame (the whole render
+ * is the cheaper one then), or, with `dedup` off, when nothing on disk has
+ * frame keys.
*/
-async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, workers, quality, assetsDir }) {
+async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, withWorkers, quality, assetsDir, dedup = true }) {
const chrome = path.join(base, "chrome");
const candidates = [target, path.join(chrome, `work-from-${stem}-frames`), path.join(chrome, `work-from-own-${stem}-frames`)];
// Every frame on disk, by key: `occ` holds each key's frames as ids
@@ -1120,14 +1165,14 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
if (!have.has(k)) have.set(k, true);
});
}
- if (!dirs.length) return null;
+ if (!dirs.length && !dedup) return null;
const missing = [];
for (let i = 0; i < fk.length; i += 1) if (!have.has(fk[i])) missing.push(i);
- if (missing.length > fk.length * 0.9) return null;
// One capture per new key.
const seen = new Set();
const capture = missing.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true)));
+ if (capture.length > fk.length * 0.9) return null;
const capDir = path.join(chrome, `work-capture-${stem}-frames`);
const capProj = path.join(chrome, `work-capture-${stem}`);
if (capture.length) {
@@ -1139,10 +1184,10 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
await writeFile(path.join(capProj, "index.html"), page, "utf8");
await writeFile(path.join(capProj, "hyperframes.json"), HF_JSON + "\n", "utf8");
await rm(capDir, { recursive: true, force: true });
- await runRenderer(hf.cmd, [
+ await withWorkers(capture.length, (w) => runRenderer(hf.cmd, [
...hf.args, "render", "--format", "png-sequence", "--quality", quality, "--fps", String(rate),
- ...(workers != null ? ["-w", String(workers)] : []), "--no-browser-gpu", "--output", capDir, capProj,
- ]);
+ ...(w != null ? ["-w", String(w)] : []), "--no-browser-gpu", "--output", capDir, capProj,
+ ]));
const got = await framesOnDisk(capDir);
if (got !== capture.length) throw new Error(`the ${region} frame capture wrote ${got} frames to ${capDir}, expected ${capture.length}`);
capture.forEach((i, j) => have.set(fk[i], path.join(capDir, frameName(j + 1))));
@@ -1184,7 +1229,10 @@ async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf
const next = path.join(chrome, `work-next-${stem}-frames`);
await rm(next, { recursive: true, force: true });
await mkdir(next, { recursive: true });
- for (let i = 0; i < fk.length; i += 1) await link(pick[i], path.join(next, frameName(i + 1)));
+ // (In batches: a whole cut is ~50,000 links, one after another a few seconds.)
+ for (let i = 0; i < fk.length; i += 512) {
+ await Promise.all(pick.slice(i, i + 512).map((src, j) => link(src, path.join(next, frameName(i + j + 1)))));
+ }
await writeFrameKeys(next, fk);
await writeFile(path.join(next, ".key"), key + "\n", "utf8");
const old = path.join(chrome, `work-old-${stem}-frames`);
diff --git a/umtool/report-to-video/frame-keys.mjs b/umtool/report-to-video/frame-keys.mjs
@@ -22,8 +22,9 @@
// times sit on the sub-frame grid (deck.mjs cueTime) and move exactly.
//
// The static part leaves out what only times the page or reaches a preview:
-// the cue list and init (keyed per frame), the window (only ever the whole
-// cut's [0, total]: a real window is refused), the cut's total and
+// the cue list and init (keyed per frame), the window (a preview's window of
+// the cut keys each frame at its cut time: the same frame keys as the whole
+// cut's there), the cut's total and
// the ids list (preview messages), and every `data-duration` (each the whole
// page's; checked). Anything else in the page's data stays in.
//
@@ -50,7 +51,8 @@
//
// Refused -- `null`, and the layer is rendered whole as before -- when the
// page is not one this models: no data script, a `data-duration` that is not
-// the page's, a window, a cue whose FROM is not what its element holds, two
+// the page's, a window not as long as its frames (or on the feed's page, or a
+// page with an offset of its own), a cue whose FROM is not what its element holds, two
// cues running on one property at once, or a property value that is neither
// a number nor a string. Conservative by construction: a frame is reused
// only when everything this knows of it is the same.
@@ -159,9 +161,17 @@ function splitPage({ html, region, assets = [], fps, frames = null, items = null
const parts = splitData(html, spec.data);
if (!parts) return null;
const { data } = parts;
- // A window is refused -- but not the whole cut written as one (a total off
- // the 4-decimal grid makes deckHtml "window" [0, r4(total)]: the identity).
- if (data.window && !(data.window.from === 0 && frames != null && Math.abs(data.window.dur - frames / fps) < 1 / fps)) return null;
+ // A window of the cut ([from, from + dur], a preview's) keys each frame at
+ // its CUT time, from + n / fps -- the page plays the cut's timeline there --
+ // so it is modelled when it is as long as its frames, on a page with no
+ // offset of its own and no events. (The whole cut written as one -- a total
+ // off the 4-decimal grid makes deckHtml "window" [0, r4(total)] -- is the identity.)
+ if (data.window) {
+ const w = data.window;
+ if (!Number.isFinite(w.from) || !Number.isFinite(w.dur) || w.from < 0) return null;
+ if (frames == null || Math.abs(w.dur - frames / fps) >= 1 / fps) return null;
+ if (w.from !== 0 && (spec.events || spec.offset)) return null;
+ }
if (spec.events ? !(Array.isArray(data.posts) && Array.isArray(data.visibility) && data.grid > 0) : !data.init || !Array.isArray(data.cues)) return null;
if (spec.offset && !Number.isFinite(data[spec.offset])) return null;
// A page's own eases are modelled only as the page writes them.
@@ -239,7 +249,7 @@ export function frameKeys({ html, region, assets = [], fps, frames, version, ite
const { data } = sp;
const init = data.init;
const cues = data.cues;
- const t0 = spec.offset ? Number(data[spec.offset]) : 0;
+ const t0 = spec.offset ? Number(data[spec.offset]) : data.window ? Number(data.window.from) : 0;
const ease = (name) => spec.eases?.[name]?.fn ?? easeOf(name);
// Slots: one per (element, property), each with its cues in time order.
diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs
@@ -112,10 +112,18 @@ test("frame keys: a changed title changes every frame (it is in the page); a cha
assert.ok(differ.at(-1) <= 20 * 30, `the counts agree again once both have landed (last at ${differ.at(-1)})`);
});
+test("frame keys: a window of the cut keys each frame as the whole cut keys it there", () => {
+ const s = schedule(0);
+ const whole = frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS }), region: "deck", fps: 30, frames: 1200, version: "v" });
+ const win = frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS, from: 5, duration: 10 }), region: "deck", fps: 30, frames: 300, version: "v" });
+ assert.equal(win.length, 300);
+ assert.deepEqual(win, whole.slice(150, 450));
+});
+
test("frame keys: refused for a page this does not model", () => {
const s = schedule(0);
- // A window.
- assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS, from: 5, duration: 10 }), region: "deck", fps: 30, frames: 300, version: "v" }), null);
+ // A window not as long as its frames.
+ assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS, from: 5, duration: 10 }), region: "deck", fps: 30, frames: 600, version: "v" }), null);
// A region it does not know.
assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS }), region: "feed", fps: 30, frames: 1200, version: "v" }), null);
// A cue whose from is not what its element holds.
@@ -191,6 +199,17 @@ test("compose-chrome: a shifted stamp layer captures only its new keys, in one r
const keys0 = readFileSync(path.join(framesDir, FRAME_KEYS_FILE), "utf8").trim().split("\n");
const oldTag = readFileSync(path.join(framesDir, "frame_000001.png"), "utf8").split(":")[0];
assert.equal(keys0.length, 1200);
+ // The first render captured each distinct key once; every frame of a key is that capture.
+ const distinct0 = new Set(keys0).size;
+ assert.ok(distinct0 < 600, `${distinct0} distinct keys in 1200 frames`);
+ assert.equal(first.captured, distinct0);
+ const { statSync } = await import("node:fs");
+ const ino0 = keys0.map((_, i) => statSync(path.join(framesDir, `frame_${String(i + 1).padStart(6, "0")}.png`)).ino);
+ keys0.forEach((k, i) => {
+ const [, cut] = readFileSync(path.join(framesDir, `frame_${String(i + 1).padStart(6, "0")}.png`), "utf8").split(":");
+ assert.equal(keys0[Number(cut)], k, `frame ${i + 1} is a capture of its key`);
+ assert.equal(ino0[keys0.indexOf(k)], ino0[i], `frame ${i + 1} is the one capture of its key`);
+ });
// Ten frames longer at the top, and the second stamp landing while the
// first is still up: only the frames with both on screen -- a state no
@@ -215,11 +234,10 @@ test("compose-chrome: a shifted stamp layer captures only its new keys, in one r
// frames, is the old end frame for frame -- not one frame of its key
// standing in for all (the renderer's workers draw a still a hair apart).
for (let i = 1150; i < 1210; i += 1) {
- const [, cut] = readFileSync(path.join(framesDir, files[i]), "utf8").split(":");
- assert.equal(Number(cut), i - 10, `frame ${i + 1} is old frame ${i - 9}`);
+ assert.equal(statSync(path.join(framesDir, files[i])).ino, ino0[i - 10], `frame ${i + 1} is old frame ${i - 9}`);
}
const log = readFileSync(path.join(out, "chrome", "renders.log"), "utf8").trim().split("\n");
- assert.deepEqual(log[0], "whole 1200");
+ assert.deepEqual(log[0], `list ${distinct0}`, "the first render: each distinct frame once");
assert.match(log[1], /^list \d+$/, "one frame-list render");
assert.equal(log.length, 2);
// Its scratch is gone; the .key is this page's: the third run is cached whole.
diff --git a/umtool/report-to-video/render-estimate.mjs b/umtool/report-to-video/render-estimate.mjs
@@ -28,11 +28,12 @@
// is the larger of the two, not their sum.
//
// render: max(ENCODE_BASE + ENCODE_PER_SEGMENT × min(segments, batch),
-// CHROME_BASE + CHROME_PER_WORKER × workers)
+// CHROME_BASE × layers + CHROME_PER_WORKER × workers)
//
// `segments` is what the run joins (a window's entries, a whole cut's; unknown:
-// a full batch); `workers` is UMTOOL_CHROME_WORKERS as build-video reads it
-// (1-16, default 4). The constants carry about 20 % over the measured line.
+// a full batch); `workers` the capture's worker budget and `layers` its
+// renders at once (chromeWorkers / chromeLayers below). The constants carry
+// about 20 % over the measured line.
//
// UMTOOL_RENDER_ESTIMATE_MB / UMTOOL_LADDER_ESTIMATE_MB override a kind's
// number; `0` declares nothing, and the job runs alone as before.
@@ -57,9 +58,66 @@ export const LADDER_ESTIMATE_MB = 1000;
/** build-video's XFADE_BATCH_DEFAULT: the segments one crossfade pass opens. */
export const XFADE_BATCH = 24;
-/** The chrome workers a render uses: build-video's CHROME_WORKERS, read the same way. */
-export function chromeWorkers(env = process.env) {
- return Math.max(1, Math.min(16, Number(env.UMTOOL_CHROME_WORKERS) || 4));
+// THE CHROME CAPTURE'S SHAPE (capture-pool.mjs). A build's chrome layers
+// capture side by side from ONE budget of renderer workers, at most
+// `chromeLayers` renders at once, each a HyperFrames process with its own
+// browser:
+//
+// chrome: CHROME_BASE × layers + CHROME_PER_WORKER × workers
+//
+// The budget, absent UMTOOL_CHROME_WORKERS, is the machine's: one and a half
+// workers per core, at most CHROME_AUTO_MAX, and no more than the chrome's
+// share of the heavy scope's cap (CHROME_MEMORY_MB) holds. Nothing else runs
+// during the capture (the segments are built before it, the encode after),
+// and a worker spends much of each frame waiting on the browser: MEASURED
+// (2026-10-29, 8 cores, Ember's deck, 10,689 distinct frames by the frame
+// list) 6 workers 210 s, 8 114 s (the machine 66 % busy), 12 98 s (86 %),
+// 16 92 s, 24 100 s; 12 workers peaked at 3.4 GB PSS. Whole renders are
+// lighter still (8 workers left it ~45 % idle). UMTOOL_CHROME_WORKERS
+// sets it outright (1-16), as it always has; UMTOOL_CHROME_LAYERS sets the
+// renders at once (1 is one layer after another, as before).
+
+/** The most workers the automatic budget takes. */
+export const CHROME_AUTO_MAX = 12;
+/** Renders at once, absent UMTOOL_CHROME_LAYERS. */
+export const CHROME_LAYERS_DEFAULT = 3;
+/** The chrome capture's share of the heavy scope's 8 GB cap (the rest: the build's node, ffprobe, slack). */
+export const CHROME_MEMORY_MB = 6144;
+
+/** This machine's cores, when it can be asked (a bundle without node:os says 4). */
+function machineCores() {
+ try {
+ const os = globalThis.process?.getBuiltinModule?.("node:os");
+ const n = os?.availableParallelism?.() ?? os?.cpus?.().length;
+ return Number.isInteger(n) && n > 0 ? n : 4;
+ } catch {
+ return 4;
+ }
+}
+
+/** The renders a build's chrome capture runs at once: UMTOOL_CHROME_LAYERS (1-8), else 3. */
+export function chromeLayers(env = process.env) {
+ const n = Number(env.UMTOOL_CHROME_LAYERS);
+ return Number.isInteger(n) && n >= 1 ? Math.min(n, 8) : CHROME_LAYERS_DEFAULT;
+}
+
+/**
+ * The chrome workers a render's capture shares (build-video's capture pool):
+ * UMTOOL_CHROME_WORKERS (1-16) when it is set; else one and a half per core,
+ * at least 2 and at most CHROME_AUTO_MAX, within CHROME_MEMORY_MB beside
+ * `chromeLayers` renders.
+ */
+export function chromeWorkers(env = process.env, cores = machineCores()) {
+ const set = Number(env.UMTOOL_CHROME_WORKERS);
+ if (set > 0) return Math.max(1, Math.min(16, Math.floor(set)));
+ const byMemory = Math.floor((CHROME_MEMORY_MB - RENDER_CHROME_BASE_MB * chromeLayers(env)) / RENDER_CHROME_PER_WORKER_MB);
+ return Math.max(2, Math.min(CHROME_AUTO_MAX, Math.ceil(1.5 * (Number(cores) || 4)), byMemory));
+}
+
+/** The chrome capture's memory (MB): its renders' bases and its workers. */
+export function chromeEstimateMb(env = process.env, cores = machineCores()) {
+ const w = chromeWorkers(env, cores);
+ return RENDER_CHROME_BASE_MB * Math.min(chromeLayers(env), w) + RENDER_CHROME_PER_WORKER_MB * w;
}
const OVERRIDE = { render: "UMTOOL_RENDER_ESTIMATE_MB", ladder: "UMTOOL_LADDER_ESTIMATE_MB" };
@@ -81,10 +139,10 @@ export function openSegments(segments, batch = XFADE_BATCH) {
*
* @param {"render" | "ladder"} [kind]
* @param {Record<string, string | undefined>} [env]
- * @param {{ segments?: number | null, batch?: number }} [shape] what the run joins, and the batch size
+ * @param {{ segments?: number | null, batch?: number, cores?: number }} [shape] what the run joins, the batch size, the machine's cores
* @returns {number | null}
*/
-export function renderEstimateMb(kind = "render", env = process.env, { segments = null, batch = XFADE_BATCH } = {}) {
+export function renderEstimateMb(kind = "render", env = process.env, { segments = null, batch = XFADE_BATCH, cores = machineCores() } = {}) {
const name = OVERRIDE[kind];
if (!name) throw new Error(`renderEstimateMb: no kind '${kind}' (render, ladder)`);
const raw = env[name];
@@ -96,8 +154,7 @@ export function renderEstimateMb(kind = "render", env = process.env, { segments
}
if (kind === "ladder") return LADDER_ESTIMATE_MB;
const encode = RENDER_ENCODE_BASE_MB + RENDER_ENCODE_PER_SEGMENT_MB * openSegments(segments, batch);
- const chrome = RENDER_CHROME_BASE_MB + RENDER_CHROME_PER_WORKER_MB * chromeWorkers(env);
- return Math.max(encode, chrome);
+ return Math.max(encode, chromeEstimateMb(env, cores));
}
/**
diff --git a/umtool/report-to-video/render-estimate.test.mjs b/umtool/report-to-video/render-estimate.test.mjs
@@ -15,6 +15,11 @@ import path from "node:path";
import test from "node:test";
import {
+ CHROME_AUTO_MAX,
+ CHROME_LAYERS_DEFAULT,
+ CHROME_MEMORY_MB,
+ chromeEstimateMb,
+ chromeLayers,
chromeWorkers,
LADDER_ESTIMATE_MB,
manifestEstimateMb,
@@ -40,14 +45,29 @@ const FLOOR = DEFAULT_MIN_FREE_MB;
const BUILD_WORDS = ["systemd-run", "--user", "--scope", "-q", "-p", "MemoryMax=5G", "-p", "MemorySwapMax=0", "--"];
const BUILD_MB = memoryCapMb(BUILD_WORDS);
const encode = (n) => RENDER_ENCODE_BASE_MB + RENDER_ENCODE_PER_SEGMENT_MB * n;
-const chrome = (w) => RENDER_CHROME_BASE_MB + RENDER_CHROME_PER_WORKER_MB * w;
+const chrome = (w, layers = 1) => RENDER_CHROME_BASE_MB * layers + RENDER_CHROME_PER_WORKER_MB * w;
+// This machine's chrome capture, as a render on it declares it.
+const CHROME = chromeEstimateMb({});
test("the estimate: the larger of the widest crossfade pass and the chrome capture", () => {
assert.equal(XFADE_BATCH, XFADE_BATCH_DEFAULT, "build-video's batch size, mirrored");
- assert.equal(chromeWorkers({}), 4, "build-video's default");
- assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "7" }), 7);
+ // The budget: one and a half per core, at least 2, at most CHROME_AUTO_MAX, within the chrome's memory.
+ assert.equal(chromeWorkers({}, 8), 12, "an 8-core machine: 12");
+ assert.equal(chromeWorkers({}, 4), 6);
+ assert.equal(chromeWorkers({}, 1), 2, "never fewer than 2");
+ assert.equal(chromeWorkers({}, 64), CHROME_AUTO_MAX, "a big machine: the cap");
+ assert.ok(chrome(CHROME_AUTO_MAX, CHROME_LAYERS_DEFAULT) <= CHROME_MEMORY_MB, "the cap fits the chrome's memory");
+ assert.equal(chromeWorkers({ UMTOOL_CHROME_LAYERS: "8" }, 64), Math.floor((CHROME_MEMORY_MB - 8 * RENDER_CHROME_BASE_MB) / RENDER_CHROME_PER_WORKER_MB), "more renders at once: fewer workers fit");
+ assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "7" }, 8), 7, "the override wins");
assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "99" }), 16, "clamped as build-video clamps it");
- assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "junk" }), 4);
+ assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "junk" }, 6), 9, "junk: the machine's");
+ assert.equal(chromeLayers({}), CHROME_LAYERS_DEFAULT);
+ assert.equal(chromeLayers({ UMTOOL_CHROME_LAYERS: "1" }), 1);
+ assert.equal(chromeLayers({ UMTOOL_CHROME_LAYERS: "0" }), CHROME_LAYERS_DEFAULT);
+ // The capture's memory: its renders' bases (never more renders than workers) and its workers.
+ assert.equal(chromeEstimateMb({}, 8), chrome(12, 3));
+ assert.equal(chromeEstimateMb({ UMTOOL_CHROME_WORKERS: "2" }, 8), chrome(2, 2));
+ assert.equal(chromeEstimateMb({ UMTOOL_CHROME_LAYERS: "1" }, 8), chrome(12, 1));
// Segments: a pass opens at most a batch; unknown is a full batch; batch 0 never batches.
assert.equal(openSegments(68), 24);
assert.equal(openSegments(5), 5);
@@ -55,11 +75,11 @@ test("the estimate: the larger of the widest crossfade pass and the chrome captu
assert.equal(openSegments(68, 0), 68);
assert.equal(openSegments(68, 12), 12);
assert.equal(RENDER, encode(24), "unknown segments: a full batch");
- assert.equal(renderEstimateMb("render", {}, { segments: 4 }), Math.max(encode(4), chrome(4)));
- assert.equal(renderEstimateMb("render", {}, { segments: 1 }), Math.max(encode(1), chrome(4)));
+ assert.equal(renderEstimateMb("render", {}, { segments: 4, cores: 8 }), Math.max(encode(4), chrome(12, 3)));
+ assert.equal(renderEstimateMb("render", {}, { segments: 1, cores: 8 }), Math.max(encode(1), chrome(12, 3)));
// Chrome workers dominate a short run once there are enough of them.
- assert.equal(renderEstimateMb("render", { UMTOOL_CHROME_WORKERS: "16" }, { segments: 1 }), chrome(16));
- assert.ok(chrome(16) > encode(1));
+ assert.equal(renderEstimateMb("render", { UMTOOL_CHROME_WORKERS: "16" }, { segments: 1 }), chrome(16, 3));
+ assert.ok(chrome(16, 3) > encode(1));
assert.equal(renderEstimateMb("ladder", {}), LADDER_ESTIMATE_MB);
assert.ok(LADDER_ESTIMATE_MB < RENDER, "the ladder's one ffmpeg is smaller than a render");
// The measured peaks sit under what is declared (render-estimate.mjs's table).
@@ -68,7 +88,7 @@ test("the estimate: the larger of the widest crossfade pass and the chrome captu
assert.ok(chrome(7) >= 2218 * 1.1, "the full deck's 7-worker capture peaked at 2218 MB");
assert.ok(LADDER_ESTIMATE_MB >= 760 * 1.25, "the ladder peaked at 760 MB");
// Every default stays under the default cap: the estimate admits, the cap limits.
- assert.ok(RENDER <= 8192 && chrome(16) <= 8192 && LADDER_ESTIMATE_MB <= 8192);
+ assert.ok(RENDER <= 8192 && chrome(16, 3) <= 8192 && LADDER_ESTIMATE_MB <= 8192);
});
test("a manifest's estimate: its segments (and the intro's), one when nothing crossfades or the run is one clip", () => {
@@ -76,12 +96,12 @@ test("a manifest's estimate: its segments (and the intro's), one when nothing cr
assert.equal(manifestSegments(m), 4);
assert.equal(manifestSegments({ ...m, render: { intro: { style: "boot" } } }), 5);
assert.equal(manifestSegments({}), null);
- assert.equal(manifestEstimateMb(m, {}), Math.max(encode(4), chrome(4)));
+ assert.equal(manifestEstimateMb(m, {}), Math.max(encode(4), CHROME));
assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}), encode(24), "a long cut: one full batch");
assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { batch: 0 }), encode(67), "never batched: every segment");
- assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { xfade: false }), Math.max(encode(1), chrome(4)));
- assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}), render: { transition: 0 } }, {}), Math.max(encode(1), chrome(4)));
- assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { single: true }), Math.max(encode(1), chrome(4)));
+ assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { xfade: false }), Math.max(encode(1), CHROME));
+ assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}), render: { transition: 0 } }, {}), Math.max(encode(1), CHROME));
+ assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { single: true }), Math.max(encode(1), CHROME));
assert.equal(manifestEstimateMb(null, {}), RENDER, "unreadable: a full batch");
assert.equal(manifestEstimateMb(m, { UMTOOL_RENDER_ESTIMATE_MB: "0" }), null);
});
@@ -91,13 +111,13 @@ test("build-video's CLI and a take read the estimate off the manifest they rende
try {
const file = path.join(dir, "video.manifest.json");
fs.writeFileSync(file, JSON.stringify({ timeline: Array(30).fill({ type: "clip" }), render: { xfadeBatch: 10 } }));
- assert.equal(await cliEstimateMb(file, {}, {}), encode(10), "render.xfadeBatch sizes the pass");
- assert.equal(await cliEstimateMb(file, {}, { REPORT_VIDEO_XFADE_BATCH: "16" }), encode(16), "the env's batch wins, as in build-video");
- assert.equal(await cliEstimateMb(file, { clipPreview: "c1" }, {}), Math.max(encode(1), chrome(4)));
- assert.equal(await cliEstimateMb(file, { noXfade: true }, {}), Math.max(encode(1), chrome(4)));
+ assert.equal(await cliEstimateMb(file, {}, {}), Math.max(encode(10), CHROME), "render.xfadeBatch sizes the pass");
+ assert.equal(await cliEstimateMb(file, {}, { REPORT_VIDEO_XFADE_BATCH: "16" }), Math.max(encode(16), CHROME), "the env's batch wins, as in build-video");
+ assert.equal(await cliEstimateMb(file, { clipPreview: "c1" }, {}), Math.max(encode(1), CHROME));
+ assert.equal(await cliEstimateMb(file, { noXfade: true }, {}), Math.max(encode(1), CHROME));
assert.equal(await cliEstimateMb(path.join(dir, "absent.json"), {}, {}), RENDER);
- assert.equal(await takeEstimateMb({ manifestPath: file, xfade: true }, {}), encode(10));
- assert.equal(await takeEstimateMb({ manifestPath: file, xfade: false }, {}), Math.max(encode(1), chrome(4)));
+ assert.equal(await takeEstimateMb({ manifestPath: file, xfade: true }, {}), Math.max(encode(10), CHROME));
+ assert.equal(await takeEstimateMb({ manifestPath: file, xfade: false }, {}), Math.max(encode(1), CHROME));
assert.equal(await takeEstimateMb({ manifestPath: path.join(dir, "absent.json"), xfade: true }, {}), RENDER);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
diff --git a/umtool/report-to-video/stats.test.mjs b/umtool/report-to-video/stats.test.mjs
@@ -233,7 +233,7 @@ for (let i = 1; i <= Math.round(dur * fps); i += 1) copyFileSync(one, out + "/fr
}
const schedule = JSON.parse(readFileSync(path.join(v, "schedule.json"), "utf8"));
assert.deepEqual(schedule.stats.clips.map((c) => c.segment), ["c1", "c2"]);
- assert.match(readFileSync(path.join(root, "renders.log"), "utf8"), /chrome\/stats\n/);
+ assert.match(readFileSync(path.join(root, "renders.log"), "utf8"), /chrome\/(work-capture-)?stats\n/);
assert.match(readFileSync(path.join(v, "chrome", "stats", "index.html"), "utf8"), /<div class="val">80,000<\/div>/);
const ok = await verifyBuild(manifestPath, {});