Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 053d9be096e94e9950f7a934c71c452b4dc87f8f
parent 31d3e5499638781f95f996e71aac813b51f8acfb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 28 Oct 2026 22:58:59 -0400

umtool: the video-modules contract -- a registry the overlay pass, the composer and the chain loop over

Every chrome region is now a MODULE (report-to-video/modules/<id>.mjs,
defineModule): its kind, slot, z, region name, page, regions, window, names,
frame-key model and the sentence that refuses a schedule it cannot draw.
modules/index.mjs registers them; modules/layout.mjs is the slot engine
(footer, footage, column, popup, stamp, panel, side, full) over deck.mjs's
geometry; modules/design.mjs holds the design-unit constants.

- composeChrome dispatches a region's page through its module (helpers for
  faces, QRs, shots handed in) and takes keyed/whole-cut/window/project
  names from it.
- renderDeck is one loop over the registry's overlays in z order (deck,
  feed, posts, stamp, stats, fx, threads, flips, finale), same events,
  same errors, same regions.
- chromeOverlayChain and the chunked encode lay a region by its module's
  placement; the region helpers (postsRegions, finaleRegions, ...) are the
  modules' regions, asserted by assertRegion.
- frame-keys' FRAME_KEY_REGIONS is the modules' frameKeys.

No behaviour change: the pages, regions and chains are the bytes they were.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mpackage.json | 2+-
Mumtool/report-to-video/build-video.mjs | 356++++++++++++++++++++-----------------------------------------------------------
Mumtool/report-to-video/compose-chrome.mjs | 229+++++++++++++++----------------------------------------------------------------
Mumtool/report-to-video/frame-keys.mjs | 24++++++++++--------------
Aumtool/report-to-video/modules/chart.mjs | 36++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/contract.mjs | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/design.mjs | 25+++++++++++++++++++++++++
Aumtool/report-to-video/modules/feed.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/finale.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/flips.mjs | 32++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/fx.mjs | 42++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/index.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/layout.mjs | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/popup-posts.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/registry.test.mjs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/shell.mjs | 42++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/stamp.mjs | 42++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/stats.mjs | 37+++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/teaser.mjs | 37+++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/modules/threads.mjs | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 2++
21 files changed, 1126 insertions(+), 469 deletions(-)

