Archilyzer · Source

archilyzer

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

commit 29c4146ff3a287fe93d0a667d1fa5beccf764728
parent 5aee9c97619ea2755efcd00b48a68cb0d11b0d90
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 26 Oct 2026 22:32:42 -0400

report-to-video: chrome frames reused by their keys -- a re-render captures only the frames no render on disk drew

The deck's and the stamps' pages are cue interpreters, so what a frame
draws is the page less its cue list plus every element's value at that
frame, computed here as GSAP draws it (its own eases, its CSS rounding):
frame-keys.mjs keys each frame so. compose-chrome assembles a layer whose
page changed from the frames on disk with the same key (its last render,
take --from's work-from-*), captures the rest in ONE frame-list render of
the page, and writes .frame-keys beside .key. Cue times sit on a 1/240 s
grid (deck.mjs cueTime) so a moved moment draws exactly what it drew;
moved by at most 4 ms against main (checked on the Huck cut's 1,539 deck
cues). Progress per layer goes to the chrome events and rebuild.ndjson.

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

Diffstat:
Mumtool/report-to-video/build-video.mjs | 55+++++++++++++++++++++++++++++++++++++------------------
Mumtool/report-to-video/chrome-deck.mjs | 10++++++----
Mumtool/report-to-video/chrome-deck.test.mjs | 7++++---
Mumtool/report-to-video/chrome-stamp.mjs | 10++++++----
Mumtool/report-to-video/claim-knobs.test.mjs | 4++--
Mumtool/report-to-video/compose-chrome.mjs | 144++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/deck-claims.test.mjs | 6+++++-
Mumtool/report-to-video/deck.mjs | 15+++++++++++++++
Mumtool/report-to-video/factcheck.test.mjs | 12+++++++-----
Aumtool/report-to-video/frame-keys.mjs | 237+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/frame-keys.test.mjs | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 667 insertions(+), 41 deletions(-)

diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -552,6 +552,7 @@ const HUMAN = { (e.total !== undefined ? `, ${Number(e.total).toFixed(3)}s` : "") + (e.duration !== undefined ? ` window ${e.from}s +${e.duration}s` : "") + (e.frames !== undefined ? `: ${e.frames} frame(s)` : "") + + (e.reused !== undefined && !e.cached ? `, ${e.reused} frame(s) reused, ${e.captured} captured` : "") + (e.seconds !== undefined ? ` in ${e.seconds}s` : "") + (e.key ? ` (key ${String(e.key).slice(0, 12)})` : "") + (e.base ? ` over ${e.base}` : ""), @@ -5058,6 +5059,14 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re */ async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null }) { const { composeChrome } = await import("./compose-chrome.mjs"); + // Each layer's outcome, said and logged (rebuild.ndjson): cached whole, + // frames reused, or rendered. + const layers = []; + const emitChrome = (fields) => { + EMIT("chrome", fields); + 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({ @@ -5072,8 +5081,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro `is ${want} (${(duration ?? schedule.total).toFixed(3)}s at ${render.fps} fps)`, ); } - EMIT("chrome", { - phase: r.cached ? "cached" : "render", + 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)), }); @@ -5094,8 +5104,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (f.frameCount !== want) { throw new Error(`the feed's sequence is ${f.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: f.cached ? "cached" : "render", region: "feed", + 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)), }); @@ -5121,8 +5132,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro `the overlay expects ${pr.frameCount} at ${pr.frames}`, ); } - EMIT("chrome", { - phase: p.cached ? "cached" : "render", region: "posts", segment: pr.segment, + 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)), }); @@ -5145,8 +5157,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (st.frameCount !== want) { throw new Error(`the stamps' sequence is ${st.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: st.cached ? "cached" : "render", region: "stamp", + 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)), }); @@ -5167,8 +5180,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (sr.frameCount !== want) { throw new Error(`the stats region's sequence is ${sr.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: sr.cached ? "cached" : "render", region: "stats", + 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)), }); @@ -5189,8 +5203,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (fr.frameCount !== want) { throw new Error(`the effects' sequence is ${fr.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: fr.cached ? "cached" : "render", region: "fx", + 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)), }); @@ -5210,8 +5225,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (th.frameCount !== want) { throw new Error(`the thread rail's sequence is ${th.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: th.cached ? "cached" : "render", region: "threads", + 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)), }); @@ -5230,8 +5246,9 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro if (fl.frameCount !== want) { throw new Error(`the flips panel's sequence is ${fl.frameCount} frames but the deck's is ${want}`); } - EMIT("chrome", { - phase: fl.cached ? "cached" : "render", region: "flips", + 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)), }); @@ -5252,14 +5269,16 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro 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}`); } - EMIT("chrome", { - phase: p.cached ? "cached" : "render", region: "finale", + 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 }); return { regions, outLabel: "[hfout]" }; } diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -38,7 +38,7 @@ import { fileURLToPath } from "node:url"; import { - claimsLayout, deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck, + claimsLayout, cueTime, cueTimeAfter, deckChoreography, deckLayout, deckMarkers, MARKER_LABEL_SIZE, MARKER_ROW, pageDuration, pipSegments, pipXs, resolveDeck, } from "./deck.mjs"; import { claimsCues, claimsMarkup } from "./chrome-claims.mjs"; import { resolveFactcheck, tallyCues, tallyFinals, tallyKey, tallyLabelOf, tallyOf, tallyPopIns, VERDICT_SHAPES } from "./factcheck.mjs"; @@ -185,7 +185,9 @@ export function deckCues(schedule, render) { // ---- events, unordered; froms are filled in below ---------------------- const ev = []; - const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); + // Cue times on the sub-frame grid (deck.mjs cueTime), durations to 4 places. + const fps = Number(schedule.fps ?? render.fps ?? 30); + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: cueTime(at, fps), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); const setSeg = (i, state, at, why) => { add(keyOf(i, "seg"), at, INSTANT, state.seg, "none", why); for (const p of PARTS) add(keyOf(i, p), at, INSTANT, state[p], "none", why); @@ -315,14 +317,14 @@ export function deckCues(schedule, render) { let { at, dur } = e; if (at < free) { const end = at + dur; - at = r4(free); + at = cueTimeAfter(free, fps); dur = r4(Math.max(INSTANT, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const p of Object.keys(e.to)) from[p] = cur[p]; Object.assign(cur, e.to); - freeAt.set(e.k, r4(at + dur)); + freeAt.set(e.k, at + dur); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why }); } return { init, cues, pips, slideY, choreography: ch, ...(markers.length ? { markers } : {}), ...(claims ? { claims } : {}) }; diff --git a/umtool/report-to-video/chrome-deck.test.mjs b/umtool/report-to-video/chrome-deck.test.mjs @@ -13,7 +13,7 @@ import test from "node:test"; import { fileURLToPath } from "node:url"; import { deckCues, deckHtml, GSAP_FILE, hostOf, mix, subtitleMarkup } from "./chrome-deck.mjs"; -import { deckChoreography, deckLayout } from "./deck.mjs"; +import { cueTime, deckChoreography, deckLayout } from "./deck.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -362,8 +362,9 @@ test("the fact-check tally is in the panel, so it slides with it; a cut without // The count steps as the stamp lands, and the page carries that cue. const { cues } = deckCues(stamped, RENDER); const step = cues.find((c) => c.k === "ty.CORROBORATED.n1"); - assert.equal(step.at, 18.78); - assert.ok(dataOf(html).cues.some((c) => c.k === "ty.CORROBORATED.n1" && c.at === 18.78)); + // (On the sub-frame cue grid, deck.mjs cueTime.) + assert.equal(step.at, cueTime(18.78, 30)); + assert.ok(dataOf(html).cues.some((c) => c.k === "ty.CORROBORATED.n1" && c.at === cueTime(18.78, 30))); // The title's column gives the tally its room. const narrowed = deckLayout(RENDER, { tally: ["CORROBORATED"] }); assert.ok(html.includes(`max-width: ${narrowed.text.width}px`)); diff --git a/umtool/report-to-video/chrome-stamp.mjs b/umtool/report-to-video/chrome-stamp.mjs @@ -11,7 +11,7 @@ // The timeline is cues, computed here, each stating its from -- a render is a // seek per frame, from parallel workers, in any order (chrome-deck.mjs says // why at length). The times are factcheck.mjs `stampSchedule`'s, untouched. -import { pageDuration, stampGeometry } from "./deck.mjs"; +import { cueTime, cueTimeAfter, pageDuration, stampGeometry } from "./deck.mjs"; import { mix, rgba } from "./chrome-deck.mjs"; import { drawnStamps, resolveFactcheck, STAMP_MOTION } from "./factcheck.mjs"; @@ -53,7 +53,9 @@ export function stampCues(schedule, render = null) { const m = STAMP_MOTION; const init = {}; const ev = []; - const add = (k, at, dur, to, ease, why) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); + // Cue times on the sub-frame grid (deck.mjs cueTime), durations to 4 places. + const fps = Number(schedule.fps ?? render?.fps ?? 30); + const add = (k, at, dur, to, ease, why) => ev.push({ k, at: cueTime(at, fps), dur: r4(Math.max(INSTANT, dur)), to, ease, why }); stamps.forEach((s, j) => { const why = `stamp ${s.claim}`; const rest = { autoAlpha: 1, scale: 1, rotation: P.rest }; @@ -90,14 +92,14 @@ export function stampCues(schedule, render = null) { const free = freeAt.get(e.k) ?? 0; if (at < free) { const end = at + dur; - at = r4(free); + at = cueTimeAfter(free, fps); dur = r4(Math.max(INSTANT, end - at)); } const cur = state[e.k] ?? (state[e.k] = {}); const from = {}; for (const p of Object.keys(e.to)) from[p] = cur[p]; Object.assign(cur, e.to); - freeAt.set(e.k, r4(at + dur)); + freeAt.set(e.k, at + dur); cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease, why: e.why }); } return { init, cues }; diff --git a/umtool/report-to-video/claim-knobs.test.mjs b/umtool/report-to-video/claim-knobs.test.mjs @@ -11,7 +11,7 @@ import { CLAIM_LIMITS, drawnStamps, normalizeClaim, resolveFactcheck, STAMP_MOTION, stampSchedule, stampsDrawn, tallyCues, tallyFinals, tallySteps, validateClaims, validateFactcheck, } from "./factcheck.mjs"; -import { deckSchedule, stampGeometry } from "./deck.mjs"; +import { cueTime, deckSchedule, stampGeometry } from "./deck.mjs"; import { deckHtml } from "./chrome-deck.mjs"; import { stampCues, stampHtml } from "./chrome-stamp.mjs"; @@ -168,7 +168,7 @@ test("stamp:false: counted in the tally, not drawn; a cut whose every claim is h assert.equal(drawnStamps(sched.factcheck.stamps).length, 1); const { cues } = stampCues(sched); assert.ok(cues.every((c) => /st0|fl0/.test(c.k))); - assert.ok(cues.some((c) => c.at === 9.72 && c.k === "st0"), "the drawn one is stamp 0"); + assert.ok(cues.some((c) => c.at === cueTime(9.72, 30) && c.k === "st0"), "the drawn one is stamp 0"); assert.equal(tallySteps(sched.factcheck.stamps).at(-1).count, 2); assert.equal(stampsDrawn(sched, RENDER), true); const none = { ...sched, factcheck: { stamps: [ST("a", "PARTLY", 5, { stamp: false })] } }; diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -31,7 +31,7 @@ // and the crossfade -- so the build writes the schedule and this reads it. // Recomputing it here would be a second implementation of segmentOffsets() and // would drift the first time the transition changed. -import { copyFile, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { copyFile, link, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { execFile, spawn } from "node:child_process"; import { promisify } from "node:util"; import path from "node:path"; @@ -40,7 +40,7 @@ import { ledgerTotals, dateKey } from "./ledger-totals.mjs"; import { selectVariant } from "./build-video.mjs"; import { ensureWriteDir } from "../lib/report/storage.mjs"; import { - chromeCacheKey, deckLayout, frameCount, hyperframesCommand, postWindows, resolveDeck, sha256, teaserSeconds, transitionOf, + chromeCacheKey, deckLayout, frameCount, pageDuration, hyperframesCommand, postWindows, resolveDeck, sha256, teaserSeconds, transitionOf, validateTeaser, } from "./deck.mjs"; import { deckHtml, GSAP_FILE } from "./chrome-deck.mjs"; @@ -53,6 +53,7 @@ import { flipsHtml } from "./chrome-flips.mjs"; import { statsHtml } from "./chrome-stats.mjs"; import { finaleHtml, finaleLayout } from "./chrome-finale.mjs"; import { fxGeometry } from "./deck.mjs"; +import { FRAME_KEY_REGIONS, frameKeys } from "./frame-keys.mjs"; const run = promisify(execFile); @@ -1054,9 +1055,9 @@ export async function composeChrome({ const hf = hyperframesCommand(process.env); let key = null; let frames = null; + const assets = []; if (keyed) { frames = frameCount(size.duration, rate); - const assets = []; for (const name of (await readdir(assetsDir)).sort()) { assets.push([name, sha256(await readFile(path.join(assetsDir, name)))]); } @@ -1092,11 +1093,28 @@ export async function composeChrome({ : path.join(base, "chrome", `${stem}.${format}`); const keyFile = path.join(target, ".key"); + // 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 && !preview && FRAME_KEY_REGIONS[region] + ? frameKeys({ html, region, assets, fps: rate, frames, version: hf.version }) + : null; if (keyed && sequence) { const onDisk = await readFile(keyFile, "utf8").then((s) => s.trim(), () => null); if (onDisk === key && (await framesOnDisk(target)) === frames) { + // Cached whole. A render from before frame keys gains them here, so the + // next change can reuse its frames. + if (fk && !(await readFile(path.join(target, FRAME_KEYS_FILE), "utf8").catch(() => null))) { + await writeFrameKeys(target, fk); + } return { ...result, frames: target, cached: true }; } + if (fk) { + const r = await reuseFrames({ + base, target, stem, fk, key, html, region, rate, hf, workers, quality, assetsDir, + }); + if (r) return { ...result, frames: target, ...r }; + } // Stale frames past the new count would be overlaid as the tail of the cut. await rm(target, { recursive: true, force: true }); } @@ -1118,9 +1136,127 @@ export async function composeChrome({ if (got !== frames) { throw new Error(`the ${region} render wrote ${got} frames to ${target}, expected ${frames} (${size.duration}s at ${rate} fps)`); } + if (fk) await writeFrameKeys(target, fk); await writeFile(keyFile, key + "\n", "utf8"); } - return { ...result, frames: target }; + return { ...result, frames: target, ...(fk ? { reused: 0, captured: frames } : {}) }; +} + +// ---- frame reuse (frame-keys.mjs) -------------------------------------------- + +/** Beside a sequence's `.key`: each frame's key, frame 1 on line 1. */ +export const FRAME_KEYS_FILE = ".frame-keys"; + +const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`; + +async function writeFrameKeys(dir, fk) { + const tmp = path.join(dir, `${FRAME_KEYS_FILE}.${process.pid}.tmp`); + await writeFile(tmp, fk.join("\n") + "\n", "utf8"); + await rename(tmp, path.join(dir, FRAME_KEYS_FILE)); +} + +/** + * Runs of a sorted list of cut frames (0-based): `[renderFrame, cutFrame, length]`, + * the render's frames in order, each run consecutive in the cut. + */ +export function frameRuns(list) { + const runs = []; + list.forEach((n, j) => { + const last = runs[runs.length - 1]; + if (last && last[1] + last[2] === n) last[2] += 1; + else runs.push([j, n, 1]); + }); + return runs; +} + +/** + * The page that renders only some of the cut's frames: its timeline is swapped, + * where the page registers it, for one that plays each run of `runs` + * (frameRuns') as a piece of the cut's timeline in turn -- the windowed + * render's own tween, once per run -- and the page declares their length. + * null when the page does not register its timeline the one way this knows. + */ +export function frameListHtml(html, region, runs, fps) { + const reg = `window.__timelines["${region}"] = tl;`; + const first = html.indexOf(reg); + if (first < 0 || html.indexOf(reg, first + 1) >= 0) return null; + const spec = FRAME_KEY_REGIONS[region]; + const dataTag = `<script id="${spec.data}" type="application/json">`; + if (html.indexOf(dataTag) < 0) return null; + const count = runs.reduce((n, r) => n + r[2], 0); + const helper = + `<script>window.__hfFrames = function (inner) {\n` + + ` const R = ${JSON.stringify(runs)}, fps = ${Number(fps)};\n` + + ` const tl = gsap.timeline({ paused: true });\n` + + ` for (const [j, n, len] of R) tl.add(inner.tweenFromTo(n / fps, (n + len) / fps, { duration: len / fps, ease: "none" }), j / fps);\n` + + ` return tl;\n` + + `};</script>\n `; + return html + .replace(reg, `window.__timelines["${region}"] = window.__hfFrames(tl);`) + .replace(dataTag, helper + dataTag) + .replace(/data-duration="[^"]*"/g, `data-duration="${pageDuration(count / fps, fps)}"`); +} + +/** + * A layer re-rendered by its frames: every frame whose key a render on disk + * has (this layer's last, or the ones `take --from` linked beside it, + * `work-from[-own]-<stem>-frames`) is that frame, hard-linked; the others are + * captured in ONE render of the frame-list page (each new key once) and the + * sequence is assembled beside, then swapped in with its `.frame-keys` and, + * last, its `.key`. null when nothing on disk has frame keys or nearly every + * frame is new (the whole render is the cheaper one then). + */ +async function reuseFrames({ base, target, stem, fk, key, html, region, rate, hf, workers, quality, assetsDir }) { + const chrome = path.join(base, "chrome"); + const candidates = [target, path.join(chrome, `work-from-${stem}-frames`), path.join(chrome, `work-from-own-${stem}-frames`)]; + const have = new Map(); + let sources = 0; + for (const dir of candidates) { + const keys = await readFile(path.join(dir, FRAME_KEYS_FILE), "utf8").then((t) => t.split("\n").filter(Boolean), () => null); + if (!keys || (await framesOnDisk(dir)) !== keys.length) continue; + sources += 1; + keys.forEach((k, i) => { if (!have.has(k)) have.set(k, path.join(dir, frameName(i + 1))); }); + } + if (!sources) return null; + const missing = []; + for (let i = 0; i < fk.length; i += 1) if (!have.has(fk[i])) missing.push(i); + if (missing.length > fk.length * 0.9) return null; + + // One capture per new key. + const seen = new Set(); + const capture = missing.filter((i) => (seen.has(fk[i]) ? false : (seen.add(fk[i]), true))); + const capDir = path.join(chrome, `work-capture-${stem}-frames`); + const capProj = path.join(chrome, `work-capture-${stem}`); + if (capture.length) { + const page = frameListHtml(html, region, frameRuns(capture), rate); + if (!page) return null; + await rm(capProj, { recursive: true, force: true }); + await mkdir(path.join(capProj, "assets"), { recursive: true }); + for (const name of await readdir(assetsDir)) await copyFile(path.join(assetsDir, name), path.join(capProj, "assets", name)); + await writeFile(path.join(capProj, "index.html"), page, "utf8"); + await writeFile(path.join(capProj, "hyperframes.json"), HF_JSON + "\n", "utf8"); + await rm(capDir, { recursive: true, force: true }); + await runRenderer(hf.cmd, [ + ...hf.args, "render", "--format", "png-sequence", "--quality", quality, "--fps", String(rate), + ...(workers != null ? ["-w", String(workers)] : []), "--no-browser-gpu", "--output", capDir, capProj, + ]); + const got = await framesOnDisk(capDir); + if (got !== capture.length) throw new Error(`the ${region} frame capture wrote ${got} frames to ${capDir}, expected ${capture.length}`); + capture.forEach((i, j) => have.set(fk[i], path.join(capDir, frameName(j + 1)))); + } + + const next = path.join(chrome, `work-next-${stem}-frames`); + await rm(next, { recursive: true, force: true }); + await mkdir(next, { recursive: true }); + for (let i = 0; i < fk.length; i += 1) await link(have.get(fk[i]), path.join(next, frameName(i + 1))); + await writeFrameKeys(next, fk); + await writeFile(path.join(next, ".key"), key + "\n", "utf8"); + const old = path.join(chrome, `work-old-${stem}-frames`); + await rm(old, { recursive: true, force: true }); + await rename(target, old).catch((e) => { if (e?.code !== "ENOENT") throw e; }); + await rename(next, target); + for (const d of [old, capDir, capProj, ...candidates.slice(1)]) await rm(d, { recursive: true, force: true }); + return { cached: false, reused: fk.length - missing.length, captured: capture.length, repeated: missing.length - capture.length }; } if (import.meta.url === `file://${process.argv[1]}`) { diff --git a/umtool/report-to-video/deck-claims.test.mjs b/umtool/report-to-video/deck-claims.test.mjs @@ -333,7 +333,11 @@ test("absent claims: the schedule, the deck's page and the finale's are byte-ide const BEFORE = { schedule: "3a6c6abc6f5d4c095333dbbbe7c85aef", - deck: "4966f5f6904d7c91e8c3bd64b16763b8", + // Re-pinned on lane/fast-rerender: the deck's cue times moved onto the + // sub-frame grid (deck.mjs CUE_GRID) and nothing else -- checked on the + // Huck cut's 1,539 deck cues against main: the same elements, values, + // eases and durations, every time within 4 ms. (Was 4966f5f6904d7c91e8c3bd64b16763b8.) + deck: "d56d6f45c667dea15c0fec5675dbcc95", finale: "e4cb165d4e3b816c0d648240cac91eb1", built: "c6a44e98fce846811cbf87d449e6b40d", }; diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -3073,6 +3073,21 @@ export function chromeCacheKey({ html, assets = [], fps, frames, version }) { return sha256(JSON.stringify({ v: 1, html: sha256(html), assets: sorted, fps, frames, version })); } +/** + * The sub-frame grid chrome cue times sit on: CUE_GRID steps a frame. A cue + * time is a segment's start (a whole frame) plus a choreography offset; on + * this grid, a cut whose earlier segments grew by m frames moves every later + * cue by exactly 8m steps, so a moved moment draws exactly what it drew -- + * which is what lets a frame of the old render stand for it (frame-keys.mjs). + * Rounded to 4 decimals instead, the same moment moved by m frames plus up to + * 0.05 ms, and a wipe or the marker in flight drew a hair elsewhere. + */ +export const CUE_GRID = 8; +/** A cue time on the grid (nearest step). */ +export const cueTime = (v, fps) => Math.round(v * fps * CUE_GRID) / (fps * CUE_GRID); +/** A cue time on the grid, never before `v` (a clamp to when an element is free). */ +export const cueTimeAfter = (v, fps) => Math.ceil(v * fps * CUE_GRID - 1e-6) / (fps * CUE_GRID); + /** Frames a render of `total` seconds at `fps` produces. */ export const frameCount = (total, fps) => Math.round(total * fps); diff --git a/umtool/report-to-video/factcheck.test.mjs b/umtool/report-to-video/factcheck.test.mjs @@ -20,6 +20,7 @@ import { import { deckGeometry, deckLayout, deckQrUrl, deckSchedule, DECK_DEFAULTS, estimateSchedule, feedGeometry, stampGeometry, validateChrome, + cueTime, } from "./deck.mjs"; import { deckCues, deckHtml } from "./chrome-deck.mjs"; import { STAMP_POSE, stampCues, stampHtml } from "./chrome-stamp.mjs"; @@ -286,20 +287,20 @@ test("tally.showAt first: a cell is hidden until its first stamp lands, pops in // Its one appearance: the pop, at the second its first stamp lands, and nothing hides it again. const own = cues.filter((c) => c.k === k); assert.equal(own.length, 1, `${k}: ${JSON.stringify(own)}`); - assert.equal(own[0].at, firstLanding(v)); + assert.equal(own[0].at, cueTime(firstLanding(v), 30)); assert.deepEqual(own[0].from, { autoAlpha: 0, scale: TALLY_POP.from }); assert.deepEqual(own[0].to, { autoAlpha: 1, scale: 1 }); assert.equal(own[0].dur, TALLY_POP.seconds); assert.equal(own[0].ease, TALLY_POP.ease); // It arrives reading its first count, and the flash fires with it. const n1 = cues.filter((c) => c.k === `${k}.n1`); - assert.equal(n1[0].at, firstLanding(v)); + assert.equal(n1[0].at, cueTime(firstLanding(v), 30)); assert.deepEqual(n1[0].to, { yPercent: 0, autoAlpha: 1 }); - assert.ok(cues.some((c) => c.k === `${k}.flash` && c.at === firstLanding(v) && c.to.opacity === 1)); + assert.ok(cues.some((c) => c.k === `${k}.flash` && c.at === cueTime(firstLanding(v), 30) && c.to.opacity === 1)); assert.ok(!cues.some((c) => c.k === `${k}.n0`), "the 0 is never rolled"); } // PARTLY's second step rolls as ever: 1 out, 2 in, at its landing. - const second = stamps.filter((x) => x.verdict === "PARTLY").map((x) => x.landed).sort((a, b) => a - b)[1]; + const second = cueTime(stamps.filter((x) => x.verdict === "PARTLY").map((x) => x.landed).sort((a, b) => a - b)[1], 30); assert.ok(cues.some((c) => c.k === "ty.PARTLY.n1" && c.at === second && c.to.autoAlpha === 0)); assert.ok(cues.some((c) => c.k === "ty.PARTLY.n2" && c.at === second && c.to.autoAlpha === 1)); // Every cue still states the from the one before it left. @@ -348,7 +349,8 @@ test("stampCues: each stamp slams in to land at its `landed`, flashes, and leave near(leave.dur, 0.5, "over the dissolve"); assert.deepEqual(leave.from, { autoAlpha: 1, scale: 1 }); near(of("fl0")[0].at, 16.28, "flash at landing"); - near(of("fl0")[1].at, 16.28 + STAMP_MOTION.flashUp, "flash down"); + // Cue times sit on the sub-frame grid (deck.mjs cueTime): within half a step. + assert.ok(Math.abs(of("fl0")[1].at - (16.28 + STAMP_MOTION.flashUp)) <= 1 / 480 + 1e-9, "flash down"); assert.equal(cues.filter((c) => c.k.startsWith("st")).length, 6); }); diff --git a/umtool/report-to-video/frame-keys.mjs b/umtool/report-to-video/frame-keys.mjs @@ -0,0 +1,237 @@ +// CHROME FRAME KEYS: what each frame of a cue-driven chrome page draws, as a +// key, computed without a browser -- so a re-render captures only the frames +// whose key is new and takes every other from a render already on disk. +// +// The deck and the fact-check stamps are each ONE page whose script is a dumb +// interpreter of a cue list (chrome-deck.mjs explains why): `init` states +// every element's properties at t = 0, and every cue is a GSAP fromTo whose +// FROM is stated -- the value the cue before it on that element left. So what +// a frame at time t draws is a pure function of +// +// - the page itself, less the cue list (its markup, styles, fonts, assets: +// the STATIC part), and +// - each element's property values at t: init's, the last finished cue's +// `to`, or a running cue's value at its progress. +// +// A frame's key hashes both. The running values are computed the way GSAP +// renders them: its own ease functions (the vendored gsap.min.js, run in a +// sandbox), `from + (to - from) * ease(progress)`, rounded as its CSS plugin +// rounds (four decimals) -- so two frames with one key set the very same CSS. +// Times in the key are the cue's OWN (t - at), never the cut's: a moment the +// cut moved (an insert, a longer intro) keys as it did, because the cue +// times sit on the sub-frame grid (deck.mjs cueTime) and move exactly. +// +// The static part leaves out what only times the page or reaches a preview: +// the cue list and init (keyed per frame), the window (only ever the whole +// cut's [0, total]: a real window is refused), the cut's total and +// the ids list (preview messages), and every `data-duration` (each the whole +// page's; checked). Anything else in the page's data stays in. +// +// Refused -- `null`, and the layer is rendered whole as before -- when the +// page is not one this models: no data script, a `data-duration` that is not +// the page's, a window, a cue whose FROM is not what its element holds, two +// cues running on one property at once, or a property value that is neither +// a number nor a string. Conservative by construction: a frame is reused +// only when everything this knows of it is the same. +// +// Plain node; every path is a parameter. + +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import vm from "node:vm"; + +import { GSAP_FILE } from "./chrome-deck.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"] }, +}); + +let gsapEase = null; +/** GSAP's own ease, by name (the vendored file, in a sandbox, once). */ +export function easeOf(name) { + if (!gsapEase) { + const sandbox = { console, setTimeout, clearTimeout }; + sandbox.self = sandbox; + vm.createContext(sandbox); + vm.runInContext(readFileSync(GSAP_FILE, "utf8"), sandbox, { filename: "gsap.min.js" }); + const g = sandbox.window?.gsap ?? sandbox.gsap; + if (!g?.parseEase) throw new Error("frame keys: the vendored GSAP did not load"); + const cache = new Map(); + gsapEase = (n) => { + if (!cache.has(n)) cache.set(n, g.parseEase(n)); + return cache.get(n); + }; + } + const f = gsapEase(name); + if (typeof f !== "function") throw new Error(`frame keys: no ease ${name}`); + return f; +} + +/** GSAP's CSS rounding (CSSPlugin: four decimals). */ +const gsapRound = (v) => Math.round(v * 10000) / 10000; + +const sha1 = (s) => createHash("sha1").update(s).digest(); + +/** The page's data script: its JSON, and the page with that JSON cut out. */ +function splitData(html, id) { + const open = `<script id="${id}" type="application/json">`; + const at = html.indexOf(open); + if (at < 0 || html.indexOf(open, at + 1) >= 0) return null; + const from = at + open.length; + const to = html.indexOf("</script>", from); + if (to < 0) return null; + let data; + try { + data = JSON.parse(html.slice(from, to)); + } catch { + return null; + } + return { data, before: html.slice(0, from), after: html.slice(to) }; +} + +/** + * The static part's key: the page less what is keyed per frame, the assets' + * hashes, the frame rate and the renderer. null when the page is not modelled. + */ +export function staticKey({ html, region, assets = [], fps, version, frames = null }) { + const spec = FRAME_KEY_REGIONS[region]; + if (!spec) return null; + const parts = splitData(html, spec.data); + if (!parts) return null; + const { data } = parts; + // A window is refused -- but not the whole cut written as one (a total off + // the 4-decimal grid makes deckHtml "window" [0, r4(total)]: the identity). + if (data.window && !(data.window.from === 0 && frames != null && Math.abs(data.window.dur - frames / fps) < 1 / fps)) return null; + if (!data.init || !Array.isArray(data.cues)) return null; + // Every data-duration is the page's own (the root and its one clip). + const durs = [...html.matchAll(/data-duration="([^"]*)"/g)].map((m) => m[1]); + if (!durs.length || durs.some((d) => d !== durs[0])) return null; + const starts = [...html.matchAll(/data-start="([^"]*)"/g)].map((m) => m[1]); + if (starts.some((s) => s !== "0")) return null; + const rest = Object.fromEntries(Object.entries(data).filter(([k]) => !spec.omit.includes(k))); + const page = (parts.before + JSON.stringify(rest) + parts.after).replace(/data-duration="[^"]*"/g, 'data-duration=""'); + const sorted = [...assets].map(([n, h]) => [String(n), String(h)]).sort((x, y) => x[0].localeCompare(y[0])); + return createHash("sha256") + .update(JSON.stringify({ v: FRAME_KEY_VERSION, region, page, assets: sorted, fps, version })) + .digest("hex"); +} + +const repr = (v) => (typeof v === "number" ? `n${gsapRound(v)}` : `s${JSON.stringify(v)}`); + +/** + * Every frame's key, `frames` frames at `fps` (frame n at n / fps), or null + * when the page is not modelled (see the top of the file). + * + * @returns {string[] | null} hex keys, frame 1 first + */ +export function frameKeys({ html, region, assets = [], fps, frames, version }) { + const sk = staticKey({ html, region, assets, fps, version, frames }); + if (!sk) return null; + const { data } = splitData(html, FRAME_KEY_REGIONS[region].data); + const init = data.init; + const cues = data.cues; + + // Slots: one per (element, property), each with its cues in time order. + const slots = new Map(); + const slot = (k, p) => { + const id = `${k}\u0000${p}`; + let s = slots.get(id); + if (!s) { + s = { id, k, p, initial: init[k] && p in init[k] ? init[k][p] : undefined, cues: [] }; + slots.set(id, s); + } + return s; + }; + for (const [k, props] of Object.entries(init)) for (const p of Object.keys(props)) slot(k, p); + cues.forEach((c, n) => { + if (!c || typeof c.k !== "string" || !(c.dur > 0) || !Number.isFinite(c.at)) throw new Error(`frame keys: cue ${n} is malformed`); + for (const p of Object.keys(c.to ?? {})) slot(c.k, p).cues.push({ ...c, n }); + }); + + // The model's checks: every FROM is what its element holds, no two cues + // run on one property at once, every value a number or a string. + const okValue = (v) => typeof v === "number" || typeof v === "string" || v === undefined; + for (const s of slots.values()) { + s.cues.sort((x, y) => x.at - y.at || x.n - y.n); + let held = s.initial; + let freeAt = -Infinity; + for (const c of s.cues) { + const from = c.from?.[s.p]; + const to = c.to[s.p]; + if (!okValue(from) || !okValue(to) || !okValue(held)) return null; + if (from !== held && !(from === undefined && held === undefined)) return null; + if (c.at < freeAt - 1e-9) return null; + held = to; + freeAt = c.at + c.dur; + } + } + + // The value of a slot at time t, as GSAP draws it. + const valueAt = (s, t) => { + let cur = null; + for (const c of s.cues) { + if (c.at <= t + 1e-9) cur = c; + else break; + } + if (!cur) return s.initial === undefined ? "u" : `i${repr(s.initial)}`; + const from = cur.from?.[s.p]; + const to = cur.to[s.p]; + const end = cur.at + cur.dur; + if (t >= end - 1e-9) return `e${repr(to)}`; + const u = Math.max(0, (t - cur.at) / cur.dur); + if (typeof from === "number" && typeof to === "number") { + return `r${gsapRound(from + (to - from) * easeOf(cur.ease)(u))}`; + } + // A string in flight: the cue and its own clock, to the microsecond. + return `x${JSON.stringify([from, to, cur.ease, cur.dur])}@${(t - cur.at).toFixed(6)}`; + }; + + // The state's hash: XOR over the slots of each slot's (id, value) hash, + // updated only where a value moves. Each slot's changes come from its own + // cue boundaries (a step) or a running cue (every frame). + const acc = Buffer.alloc(20); + const xor = (b) => { + for (let i = 0; i < 20; i += 1) acc[i] ^= b[i]; + }; + const cur = new Map(); + for (const s of slots.values()) { + const v = valueAt(s, 0); + cur.set(s.id, v); + xor(sha1(`${s.id}\u0001${v}`)); + } + // Per frame, the slots that may move: those with a cue starting by it or running at it. + const frameOf = (t) => Math.ceil(t * fps - 1e-6); + const touch = new Map(); // frame -> slots + const push = (f, s) => { + if (f < 0 || f >= frames) return; + let l = touch.get(f); + if (!l) touch.set(f, (l = new Set())); + l.add(s); + }; + for (const s of slots.values()) { + for (const c of s.cues) { + const f0 = Math.max(0, frameOf(c.at)); + const f1 = Math.min(frames - 1, frameOf(c.at + c.dur)); + for (let f = f0; f <= f1; f += 1) push(f, s); + } + } + const out = new Array(frames); + for (let f = 0; f < frames; f += 1) { + const t = f / fps; + for (const s of touch.get(f) ?? []) { + const v = valueAt(s, t); + const was = cur.get(s.id); + if (v === was) continue; + xor(sha1(`${s.id}\u0001${was}`)); + xor(sha1(`${s.id}\u0001${v}`)); + cur.set(s.id, v); + } + out[f] = createHash("sha1").update(sk).update(acc).digest("hex"); + } + return out; +} diff --git a/umtool/report-to-video/frame-keys.test.mjs b/umtool/report-to-video/frame-keys.test.mjs @@ -0,0 +1,208 @@ +// Chrome frame keys (frame-keys.mjs) and compose-chrome's frame reuse: a +// frame's key is the page less its cue list plus every element's value at +// that frame, as GSAP draws it; a cut that moved keys its moved frames as it +// did; a changed value changes exactly the frames it shows in; a page this +// does not model has no keys. Then compose-chrome with the renderer stubbed: +// a re-render after a shift captures only the new keys -- in one frame-list +// render -- and assembles the rest from the old frames. +// +// Run with: node --test umtool/report-to-video/frame-keys.test.mjs +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { deckHtml } from "./chrome-deck.mjs"; +import { easeOf, frameKeys, staticKey } from "./frame-keys.mjs"; +import { stampHtml } from "./chrome-stamp.mjs"; + +const RENDER = { + width: 1920, height: 1080, fps: 30, transition: 0.5, + palette: { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }, + chrome: { engine: "hyperframes", layout: "deck", deck: {} }, +}; +const FONTS = { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf" }; + +/** The chrome-deck fixture, its opening card `grow` seconds longer. */ +function schedule(grow = 0, titles = {}) { + const seg = (id, type, start, duration, extra = {}) => ({ + id, type, start, duration, end: start + duration, + title: titles[id] ?? "", subtitle: "", qrUrl: null, hideDeck: false, ...extra, + }); + const g = grow; + return { + version: 1, kind: "deck", estimated: true, fps: 30, transition: 0.5, total: 40 + g, multiChannel: false, + segments: [ + seg("t00", "card", 0, 5 + g, { title: "Opening", subtitle: "a card", hideDeck: true }), + seg("c01", "clip", 4.5 + g, 10, { title: titles.c01 ?? "He said", subtitle: "Ferret Rescue · Sep 5, 2024" }), + seg("c02", "clip", 14 + g, 8, { title: titles.c02 ?? "A sanctuary", subtitle: "Ferret Rescue · Sep 5, 2024" }), + seg("c03", "clip", 21.5 + g, 13, { subtitle: "Untitled source · Sep 29, 2024" }), + seg("end", "card", 34 + g, 6, { title: "Close", subtitle: "", hideDeck: true }), + ], + }; +} +const keysOf = (s, render = RENDER) => frameKeys({ + html: deckHtml(s, render, { fonts: FONTS }), region: "deck", fps: 30, frames: Math.round(s.total * 30), version: "v", +}); + +test("easeOf: GSAP's own eases", () => { + assert.equal(easeOf("none")(0.3), 0.3); + assert.ok(Math.abs(easeOf("power1.out")(0.5) - 0.75) < 1e-12); + assert.ok(easeOf("back.out(2.2)")(0.6) > 1, "an overshoot"); +}); + +test("frame keys: the moved frames of a longer opening key as they did", () => { + const A = keysOf(schedule(0)); + const B = keysOf(schedule(1 / 3)); // 10 frames longer + assert.equal(A.length, 1200); + assert.equal(B.length, 1210); + // From the end of the first handover on (6 s), every frame is the old one 10 frames on. + let same = 0; + for (let n = 180; n < A.length; n += 1) if (B[n + 10] === A[n]) same += 1; + assert.equal(same, A.length - 180); + // The opening itself is the card's, hidden deck; while it is longer nothing moves either. + assert.equal(new Set(A.slice(0, 100)).size, 1, "a still deck keys as one frame"); + // Frames that differ are not the same key by accident. + assert.notEqual(A[400], A[700]); +}); + +test("frame keys: a changed title changes every frame (it is in the page); a changed value only where it shows", () => { + const A = keysOf(schedule(0)); + const T = keysOf(schedule(0, { c02: "Another sanctuary" })); + assert.ok(A.every((k, n) => k !== T[n]), "the page's text is part of every frame's key"); + // The tally steps at its stamp's landing: frames before it are the same, after it not. + const stamped = (landed) => { + const s = schedule(0); + return { + ...s, + segments: s.segments.map((x) => (x.id === "c02" ? { ...x, claim: { id: "k1", verdict: "CORROBORATED" } } : x)), + factcheck: { stamps: [{ claim: "k1", verdict: "CORROBORATED", segment: "c02", at: landed - 0.3, landed, out: [21.5, 22] }] }, + }; + }; + const P = keysOf(stamped(18)); + const Q = keysOf(stamped(19)); + const differ = P.map((k, n) => (k !== Q[n] ? n : null)).filter((n) => n != null); + assert.ok(differ.length > 0); + assert.ok(differ[0] >= 18 * 30 - 1, `nothing differs before the earlier landing (first at ${differ[0]})`); + assert.ok(differ.at(-1) <= 20 * 30, `the counts agree again once both have landed (last at ${differ.at(-1)})`); +}); + +test("frame keys: refused for a page this does not model", () => { + const s = schedule(0); + // A window. + assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS, from: 5, duration: 10 }), region: "deck", fps: 30, frames: 300, version: "v" }), null); + // A region it does not know. + assert.equal(frameKeys({ html: deckHtml(s, RENDER, { fonts: FONTS }), region: "feed", fps: 30, frames: 1200, version: "v" }), null); + // A cue whose from is not what its element holds. + const html = deckHtml(s, RENDER, { fonts: FONTS }); + const broken = html.replace(/"from":\{"xPercent":0\}/, '"from":{"xPercent":7}'); + assert.notEqual(broken, html); + assert.equal(frameKeys({ html: broken, region: "deck", fps: 30, frames: 1200, version: "v" }), null); + // The assets, the frame rate and the renderer are in the key. + const k = (o) => staticKey({ html, region: "deck", assets: [["a.png", "1"]], fps: 30, version: "v", ...o }); + assert.notEqual(k({ assets: [["a.png", "2"]] }), k({})); + assert.notEqual(k({ version: "w" }), k({})); + assert.notEqual(k({ fps: 25 }), k({})); +}); + +// ---- compose-chrome's frame reuse, the renderer stubbed -------------------------- + +const STUB = `#!/usr/bin/env node +// A renderer that writes, for each frame, the cut frame it shows and the page's cue list's hash. +import { createHash } from "node:crypto"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +const a = process.argv.slice(2); +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const data = /<script id="[a-z]+-data" type="application\\/json">([\\s\\S]*?)<\\/script>/.exec(html)[1]; +const tag = createHash("md5").update(JSON.stringify(JSON.parse(data).cues)).digest("hex").slice(0, 8); +const runs = /const R = (\\[[^;]*\\]), fps/.exec(html); +const R = runs ? JSON.parse(runs[1]) : null; +const n = Math.round(dur * fps); +mkdirSync(out, { recursive: true }); +for (let j = 0; j < n; j += 1) { + let cut = j; + if (R) { const r = R.find(([j0, , len]) => j >= j0 && j < j0 + len); cut = r[1] + (j - r[0]); } + writeFileSync(out + "/frame_" + String(j + 1).padStart(6, "0") + ".png", tag + ":" + cut); +} +writeFileSync(out + "/../renders.log", (R ? "list " : "whole ") + n + "\\n", { flag: "a" }); +`; + +test("compose-chrome: a shifted stamp layer captures only its new keys, in one render, and reuses the rest", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "frame-reuse-")); + const env = process.env.HYPERFRAMES_BIN; + try { + const stub = path.join(dir, "hf-stub.mjs"); + writeFileSync(stub, STUB); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + const font = path.join(dir, "face.ttf"); + writeFileSync(font, "face"); + const render = { ...RENDER, fontRegular: font, fontBold: font }; + const mp = path.join(dir, "video.manifest.json"); + writeFileSync(mp, JSON.stringify({ slug: "f", render, timeline: [] })); + const out = path.join(dir, "out", "sourced"); + mkdirSync(out, { recursive: true }); + const stamps = (g, late = 0) => { + const s = schedule(g); + return { + ...s, + segments: s.segments.map((x) => (x.id === "c02" ? { ...x, claim: { id: "k1", verdict: "PARTLY" } } : x.id === "c03" ? { ...x, claim: { id: "k2", verdict: "CONTRADICTED" } } : x)), + factcheck: { + stamps: [ + { claim: "k1", verdict: "PARTLY", segment: "c02", at: 16 + g, landed: 16.28 + g, out: [21.5 + g, 22 + g] }, + { claim: "k2", verdict: "CONTRADICTED", segment: "c03", at: 25 + g + late, landed: 25.28 + g + late, out: [34 + g, 34.5 + g] }, + ], + }, + }; + }; + const { composeChrome, FRAME_KEYS_FILE } = await import("./compose-chrome.mjs"); + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(stamps(0))); + const first = await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 }); + assert.equal(first.cached, false); + const framesDir = first.frames; + const keys0 = readFileSync(path.join(framesDir, FRAME_KEYS_FILE), "utf8").trim().split("\n"); + const oldTag = readFileSync(path.join(framesDir, "frame_000001.png"), "utf8").split(":")[0]; + assert.equal(keys0.length, 1200); + + // Ten frames longer at the top, and the second stamp landing while the + // first is still up: only the frames with both on screen -- a state no + // frame of the old render drew -- are captured. + writeFileSync(path.join(out, "schedule.json"), JSON.stringify(stamps(1 / 3, -5))); + const second = await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 }); + assert.equal(second.cached, false); + assert.equal(second.frameCount, 1210); + assert.ok(second.reused >= 1100, `${second.reused} reused`); + assert.ok(second.captured > 0 && second.captured <= 60, `${second.captured} captured`); + const keys1 = readFileSync(path.join(framesDir, FRAME_KEYS_FILE), "utf8").trim().split("\n"); + assert.equal(keys1.length, 1210); + const files = readdirSync(framesDir).filter((f) => /^frame_\d+\.png$/.test(f)).sort(); + assert.equal(files.length, 1210); + // Each frame is the old render's frame of the same key, or a fresh capture of this very frame. + files.forEach((f, i) => { + const [tag, cut] = readFileSync(path.join(framesDir, f), "utf8").split(":"); + if (tag === oldTag) assert.equal(keys0[Number(cut)], keys1[i], `frame ${i + 1} reuses old frame ${Number(cut) + 1}, of its key`); + else assert.equal(keys1[Number(cut)], keys1[i], `frame ${i + 1} is the capture of a frame of its key`); + }); + const log = readFileSync(path.join(out, "chrome", "renders.log"), "utf8").trim().split("\n"); + assert.deepEqual(log[0], "whole 1200"); + assert.match(log[1], /^list \d+$/, "one frame-list render"); + assert.equal(log.length, 2); + // Its scratch is gone; the .key is this page's: the third run is cached whole. + assert.ok(!readdirSync(path.join(out, "chrome")).some((n) => n.startsWith("work-"))); + assert.equal((await composeChrome({ manifestPath: mp, region: "stamp", doRender: true, fps: 30 })).cached, true); + } finally { + if (env === undefined) delete process.env.HYPERFRAMES_BIN; + else process.env.HYPERFRAMES_BIN = env; + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("stampHtml registers its timeline the one way the frame list replaces", () => { + const html = stampHtml({ total: 10, fps: 30, factcheck: { stamps: [{ claim: "a", verdict: "PARTLY", at: 2, landed: 2.28, out: [5, 5.5] }] } }, RENDER, {}); + assert.equal(html.split('window.__timelines["stamp"] = tl;').length, 2); + assert.equal(deckHtml(schedule(0), RENDER, { fonts: FONTS }).split('window.__timelines["deck"] = tl;').length, 2); +});