diff --git a/package.json b/package.json @@ -24,7 +24,7 @@ "wt": "node scripts/worktree.mjs", "e2e:sharded": "node scripts/run-sharded-e2e.mjs", "e2e:all": "node scripts/e2e-all.mjs", - "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs", + "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs", "test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]", "typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit", "lint": "pnpm --filter export run lint", diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -165,6 +165,7 @@ import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; import { validateStatsEntries } from "./stats.mjs"; +import { deckOverlays, moduleById, placementOf } from "./modules/index.mjs"; // The upload's text (release 28 M6): composed by code, written beside the cut. import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs"; import { socialTexts } from "./social.mjs"; @@ -3304,9 +3305,11 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts // The effects region (`name: "fx"`) likewise. // The finale (`name: "finale"`, chrome-finale.mjs) is a window like a // posts window's -- the whole frame, laid last. - const deck = r.name === "deck" || r.name === "feed" || r.name === "stamp" || r.name === "threads" || r.name === "flips" || - r.name === "stats" || r.name === "fx"; - const posts = r.name === "posts" || r.name === "finale"; + // How each region is laid is its module's (modules/index.mjs placementOf): + // a whole-cut sequence laid as the deck's is, or a window at its second. + const placement = placementOf(r.name); + const deck = placement === "whole"; + const posts = placement === "window"; inputs.push( ...(deck || posts ? ["-reinit_filter", "0"] : []), ...(posts ? ["-itsoffset", offsetArg(r.offset)] : []), @@ -3343,80 +3346,52 @@ const offsetArg = (v) => { }; /** - * The posts windows as overlay regions: one per clip that carries posts - * (`postWindows`), snapped to the frame grid (`snapWindow`), at - * `postsGeometry`. `offset` is the second the window's frame 1 lands on in the - * BASE's clock -- the cut's, or a preview's that starts `shift` seconds in. - * `clip` (`{at, dur}`) keeps only the windows that intersect it. No posts, no + * The posts windows as overlay regions (modules/popup-posts.mjs): one per + * clip that carries posts, snapped to the frame grid, at `postsGeometry`. + * `offset` is the second the window's frame 1 lands on in the BASE's clock + * -- the cut's, or a preview's that starts `shift` seconds in. `clip` + * (`{at, dur}`) keeps only the windows that intersect it. No posts, no * regions: the deck's overlay is then exactly what it was. */ export function postsRegions(render, outDir, schedule, { shift = 0, clip = null } = {}) { - const fps = Number(schedule.fps ?? render.fps); - const g = postsGeometry(render); - return postWindows(schedule) - .map((w) => ({ w, s: snapWindow(w, { fps, total: schedule.total }) })) - .filter(({ s }) => !clip || (s.from < clip.at + clip.dur && s.to > clip.at)) - .map(({ w, s }) => ({ - name: "posts", - segment: s.segment, - window: w, - frames: path.join(outDir, "chrome", `posts-${s.segment}-frames`), - x: g.x, y: g.y, width: g.width, height: g.height, - offset: s.from - shift, - frameCount: s.frames, - })); + return moduleById("popup-posts").regions(schedule, { render, outDir, shift, clip }); } /** - * The finale's page (a schedule with `finale`, chrome-finale.mjs) as an - * overlay region: the whole frame, its window snapped to the frame grid - * (`snapWindow`) and laid at its own second like a posts window -- `offset` - * in the BASE's clock (the cut's, or a preview's that starts `shift` in). - * `clip` (`{at, dur}`) keeps it only when it intersects. No finale: none. + * The finale's page as an overlay region (modules/finale.mjs): the whole + * frame, its window snapped to the frame grid and laid at its own second like + * a posts window. No finale: none. * * @returns {Array<{ name: "finale", frames: string, x: number, y: number, width: number, height: number, * offset: number, frameCount: number, window: object }>} */ export function finaleRegions(render, outDir, schedule, { shift = 0, clip = null } = {}) { - const f = schedule?.finale; - if (!f) return []; - const fps = Number(schedule.fps ?? render.fps); - const s = snapWindow({ segment: "finale", from: f.from, to: f.to }, { fps, total: schedule.total }); - if (clip && !(s.from < clip.at + clip.dur && s.to > clip.at)) return []; - return [{ - name: "finale", - frames: path.join(outDir, "chrome", "finale-frames"), - x: 0, y: 0, width: render.width ?? 1920, height: render.height ?? 1080, - offset: s.from - shift, - frameCount: s.frames, - window: s, - }]; + return moduleById("finale").regions(schedule, { render, outDir, shift, clip }); } /** The posts feed as an overlay region: its frames at feedGeometry's column. */ export function feedRegion(render, frames) { - return { name: "feed", frames, ...feedGeometry(render).column }; + return moduleById("feed").regions(null, { render, frames })[0]; } /** The thread rail as an overlay region: its frames at threadsGeometry's box. */ export function threadsRegion(render, frames, name = "threads") { - const { cards: _c, ...box } = threadsGeometry(render); - return { name, frames, ...box }; + return moduleById(name === "flips" ? "flips" : "threads").regions(null, { render, frames })[0]; } /** The fact-check stamps as an overlay region: their frames at stampGeometry's box. */ export function stampRegion(render, frames, schedule) { - return { name: "stamp", frames, ...stampGeometry(render, { feed: schedule.layout === "feed" }) }; + return moduleById("stamp").regions(schedule, { render, frames })[0]; } /** The stats region as an overlay region: its frames at statsGeometry's panel. */ export function statsRegion(render, frames, schedule) { - return { name: "stats", frames, ...statsGeometry(render, { feed: schedule.layout === "feed" }) }; + return moduleById("stats").regions(schedule, { render, frames })[0]; } /** The effects region as an overlay region: its frames over the footage box (fxGeometry). */ export function fxRegion(render, frames, schedule) { - return { name: "fx", frames, ...fxGeometry(render, { feed: schedule.layout === "feed" }) }; + return moduleById("fx").regions(schedule, { render, frames })[0]; } /** @@ -3432,21 +3407,7 @@ export function fxRegion(render, frames, schedule) { * band's branch rather than joining it: the deck refuses `chromeEngine`. */ export function chromeRegions(render, outDir) { - if (deckOn(render)) { - const { deck } = deckGeometry(render); - return [{ name: "deck", frames: path.join(outDir, "chrome", "deck-frames"), ...deck }]; - } - const H = render.chart?.height ?? 200; - return [ - { - name: "chart", - frames: path.join(outDir, "chrome", "chart-frames"), - x: 0, - y: render.height - H, - width: contentWidth(render), - height: H, - }, - ]; + return moduleById(deckOn(render) ? "shell" : "chart").regions(null, { render, outDir }); } /** @@ -4575,7 +4536,7 @@ const cutAudioEncodeArgs = (render) => [ ]; /** Overlay regions laid like a posts window: a short sequence at its own second. */ -const WINDOW_REGIONS = new Set(["posts", "finale"]); +const WINDOW_REGIONS = { has: (name) => placementOf(name) === "window" }; /** * One chunk's ffmpeg argv (picture only), and the same argv in KEY form with @@ -5073,218 +5034,75 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (fields.phase !== "compose") layers.push({ region: fields.region ?? "deck", segment: fields.segment, phase: fields.phase, frames: fields.frames, reused: fields.reused, captured: fields.captured, seconds: fields.seconds }); }; - EMIT("chrome", { phase: "compose", ...(duration != null ? { from, duration } : {}) }); - const t0 = Date.now(); - const r = await composeChrome({ - manifestPath, outDir, variant, region: "deck", doRender: true, - fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); const want = frameCount(duration ?? schedule.total, render.fps); - if (r.frameCount !== want) { - throw new Error( - `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)`, - ); - } - emitChrome({ - phase: r.cached ? "cached" : r.reused > 0 ? "reuse" : "render", - ...(r.reused != null ? { reused: r.reused, captured: r.captured } : {}), - frames: r.frameCount, key: r.key, dir: r.frames, - seconds: Number(((Date.now() - t0) / 1000).toFixed(1)), - }); - const regions = chromeRegions(render, outDir).map((g) => ({ ...g, frames: r.frames })); - - // The posts FEED (a schedule with `layout: "feed"`): one sequence for the - // whole cut -- or the same window as the deck's -- at feedGeometry's column, - // laid like the deck's. postWindows has none for a feed, so the loop below - // adds nothing. - if (schedule.layout === "feed") { - EMIT("chrome", { phase: "compose", region: "feed", ...(duration != null ? { from, duration } : {}) }); - const t1 = Date.now(); - const f = await composeChrome({ - manifestPath, outDir, variant, region: "feed", doRender: true, - fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); - if (f.frameCount !== want) { - throw new Error(`the feed's sequence is ${f.frameCount} frames but the deck's is ${want}`); - } - emitChrome({ - phase: f.cached ? "cached" : f.reused > 0 ? "reuse" : "render", region: "feed", - ...(f.reused != null ? { reused: f.reused, captured: f.captured } : {}), - frames: f.frameCount, key: f.key, dir: f.frames, - seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), - }); - regions.push(feedRegion(render, f.frames)); - } - - // Then the posts: one short sequence per clip that carries them, each with - // its own cache, laid over the deck at its own second. A preview window - // (`duration` given) takes only the windows it intersects, shifted into its - // own clock; their frames are the build's, so a preview renders nothing a - // build would not. + const win = duration != null ? { from, duration } : {}; + // A preview window (`duration` given) takes only the windows it + // intersects, shifted into its own clock; their frames are the build's, so + // a preview renders nothing a build would not. const clip = duration != null ? { at: from, dur: duration } : null; - for (const pr of postsRegions(render, outDir, schedule, { shift: clip ? clip.at : 0, clip })) { - EMIT("chrome", { phase: "compose", region: "posts", segment: pr.segment }); - const t1 = Date.now(); - const p = await composeChrome({ - manifestPath, outDir, variant, region: "posts", window: pr.window, doRender: true, - fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence", - }); - if (p.frames !== pr.frames || p.frameCount !== pr.frameCount) { - throw new Error( - `the posts window for ${pr.segment} 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: "posts", 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; - regions.push(region); - } - - // The fact-check stamps (a schedule whose `factcheck` stamps a claim): one - // sequence for the whole cut -- or the deck's window -- laid last, over the - // posts, at stampGeometry's box in the footage. With `stamp.show: false` - // none is composed or laid; the deck's tally still counts each claim. - if (stampsDrawn(schedule, render)) { - EMIT("chrome", { phase: "compose", region: "stamp", ...(duration != null ? { from, duration } : {}) }); - const t1 = Date.now(); - const st = await composeChrome({ - manifestPath, outDir, variant, region: "stamp", doRender: true, - fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); - if (st.frameCount !== want) { - throw new Error(`the stamps' sequence is ${st.frameCount} frames but the deck's is ${want}`); - } - emitChrome({ - phase: st.cached ? "cached" : st.reused > 0 ? "reuse" : "render", region: "stamp", - ...(st.reused != null ? { reused: st.reused, captured: st.captured } : {}), - frames: st.frameCount, key: st.key, dir: st.frames, - seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), - }); - regions.push(stampRegion(render, st.frames, schedule)); - } - - // The stats region (a schedule whose `stats` draws a clip, stats.mjs): one - // sequence for the whole cut -- or the deck's window -- in a corner of the - // footage, laid like the stamps'. - if (schedule.stats?.clips?.length) { - EMIT("chrome", { phase: "compose", region: "stats", ...(duration != null ? { from, duration } : {}) }); - const t1 = Date.now(); - const sr = await composeChrome({ - manifestPath, outDir, variant, region: "stats", doRender: true, - fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); - if (sr.frameCount !== want) { - throw new Error(`the stats region's sequence is ${sr.frameCount} frames but the deck's is ${want}`); - } - emitChrome({ - phase: sr.cached ? "cached" : sr.reused > 0 ? "reuse" : "render", region: "stats", - ...(sr.reused != null ? { reused: sr.reused, captured: sr.captured } : {}), - frames: sr.frameCount, key: sr.key, dir: sr.frames, - seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), - }); - regions.push(statsRegion(render, sr.frames, schedule)); - } - - // The effects (a schedule with `fx`, fx.mjs): one sequence for the whole cut - // -- or the deck's window -- exactly over the footage box, laid over the - // stats. - if (schedule.fx) { - EMIT("chrome", { phase: "compose", region: "fx", ...(duration != null ? { from, duration } : {}) }); - const t1 = Date.now(); - const fr = await composeChrome({ - manifestPath, outDir, variant, region: "fx", doRender: true, - fps: render.fps, workers: CHROME_WORKERS, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); - if (fr.frameCount !== want) { - throw new Error(`the effects' sequence is ${fr.frameCount} frames but the deck's is ${want}`); - } - emitChrome({ - phase: fr.cached ? "cached" : fr.reused > 0 ? "reuse" : "render", region: "fx", - ...(fr.reused != null ? { reused: fr.reused, captured: fr.captured } : {}), - frames: fr.frameCount, key: fr.key, dir: fr.frames, - seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), - }); - regions.push(fxRegion(render, fr.frames, schedule)); - } - - // The thread rail (a schedule with `threads`): one sequence for the whole - // cut -- or the deck's window -- beside the footage, laid like the deck's. - if (schedule.threads?.threads?.length) { - EMIT("chrome", { phase: "compose", region: "threads", ...(duration != null ? { from, duration } : {}) }); - const t1 = Date.now(); - const th = await composeChrome({ - manifestPath, outDir, variant, region: "threads", doRender: true, - fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); - if (th.frameCount !== want) { - throw new Error(`the thread rail's sequence is ${th.frameCount} frames but the deck's is ${want}`); - } - emitChrome({ - phase: th.cached ? "cached" : th.reused > 0 ? "reuse" : "render", region: "threads", - ...(th.reused != null ? { reused: th.reused, captured: th.captured } : {}), - frames: th.frameCount, key: th.key, dir: th.frames, - seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), - }); - regions.push(threadsRegion(render, th.frames)); - } - - // The flips panel (a schedule with `flips`): the same region as the rail. - if (schedule.flips?.pairs?.length) { - EMIT("chrome", { phase: "compose", region: "flips", ...(duration != null ? { from, duration } : {}) }); - const t1 = Date.now(); - const fl = await composeChrome({ - manifestPath, outDir, variant, region: "flips", doRender: true, - fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence", - ...(duration != null ? { from, duration } : {}), - }); - if (fl.frameCount !== want) { - throw new Error(`the flips panel's sequence is ${fl.frameCount} frames but the deck's is ${want}`); + const regions = []; + // Every overlay module the schedule draws, in z order (modules/index.mjs): + // the deck's shell first, then the feed, each posts window, the stamps, the + // stats, the effects, the side panel, and the finale LAST -- its ground + // 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. + 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)), + }); + regions.push(...mod.regions(schedule, { render, outDir, frames: r.frames })); + continue; } - emitChrome({ - phase: fl.cached ? "cached" : fl.reused > 0 ? "reuse" : "render", region: "flips", - ...(fl.reused != null ? { reused: fl.reused, captured: fl.captured } : {}), - frames: fl.frameCount, key: fl.key, dir: fl.frames, - seconds: Number(((Date.now() - t1) / 1000).toFixed(1)), - }); - regions.push(threadsRegion(render, fl.frames, "flips")); - } - - // The finale (a schedule with `finale`, chrome-finale.mjs): one full-frame - // window over the run's seconds, laid LAST -- its ground covers every - // region under it while it is up. A preview window takes it only when it - // intersects; its frames are the build's, as the posts windows' are. - for (const fr of finaleRegions(render, outDir, schedule, { shift: clip ? clip.at : 0, clip })) { - EMIT("chrome", { phase: "compose", region: "finale" }); - const t1 = Date.now(); - const p = await composeChrome({ - manifestPath, outDir, variant, region: "finale", doRender: true, - fps: render.fps, workers: CHROME_WORKERS_SMALL, quality: "high", format: "png-sequence", - }); - if (p.frames !== fr.frames || p.frameCount !== fr.frameCount) { - throw new Error(`the finale rendered ${p.frameCount} frames to ${p.frames}; the overlay expects ${fr.frameCount} at ${fr.frames}`); + 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)), + }); + const { window: _w, ...region } = pr; + regions.push(region); } - emitChrome({ - phase: p.cached ? "cached" : p.reused > 0 ? "reuse" : "render", region: "finale", - ...(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 } = fr; - regions.push(region); } - if (duration == null && layers.length) await logRebuild(outDir, { phase: "chrome", layers }); + if (duration == null && layers.length) await logRebuild(outDir, { phase: "chrome", layers }); return { regions, outLabel: "[hfout]" }; } diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -36,24 +36,14 @@ import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; import path from "node:path"; -import { ledgerTotals, dateKey } from "./ledger-totals.mjs"; +import { dateKey } from "./ledger-totals.mjs"; import { selectVariant } from "./build-video.mjs"; import { ensureWriteDir } from "../lib/report/storage.mjs"; -import { - chromeCacheKey, deckLayout, frameCount, pageDuration, hyperframesCommand, postWindows, resolveDeck, sha256, teaserSeconds, transitionOf, - validateTeaser, -} from "./deck.mjs"; -import { deckHtml, GSAP_FILE } from "./chrome-deck.mjs"; -import { postsHtml, snapWindow, windowPosts } from "./chrome-posts.mjs"; -import { feedHtml } from "./chrome-feed.mjs"; -import { stampHtml } from "./chrome-stamp.mjs"; -import { stampsDrawn } from "./factcheck.mjs"; -import { threadsHtml } from "./chrome-threads.mjs"; -import { flipsHtml } from "./chrome-flips.mjs"; -import { statsHtml } from "./chrome-stats.mjs"; -import { finaleHtml, finaleLayout } from "./chrome-finale.mjs"; +import { chromeCacheKey, frameCount, pageDuration, hyperframesCommand, sha256, transitionOf } from "./deck.mjs"; +import { GSAP_FILE } from "./chrome-deck.mjs"; import { fxGeometry } from "./deck.mjs"; import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; +import { regionCaching, regionModule } from "./modules/index.mjs"; const run = promisify(execFile); @@ -723,114 +713,26 @@ export async function fxThumbs(schedule, base, render, assetsDir) { /** * Which HTML each chrome region is, with the assets it needs written into - * `projDir/assets`. The chart's branch is the band as it shipped; only where - * its GSAP comes from has changed. + * `projDir/assets`: the region's MODULE writes it (modules/<id>.mjs `page`), + * handed what it may touch -- the faces, the QR maker, the shots -- as + * helpers, so a module never reaches into the file system itself. */ async function regionHtml(region, { manifest, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, teaser, transition }) { - if (region === "fx") { - // The effects (chrome-fx.mjs): the deck's faces, a mono, the screenshots - // the receipts and the zoom show, and the scrubber's thumbnails. - // A page module reached by a dynamic import, as the teaser's: it carries - // its mono as an asset URL (docs/quirks.md). - const { fxHtml, FX_MONO_FILE } = await import("./chrome-fx.mjs"); - const render = manifest.render; - const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - await copyFile(FX_MONO_FILE, path.join(assetsDir, "FxMono.ttf")); - fonts.mono = "assets/FxMono.ttf"; - const shots = await copyFxShots(schedule.fx, manifestDir, assetsDir); - const thumbs = schedule.fx.scrubber?.thumbs ? await fxThumbs(schedule, base, render, assetsDir) : {}; - return fxHtml(schedule, render, { fonts, assets: { shots, thumbs }, from, duration }); - } - if (region === "chart") { - const sched = schedule ?? JSON.parse(await readFile(path.join(base, "schedule.json"), "utf8")); - const fonts = await copyFonts(manifest.render, assetsDir, { regular: "regular", bold: "bold" }, { strict: false }); - const totals = ledgerTotals(manifest.ledger); - return chartBandHtml(manifest, totals, sched, { fonts, ...(duration ? { duration } : {}) }); - } - if (region === "deck") { - const render = manifest.render; - const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - // With the schedule: a staggered marker band moves the QR down and may shrink it. - const lay = deckLayout(render, { schedule }); - const qrSrcs = {}; - if (lay.qr) { - const byUrl = await qrPngsFor(schedule.segments.map((s) => s.qrUrl), render, lay.qr.size, assetsDir); - for (const s of schedule.segments) if (s.qrUrl) qrSrcs[s.id] = byUrl.get(s.qrUrl); - } - return deckHtml(schedule, render, { fonts, qrSrcs, from, duration }); - } - if (region === "posts") { - // The deck's faces and the deck's QR maker: a card is part of the deck's - // family, not a second design. - const render = manifest.render; - const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - const posts = windowPosts(schedule, window.segment); - // `posts.qr: false`: no codes are made, and the page draws none. - const byUrl = resolveDeck(render).posts.qr === false - ? new Map() - : await qrPngsFor(posts.map((p) => p.qrUrl), render, resolveDeck(render).posts.qrSize, assetsDir); - const qrSrcs = {}; - for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl); - const shotSrcs = await copyShots(posts, manifestDir, assetsDir); - const logoSrcs = await copyShots(posts, manifestDir, assetsDir, "logo"); - return postsHtml(schedule, render, window, { fonts, qrSrcs, shotSrcs, logoSrcs }); - } - if (region === "feed") { - // The posts feed: the deck's faces and QR maker, one page for the whole cut. - const render = manifest.render; - const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - const posts = schedule.posts ?? []; - // `posts.qr: false`: no codes are made, and the page draws none. - const byUrl = resolveDeck(render).posts.qr === false - ? new Map() - : await qrPngsFor(posts.map((p) => p.qrUrl), render, resolveDeck(render).posts.qrSize, assetsDir); - const qrSrcs = {}; - for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl); - const shotSrcs = await copyShots(posts, manifestDir, assetsDir); - return feedHtml(schedule, render, { fonts, qrSrcs, shotSrcs, from, duration }); - } - if (region === "stamp") { - // The fact-check stamps (chrome-stamp.mjs): the deck's faces, no QR. - const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - return stampHtml(schedule, manifest.render, { fonts, from, duration }); - } - if (region === "threads") { - // The thread rail (chrome-threads.mjs): the deck's faces, no QR. - const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - return threadsHtml(schedule, manifest.render, { fonts, from, duration }); - } - if (region === "flips") { - // The flips panel (chrome-flips.mjs): the deck's faces, no QR. - const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - return flipsHtml(schedule, manifest.render, { fonts, from, duration }); - } - if (region === "stats") { - // The stats region (chrome-stats.mjs): the deck's faces, no QR. - const fonts = await copyFonts(manifest.render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - return statsHtml(schedule, manifest.render, { fonts, from, duration }); - } - if (region === "finale") { - // The finale (chrome-finale.mjs): the deck's faces and QR maker, one page - // for its window. - const render = manifest.render; - const fonts = await copyFonts(render, assetsDir, { regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); - const L = finaleLayout(schedule, render); - const qrSrcs = {}; - if (resolveDeck(render).qr.show) { - const byUrl = await qrPngsFor(L.captions.map((c) => c.qrUrl), render, L.geo.qr.size, assetsDir); - for (const c of L.captions) if (c.qrUrl) qrSrcs[c.id] = byUrl.get(c.qrUrl); - } - return finaleHtml(schedule, render, window, { fonts, qrSrcs }); - } - if (region === "teaser") { - // A page module reached by a dynamic import, so nothing that imports this - // file -- umtool's preview helper, the build -- loads its face's URL - // unless a teaser is being composed (docs/quirks.md). - const { teaserHtml, TEASER_FONT_FILE, TEASER_FONT_ASSET } = await import("./chrome-teaser.mjs"); - await copyFile(TEASER_FONT_FILE, path.join(projDir, TEASER_FONT_ASSET)); - return teaserHtml(teaser, manifest.render, { font: TEASER_FONT_ASSET, transition }); - } - throw new Error(`unknown chrome region: ${region}`); + const mod = regionModule(region); + const render = manifest.render; + return mod.page({ + manifest, render, manifestDir, base, projDir, assetsDir, schedule, duration, from, window, entry: teaser, transition, + fonts: (names, opts) => copyFonts(render, assetsDir, names, opts), + qrs: (urls, size) => qrPngsFor(urls, render, size, assetsDir), + shots: (posts, key = "shot") => copyShots(posts, manifestDir, assetsDir, key), + fxShots: (fx) => copyFxShots(fx, manifestDir, assetsDir), + fxThumbs: (sched) => fxThumbs(sched, base, render, assetsDir), + asset: async (src, name) => { + await copyFile(src, path.join(assetsDir, name)); + return `assets/${name}`; + }, + projectFile: (src, rel) => copyFile(src, path.join(projDir, rel)), + }); } /** The root's declared size and length, read back off the HTML rather than re-derived. */ @@ -957,22 +859,18 @@ export async function composeChrome({ await ensureWriteDir(base); from = Number(from ?? 0); - // The regions keyed by the render cache: the two drawn from the deck's - // schedule, and a teaser, drawn from its own timeline entry. - const keyed = region === "deck" || region === "feed" || region === "posts" || region === "teaser" || region === "stamp" || - region === "threads" || region === "flips" || region === "stats" || region === "fx" || region === "finale"; - // The regions drawn over the whole cut from its schedule, windowable alike. - const wholeCut = region === "deck" || region === "feed" || region === "stamp" || region === "threads" || region === "flips" || - region === "stats" || region === "fx"; + // The region's module (modules/index.mjs) says how it is cached and laid: + // keyed by the render cache (every page but the legacy chart band), and + // drawn over the whole cut from its schedule, windowable (`overlay-whole`). + const mod = regionModule(region); + const { keyed, wholeCut } = regionCaching(region); let teaser = null; - if (region === "teaser") { - teaser = (manifest.timeline ?? []).find((e) => e.id === segment && e.type === "teaser") ?? null; - if (!teaser) throw new Error(`no teaser entry ${segment ?? "(none named)"} in the ${variant} cut`); - const errors = validateTeaser(teaser); - if (errors.length) throw new Error(`teaser ${teaser.id}: ${errors.join("; ")}`); + if (mod.kind === "segment") { + teaser = mod.entry(manifest, segment); + if (!teaser) throw new Error(`no ${region} entry ${segment ?? "(none named)"} in the ${variant} cut`); } let sched = schedule; - if ((wholeCut || region === "posts" || region === "finale") && !sched) { + if (keyed && mod.kind !== "segment" && !sched) { const p = path.join(base, "schedule.json"); try { sched = JSON.parse(await readFile(p, "utf8")); @@ -981,62 +879,23 @@ export async function composeChrome({ } if (sched.kind !== "deck") throw new Error(`${p} is not a deck schedule (kind ${sched.kind ?? "missing"})`); } - if (region === "feed" && sched.layout !== "feed") { - throw new Error("the feed region needs a feed's schedule (layout \"feed\": posts.layout \"feed\" and posts to draw)"); - } - if (region === "flips" && !sched.flips?.pairs?.length) { - throw new Error("the flips region needs a schedule with flip pairs (render.chrome.flips)"); - } - if (region === "threads" && !sched.threads?.threads?.length) { - throw new Error("the threads region needs a schedule with a thread rail (render.chrome.threads)"); - } - if (region === "stats" && !sched.stats?.clips?.length) { - throw new Error("the stats region needs a schedule with a clip that declares it (render.chrome.stats or a clip's stats, and frameScan.overlay points)"); - } - if (region === "fx" && !sched.fx) { - throw new Error("the fx region needs a schedule with an effect on (render.chrome.fx)"); - } - if (region === "finale" && !sched.finale) { - throw new Error("the finale region needs a schedule with a finale (a clip with layout \"finale\", render.chrome.deck.finale)"); - } - if (region === "stamp" && !sched.factcheck?.stamps?.length) { - throw new Error("the stamp region needs a schedule that stamps a claim (an entry with a `claim`)"); - } - if (region === "stamp" && !stampsDrawn(sched, manifest.render)) { - throw new Error("the stamps are off (render.chrome.factcheck.stamp.show: false): there is no stamp region to compose"); - } + const refused = mod.check ? mod.check(sched, manifest.render) : null; + if (refused) throw new Error(refused); const D = transition ?? transitionOf(manifest.render); const rate = Number(fps ?? sched?.fps ?? manifest.render.fps ?? 30); - const total = teaser ? teaserSeconds(teaser, D, rate) : keyed ? sched.total : null; + const total = teaser ? mod.seconds(teaser, D, rate) : keyed ? sched.total : null; const windowed = wholeCut && (from > 0 || (duration != null && Math.abs(Number(duration) - total) > 1e-6)); const suffix = windowed ? `-from${fmtSeconds(from)}` : ""; - // A posts window: the one asked for, or the segment's from the schedule. - let win = null; - if (region === "posts") { - const want = window ?? postWindows(sched).find((w) => w.segment === segment); - if (!want) { - throw new Error( - segment ? `no post rides on ${segment} in this schedule` : "the posts region needs a window (or a segment)", - ); - } - if (!/^[A-Za-z0-9_-]+$/.test(String(want.segment))) throw new Error(`posts: ${want.segment} is not a segment id`); - win = snapWindow(want, { fps: rate, total }); - } - // The finale's window: the schedule's, snapped outward to the frame grid. - if (region === "finale") win = snapWindow({ segment: "finale", from: sched.finale.from, to: sched.finale.to }, { fps: rate, total }); - - const projName = - region === "posts" - ? `posts-${preview ? "preview-" : ""}${win.segment}` - : region === "finale" - ? `finale${preview ? "-preview" : ""}` - : region === "teaser" - ? `teaser-${preview ? "preview-" : ""}${teaser.id}` - : wholeCut && preview ? `${region}-preview` : `${region}${suffix}`; - const projDir = path.join(base, "chrome", projName); + // A window (a posts window, the finale's): the one asked for, snapped to the frame grid. + const win = mod.window ? mod.window(sched, { window, segment, fps: rate, total }) : null; + + const names = mod.names + ? mod.names({ preview, window: win, entry: teaser, suffix }) + : { project: wholeCut && preview ? `${region}-preview` : `${region}${suffix}`, stem: `${region}${suffix}` }; + const projDir = path.join(base, "chrome", names.project); const assetsDir = path.join(projDir, "assets"); // The deck's assets are rebuilt every time: a QR from a clip that has since // left the cut must not sit in the directory the cache key hashes. @@ -1087,7 +946,7 @@ export async function composeChrome({ // A sequence is a directory; every other format is a file. const sequence = format === "png-sequence"; - const stem = region === "posts" ? `posts-${win.segment}` : region === "finale" ? "finale" : region === "teaser" ? `teaser-${teaser.id}` : `${region}${suffix}`; + const stem = names.stem; const target = sequence ? path.join(base, "chrome", `${stem}-frames`) : path.join(base, "chrome", `${stem}.${format}`); @@ -1096,7 +955,7 @@ export async function composeChrome({ // Each frame's key (frame-keys.mjs), for a whole-cut page it models: a // render that is not cached whole captures only the frames no render on // disk has drawn. - const fk = keyed && sequence && ((wholeCut && !windowed) || region === "finale") && !preview && FRAME_KEY_REGIONS[region] + const fk = keyed && sequence && ((wholeCut && !windowed) || mod.kind === "overlay-window") && !preview && mod.frameKeys ? frameKeys({ html, region, assets, fps: rate, frames, version: hf.version }) : null; if (keyed && sequence) { @@ -1335,7 +1194,7 @@ if (import.meta.url === `file://${process.argv[1]}`) { still: num("--still"), png: flag("--png"), // The deck renders four-wide by default; the band keeps the renderer's own default. - workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" || region === "fx" ? 4 : region === "posts" || region === "finale" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null), + workers: num("--workers") ?? ({ wide: 4, narrow: 2 }[regionModule(region).workers] ?? null), quality: flag("--quality") ?? "high", format: flag("--format") ?? "png-sequence", fps: num("--fps"), diff --git a/umtool/report-to-video/frame-keys.mjs b/umtool/report-to-video/frame-keys.mjs @@ -42,24 +42,20 @@ import vm from "node:vm"; import { GSAP_FILE } from "./chrome-deck.mjs"; import { feedCues } from "./chrome-feed.mjs"; +import { MODULES } from "./modules/index.mjs"; /** Bumped when what a frame key covers changes: every frame is captured once more. */ export const FRAME_KEY_VERSION = 1; -/** The regions whose pages this models, and the data fields their key leaves out of the static part. */ -export const FRAME_KEY_REGIONS = Object.freeze({ - deck: { data: "deck-data", omit: ["init", "cues", "window", "total", "ids"] }, - stamp: { data: "stamp-data", omit: ["init", "cues", "window", "total", "ids"] }, - // The feed plans its cues IN the page, from the heights its cards measure - // (chrome-feed.mjs): keyed by its EVENTS instead (feedFrameKeys). - feed: { data: "feed-data", omit: ["window", "total", "ids", "posts", "visibility"], events: true }, - // The finale is a window of the cut by design: its frame n is cut time - // `from` + n / fps, and its one ease of its own is the page's smoothstep. - finale: { - data: "finale-data", omit: ["init", "cues", "from", "dur"], offset: "from", - eases: { smoothstep: { page: "const EASES = { smoothstep: (p) => p * p * (3 - 2 * p) };", fn: (p) => p * p * (3 - 2 * p) } }, - }, -}); +/** + * The regions whose pages this models, and the data fields their key leaves + * out of the static part: each module's own `frameKeys` (modules/<id>.mjs), + * by its region -- the shell's deck, the stamps, the feed (keyed by its + * EVENTS: it plans its cues in the page), the finale (a window of the cut). + */ +export const FRAME_KEY_REGIONS = Object.freeze( + Object.fromEntries(MODULES.filter((m) => m.region && m.frameKeys).map((m) => [m.region, m.frameKeys])), +); /** * How long after a feed event (a post in, the column hidden or shown) its diff --git a/umtool/report-to-video/modules/chart.mjs b/umtool/report-to-video/modules/chart.mjs @@ -0,0 +1,36 @@ +// THE CHART BAND (module `chart`, region `chart`): the headcount band the +// first report cuts drew in place of the footer -- the legacy chrome, before +// the deck (`render.chromeEngine`). Not render-cached: it re-renders whole. +// compose-chrome.mjs `chartBandHtml` writes the page. +import path from "node:path"; +import { readFile } from "node:fs/promises"; + +import { contentWidth } from "../render-cards.mjs"; +import { ledgerTotals } from "../ledger-totals.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "chart", + version: 1, + z: 5, + kind: "overlay-whole", + slot: "footer", + title: "Chart band (legacy)", + summary: "The headcount band of the first cuts, drawn in place of the footer.", + region: "chart", + cached: false, + async page(ctx) { + const { chartBandHtml } = await import("../compose-chrome.mjs"); + const sched = ctx.schedule ?? JSON.parse(await readFile(path.join(ctx.base, "schedule.json"), "utf8")); + const fonts = await ctx.fonts({ regular: "regular", bold: "bold" }, { strict: false }); + const totals = ledgerTotals(ctx.manifest.ledger); + return chartBandHtml(ctx.manifest, totals, sched, { fonts, ...(ctx.duration ? { duration: ctx.duration } : {}) }); + }, + regions(_schedule, { render, outDir }) { + const H = render.chart?.height ?? 200; + return [assertRegion({ + name: "chart", frames: path.join(outDir, "chrome", "chart-frames"), + x: 0, y: render.height - H, width: contentWidth(render), height: H, + })]; + }, +}); diff --git a/umtool/report-to-video/modules/contract.mjs b/umtool/report-to-video/modules/contract.mjs @@ -0,0 +1,183 @@ +// THE MODULE CONTRACT (release 39, the video-modules toolkit). +// +// Every piece of a report video's chrome -- the deck's shell, its subtitle, +// QR, rail and counter, the stamps, the posts, the finale, the intro, the +// teaser, the effects -- is a MODULE: one file under modules/ that exports +// `defineModule({...})` and is registered in modules/index.mjs. A module says +// what it is (`kind`, `slot`, `z`), where its settings live in the manifest +// (`configKey`, `defaults`), how they are checked (`validate`) and filled +// (`resolve`), what it reads of other modules (`deps`, by NAME -- never by +// reaching into their slice), how it is drawn (`page` for a HyperFrames page, +// `render` for an ffmpeg/IM one), where its frames land (`region`), what its +// render cache keys on (`frameKeys`: the static part and the frame events), +// and how umtool shows it (`ui`, `preview`, `docs`). +// +// A PART (`host` set) is drawn inside its host module's page -- the subtitle, +// the QR, the rail and the counter are all inside the deck's one page, so +// their frames are the shell's. It owns its settings, validation, defaults, +// docs and UI; its pixels are the host's region. +// +// Pure: no fs, no ffmpeg, no network. The registry and every module file are +// imported by the build, the composer and umtool alike. + +/** What a module is: how its pixels reach the cut. */ +export const MODULE_KINDS = Object.freeze([ + // A page over the whole cut (or a window of it), laid by its region at frame 1. + "overlay-whole", + // Pages laid at their own second: short sequences over a stretch of the cut. + "overlay-window", + // A segment inserted into the timeline (the intro, a teaser). + "segment", + // A filter on the footage itself (a clip's blur). + "input", + // After the master (a trailer, the variant ladder). + "post", + // Drawn inside another module's page (`host`): settings, checks and docs of its own. + "part", +]); + +/** + * The layout slots a module may ask for (layout.mjs `slotRect`): the deck's + * band at the foot of the frame, the posts column, the stamp's box in the + * footage, the footage box itself, the side panel beside it, a popup column + * over the footage, the whole frame, or `inline` (a part, in its host's slot). + */ +export const MODULE_SLOTS = Object.freeze(["footer", "column", "popup", "stamp", "panel", "footage", "side", "full", "inline"]); + +/** How a region is laid over the cut: a whole-cut sequence from frame 1, or a window at its own second. */ +export const REGION_PLACEMENTS = Object.freeze(["whole", "window"]); + +const ID_RE = /^[a-z][a-z0-9-]{0,31}$/; +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const isFn = (v) => typeof v === "function"; + +/** The keys a module definition may carry, each with what it must be. */ +const SPEC = Object.freeze({ + id: "an id: lower-case letters, digits and dashes", + version: "a whole number from 1: bumped when what it draws changes", + z: "a number: its stack order, lowest first", + kind: `one of ${MODULE_KINDS.join(", ")}`, + slot: `one of ${MODULE_SLOTS.join(", ")}`, + title: "words: what the module is called in umtool and the docs", + summary: "a sentence: what it draws", + host: "a part's host module id", + region: "the name its frames and project are filed under (chrome/<region>-frames)", + configKey: "a dotted manifest path its settings live at (render.chrome.deck.qr)", + configKeys: "more dotted paths it owns beside configKey", + defaults: "an object: every setting and its default", + validate: "a function (config, ctx) => string[]", + resolve: "a function (render) => its settings with the defaults filled", + deps: "the named outputs of other modules it reads (counter.totals)", + provides: "the named outputs it gives (counter.totals)", + on: "a function (render, manifest?) => boolean: is it drawn at all", + schedule: "a function (doc, ctx) => its slice of the deck schedule", + page: "an async function (ctx) => the HTML of its page", + render: "an async function (ctx) => what it renders without a page", + regions: "a function (schedule, ctx) => its overlay regions", + composes: "a function (schedule, ctx) => the compose requests a build makes for it", + frameKeys: "its frame-key model: { data, omit, offset?, eases?, events?, items? }", + ui: "a field descriptor list for umtool's generic panel", + preview: "a function (slice, ctx) => a single-layer preview request", + docs: "its knobs.md section: { heading, intro?, rows: [[knob, range, terminal]], after? }", + workers: "\"wide\" or \"narrow\": how many renderer workers its page takes", + noun: "how a message names its sequence (\"the stamps'\")", + cached: "false for a page the render cache does not key (the legacy chart band)", + check: "a function (schedule, render) => the sentence why this schedule cannot draw it, or null", + window: "a function (schedule, { window, segment, fps, total }) => the window it composes", + names: "a function ({ preview, window, entry, suffix }) => { project, stem }", + entry: "a function (manifest, segment) => the timeline entry a segment module draws", + seconds: "a function (entry, transition, fps) => how long a segment module's page is", +}); + +/** + * One module, checked and frozen. Throws a sentence naming the key on a + * definition no registry should hold: a module that mis-declares itself is a + * bug in the build, not a manifest problem. + * + * @template T + * @param {T & { id: string, kind: string }} def + * @returns {Readonly<T>} + */ +export function defineModule(def) { + if (!isObj(def)) throw new Error("defineModule: a module is an object"); + const where = `module ${def.id ?? "(no id)"}`; + for (const k of Object.keys(def)) { + if (!(k in SPEC)) throw new Error(`${where}: ${k} is not a module key (${Object.keys(SPEC).join(", ")})`); + } + if (typeof def.id !== "string" || !ID_RE.test(def.id)) throw new Error(`${where}: id must be ${SPEC.id}`); + if (!(Number.isInteger(def.version) && def.version >= 1)) throw new Error(`${where}: version must be ${SPEC.version}`); + if (typeof def.z !== "number" || !Number.isFinite(def.z)) throw new Error(`${where}: z must be ${SPEC.z}`); + if (!MODULE_KINDS.includes(def.kind)) throw new Error(`${where}: kind must be ${SPEC.kind}`); + if (!MODULE_SLOTS.includes(def.slot)) throw new Error(`${where}: slot must be ${SPEC.slot}`); + if (typeof def.title !== "string" || !def.title.trim()) throw new Error(`${where}: title must be ${SPEC.title}`); + if (def.kind === "part") { + if (typeof def.host !== "string" || !ID_RE.test(def.host)) throw new Error(`${where}: a part names its host`); + if (def.slot !== "inline") throw new Error(`${where}: a part's slot is inline (it draws in its host's)`); + if (def.region !== undefined || def.page !== undefined) throw new Error(`${where}: a part has no region or page of its own`); + } else if (def.host !== undefined) { + throw new Error(`${where}: only a part has a host`); + } + if ((def.kind === "overlay-whole" || def.kind === "overlay-window") && typeof def.region !== "string") { + throw new Error(`${where}: an overlay names its region`); + } + for (const k of ["validate", "resolve", "on", "schedule", "page", "render", "regions", "composes", "preview", "check", "window", "names", "entry", "seconds"]) { + if (def[k] !== undefined && !isFn(def[k])) throw new Error(`${where}: ${k} must be ${SPEC[k]}`); + } + if (def.configKey !== undefined && !/^render(\.[A-Za-z]+)+$/.test(def.configKey)) { + throw new Error(`${where}: configKey must be ${SPEC.configKey}`); + } + if (def.configKeys !== undefined && !(Array.isArray(def.configKeys) && def.configKeys.every((k) => /^[a-z]+(\.[A-Za-z]+)*$/.test(k)))) { + throw new Error(`${where}: configKeys must be ${SPEC.configKeys}`); + } + for (const k of ["deps", "provides"]) { + if (def[k] !== undefined && !(Array.isArray(def[k]) && def[k].every((n) => /^[a-z][a-z0-9-]*\.[a-zA-Z]+$/.test(n)))) { + throw new Error(`${where}: ${k} must be ${SPEC[k]}`); + } + } + for (const p of def.provides ?? []) { + if (!p.startsWith(`${def.id}.`)) throw new Error(`${where}: it provides ${p}, which is not its own (${def.id}.<name>)`); + } + if (def.defaults !== undefined && !isObj(def.defaults)) throw new Error(`${where}: defaults must be ${SPEC.defaults}`); + if (def.frameKeys !== undefined && def.frameKeys !== null) { + const f = def.frameKeys; + if (!isObj(f) || typeof f.data !== "string" || !Array.isArray(f.omit)) throw new Error(`${where}: frameKeys must be ${SPEC.frameKeys}`); + } + if (def.ui !== undefined && !Array.isArray(def.ui)) throw new Error(`${where}: ui must be ${SPEC.ui}`); + if (def.docs !== undefined && !(isObj(def.docs) && typeof def.docs.heading === "string")) throw new Error(`${where}: docs must be ${SPEC.docs}`); + if (def.workers !== undefined && !["wide", "narrow"].includes(def.workers)) throw new Error(`${where}: workers must be ${SPEC.workers}`); + return Object.freeze({ ...def }); +} + +// --------------------------------------------------------------------------- +// Regions: where a module's frames land in the cut. +// --------------------------------------------------------------------------- + +const num = (v) => typeof v === "number" && Number.isFinite(v); + +/** + * An overlay region, checked: `{ name, frames, x, y, width, height }`, and + * for a window `offset` (the cut second its frame 1 lands on) and + * `frameCount`; a chunk of the final encode reads a whole-cut sequence from + * `startNumber`. What chromeOverlayChain and the chunked encode take. Returns + * the region; throws a sentence on a malformed one. + * + * @template {{ name: string, frames: string, x: number, y: number, width: number, height: number, + * offset?: number, frameCount?: number, startNumber?: number }} R + * @param {R} r + * @param {"whole" | "window" | null} [placement] + * @returns {R} + */ +export function assertRegion(r, placement = null) { + const where = `region ${r?.name ?? "(no name)"}`; + if (!isObj(r) || typeof r.name !== "string" || !r.name) throw new Error(`${where}: a region has a name`); + if (typeof r.frames !== "string" || !r.frames) throw new Error(`${where}: a region names its frames' directory`); + for (const k of ["x", "y", "width", "height"]) if (!num(r[k])) throw new Error(`${where}: ${k} must be a number`); + if (placement === "window") { + if (!num(r.offset)) throw new Error(`${where}: a window region has an offset (the cut second its frame 1 lands on)`); + if (!(Number.isInteger(r.frameCount) && r.frameCount > 0)) throw new Error(`${where}: a window region has a frame count`); + } + if (r.startNumber !== undefined && !(Number.isInteger(r.startNumber) && r.startNumber >= 1)) { + throw new Error(`${where}: startNumber must be a frame number from 1`); + } + return r; +} diff --git a/umtool/report-to-video/modules/design.mjs b/umtool/report-to-video/modules/design.mjs @@ -0,0 +1,25 @@ +// THE DESIGN UNITS every chrome module lays out in (release 39, the +// video-modules toolkit). A module's own pixel constants are in these units -- +// a 1920×1080 frame -- and the layout engine (layout.mjs) scales them to the +// output size. A constant another module needs lives HERE, once: no module +// owns a pixel constant for another (the tally's 124 px cell used to be +// written in deck.mjs and again in factcheck.mjs). +// +// No imports. deck.mjs, factcheck.mjs and the modules all read this file, and +// it must evaluate before any of them whatever imports first (a cycle through +// a module that computes a constant from another's at load is a TDZ error). + +/** The design frame: every design-unit constant is a pixel of a frame this size. */ +export const DESIGN = Object.freeze({ width: 1920, height: 1080 }); + +/** The deck's side padding: the rail's ends, the text's left, the QR's right. */ +export const DECK_PAD_X = 48; + +/** + * The counter's (the fact-check tally's) cell: one per series the cut counts, + * `cell` wide with `gap` between, its label in the cell less `labelPad` a side. + */ +export const COUNTER_CELL = Object.freeze({ cell: 124, gap: 10, labelPad: 6 }); + +/** A design-unit length at this render's width (what the scaled geometry multiplies by). */ +export const designScale = (render) => (render?.width ?? DESIGN.width) / DESIGN.width; diff --git a/umtool/report-to-video/modules/feed.mjs b/umtool/report-to-video/modules/feed.mjs @@ -0,0 +1,46 @@ +// THE FEED (module `feed`, region `feed`): the posts in a column of their own +// beside the footage for the whole cut, each ticking in as its clip starts +// (`render.chrome.deck.posts.layout: "feed"`). chrome-feed.mjs writes the +// page; deck.mjs `feedGeometry` lays the column and the footage beside it. +import path from "node:path"; + +import { feedGeometry, resolveDeck } from "../deck.mjs"; +import { feedHtml } from "../chrome-feed.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "feed", + version: 1, + z: 20, + kind: "overlay-whole", + slot: "column", + title: "Posts feed", + summary: "The cut's posts in a column beside the footage, each ticking in as its clip starts.", + region: "feed", + workers: "wide", + noun: "the feed's", + on: (schedule) => schedule?.layout === "feed", + check: (schedule) => (schedule.layout !== "feed" + ? "the feed region needs a feed's schedule (layout \"feed\": posts.layout \"feed\" and posts to draw)" + : null), + async page(ctx) { + // The posts feed: the deck's faces and QR maker, one page for the whole cut. + const { render, schedule } = ctx; + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + const posts = schedule.posts ?? []; + // `posts.qr: false`: no codes are made, and the page draws none. + const byUrl = resolveDeck(render).posts.qr === false + ? new Map() + : await ctx.qrs(posts.map((p) => p.qrUrl), resolveDeck(render).posts.qrSize); + const qrSrcs = {}; + for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl); + const shotSrcs = await ctx.shots(posts); + return feedHtml(schedule, render, { fonts, qrSrcs, shotSrcs, from: ctx.from, duration: ctx.duration }); + }, + regions(_schedule, { render, outDir, frames = null }) { + return [assertRegion({ name: "feed", frames: frames ?? path.join(outDir, "chrome", "feed-frames"), ...feedGeometry(render).column })]; + }, + // The feed plans its cues IN the page, from the heights its cards measure + // (chrome-feed.mjs): keyed by its EVENTS instead (frame-keys.mjs feedFrameKeys). + frameKeys: { data: "feed-data", omit: ["window", "total", "ids", "posts", "visibility"], events: true }, +}); diff --git a/umtool/report-to-video/modules/finale.mjs b/umtool/report-to-video/modules/finale.mjs @@ -0,0 +1,71 @@ +// THE FINALE (module `finale`, region `finale`): the cut's last clips with the +// rail redrawn large across the top, the counter's final totals under it, +// stats cards beside them and the clip in a smaller box (a clip's `layout: +// "finale"`, `render.chrome.deck.finale`, finale.mjs). One full-frame window +// over the run, laid LAST: its ground covers every region under it while it +// is up. chrome-finale.mjs writes the page. +import path from "node:path"; + +import { resolveDeck, snapWindow } from "../deck.mjs"; +import { finaleHtml, finaleLayout } from "../chrome-finale.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "finale", + version: 1, + z: 90, + kind: "overlay-window", + slot: "full", + title: "Finale", + summary: "The cut's last clips under the rail redrawn large, the final totals and stats cards.", + region: "finale", + workers: "narrow", + noun: "the finale's", + on: (schedule) => !!schedule?.finale, + check: (schedule) => (!schedule.finale + ? "the finale region needs a schedule with a finale (a clip with layout \"finale\", render.chrome.deck.finale)" + : null), + // The finale's window: the schedule's, snapped outward to the frame grid. + window: (schedule, { fps, total }) => snapWindow({ segment: "finale", from: schedule.finale.from, to: schedule.finale.to }, { fps, total }), + names: ({ preview }) => ({ project: `finale${preview ? "-preview" : ""}`, stem: "finale" }), + async page(ctx) { + // The finale (chrome-finale.mjs): the deck's faces and QR maker, one page + // for its window. + const { render, schedule } = ctx; + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + const L = finaleLayout(schedule, render); + const qrSrcs = {}; + if (resolveDeck(render).qr.show) { + const byUrl = await ctx.qrs(L.captions.map((c) => c.qrUrl), L.geo.qr.size); + for (const c of L.captions) if (c.qrUrl) qrSrcs[c.id] = byUrl.get(c.qrUrl); + } + return finaleHtml(schedule, render, ctx.window, { fonts, qrSrcs }); + }, + /** + * The finale's page as an overlay region: the whole frame, its window + * snapped to the frame grid and laid at its own second like a posts window + * -- `offset` in the BASE's clock (the cut's, or a preview's that starts + * `shift` in). `clip` (`{at, dur}`) keeps it only when it intersects. + */ + regions(schedule, { render, outDir, shift = 0, clip = null }) { + const f = schedule?.finale; + if (!f) return []; + const fps = Number(schedule.fps ?? render.fps); + const s = snapWindow({ segment: "finale", from: f.from, to: f.to }, { fps, total: schedule.total }); + if (clip && !(s.from < clip.at + clip.dur && s.to > clip.at)) return []; + return [assertRegion({ + name: "finale", + frames: path.join(outDir, "chrome", "finale-frames"), + x: 0, y: 0, width: render.width ?? 1920, height: render.height ?? 1080, + offset: s.from - shift, + frameCount: s.frames, + window: s, + }, "window")]; + }, + // The finale is a window of the cut by design: its frame n is cut time + // `from` + n / fps, and its one ease of its own is the page's smoothstep. + frameKeys: { + data: "finale-data", omit: ["init", "cues", "from", "dur"], offset: "from", + eases: { smoothstep: { page: "const EASES = { smoothstep: (p) => p * p * (3 - 2 * p) };", fn: (p) => p * p * (3 - 2 * p) } }, + }, +}); diff --git a/umtool/report-to-video/modules/flips.mjs b/umtool/report-to-video/modules/flips.mjs @@ -0,0 +1,32 @@ +// THE FLIPS PANEL (module `flips`, region `flips`): then-and-now pairs in the +// side panel -- the thread rail's region, one or the other +// (`render.chrome.flips`, flips.mjs). chrome-flips.mjs writes the page. +import path from "node:path"; + +import { flipsHtml } from "../chrome-flips.mjs"; +import { defineModule } from "./contract.mjs"; +import { sideRegion } from "./threads.mjs"; + +export default defineModule({ + id: "flips", + version: 1, + z: 80, + kind: "overlay-whole", + slot: "side", + title: "Flips", + summary: "Pairs of what was said then and now, in the side panel.", + region: "flips", + workers: "narrow", + noun: "the flips panel's", + configKey: "render.chrome.flips", + on: (schedule) => !!schedule?.flips?.pairs?.length, + check: (schedule) => (!schedule.flips?.pairs?.length ? "the flips region needs a schedule with flip pairs (render.chrome.flips)" : null), + async page(ctx) { + // The flips panel (chrome-flips.mjs): the deck's faces, no QR. + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + return flipsHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration }); + }, + regions(_schedule, { render, outDir, frames = null }) { + return [sideRegion(render, frames ?? path.join(outDir, "chrome", "flips-frames"), "flips")]; + }, +}); diff --git a/umtool/report-to-video/modules/fx.mjs b/umtool/report-to-video/modules/fx.mjs @@ -0,0 +1,42 @@ +// THE EFFECTS (module `fx`, region `fx`): overlays drawn over the footage box +// -- receipts, a zoom, a scrubber, captions (`render.chrome.fx`, fx.mjs). +// chrome-fx.mjs writes the page. +import path from "node:path"; + +import { fxGeometry } from "../deck.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "fx", + version: 1, + z: 60, + kind: "overlay-whole", + slot: "footage", + title: "Effects", + summary: "Overlays on the picture: receipts, a zoom, a scrubber, captions.", + region: "fx", + workers: "wide", + noun: "the effects'", + configKey: "render.chrome.fx", + on: (schedule) => !!schedule?.fx, + check: (schedule) => (!schedule.fx ? "the fx region needs a schedule with an effect on (render.chrome.fx)" : null), + async page(ctx) { + // The effects (chrome-fx.mjs): the deck's faces, a mono, the screenshots + // the receipts and the zoom show, and the scrubber's thumbnails. + // A page module reached by a dynamic import, as the teaser's: it carries + // its mono as an asset URL (docs/quirks.md). + const { fxHtml, FX_MONO_FILE } = await import("../chrome-fx.mjs"); + const { schedule, render } = ctx; + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + fonts.mono = await ctx.asset(FX_MONO_FILE, "FxMono.ttf"); + const shots = await ctx.fxShots(schedule.fx); + const thumbs = schedule.fx.scrubber?.thumbs ? await ctx.fxThumbs(schedule) : {}; + return fxHtml(schedule, render, { fonts, assets: { shots, thumbs }, from: ctx.from, duration: ctx.duration }); + }, + regions(schedule, { render, outDir, frames = null }) { + return [assertRegion({ + name: "fx", frames: frames ?? path.join(outDir, "chrome", "fx-frames"), + ...fxGeometry(render, { feed: schedule.layout === "feed" }), + })]; + }, +}); diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -0,0 +1,88 @@ +// THE MODULE REGISTRY (release 39): every chrome module, once. The build's +// overlay pass, the composer, the validator and umtool's panels all loop over +// this list -- a module joins the video by being registered here, and by +// nothing else. The order a list is in is its `z`: a region with a higher z +// is laid over one with a lower. +// +// Pure: the module files are, and so is this. +import { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, REGION_PLACEMENTS } from "./contract.mjs"; + +import chart from "./chart.mjs"; +import shell from "./shell.mjs"; +import feed from "./feed.mjs"; +import popupPosts from "./popup-posts.mjs"; +import stamp from "./stamp.mjs"; +import stats from "./stats.mjs"; +import fx from "./fx.mjs"; +import threads from "./threads.mjs"; +import flips from "./flips.mjs"; +import finale from "./finale.mjs"; +import teaser from "./teaser.mjs"; + +export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, REGION_PLACEMENTS }; + +/** Every module, by z (stack order), then id. */ +export const MODULES = Object.freeze( + [chart, shell, feed, popupPosts, stamp, stats, fx, threads, flips, finale, teaser] + .sort((a, b) => a.z - b.z || a.id.localeCompare(b.id)), +); + +{ + const ids = new Set(); + const regions = new Set(); + for (const m of MODULES) { + if (ids.has(m.id)) throw new Error(`registry: two modules are ${m.id}`); + ids.add(m.id); + if (m.region) { + if (regions.has(m.region)) throw new Error(`registry: two modules file their frames as ${m.region}`); + regions.add(m.region); + } + } + for (const m of MODULES) { + if (m.host && !ids.has(m.host)) throw new Error(`registry: ${m.id}'s host ${m.host} is not a module`); + } +} + +const BY_ID = new Map(MODULES.map((m) => [m.id, m])); +const BY_REGION = new Map(MODULES.filter((m) => m.region).map((m) => [m.region, m])); + +/** A module by id, or undefined. */ +export const moduleById = (id) => BY_ID.get(id); + +/** The module that files its frames as `region` (`deck` is the shell's), or undefined. */ +export const moduleOfRegion = (region) => BY_REGION.get(region); + +/** A module by region, or a sentence saying there is none. */ +export function regionModule(region) { + const m = BY_REGION.get(region); + if (!m) throw new Error(`unknown chrome region: ${region}`); + return m; +} + +/** + * The overlays a deck build composes and lays, in z order: every + * render-cached overlay module (the deck's shell first, the finale last). + */ +export const deckOverlays = () => MODULES.filter((m) => (m.kind === "overlay-whole" || m.kind === "overlay-window") && m.cached !== false); + +/** + * How a region is laid over the cut: "whole" (a sequence as long as the cut, + * from frame 1 -- or a chunk's `startNumber`), "window" (a short sequence at + * its own second), or null for the legacy chart band (its chain stays as it + * shipped). + */ +export function placementOf(region) { + const m = BY_REGION.get(region); + if (!m || m.cached === false) return null; + return m.kind === "overlay-window" ? "window" : m.kind === "overlay-whole" ? "whole" : null; +} + +/** A region's render cache: is its page keyed (`.key`, frame keys), and is it drawn over the whole cut (windowable)? */ +export function regionCaching(region) { + const m = regionModule(region); + const keyed = m.cached !== false; + return { keyed, wholeCut: keyed && m.kind === "overlay-whole" }; +} + +/** The parts drawn in `host`'s page, by z. */ +export const partsOf = (host) => MODULES.filter((m) => m.host === host); diff --git a/umtool/report-to-video/modules/layout.mjs b/umtool/report-to-video/modules/layout.mjs @@ -0,0 +1,69 @@ +// THE LAYOUT ENGINE (release 39): every module asks for a SLOT and gets a +// rect in the output frame. The slots generalise deckGeometry: the deck's +// band at the foot of the frame, the footage box above it (moved for the +// feed's column or the side panel), and the boxes the posts, the stamp and +// the stats stand in inside it. A module draws in its slot's rect and never +// in another's: the geometry is computed here, once, from the render block, +// in design units (design.mjs) scaled to the output size. +// +// Pure. The numbers are deck.mjs's geometry functions' -- those stay the one +// arithmetic, and this file is the one place a module asks them. +import { + deckGeometry, feedGeometry, fxGeometry, postsGeometry, stampGeometry, statsGeometry, threadsGeometry, +} from "../deck.mjs"; +import { MODULE_SLOTS } from "./contract.mjs"; +import { DESIGN, designScale } from "./design.mjs"; + +export { DESIGN, designScale }; + +/** + * A slot's rect in the output frame, `{ x, y, width, height }`. + * + * - `footer`: the deck's band, full width at the foot of the frame. + * - `footage`: the picture's box -- the feed's (beside its column) when + * `feed`, else the deck's (beside the side panel when that is on). + * - `column`: the posts feed's column, flush with the frame's side and top. + * - `popup`: where the popup posts stack (in the footage box, or at the + * frame's edge when the footage shifts away for them). + * - `stamp`: the fact-check stamp's box in the footage, at its position. + * - `panel`: the stats panel in the footage, at its position. + * - `side`: the side panel (the thread rail, the flips) beside the footage. + * - `full`: the whole frame. + * + * @param {string} slot + * @param {any} render + * @param {{ feed?: boolean }} [opts] + * @returns {{ x: number, y: number, width: number, height: number }} + */ +export function slotRect(slot, render, { feed = false } = {}) { + switch (slot) { + case "footer": + return { ...deckGeometry(render).deck }; + case "footage": + return fxGeometry(render, { feed }); + case "column": + return { ...feedGeometry(render).column }; + case "popup": + return postsGeometry(render); + case "stamp": + return stampGeometry(render, { feed }); + case "panel": + return statsGeometry(render, { feed }); + case "side": { + const { cards: _c, ...box } = threadsGeometry(render); + return box; + } + case "full": + return { x: 0, y: 0, width: render?.width ?? DESIGN.width, height: render?.height ?? DESIGN.height }; + default: + throw new Error(`layout: ${slot} is not a slot (${MODULE_SLOTS.filter((s) => s !== "inline").join(", ")})`); + } +} + +/** Every slot's rect at once: what umtool's layout view and the module docs draw. */ +export function slotRects(render, opts = {}) { + return Object.fromEntries(MODULE_SLOTS.filter((s) => s !== "inline").map((s) => [s, slotRect(s, render, opts)])); +} + +/** A design-unit length in this render's pixels, rounded. */ +export const scaled = (v, render) => Math.round(v * designScale(render)); diff --git a/umtool/report-to-video/modules/popup-posts.mjs b/umtool/report-to-video/modules/popup-posts.mjs @@ -0,0 +1,74 @@ +// THE POPUP POSTS (module `popup-posts`, region `posts`): a clip's posts as +// cards over the footage at the end of the clip (or from its start), one +// short page per clip that carries them, laid at its own second. +// chrome-posts.mjs writes the page; deck.mjs `postWindows` / `snapWindow` +// time it and `postsGeometry` places it. +import path from "node:path"; + +import { postsGeometry, postWindows, resolveDeck, snapWindow } from "../deck.mjs"; +import { postsHtml, windowPosts } from "../chrome-posts.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +const SEGMENT_RE = /^[A-Za-z0-9_-]+$/; + +export default defineModule({ + id: "popup-posts", + version: 1, + z: 30, + kind: "overlay-window", + slot: "popup", + title: "Popup posts", + summary: "A clip's posts as cards over the footage, each window its own short page at its own second.", + region: "posts", + workers: "narrow", + noun: "the posts window's", + on: (schedule) => postWindows(schedule).length > 0, + window(schedule, { window = null, segment = null, fps, total }) { + const want = window ?? postWindows(schedule).find((w) => w.segment === segment); + if (!want) { + throw new Error(segment ? `no post rides on ${segment} in this schedule` : "the posts region needs a window (or a segment)"); + } + if (!SEGMENT_RE.test(String(want.segment))) throw new Error(`posts: ${want.segment} is not a segment id`); + return snapWindow(want, { fps, total }); + }, + names: ({ preview, window }) => ({ project: `posts-${preview ? "preview-" : ""}${window.segment}`, stem: `posts-${window.segment}` }), + async page(ctx) { + // The deck's faces and the deck's QR maker: a card is part of the deck's + // family, not a second design. + const { render, schedule, window } = ctx; + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + const posts = windowPosts(schedule, window.segment); + // `posts.qr: false`: no codes are made, and the page draws none. + const byUrl = resolveDeck(render).posts.qr === false + ? new Map() + : await ctx.qrs(posts.map((p) => p.qrUrl), resolveDeck(render).posts.qrSize); + const qrSrcs = {}; + for (const p of posts) if (p.qrUrl) qrSrcs[p.id] = byUrl.get(p.qrUrl); + const shotSrcs = await ctx.shots(posts); + const logoSrcs = await ctx.shots(posts, "logo"); + return postsHtml(schedule, render, window, { fonts, qrSrcs, shotSrcs, logoSrcs }); + }, + /** + * The posts windows as overlay regions: one per clip that carries posts + * (`postWindows`), snapped to the frame grid (`snapWindow`), at + * `postsGeometry`. `offset` is the second the window's frame 1 lands on in + * the BASE's clock -- the cut's, or a preview's that starts `shift` seconds + * in. `clip` (`{at, dur}`) keeps only the windows that intersect it. + */ + regions(schedule, { render, outDir, shift = 0, clip = null }) { + const fps = Number(schedule.fps ?? render.fps); + const g = postsGeometry(render); + return postWindows(schedule) + .map((w) => ({ w, s: snapWindow(w, { fps, total: schedule.total }) })) + .filter(({ s }) => !clip || (s.from < clip.at + clip.dur && s.to > clip.at)) + .map(({ w, s }) => assertRegion({ + name: "posts", + segment: s.segment, + window: w, + frames: path.join(outDir, "chrome", `posts-${s.segment}-frames`), + x: g.x, y: g.y, width: g.width, height: g.height, + offset: s.from - shift, + frameCount: s.frames, + }, "window")); + }, +}); diff --git a/umtool/report-to-video/modules/registry.test.mjs b/umtool/report-to-video/modules/registry.test.mjs @@ -0,0 +1,118 @@ +// The module contract and registry (modules/contract.mjs, modules/index.mjs). +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { assertRegion, defineModule, MODULE_KINDS } from "./contract.mjs"; +import { + deckOverlays, MODULES, moduleById, moduleOfRegion, partsOf, placementOf, regionCaching, regionModule, +} from "./index.mjs"; +import { slotRect } from "./layout.mjs"; +import { chromeOverlayChain, chromeRegions, feedRegion, finaleRegions, postsRegions, stampRegion, threadsRegion } from "../build-video.mjs"; +import { deckGeometry, feedGeometry, postsGeometry, stampGeometry, threadsGeometry } from "../deck.mjs"; + +const RENDER = { + width: 1920, height: 1080, fps: 30, + palette: { bg: "#101219", fg: "#f2f0ea", muted: "#979caa", accent: "#e5534b", amber: "#ffc860" }, + chrome: { engine: "hyperframes", layout: "deck", deck: {} }, +}; + +test("defineModule refuses a definition the registry should not hold, by name", () => { + const base = { id: "x", version: 1, z: 1, kind: "overlay-whole", slot: "footer", title: "X", region: "x" }; + assert.equal(defineModule(base).id, "x"); + assert.ok(Object.isFrozen(defineModule(base))); + assert.throws(() => defineModule({ ...base, colour: 1 }), /colour is not a module key/); + assert.throws(() => defineModule({ ...base, id: "Bad Id" }), /id must be/); + assert.throws(() => defineModule({ ...base, kind: "overlay" }), /kind must be one of/); + assert.throws(() => defineModule({ ...base, slot: "middle" }), /slot must be/); + assert.throws(() => defineModule({ ...base, region: undefined }), /an overlay names its region/); + assert.throws(() => defineModule({ ...base, kind: "part", host: "shell" }), /a part's slot is inline/); + assert.throws(() => defineModule({ ...base, kind: "part", slot: "inline", host: "shell" }), /no region or page/); + assert.throws(() => defineModule({ ...base, provides: ["other.thing"] }), /not its own/); + assert.throws(() => defineModule({ ...base, validate: [] }), /validate must be a function/); + assert.deepEqual(MODULE_KINDS, ["overlay-whole", "overlay-window", "segment", "input", "post", "part"]); +}); + +test("assertRegion: a window has an offset and a frame count; a malformed region is refused", () => { + const r = { name: "deck", frames: "/f", x: 0, y: 890, width: 1920, height: 190 }; + assert.equal(assertRegion(r), r); + assert.throws(() => assertRegion({ ...r, x: "0" }), /x must be a number/); + assert.throws(() => assertRegion(r, "window"), /offset/); + assert.throws(() => assertRegion({ ...r, offset: 1 }, "window"), /frame count/); + assert.ok(assertRegion({ ...r, offset: 1, frameCount: 30 }, "window")); + assert.throws(() => assertRegion({ ...r, startNumber: 0 }), /startNumber/); +}); + +test("the registry: unique ids and regions, sorted by z, the deck's overlays in today's order", () => { + const ids = MODULES.map((m) => m.id); + assert.equal(new Set(ids).size, ids.length); + for (let i = 1; i < MODULES.length; i += 1) assert.ok(MODULES[i - 1].z <= MODULES[i].z); + // The order the build has always laid them in: the finale last. + assert.deepEqual(deckOverlays().map((m) => m.region), ["deck", "feed", "posts", "stamp", "stats", "fx", "threads", "flips", "finale"]); + assert.equal(moduleOfRegion("deck").id, "shell"); + assert.equal(regionModule("posts").id, "popup-posts"); + assert.throws(() => regionModule("nope"), /unknown chrome region: nope/); + assert.equal(moduleById("teaser").kind, "segment"); + for (const m of MODULES.filter((x) => x.host)) assert.ok(moduleById(m.host), `${m.id}'s host`); + assert.deepEqual(partsOf("feed"), []); +}); + +test("placement and caching come from the module's kind", () => { + for (const r of ["deck", "feed", "stamp", "stats", "fx", "threads", "flips"]) assert.equal(placementOf(r), "whole", r); + for (const r of ["posts", "finale"]) assert.equal(placementOf(r), "window", r); + assert.equal(placementOf("chart"), null); + assert.equal(placementOf("teaser"), null); + assert.deepEqual(regionCaching("deck"), { keyed: true, wholeCut: true }); + assert.deepEqual(regionCaching("posts"), { keyed: true, wholeCut: false }); + assert.deepEqual(regionCaching("teaser"), { keyed: true, wholeCut: false }); + assert.deepEqual(regionCaching("chart"), { keyed: false, wholeCut: false }); +}); + +test("the layout engine's slots are the deck geometry's rects", () => { + const feedRender = { ...RENDER, chrome: { ...RENDER.chrome, deck: { posts: { layout: "feed" } } } }; + assert.deepEqual(slotRect("footer", RENDER), deckGeometry(RENDER).deck); + assert.deepEqual(slotRect("footage", RENDER), deckGeometry(RENDER).footage); + assert.deepEqual(slotRect("footage", feedRender, { feed: true }), feedGeometry(feedRender).footage); + assert.deepEqual(slotRect("column", feedRender), feedGeometry(feedRender).column); + assert.deepEqual(slotRect("popup", RENDER), postsGeometry(RENDER)); + assert.deepEqual(slotRect("stamp", RENDER), stampGeometry(RENDER)); + const { cards: _c, ...side } = threadsGeometry(RENDER); + assert.deepEqual(slotRect("side", RENDER), side); + assert.deepEqual(slotRect("full", RENDER), { x: 0, y: 0, width: 1920, height: 1080 }); + assert.throws(() => slotRect("inline", RENDER), /not a slot/); +}); + +test("the build's region helpers are the modules' regions, shaped as they always were", () => { + const deck = chromeRegions(RENDER, "/o"); + assert.deepEqual(deck, [{ name: "deck", frames: "/o/chrome/deck-frames", ...deckGeometry(RENDER).deck }]); + assert.deepEqual(Object.keys(deck[0]), ["name", "frames", "x", "y", "width", "height"]); + const feedRender = { ...RENDER, chrome: { ...RENDER.chrome, deck: { posts: { layout: "feed" } } } }; + assert.deepEqual(feedRegion(feedRender, "/f"), { name: "feed", frames: "/f", ...feedGeometry(feedRender).column }); + assert.deepEqual(stampRegion(RENDER, "/s", { layout: "deck" }), { name: "stamp", frames: "/s", ...stampGeometry(RENDER) }); + assert.equal(threadsRegion(RENDER, "/t", "flips").name, "flips"); + const schedule = { + fps: 30, total: 20, + posts: [{ segment: "a", appear: 2, out: [5, 5.5], slot: 0 }, { segment: "b", appear: 9, out: [12, 12.5], slot: 0 }], + finale: { from: 15, to: 20 }, + }; + const posts = postsRegions(RENDER, "/o", schedule); + assert.deepEqual(posts.map((p) => [p.segment, p.offset, p.frameCount]), [["a", 2, 105], ["b", 9, 105]]); + assert.deepEqual(postsRegions(RENDER, "/o", schedule, { shift: 8, clip: { at: 8, dur: 2 } }).map((p) => [p.segment, p.offset]), [["b", 1]]); + const fin = finaleRegions(RENDER, "/o", schedule); + assert.deepEqual(fin.map((f) => [f.name, f.offset, f.frameCount, f.width]), [["finale", 15, 150, 1920]]); + assert.deepEqual(finaleRegions(RENDER, "/o", { ...schedule, finale: undefined }), []); +}); + +test("the overlay chain lays a module's region by its placement", () => { + const regions = [ + { name: "deck", frames: "/d", x: 0, y: 890, width: 1920, height: 190 }, + { name: "posts", frames: "/p", x: 1, y: 2, width: 3, height: 4, offset: 2.5, frameCount: 10 }, + ]; + const c = chromeOverlayChain({ fps: 30 }, regions, "[v]", 1); + assert.deepEqual(c.inputs.slice(0, 2), ["-reinit_filter", "0"]); + assert.ok(c.inputs.includes("-itsoffset")); + assert.match(c.chain, /overlay=x=0:y=890:format=yuv444:shortest=1\[hf0\]/); + assert.match(c.chain, /overlay=x=1:y=2:format=yuv444:eof_action=pass\[hf1\]/); + const legacy = chromeOverlayChain({ fps: 30 }, [{ name: "chart", frames: "/c", x: 0, y: 880, width: 1920, height: 200 }], "[v]", 1); + assert.equal(legacy.inputs[0], "-framerate"); + assert.doesNotMatch(legacy.chain, /format=rgba/); +}); diff --git a/umtool/report-to-video/modules/shell.mjs b/umtool/report-to-video/modules/shell.mjs @@ -0,0 +1,42 @@ +// THE SHELL (module `shell`, region `deck`): the deck's one page at the foot +// of the frame -- its panel and title, and the band its parts draw in: the +// subtitle (subtitle.mjs), the QR (qr.mjs), the rail (rail.mjs), the counter +// (counter.mjs) and the claim checks (claims.mjs) are parts of this page, so +// their frames are the shell's. chrome-deck.mjs writes the page; deck.mjs +// holds its arithmetic. +import path from "node:path"; + +import { deckGeometry, deckLayout } from "../deck.mjs"; +import { deckHtml } from "../chrome-deck.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "shell", + version: 1, + z: 10, + kind: "overlay-whole", + slot: "footer", + title: "Deck", + summary: "The panel at the foot of the frame: each clip's title, and the band the subtitle, QR, rail and counter draw in.", + region: "deck", + workers: "wide", + noun: "the deck's", + on: () => true, + async page(ctx) { + const { render, schedule } = ctx; + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + // With the schedule: a staggered marker band moves the QR down and may shrink it. + const lay = deckLayout(render, { schedule }); + const qrSrcs = {}; + if (lay.qr) { + const byUrl = await ctx.qrs(schedule.segments.map((s) => s.qrUrl), lay.qr.size); + for (const s of schedule.segments) if (s.qrUrl) qrSrcs[s.id] = byUrl.get(s.qrUrl); + } + return deckHtml(schedule, render, { fonts, qrSrcs, from: ctx.from, duration: ctx.duration }); + }, + regions(_schedule, { render, outDir, frames = null }) { + const { deck } = deckGeometry(render); + return [assertRegion({ name: "deck", frames: frames ?? path.join(outDir, "chrome", "deck-frames"), ...deck })]; + }, + frameKeys: { data: "deck-data", omit: ["init", "cues", "window", "total", "ids"] }, +}); diff --git a/umtool/report-to-video/modules/stamp.mjs b/umtool/report-to-video/modules/stamp.mjs @@ -0,0 +1,42 @@ +// THE STAMPS (module `stamp`, region `stamp`): each counted mark's word +// stamped over the footage as it lands (`render.chrome.factcheck.stamp`). +// chrome-stamp.mjs writes the page; factcheck.mjs `stampSchedule` times it. +import path from "node:path"; + +import { stampGeometry } from "../deck.mjs"; +import { stampHtml } from "../chrome-stamp.mjs"; +import { stampsDrawn } from "../factcheck.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "stamp", + version: 1, + z: 40, + kind: "overlay-whole", + slot: "stamp", + title: "Stamps", + summary: "Each counted mark's word, stamped over the footage as it lands.", + region: "stamp", + workers: "narrow", + noun: "the stamps'", + on: (schedule, render) => stampsDrawn(schedule, render), + check(schedule, render) { + if (!schedule.factcheck?.stamps?.length) return "the stamp region needs a schedule that stamps a claim (an entry with a `claim`)"; + if (!stampsDrawn(schedule, render)) { + return "the stamps are off (render.chrome.factcheck.stamp.show: false): there is no stamp region to compose"; + } + return null; + }, + async page(ctx) { + // The fact-check stamps (chrome-stamp.mjs): the deck's faces, no QR. + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + return stampHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration }); + }, + regions(schedule, { render, outDir, frames = null }) { + return [assertRegion({ + name: "stamp", frames: frames ?? path.join(outDir, "chrome", "stamp-frames"), + ...stampGeometry(render, { feed: schedule.layout === "feed" }), + })]; + }, + frameKeys: { data: "stamp-data", omit: ["init", "cues", "window", "total", "ids"] }, +}); diff --git a/umtool/report-to-video/modules/stats.mjs b/umtool/report-to-video/modules/stats.mjs @@ -0,0 +1,37 @@ +// THE STATS (module `stats`, region `stats`): a frame scan's running numbers +// over the clips that declare them, in a panel in the footage +// (`render.chrome.stats`, stats.mjs). chrome-stats.mjs writes the page. +import path from "node:path"; + +import { statsGeometry } from "../deck.mjs"; +import { statsHtml } from "../chrome-stats.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "stats", + version: 1, + z: 50, + kind: "overlay-whole", + slot: "panel", + title: "Stats", + summary: "A frame scan's running numbers over the clips that declare them.", + region: "stats", + workers: "narrow", + noun: "the stats region's", + configKey: "render.chrome.stats", + on: (schedule) => !!schedule?.stats?.clips?.length, + check: (schedule) => (!schedule.stats?.clips?.length + ? "the stats region needs a schedule with a clip that declares it (render.chrome.stats or a clip's stats, and frameScan.overlay points)" + : null), + async page(ctx) { + // The stats region (chrome-stats.mjs): the deck's faces, no QR. + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + return statsHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration }); + }, + regions(schedule, { render, outDir, frames = null }) { + return [assertRegion({ + name: "stats", frames: frames ?? path.join(outDir, "chrome", "stats-frames"), + ...statsGeometry(render, { feed: schedule.layout === "feed" }), + })]; + }, +}); diff --git a/umtool/report-to-video/modules/teaser.mjs b/umtool/report-to-video/modules/teaser.mjs @@ -0,0 +1,37 @@ +// THE TEASER (module `teaser`, a segment): a full-frame card of lines that pop +// in on the beat, inserted into the cut as a timeline entry of its own +// (`{ type: "teaser" }`, deck.mjs). chrome-teaser.mjs writes the page; the +// build encodes its frames into segments/<id>.mp4 (build-video's +// buildTeaserSegment). +import { teaserSeconds, validateTeaser } from "../deck.mjs"; +import { defineModule } from "./contract.mjs"; + +export default defineModule({ + id: "teaser", + version: 1, + z: 0, + kind: "segment", + slot: "full", + title: "Teaser", + summary: "A full-frame card of lines popping in on the beat, inserted as its own segment.", + region: "teaser", + workers: "wide", + noun: "the teaser's", + entry(manifest, segment) { + const teaser = (manifest.timeline ?? []).find((e) => e.id === segment && e.type === "teaser") ?? null; + if (!teaser) return null; + const errors = validateTeaser(teaser); + if (errors.length) throw new Error(`teaser ${teaser.id}: ${errors.join("; ")}`); + return teaser; + }, + seconds: (entry, D, fps) => teaserSeconds(entry, D, fps), + names: ({ preview, entry }) => ({ project: `teaser-${preview ? "preview-" : ""}${entry.id}`, stem: `teaser-${entry.id}` }), + async page(ctx) { + // A page module reached by a dynamic import, so nothing that imports this + // file -- umtool's preview helper, the build -- loads its face's URL + // unless a teaser is being composed (docs/quirks.md). + const { teaserHtml, TEASER_FONT_FILE, TEASER_FONT_ASSET } = await import("../chrome-teaser.mjs"); + await ctx.projectFile(TEASER_FONT_FILE, TEASER_FONT_ASSET); + return teaserHtml(ctx.entry, ctx.render, { font: TEASER_FONT_ASSET, transition: ctx.transition }); + }, +}); diff --git a/umtool/report-to-video/modules/threads.mjs b/umtool/report-to-video/modules/threads.mjs @@ -0,0 +1,40 @@ +// THE THREAD RAIL (module `threads`, region `threads`): the left panel beside +// the footage, a card per thread lit as its clips play (`render.chrome.threads`, +// threads.mjs). chrome-threads.mjs writes the page. +import path from "node:path"; + +import { threadsGeometry } from "../deck.mjs"; +import { threadsHtml } from "../chrome-threads.mjs"; +import { assertRegion, defineModule } from "./contract.mjs"; + +/** The side panel as an overlay region (the thread rail's and the flips'). */ +export function sideRegion(render, frames, name) { + const { cards: _c, ...box } = threadsGeometry(render); + return assertRegion({ name, frames, ...box }); +} + +export default defineModule({ + id: "threads", + version: 1, + z: 70, + kind: "overlay-whole", + slot: "side", + title: "Thread rail", + summary: "A card per thread beside the footage, lit as its clips play.", + region: "threads", + workers: "narrow", + noun: "the thread rail's", + configKey: "render.chrome.threads", + on: (schedule) => !!schedule?.threads?.threads?.length, + check: (schedule) => (!schedule.threads?.threads?.length + ? "the threads region needs a schedule with a thread rail (render.chrome.threads)" + : null), + async page(ctx) { + // The thread rail (chrome-threads.mjs): the deck's faces, no QR. + const fonts = await ctx.fonts({ regular: "DeckSans", bold: "DeckSansBold" }, { strict: true }); + return threadsHtml(ctx.schedule, ctx.render, { fonts, from: ctx.from, duration: ctx.duration }); + }, + regions(_schedule, { render, outDir, frames = null }) { + return [sideRegion(render, frames ?? path.join(outDir, "chrome", "threads-frames"), "threads")]; + }, +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -44,6 +44,8 @@ "./local-media": "./local-media.mjs", "./join-preview": "./join-preview.mjs", "./look": "./look.mjs", + "./modules": "./modules/index.mjs", + "./modules/*": "./modules/*.mjs", "./mute": "./mute.mjs", "./narration": "./narration.mjs", "./narration-review": "./narration-review.mjs",