Archilyzer · Source

archilyzer

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

commit 3e6b3b17637553abb6e5ed2155ca7098798f7df9
parent e8bab6bc627a1bca591de9e4f862f75607244410
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 01:51:01 -0400

umtool: a frame scan's supercut is ranked into a length budget and wears a stats overlay — frames-cut ranks the events (rankOf/compareRank: scoops — the tournament won, big pots, all-ins won or doubled, double-ups, knockouts — then milestones — the bust, the final table, players-left marks — then swings, plain pots, level-ups last; confirmed before unconfirmed) and takes them while the merged, sentence-widened windows fit `target` seconds (default 240; a plain pot or level-up gets a short window), keeping each clip's frameScan.overlay points; `umtool new … --seed frames [--target S]` turns on the deck with the new `stats` chrome region (render.chrome.stats {position, fields, name}; a clip's `stats: false`/`true`), its QR off without --site-origin, and each subtitle the event's own words. The region: stats.mjs (validation, which clips declare it, statsSchedule into the cut's clock, step-held between points), chrome-stats.mjs (the page, one block per state, the palette's roles), deck.mjs statsGeometry and schedule `stats`, compose-chrome `--region stats`, the build lays it after the stamps, the lint and the build refuse bad `stats` keys, and verify-build fails on a declared clip missing from the schedule or a missing/short stats-frames sequence

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

Diffstat:
Mumtool/bin/umtool.mjs | 10++++++----
Mumtool/docs/cli.md | 13++++++++++++-
Mumtool/lib/projects/scaffold.mjs | 32+++++++++++++++++++++-----------
Mumtool/lib/scaffold-frames.test.mjs | 15++++++++++++++-
Mumtool/report-to-video/README.md | 41+++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 42+++++++++++++++++++++++++++++++++++++-----
Aumtool/report-to-video/chrome-stats.mjs | 274+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/compose-chrome.mjs | 22++++++++++++++++++----
Mumtool/report-to-video/deck.mjs | 46++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/frames-cut.mjs | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/report-to-video/frames-cut.test.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/report-to-video/lint.mjs | 8++++++--
Aumtool/report-to-video/stats.mjs | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/stats.test.mjs | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/verify-build.mjs | 31+++++++++++++++++++++++++++++--
15 files changed, 1140 insertions(+), 73 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -33,7 +33,7 @@ // --deck adds the on-screen deck to a cut with none before the flips // umtool index [--rebuild] [--prune] [--since MS] [--json] // umtool new <slug> [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>] -// [--site-origin URL] [--seed chapters|frames] [--brand archilyzer-media] +// [--site-origin URL] [--seed chapters|frames [--target S]] [--brand archilyzer-media] // umtool doctor [--json] exit 1 if the report pipeline is missing a tool // or the media root is set and not there // umtool storage [move-out|move-back <project>|--all] [--dry-run] [--json] @@ -692,8 +692,9 @@ function usage() { " --deck adds a step before the flips: the minimal on-screen deck on a cut with none", " umtool index [--rebuild] [--prune] [--since MS] [--json]", " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters|frames]", - " --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — a clip", - " around each event, the running stats as each clip's subtitle and the frameScan overlay block", + " --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — the events", + " ranked (scoops, milestones, swings, pots, level-ups) into --target <seconds> (default 240), the", + " deck on with the stats region drawing frameScan.overlay over each clip", " [--brand archilyzer-media] render.brand: the report-to-video brand preset", " umtool doctor [--json] exit 1 if the report pipeline is missing a tool", " or the media root is set and not there; the roots, and a leftover old cache", @@ -1089,7 +1090,7 @@ async function cmdNew() { die( "usage: umtool new <slug> [--kind report-video] [--title T]\n" + " [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" + - " [--site-origin <url>] [--seed chapters|frames] [--brand archilyzer-media]", + " [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]", ); } const kind = val("--kind") ?? "report-video"; @@ -1105,6 +1106,7 @@ async function cmdNew() { siteOrigin: val("--site-origin") ?? null, seed: val("--seed") ?? null, brand: val("--brand") ?? null, + ...(val("--target") != null ? { target: Number(val("--target")) } : {}), }); } catch (e) { die(e?.message ?? String(e)); diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -25,7 +25,7 @@ Inbox cannot disagree about what is wrong with one. | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | | `index [--rebuild] [--prune] [--since MS] [--json]` | the cache | -| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters]` | scaffold | +| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` | scaffold | | `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there | | `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch | | `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building | @@ -165,3 +165,14 @@ id, `enabled: false` drops), and writes one unlocked clip per chapter — lists them as "seeded from digest chapters — review each". It refuses when the video directory or the digest is missing. Local media files are not a source: the manifest model is archive ids with cue files. + +**`--seed frames`** (release 30; ranked since release 31) reads the video's +`frame-scan.<profile>.json` (`pnpm ops frame-scan`) through `frames-cut.mjs`: the +derived events RANKED — scoops (a big pot, an all-in won or doubled, a +double-up, a knockout), then milestones (the final table, players-left marks, +the bust), swings, plain pots, level-ups last; confirmed before unconfirmed — +and taken while the merged, sentence-widened windows fit `--target` seconds +(default 240). The deck is turned on with the `stats` region drawing +`frameScan.overlay` over each clip (its QR off without `--site-origin`), and +each subtitle is the event's own words. It refuses an existing directory: a +re-seed is a new slug. diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs @@ -6,7 +6,7 @@ import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { BRAND_IDS } from "umtool-report-to-video/brand-ids"; -import { framesCut } from "umtool-report-to-video/frames-cut"; +import { FRAMES_CUT_DEFAULTS, framesCut } from "umtool-report-to-video/frames-cut"; import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs"; export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/; @@ -177,7 +177,7 @@ export async function chaptersAsClips({ channelsDir, channel, video }) { * a clip around each event, cut on the cues' sentence edges — and the scan's * running stats as the manifest's `frameScan` overlay block. */ -export async function framesAsClips({ channelsDir, channel, video, profile = "poker" }) { +export async function framesAsClips({ channelsDir, channel, video, profile = "poker", target = undefined, stats = false }) { const dir = path.join(channelsDir, channel, "data", video); const scan = await readJson(path.join(dir, `frame-scan.${profile}.json`)); if (!scan) throw new Error(`${channel}/${video} has no frame-scan.${profile}.json — run pnpm ops frame-scan first`); @@ -185,7 +185,7 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po const cues = Array.isArray(cuesDoc?.cues) ? cuesDoc.cues.filter((c) => c && Number.isFinite(c.start) && Number.isFinite(c.end) && typeof c.text === "string").sort((a, b) => a.start - b.start) : null; - return framesCut(scan, { channel, video, cues }); + return framesCut(scan, { channel, video, cues, stats, ...(target !== undefined ? { target } : {}) }); } /** @@ -198,7 +198,7 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po * * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null }} args */ -export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null }) { +export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined }) { if (!SLUG_RE.test(String(slug ?? ""))) { throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`); } @@ -217,6 +217,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site if (seed && seed !== "chapters" && seed !== "frames") throw new Error(`--seed must be "chapters" or "frames", not "${seed}"`); if (seed && src?.kind !== "video") throw new Error(`--seed ${seed} needs --from to be a video ref`); if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed"); + if (target !== undefined && seed !== "frames") throw new Error("--target is the frames seed's length budget: give it with --seed frames"); + if (target !== undefined && !(Number.isFinite(target) && target >= 10 && target <= 3600)) { + throw new Error("--target must be a number of seconds from 10 to 3600"); + } if (timeline && (!Array.isArray(timeline) || !timeline.every(isBoardClip))) { throw new Error("a timeline is a list of clips, each { type: \"clip\", id, channel, video, start, end }"); } @@ -259,9 +263,14 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site let framesSeeded = false; if (seed === "frames") { - const cut = await framesAsClips({ channelsDir, channel: src.channel, video: src.video }); + // The deck on, with the stats region (release 31): the running numbers + // are drawn over each clip, so each subtitle says what happened. With + // no archive to link a moment to (no --site-origin), the deck's QR is off. + const cut = await framesAsClips({ channelsDir, channel: src.channel, video: src.video, target, stats: true }); doc.timeline = cut.timeline; doc.frameScan = cut.frameScan; + doc.render.chrome = { engine: "hyperframes", layout: "deck", deck: provenance.siteOrigin ? {} : { qr: { show: false } }, stats: {} }; + notes.push(`${cut.seconds} s of clips against a ${target ?? FRAMES_CUT_DEFAULTS.target} s budget (--target)`); seeded = cut.timeline.length; framesSeeded = true; if (cut.skipped) notes.push(`${cut.skipped} lesser event(s) left out (the most important kept)`); @@ -301,12 +310,13 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site lines.push( "## Clips seeded from the frame scan — review each", "", - "Every window below is a moment the frame scan derived (a double-up, a bust,", - "the final table…) with a margin either side, widened to the transcript's", - "sentence edges. The scan reads a model's readings of sampled frames, so an", - "event can be wrong: check each in the bench before you keep it. Each clip's", - "on-screen subtitle is the running stats there; `frameScan.overlay` holds them", - "for a stats overlay (not rendered yet).", + "Every window below is a moment the frame scan derived (a big pot, an all-in,", + "players-left milestones, the final table, the bust…) with a margin either", + "side, widened to the transcript's sentence edges, ranked into a length budget", + "(scoops first, level-ups last). The scan reads a model's readings of sampled", + "frames, so an event can be wrong: check each in the bench before you keep it.", + "The deck's `stats` region draws the running numbers from `frameScan.overlay`", + "over each clip (a clip's `stats: false` leaves it out).", "", ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.channel}/${c.video} ${c.start}–${c.end} ${c.onscreen?.title ?? ""}: ${c.onscreen?.subtitle ?? ""}`), ); diff --git a/umtool/lib/scaffold-frames.test.mjs b/umtool/lib/scaffold-frames.test.mjs @@ -39,11 +39,24 @@ test("--seed frames: a clip per event, the stats as subtitles, the overlay block ["f01", "synth-poker", "synthstream1", "Doubles up"], ["f02", "synth-poker", "synthstream1", "Busts out"], ]); - assert.equal(doc.timeline[0].onscreen.subtitle, "85 left · 41,000 chips"); + // Release 31: the deck on with the stats region drawing the running + // numbers, so each subtitle is what happened; no --site-origin, no QR. + assert.equal(doc.timeline[0].onscreen.subtitle, "20,000 → 41,000 chips (2.1×)"); + assert.deepEqual(doc.render.chrome, { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } }, stats: {} }); assert.equal(doc.frameScan.file, "frame-scan.poker.json"); assert.equal(doc.frameScan.overlay.length, 2); const readme = await readFile(path.join(r.dir, "README.md"), "utf8"); assert.match(readme, /Clips seeded from the frame scan/); + assert.match(readme, /\d+(\.\d+)? s of clips against a 240 s budget \(--target\)/); + // A budget: a shorter one leaves the lesser event out; with an archive, the QR stays. + const short = await scaffoldReportVideo({ root: path.join(tmp, "reports"), slug: "poker-short", from: "synth-poker/synthstream1", seed: "frames", channelsDir, target: 50, siteOrigin: "https://archive.example" }); + const sdoc = JSON.parse(await readFile(path.join(short.dir, "video.manifest.json"), "utf8")); + assert.deepEqual(sdoc.timeline.map((c) => c.onscreen.title), ["Doubles up"]); + assert.deepEqual(sdoc.render.chrome.deck, {}); + await assert.rejects( + scaffoldReportVideo({ root: path.join(tmp, "reports"), slug: "poker-x", from: "synth-poker/synthstream1", seed: "chapters", channelsDir, target: 60 }), + /--target is the frames seed's length budget/, + ); await assert.rejects( scaffoldReportVideo({ root: path.join(tmp, "reports"), slug: "poker-cut-2", from: "synth-poker/none", seed: "frames", channelsDir }), /no frame-scan\.poker\.json — run pnpm ops frame-scan first/, diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -403,6 +403,11 @@ whatever a manifest omits, one level deep: "verdicts": { "PARTLY": { "label": "Partly true", "color": "#e3b23c" } }, // per verdict: label ≤ 24 characters, a #rgb/#rrggbb colour "stamp": { "seconds": 3, "position": "top-left" }, // seconds 1–10; top-left | top-right | bottom-left | bottom-right | center "tally": { "show": true, "position": "right" } // position "right" (beside the QR) | "left" (before the title) + }, + "stats": { // a frame scan's running numbers over each clip (below); every key optional + "position": "bottom-left", // top-left | top-right | bottom-left | bottom-right + "fields": ["stack", "stackBB", "playersLeft", "level"], // which numbers, each at most once + "name": true // the tournament's name over them } } } @@ -619,6 +624,42 @@ a verdict named without a colour keeps the default's), the stamp's seconds and corner, and whether and where the tally is drawn; `validateChrome()` refuses an unknown key there as everywhere in the block. +### `render.chrome.stats` — a frame scan's running numbers (release 31) + +A cut seeded from a frame scan (`umtool new <slug> --from <channel>/<id> --seed +frames`, `frames-cut.mjs`) carries `frameScan.overlay`: per clip, the stats at +its start and at every change inside it — `{ at, stack, stackBB, playersLeft, +level, name }`, `at` in SOURCE seconds. The stats region draws them in a corner +of the footage box over each clip, each number held until the next point. + +```jsonc +"render": { "chrome": { …, "stats": {} } } // every clip with overlay points +{ "type": "clip", "id": "f03", …, "stats": false } // this clip without them +{ "type": "clip", "id": "f04", …, "stats": true } // this clip only (no render.chrome.stats) +``` + +- **Which clips.** A clip DECLARES the region when it asks for it (the cut's + `stats`, not its own `false`; or its own `true`) and `frameScan.overlay` + has points for it (`stats.mjs` `statsClips`). `validateStatsEntries()` + refuses a non-boolean, a `stats` on anything but a clip, a `true` with no + points or without the deck; the lint says the same. +- **The schedule.** `schedule.json` gains `stats: { position, fields, name, + clips: [{ segment, in, out, name, states: [{ at, values }] }] }` + (`statsSchedule`) — only when a clip declares it. A source second `t` lands + at `start + (t − from)`, `from` the play window's (the build snaps a clip's + ends to a silence, so a state may land up to `snapWindow` from its frame); + a panel is up from mid-dissolve to mid-dissolve, and stays up across a cut + between two clips that both carry it. +- **The render.** `chrome-stats.mjs` is the page (pure; one block per state, + so a seek lands on the same pixels either way), on the palette's roles (the + ground `bg` at 84%, the numbers `fg`, the labels `muted`, a rule in + `accent`); 48 px plus 150 a field wide and 150 tall at 1920 (112 with no + name), `28` px in from the corner (`statsGeometry`). `compose-chrome.mjs + --region stats` composes and renders it for the whole cut (`chrome/stats/`, + `chrome/stats-frames/`, cached by its key, windowed as the stamps' are), and + the build lays it after the stamps. `verify-build.mjs` fails when a declared + clip is not in the schedule's `stats`, or the frames are missing or short. + ### `thread` and `render.chrome.threads` — the thread rail A cut whose clips make a few lines of argument can draw them as a rail of cards diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -137,12 +137,13 @@ import { ensureWriteDir } from "../lib/report/storage.mjs"; import { assertChrome, deckGeometry, deckOn, deckSchedule, endFadeOf, feedGeometry, feedOn, frameCount, hidesDeck, MUTE_FADE, dipOf, muteSegmentSeconds, playWindow, postsGeometry, postWindows, resolveDeck, scheduleFrom, snapWindow, stampGeometry, - teaserHits, teaserSeconds, teaserTitle, threadsGeometry, + statsGeometry, teaserHits, teaserSeconds, teaserTitle, threadsGeometry, validateCutEdits, validatePosts, validateTeasers, } from "./deck.mjs"; import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; +import { validateStatsEntries } from "./stats.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"; @@ -2492,7 +2493,9 @@ export function chromeOverlayChain(render, regions, inLabel, firstInputIdx, opts // The posts feed (`name: "feed"`) and the fact-check stamps (`name: // "stamp"`) are whole-cut sequences like the deck's, laid exactly as the // deck's is. - const deck = r.name === "deck" || r.name === "feed" || r.name === "stamp" || r.name === "threads" || r.name === "flips"; + // The stats region (`name: "stats"`) likewise. + const deck = r.name === "deck" || r.name === "feed" || r.name === "stamp" || r.name === "threads" || r.name === "flips" || + r.name === "stats"; const posts = r.name === "posts"; inputs.push( ...(deck || posts ? ["-reinit_filter", "0"] : []), @@ -2568,6 +2571,11 @@ export function stampRegion(render, frames, schedule) { return { name: "stamp", frames, ...stampGeometry(render, { feed: schedule.layout === "feed" }) }; } +/** 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" }) }; +} + /** * Where each rendered chrome region sits in the frame. * @@ -3685,8 +3693,9 @@ export function previewFromSegmentsArgs({ segments, durs, starts, D, at, dur, re * Compose and render the deck (cached by compose-chrome's key), and check the * sequence is as long as the cut -- or the window -- it will be laid over; * then the posts windows the schedule carries, the same way, and the - * fact-check stamps when it stamps a claim. Returns the overlay plan: the - * deck's region first, then the feed's, each posts window's, the stamps'. + * fact-check stamps when it stamps a claim, and the stats when a clip + * declares them. Returns the overlay plan: the deck's region first, then the + * feed's, each posts window's, the stamps', the stats'. * Dynamic import: compose-chrome imports this file. */ async function renderDeck({ manifestPath, render, outDir, variant, schedule, from = 0, duration = null }) { @@ -3785,6 +3794,28 @@ async function renderDeck({ manifestPath, render, outDir, variant, schedule, fro 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: 2, 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}`); + } + EMIT("chrome", { + phase: sr.cached ? "cached" : "render", region: "stats", + 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 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) { @@ -3948,7 +3979,7 @@ export async function measureChromeSchedule({ manifest, entries, segments, D }) } // The variant's posts, placed on the clips this cut plays with their real // upload dates. A manifest without posts writes the schedule it always did. - return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [] }); + return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [], frameScan: manifest.frameScan ?? null }); } // Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`, @@ -4180,6 +4211,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const errors = [ ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole), + ...validateStatsEntries(whole), ]; if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`); } diff --git a/umtool/report-to-video/chrome-stats.mjs b/umtool/report-to-video/chrome-stats.mjs @@ -0,0 +1,274 @@ +// The STATS region's composition (release 31, lane P3): one HyperFrames page +// for a whole report cut, a small transparent region in a corner of the +// footage box (deck.mjs statsGeometry) where a frame scan's running numbers +// -- the stack, big blinds, players left, the level -- sit over each clip +// that declares them, each number held until the scan's next point. +// +// PURE, like chrome-stamp.mjs: a schedule and a render block in, an HTML +// string out. compose-chrome.mjs copies the assets in beside it, writes it and +// renders it (`region: "stats"`); the build lays the frames over the cut as +// it lays the stamps'. +// +// 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). Each STATE of a clip (its numbers between two points) is +// its own block, shown over exactly its span: no text is rewritten by a +// callback, so a seek backwards lands on the same pixels as one forwards. +// The times are stats.mjs `statsSchedule`'s, untouched. +import { pageDuration, statsGeometry } from "./deck.mjs"; +import { rgba } from "./chrome-deck.mjs"; +import { STATS_LABELS, STATS_MOTION } from "./stats.mjs"; + +/** Instant cues still take a millisecond: a zero-duration tween has its own seek rules. */ +const INSTANT = 0.001; + +const esc = (s) => + String(s ?? "") + .replace(/&/g, "&amp;") + .replace(/</g, "&lt;") + .replace(/>/g, "&gt;") + .replace(/"/g, "&quot;"); + +const r4 = (v) => Math.round(v * 10000) / 10000; + +/** + * A number as the panel shows it: chips grouped under 100,000, then K and M + * ("323.2K", "1.25M"); big blinds to a tenth under 100; the rest whole. A + * field not read yet is a dash. + */ +export function statsValue(field, v) { + if (v === null || v === undefined || !Number.isFinite(v)) return "—"; + const trim = (x, d) => x.toFixed(d).replace(/\.0+$/, "").replace(/(\.\d*?)0+$/, "$1"); + if (field === "stack") { + if (v >= 1e6) return `${trim(v / 1e6, 2)}M`; + if (v >= 1e5) return `${trim(v / 1e3, 1)}K`; + return Math.round(v).toLocaleString("en-US"); + } + if (field === "stackBB") return v >= 100 ? String(Math.round(v)) : trim(v, 1); + return Math.round(v).toLocaleString("en-US"); +} + +/** + * The panel's spans: each clip's [in, out], with clips that touch joined, so + * the panel stays up across a cut between two clips that both carry it. + */ +export function panelSpans(clips) { + const out = []; + for (const c of clips) { + const last = out[out.length - 1]; + if (last && c.in - last.out <= 1e-6) last.out = c.out; + else out.push({ in: c.in, out: c.out }); + } + return out; +} + +/** + * Everything the timeline does, as data. The panel is `pn` (autoAlpha), in + * over STATS_MOTION.in at each span's start, out over STATS_MOTION.out before + * its end; state j of clip i is `s<i>_<j>` (autoAlpha), shown instantly at + * its `at` and hidden at the next state's (or its clip's out). + * + * @returns {{ init: Record<string, object>, cues: Array<{ k: string, at: number, + * dur: number, from: object, to: object, ease: string }> }} + */ +export function statsCues(schedule) { + const clips = schedule.stats?.clips ?? []; + const m = STATS_MOTION; + const init = { pn: { autoAlpha: 0 } }; + const ev = []; + const add = (k, at, dur, to, ease) => ev.push({ k, at: r4(at), dur: r4(Math.max(INSTANT, dur)), to, ease }); + for (const sp of panelSpans(clips)) { + add("pn", sp.in, Math.min(m.in, (sp.out - sp.in) / 2), { autoAlpha: 1 }, "power2.out"); + add("pn", Math.max(sp.in, sp.out - m.out), Math.min(m.out, (sp.out - sp.in) / 2), { autoAlpha: 0 }, "power1.in"); + } + clips.forEach((c, i) => { + c.states.forEach((st, j) => { + const k = `s${i}_${j}`; + init[k] = { autoAlpha: 0 }; + const until = c.states[j + 1]?.at ?? c.out; + add(k, st.at, INSTANT, { autoAlpha: 1 }, "none"); + add(k, until, INSTANT, { autoAlpha: 0 }, "none"); + }); + }); + // Order, clamp (a cue never starts before the last on its element ends), + // and state every from: the last to on its element, or its init. + ev.forEach((e, n) => { e.n = n; }); + ev.sort((a, b) => a.at - b.at || a.n - b.n); + const state = Object.fromEntries(Object.entries(init).map(([k, v]) => [k, { ...v }])); + const freeAt = new Map(); + const cues = []; + for (const e of ev) { + let { at, dur } = e; + const free = freeAt.get(e.k) ?? 0; + if (at < free) { + const end = at + dur; + at = r4(free); + 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)); + cues.push({ k: e.k, at, dur, from, to: e.to, ease: e.ease }); + } + return { init, cues }; +} + +/** + * The stats composition's HTML, for the whole cut -- or a window of it + * (`from`/`duration`, as the deck's). `fonts` = `{ regular, bold }` + * asset-relative paths (DeckSans / DeckSansBold); `gsap` the vendored script. + * The region is `statsGeometry(render, { feed })`, region-local, transparent + * outside the panel. Colours are the cut's palette roles (bg, fg, muted, + * accent). `?still=<t>` and the preview's `deck:seek` take CUT seconds. + */ +export function statsHtml(schedule, render, opts = {}) { + const st = schedule.stats; + if (!st?.clips?.length) throw new Error("stats: the schedule draws no clip's stats"); + const geo = statsGeometry(render, { feed: schedule.layout === "feed" }); + const pal = render.palette; + const W = geo.width, H = geo.height; + const k = (render.width ?? 1920) / 1920; + const px = (v) => Math.max(1, Math.round(v * k)); + const fonts = opts.fonts ?? {}; + const gsapSrc = opts.gsap ?? "assets/gsap.min.js"; + const total = schedule.total; + const from = Number(opts.from ?? 0); + const dur = opts.duration != null ? r4(Number(opts.duration)) : r4(total - from); + if (!(dur > 0)) throw new Error(`stats: nothing to render from ${from}s of a ${total}s cut`); + const windowed = from > 0 || Math.abs(dur - total) > 1e-6; + const { init, cues } = statsCues(schedule); + const fields = st.fields; + + // The cells share the panel's width, the stack's a third wider (its + // number is the longest: "323.2K", "41,000"). + const pad = px(24); + const weight = (f) => (f === "stack" ? 1.3 : 1); + const unit = (W - 2 * pad) / fields.reduce((n, f) => n + weight(f), 0); + const cellW = (f) => Math.floor(unit * weight(f)); + const states = st.clips + .flatMap((c, i) => + c.states.map((s, j) => { + const cells = fields + .map((f) => `<div class="cell" data-field="${esc(f)}" style="width:${cellW(f)}px"><div class="lab">${esc(STATS_LABELS[f] ?? f)}</div><div class="val">${esc(statsValue(f, s.values[f]))}</div></div>`) + .join(""); + const name = st.name && c.name ? `<div class="name">${esc(c.name)}</div>` : ""; + return `<div class="state" data-k="s${i}_${j}" data-segment="${esc(c.segment)}" data-at="${s.at}">${name}<div class="cells">${cells}</div></div>`; + }), + ) + .join("\n "); + + const data = { + total: r4(total), + window: windowed ? { from: r4(from), dur } : null, + ids: st.clips.map((c) => c.segment), + init, + cues, + }; + // `</script>` inside a JSON string would close the tag; a name is the scan's. + const json = JSON.stringify(data).replace(/</g, "\\u003c"); + const fps = schedule.fps ?? render.fps ?? 30; + + return `<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=${W}, height=${H}" /> + <script src="${esc(gsapSrc)}"></script> + <style> + /* The deck's faces, under the deck's private names -- see docs/quirks.md. */ + @font-face { font-family: 'DeckSans'; font-weight: 400; font-style: normal; + src: url('${esc(fonts.regular ?? "")}'); } + @font-face { font-family: 'DeckSansBold'; font-weight: 400; font-style: normal; + src: url('${esc(fonts.bold ?? "")}'); } + * { margin: 0; padding: 0; box-sizing: border-box; } + html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: transparent; } + body { font-family: 'DeckSans', sans-serif; font-synthesis: none; + -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; } + #root { position: relative; width: ${W}px; height: ${H}px; overflow: hidden; } + #stats-clip { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px; } + /* The panel: the palette's ground, dark enough to read over any + footage, an accent rule down its left edge. Hidden until a clip. */ + #panel { position: absolute; inset: 0; border-radius: ${px(10)}px; visibility: hidden; opacity: 0; + background: ${rgba(pal.bg, 0.84)}; border-left: ${px(5)}px solid ${pal.accent}; + box-shadow: 0 ${px(8)}px ${px(26)}px rgba(0, 0, 0, 0.4); } + .state { position: absolute; inset: 0; padding: ${px(14)}px ${pad}px ${px(14)}px ${pad}px; + display: flex; flex-direction: column; justify-content: center; gap: ${px(6)}px; + visibility: hidden; opacity: 0; } + .name { font-family: 'DeckSansBold', sans-serif; font-size: ${px(22)}px; line-height: ${px(28)}px; + letter-spacing: 0.08em; text-transform: uppercase; color: ${pal.muted}; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .cells { display: flex; } + .cell { display: flex; flex-direction: column; gap: ${px(2)}px; } + .lab { font-size: ${px(16)}px; line-height: ${px(20)}px; letter-spacing: 0.06em; text-transform: uppercase; + color: ${pal.muted}; white-space: nowrap; } + .val { font-family: 'DeckSansBold', sans-serif; font-size: ${px(42)}px; line-height: ${px(48)}px; + color: ${pal.fg}; font-variant-numeric: tabular-nums; white-space: nowrap; } + </style> + </head> + <body> + <div id="root" data-composition-id="stats" data-start="0" data-duration="${pageDuration(dur, fps)}" + data-width="${W}" data-height="${H}"> + <div id="stats-clip" class="clip" data-start="0" data-duration="${pageDuration(dur, fps)}" data-track-index="1"> + <div id="panel" data-k="pn"> + ${states} + </div> + </div> + </div> + + <script id="stats-data" type="application/json">${json}</script> + <script> + const S = JSON.parse(document.getElementById("stats-data").textContent); + const byK = {}; + for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el; + + // t = 0, then the cues. Every cue states its from, so a seek from + // anywhere to anywhere lands on the same pixels. + for (const k of Object.keys(S.init)) if (byK[k]) gsap.set(byK[k], S.init[k]); + const inner = gsap.timeline({ paused: true }); + for (const c of S.cues) { + const el = byK[c.k]; + if (!el) continue; + inner.fromTo(el, c.from, { ...c.to, duration: c.dur, ease: c.ease, immediateRender: false }, c.at); + } + // The timeline runs to the cut's end, whatever its last cue. + inner.set({}, {}, S.total); + let tl = inner; + if (S.window) { + tl = gsap.timeline({ paused: true }); + tl.add(inner.tweenFromTo(S.window.from, S.window.from + S.window.dur, { duration: S.window.dur, ease: "none" }), 0); + } + window.__timelines = window.__timelines || {}; + window.__timelines["stats"] = tl; + + const ready = document.fonts.ready.catch(() => {}).then(() => { document.documentElement.dataset.fit = "1"; }); + const params = new URLSearchParams(location.search); + // A window plays the cut's [from, from + dur]; the page is seeked in its own seconds. + const local = (t) => { + const v = Number(t) || 0; + return S.window ? Math.max(0, Math.min(S.window.dur, v - S.window.from)) : Math.max(0, v); + }; + const still = params.get("still"); + if (still !== null) { + tl.seek(local(still), false); + ready.then(() => tl.seek(local(still), false)); + } + + // umtool's live preview: the parent seeks in cut seconds, as it seeks the deck. + if (params.get("preview") === "1") { + window.addEventListener("message", (e) => { + const m = e.data || {}; + if (m.type === "deck:seek") tl.seek(local(m.t), false); + }); + ready.then(() => { + if (window.parent !== window) { + window.parent.postMessage({ type: "stats:ready", total: S.total, ids: S.ids }, "*"); + } + }); + } + </script> + </body> +</html> +`; +} diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -49,6 +49,7 @@ import { feedHtml } from "./chrome-feed.mjs"; import { stampHtml } from "./chrome-stamp.mjs"; import { threadsHtml } from "./chrome-threads.mjs"; import { flipsHtml } from "./chrome-flips.mjs"; +import { statsHtml } from "./chrome-stats.mjs"; const run = promisify(execFile); @@ -704,6 +705,11 @@ async function regionHtml(region, { manifest, manifestDir, base, projDir, assets 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 === "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 @@ -796,6 +802,10 @@ function runRenderer(cmd, args) { * `chrome/stamp-frames/` and their `.key`, a window `stamp-from<s>[-frames]`, * cached as the deck's are. * + * Stats (`region: "stats"`, a schedule with `stats`): a frame scan's running + * numbers over the clips that declare them, exactly as the stamps -- project + * `chrome/stats/`, frames `chrome/stats-frames/`, windowed and cached alike. + * * Threads (`region: "threads"`, a schedule with `threads`): the thread rail * for the whole cut, exactly as the stamps -- project `chrome/threads/`, * frames `chrome/threads-frames/`, windowed and cached alike. @@ -838,9 +848,10 @@ export async function composeChrome({ // 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 === "threads" || region === "flips" || region === "stats"; // The regions drawn over the whole cut from its schedule, windowable alike. - const wholeCut = region === "deck" || region === "feed" || region === "stamp" || region === "threads" || region === "flips"; + const wholeCut = region === "deck" || region === "feed" || region === "stamp" || region === "threads" || region === "flips" || + region === "stats"; let teaser = null; if (region === "teaser") { teaser = (manifest.timeline ?? []).find((e) => e.id === segment && e.type === "teaser") ?? null; @@ -867,6 +878,9 @@ export async function composeChrome({ 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 === "stamp" && !sched.factcheck?.stamps?.length) { throw new Error("the stamp region needs a schedule that stamps a claim (an entry with a `claim`)"); } @@ -995,7 +1009,7 @@ if (import.meta.url === `file://${process.argv[1]}`) { const manifestPath = argv.find((a, i) => !a.startsWith("--") && !VALUED.has(argv[i - 1])); if (!manifestPath) { console.error( - "usage: compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|threads|flips|posts|teaser] [--variant sourced|full]\n" + + "usage: compose-chrome.mjs <manifest.json> [--region chart|deck|feed|stamp|stats|threads|flips|posts|teaser] [--variant sourced|full]\n" + " [--segment <id>] (posts: the clip whose window to compose; teaser: its entry)\n" + " [--from <s>] [--duration <s>] [--out <dir>] [--preview]\n" + " [--still <s> --png <path>]\n" + @@ -1018,7 +1032,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" ? 4 : region === "posts" || region === "stamp" || region === "threads" || region === "flips" ? 2 : null), + workers: num("--workers") ?? (region === "deck" || region === "feed" || region === "teaser" ? 4 : region === "posts" || region === "stamp" || region === "stats" || region === "threads" || region === "flips" ? 2 : null), quality: flag("--quality") ?? "high", format: flag("--format") ?? "png-sequence", fps: num("--fps"), diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -22,6 +22,7 @@ import { } from "./factcheck.mjs"; import { threadOf, threadSchedule, threadsOn, validateThreads } from "./threads.mjs"; import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs"; +import { overlayPointsOf, resolveStats, statsSchedule, statsWanted, validateStats } from "./stats.mjs"; import { estimatedNarratedCardSeconds, hasNarration } from "./narration.mjs"; /** Is the left panel on: the thread rail (threads.mjs) or the flips panel (flips.mjs) -- one region, one or the other. */ @@ -138,7 +139,7 @@ export function validateChrome(chrome, render = {}) { const errors = []; if (chrome === undefined || chrome === null) return errors; if (!isObj(chrome)) return ["render.chrome must be an object"]; - unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips"], "render.chrome", errors); + unknownKeys(chrome, ["engine", "layout", "deck", "factcheck", "threads", "flips", "stats"], "render.chrome", errors); if (chrome.engine !== "hyperframes") errors.push('render.chrome.engine must be "hyperframes"'); if (chrome.layout !== "deck") errors.push('render.chrome.layout must be "deck"'); if (render.rail) errors.push("render.chrome (the deck) and render.rail cannot both be set"); @@ -154,6 +155,8 @@ export function validateChrome(chrome, render = {}) { errors.push(...validateThreads(chrome.threads)); // The flips panel (flips.mjs): the same region as the rail, so not both. errors.push(...validateFlips(chrome.flips)); + // The stats region (stats.mjs): a frame scan's running numbers over the footage. + errors.push(...validateStats(chrome.stats)); if (threadsOn({ chrome }) && flipsOn({ chrome })) errors.push("render.chrome.threads and render.chrome.flips share the left panel: set one"); const d = chrome.deck ?? {}; if (!isObj(d)) return [...errors, "render.chrome.deck must be an object"]; @@ -630,7 +633,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin * at: number, landed: number, out: [number, number] }> } }} */ export function deckSchedule({ - entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], + entries, durs, D, render, provenance = {}, metas = [], estimated = false, posts = [], frameScan = null, }) { const deck = resolveDeck(render); const fps = render.fps ?? 30; @@ -654,6 +657,17 @@ export function deckSchedule({ ? threadSchedule({ segments: segs.map((s, i) => ({ ...s, thread: threadOf(entries[i]) })), D, total, render, moves }) : null; const flips = flipsOn(render) ? flipSchedule({ segments: segs, total, render, moves }) : null; + // The stats region (stats.mjs): on the clips that declare it, their overlay + // points from the play window's first source second. + const stats = statsSchedule({ + segments: segs.map((s, i) => { + const e = entries[i]; + if (!statsWanted(e, render)) return s; + const points = overlayPointsOf({ frameScan }, e.id); + return points.length ? { ...s, points, sourceFrom: playWindow(e, render).from } : s; + }), + D, total, render, + }); return { version: 1, kind: "deck", @@ -689,6 +703,8 @@ export function deckSchedule({ ...(threads ? { threads } : {}), // The flips panel: present only when it is on. ...(flips ? { flips } : {}), + // The stats region: present only when a clip declares it. + ...(stats ? { stats } : {}), // Present only when there are posts to draw, so a cut without them writes // the schedule it always did. ...(placed.length ? { posts: roundPosts(placed) } : {}), @@ -720,6 +736,7 @@ export function estimateSchedule(manifest, { metas = [], noXfade = false } = {}) provenance: manifest.provenance ?? {}, metas, estimated: true, + frameScan: manifest.frameScan ?? null, }); } @@ -1261,6 +1278,31 @@ export function stampGeometry(render, { feed = false } = {}) { } /** + * Where the stats region sits in the frame (chrome-stats.mjs, stats.mjs): a + * panel in the footage box -- the feed's when `feed`, else the deck's -- at + * `stats.position`, `inset` clear of its edges: 48 px plus 150 a field wide + * (648 with all four) and 150 tall at 1920 wide (112 with no name line), + * scaled with the frame. + * + * @param {any} render + * @param {{ feed?: boolean }} [opts] + * @returns {{ x: number, y: number, width: number, height: number }} + */ +export function statsGeometry(render, { feed = false } = {}) { + const { W } = deckGeometry(render); + const f = feed ? feedGeometry(render).footage : deckGeometry(render).footage; + const k = W / 1920; + const cfg = resolveStats(render); + const width = Math.min(even((48 + 150 * cfg.fields.length) * k), even(f.width)); + const height = Math.min(even((cfg.name ? 150 : 112) * k), even(f.height)); + const inset = Math.round(28 * k); + const [v, h] = cfg.position.split("-"); + const x = h === "left" ? f.x + inset : f.x + f.width - inset - width; + const y = v === "top" ? f.y + inset : f.y + f.height - inset - height; + return { x: Math.round(x), y: Math.round(y), width, height }; +} + +/** * Is this cut a FEED: the deck on, its posts shown in the `feed` layout, and * at least one post to draw on a clip of `entries` (the cut's whole timeline, * never an `--only` slice of it)? The build frames its footage into diff --git a/umtool/report-to-video/frames-cut.mjs b/umtool/report-to-video/frames-cut.mjs @@ -7,15 +7,73 @@ // level), read at any second by `frameTotals`. // // Plain ESM with no I/O, ledger-totals.mjs's pattern: the scaffold (`umtool -// new --seed frames`) calls it with the parsed sidecar, a future chrome region -// calls `frameTotals` for its numbers, and `node --test` runs it with literals. -// Every consumer gets the same arithmetic. No render here: the clips are a -// draft to review in the bench, and the overlay is data until a region draws it. +// new --seed frames`) calls it with the parsed sidecar and `node --test` runs +// it with literals. Every consumer gets the same arithmetic. No render here: +// the clips are a draft to review in the bench. Since release 31 the events +// are RANKED (`rankOf`: scoops, milestones, swings, pots, level-ups) into a +// length budget (`target`), and the `stats` chrome region (stats.mjs, +// chrome-stats.mjs) draws the overlay points over each clip. import { widen } from "yt-dlp-transcript-common/lib/cueWiden.mjs"; -/** Events worth a clip, most important first; the rest are left out. */ -export const CUT_EVENT_KINDS = ["won", "bust", "final-table", "knockout", "double-up", "big-pot", "big-loss", "all-in", "eliminated"]; +/** Events worth a clip, most important first (release 30's order; `rankOf` ranks since release 31). */ +export const CUT_EVENT_KINDS = ["won", "bust", "final-table", "knockout", "double-up", "big-pot", "big-loss", "all-in", "eliminated", "players-left", "pot", "level-up"]; + +/** + * The tiers a supercut fills its length budget from (release 31), first + * first: the SCOOPS (the tournament won, a big pot, an all-in won or + * doubled, a double-up, a knockout), the MILESTONES (the final table and the + * players-left marks, the bust that ends it), the rest of the swings (an + * all-in lost or unread, a big loss), the plain pots, and the level-ups last. + * Within a tier a confirmed event before an unconfirmed one, then the + * score, then the earlier. + */ +export const CUT_TIERS = Object.freeze(["scoop", "milestone", "swing", "pot", "level"]); + +const WON_ALL_IN = new Set(["doubled", "won"]); + +/** `{ tier, score }` for an event (lower tier first, higher score first); null when it is no clip. */ +export function rankOf(e) { + const ev = e.evidence ?? {}; + const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0); + switch (e.kind) { + case "won": return { tier: 0, score: 1e6 }; + case "all-in": return WON_ALL_IN.has(ev.outcome) ? { tier: 0, score: 5000 + (ev.outcome === "doubled" ? 1000 : 0) } : { tier: 2, score: 100 }; + case "big-pot": return { tier: 0, score: 1000 + n(ev.potBB) }; + case "double-up": return { tier: 0, score: 900 }; + case "knockout": return { tier: 0, score: 800 }; + case "bust": return { tier: 1, score: 5000 }; + case "final-table": return { tier: 1, score: 4000 }; + case "players-left": return { tier: 1, score: 1000 - n(ev.milestone) }; + case "eliminated": return { tier: 1, score: 10 }; + case "big-loss": return { tier: 2, score: 50 }; + case "pot": return { tier: 3, score: n(ev.potBB) }; + case "level-up": return { tier: 4, score: n(ev.bigBlind) }; + default: return null; + } +} + +/** Ranked first-first: tier, confirmed, score, then the earlier. */ +export function compareRank(a, b) { + const ra = rankOf(a); + const rb = rankOf(b); + return ra.tier - rb.tier || + (a.confidence === "unconfirmed") - (b.confidence === "unconfirmed") || + rb.score - ra.score || + a.t - b.t; +} + +const ALL_IN_TITLE = { doubled: "All in, doubles up", won: "All in and wins", lost: "All in, loses chips", busted: "All in and out" }; + +/** A clip's on-screen title from the event that leads it. */ +export function titleOf(e) { + const ev = e.evidence ?? {}; + if (e.kind === "all-in") return ALL_IN_TITLE[ev.outcome] ?? "All in"; + if (e.kind === "players-left" && typeof ev.milestone === "number") { + return ev.playersLeft === ev.milestone ? `Down to ${fmt(ev.milestone)}` : `Under ${fmt(ev.milestone)} left`; + } + return TITLES[e.kind] ?? e.kind; +} const TITLES = { won: "Wins it", @@ -27,9 +85,15 @@ const TITLES = { "all-in": "All in", knockout: "Knocks one out", "big-pot": "Takes a big pot", + pot: "Takes a pot", + "level-up": "Blinds go up", }; -export const FRAMES_CUT_DEFAULTS = Object.freeze({ pre: 20, post: 25, maxClips: 20, mergeGap: 5 }); +// `pre`/`post` frame a scoop, a milestone or a swing; `short` a plain pot +// or a level-up. `target` is the length budget in seconds the clips fill +// (merged, widened): ranked first-first, an event whose window would take +// the cut past it is passed over for a later, smaller one. +export const FRAMES_CUT_DEFAULTS = Object.freeze({ pre: 20, post: 25, short: Object.freeze({ pre: 6, post: 10 }), maxClips: 20, mergeGap: 5, target: 240 }); const fmt = (v) => (Number.isInteger(v) ? v.toLocaleString("en-US") : String(Math.round(v * 10) / 10)); const round2 = (v) => Math.round(v * 100) / 100; @@ -76,30 +140,31 @@ export function statsLine(totals) { } /** - * The draft: `{ timeline, frameScan, skipped }`. `scan` is the parsed - * sidecar; `cues` the video's cues (sorted), or none. A window is - * `[t - pre, t + post]`, widened to sentence edges where cues exist, clamped - * to the video; windows within `mergeGap` of each other are one clip. At most - * `maxClips`, the most important events kept, in time order. + * The draft: `{ timeline, frameScan, skipped, seconds }`. `scan` is the + * parsed sidecar; `cues` the video's cues (sorted), or none. A window is + * `[t - pre, t + post]` (`short` for a plain pot or a level-up), widened to + * sentence edges where cues exist, clamped to the video; windows within + * `mergeGap` of each other are one clip. The events are taken ranked + * (`compareRank`) while the merged clips fit the `target` seconds and + * `maxClips`, and played in time order. `stats: true` (the cut draws the + * stats region, which shows the running numbers) makes each subtitle the + * leading event's detail; otherwise it is the stats line. */ -export function framesCut(scan, { channel, video, cues = null, at = new Date().toISOString(), ...o } = {}) { - const opt = { ...FRAMES_CUT_DEFAULTS, ...o }; +export function framesCut(scan, { channel, video, cues = null, at = new Date().toISOString(), stats = false, ...o } = {}) { + const opt = { ...FRAMES_CUT_DEFAULTS, ...o, short: { ...FRAMES_CUT_DEFAULTS.short, ...(o.short ?? {}) } }; if (!channel || !video) throw new Error("framesCut needs the channel and the video"); const duration = scan?.source?.durationSeconds ?? scan?.sampling?.to ?? Infinity; - const rank = (k) => CUT_EVENT_KINDS.indexOf(k); const events = (scan?.derived?.events ?? []) - .filter((e) => rank(e.kind) >= 0) + .filter((e) => rankOf(e) !== null) // A bust and the "eliminated" banner on the same moment are one event, // and so is one kind seen twice within a minute (the log and the series). .filter((e, _, all) => !(e.kind === "eliminated" && all.some((x) => x.kind === "bust" && Math.abs(x.t - e.t) <= 60))) .filter((e, i, all) => !all.some((x, j) => j < i && x.kind === e.kind && Math.abs(x.t - e.t) <= 60)); - const chosen = [...events].sort((a, b) => rank(a.kind) - rank(b.kind) || a.t - b.t).slice(0, opt.maxClips); - const skipped = events.length - chosen.length; - chosen.sort((a, b) => a.t - b.t); - const windows = chosen.map((e) => { - let start = Math.max(0, e.t - opt.pre); - let end = Math.min(duration, e.t + opt.post); + const windowOf = (e) => { + const short = e.kind === "pot" || e.kind === "level-up"; + let start = Math.max(0, e.t - (short ? opt.short.pre : opt.pre)); + let end = Math.min(duration, e.t + (short ? opt.short.post : opt.post)); if (cues?.length) { // Only ever WIDER, and only as far as widen's own budgets (8 s before, // 12 s after): a cue past a silence is not this moment's sentence. @@ -108,18 +173,34 @@ export function framesCut(scan, { channel, video, cues = null, at = new Date().t if (w.end >= end && w.end <= end + 12) end = Math.min(duration, w.end); } return { start, end, events: [e] }; - }); - const merged = []; - for (const w of windows) { - const last = merged[merged.length - 1]; - if (last && w.start <= last.end + opt.mergeGap) { - last.end = Math.max(last.end, w.end); - last.events.push(...w.events); - } else merged.push({ ...w, events: [...w.events] }); + }; + const mergeAll = (windows) => { + const merged = []; + for (const w of [...windows].sort((a, b) => a.start - b.start)) { + const last = merged[merged.length - 1]; + if (last && w.start <= last.end + opt.mergeGap) { + last.end = Math.max(last.end, w.end); + last.events.push(...w.events); + } else merged.push({ ...w, events: [...w.events] }); + } + return merged; + }; + const lengthOf = (merged) => merged.reduce((n, w) => n + (w.end - w.start), 0); + + // Ranked first-first, each taken while the merged cut stays within the + // budget and the clip count (the first always: a cut of one long clip is + // still a cut); one that would pass either is skipped for a smaller one. + const chosen = []; + for (const e of [...events].sort(compareRank)) { + const trial = mergeAll([...chosen, windowOf(e)]); + if (chosen.length && (lengthOf(trial) > opt.target || trial.length > opt.maxClips)) continue; + chosen.push(windowOf(e)); } + const skipped = events.length - chosen.length; + const merged = mergeAll(chosen).map((w) => ({ ...w, events: w.events.sort((a, b) => a.t - b.t) })); const timeline = merged.map((w, i) => { - const lead = [...w.events].sort((a, b) => rank(a.kind) - rank(b.kind))[0]; + const lead = [...w.events].sort(compareRank)[0]; const totals = frameTotals(scan, lead.t); return { type: "clip", @@ -130,11 +211,11 @@ export function framesCut(scan, { channel, video, cues = null, at = new Date().t end: round2(w.end), cite: Math.floor(lead.t), quote: "", - onscreen: { title: TITLES[lead.kind] ?? lead.kind, subtitle: statsLine(totals) || lead.detail }, + onscreen: { title: titleOf(lead), subtitle: stats ? lead.detail : statsLine(totals) || lead.detail }, // Code's draft (release 28's mark, `model: "code"`): no review row, and // an edit makes it the operator's. drafted: { onscreen: { task: "frames", model: "code", at, attempt: 1 } }, - frameEvents: w.events.map((e) => ({ t: e.t, kind: e.kind, detail: e.detail })), + frameEvents: w.events.map((e) => ({ t: e.t, kind: e.kind, detail: e.detail, ...(e.confidence ? { confidence: e.confidence } : {}) })), }; }); @@ -159,5 +240,6 @@ export function framesCut(scan, { channel, video, cues = null, at = new Date().t overlay, }, skipped, + seconds: round2(lengthOf(merged)), }; } diff --git a/umtool/report-to-video/frames-cut.test.mjs b/umtool/report-to-video/frames-cut.test.mjs @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { framesCut, frameTotals, statsLine, valueAt } from "./frames-cut.mjs"; +import { compareRank, framesCut, frameTotals, rankOf, statsLine, titleOf, valueAt } from "./frames-cut.mjs"; // A synthetic frame-scan sidecar (the shape common/lib/frameScan-server.ts writes). const scan = () => ({ @@ -44,16 +44,18 @@ test("valueAt, frameTotals, statsLine: the running stats at a second", () => { assert.equal(statsLine(null), ""); }); -test("framesCut: a clip around each event, overlapping windows merged, the most important event titles it", () => { - const { timeline, frameScan, skipped } = framesCut(scan(), { channel: "synth", video: "s1" }); +test("framesCut: a clip around each event, overlapping windows merged, the highest-ranked event titles it", () => { + const { timeline, frameScan, skipped, seconds } = framesCut(scan(), { channel: "synth", video: "s1" }); assert.equal(skipped, 0); // 90 (70–115) and 120 (100–145) overlap: one clip; 180 alone (the banner folded into the bust). + // The double-up is a scoop and leads the merged clip (release 31's ranking). assert.deepEqual(timeline.map((c) => [c.id, c.start, c.end, c.cite, c.onscreen.title]), [ - ["f01", 70, 145, 120, "Final table"], + ["f01", 70, 145, 90, "Doubles up"], ["f02", 160, 205, 180, "Busts out"], ]); + assert.equal(seconds, 120); assert.deepEqual(timeline[0].frameEvents.map((e) => e.kind), ["double-up", "final-table", "big-loss"]); - assert.equal(timeline[0].onscreen.subtitle, "Level 5 · 9 left · 9,000 chips (22.5 BB)"); + assert.equal(timeline[0].onscreen.subtitle, "Level 4 · 60 left · 41,000 chips (136.7 BB)"); assert.equal(timeline[1].quote, ""); assert.equal(timeline[0].drafted.onscreen.model, "code"); assert.equal(frameScan.file, "frame-scan.poker.json"); @@ -77,11 +79,11 @@ test("framesCut: cut on sentence edges where cues exist, clamped to the video", test("framesCut: at most maxClips, the most important kept, in time order", () => { const { timeline, skipped } = framesCut(scan(), { channel: "synth", video: "s1", maxClips: 2, pre: 1, post: 1 }); assert.equal(skipped, 2); - assert.deepEqual(timeline.map((c) => c.onscreen.title), ["Final table", "Busts out"]); + assert.deepEqual(timeline.map((c) => c.onscreen.title), ["Doubles up", "Busts out"]); assert.throws(() => framesCut(scan(), {}), /channel and the video/); }); -test("framesCut: a big pot and a knockout are clips; a plain pot is not; one kind twice within a minute is one", () => { +test("framesCut: a big pot and a knockout before a plain pot; one kind twice within a minute is one", () => { const sc = scan(); sc.derived.events = [ { t: 30, kind: "pot", detail: "takes the pot 1,600 (8 BB)", source: "log" }, @@ -90,6 +92,77 @@ test("framesCut: a big pot and a knockout are clips; a plain pot is not; one kin { t: 180, kind: "bust", detail: "out", source: "series" }, { t: 200, kind: "bust", detail: "SynthHero has finished the tournament in 9th", source: "log" }, ]; - const { timeline } = framesCut(sc, { channel: "synth", video: "s1", pre: 5, post: 5 }); + // A 30-s budget: the three 10-s windows fill it, the pot's 16 s would pass it. + const { timeline, skipped } = framesCut(sc, { channel: "synth", video: "s1", pre: 5, post: 5, target: 30 }); assert.deepEqual(timeline.map((c) => [c.cite, c.onscreen.title]), [[60, "Takes a big pot"], [150, "Knocks one out"], [180, "Busts out"]]); + assert.equal(skipped, 1); + // With room, the plain pot is a (short) clip too. + const roomy = framesCut(sc, { channel: "synth", video: "s1", pre: 5, post: 5 }); + assert.deepEqual(roomy.timeline.map((c) => [c.cite, c.start, c.end]), [[30, 24, 40], [60, 55, 65], [150, 145, 155], [180, 175, 185]]); +}); + +// Release 31: the events lane P3's derivation makes, as the sidecar holds them. +const R31 = [ + { t: 0, kind: "level-up", detail: "blinds 500/1,000", source: "log", rule: "log-blinds", evidence: { bigBlind: 1000 }, confidence: "unconfirmed" }, + { t: 300, kind: "level-up", detail: "blinds 600/1,200 (from 1,000), level 2", source: "log", evidence: { bigBlind: 1200, from: 1000 }, confidence: "confirmed" }, + { t: 400, kind: "players-left", detail: "100 players left (under 100)", source: "series", evidence: { milestone: 100, playersLeft: 100 }, confidence: "confirmed" }, + { t: 500, kind: "big-pot", detail: "takes the pot 40,000 (33 BB)", source: "log", evidence: { pot: 40000, potBB: 33.3 }, confidence: "confirmed" }, + { t: 700, kind: "pot", detail: "takes the pot 3,000 (3 BB)", source: "log", evidence: { pot: 3000, potBB: 2.5 }, confidence: "confirmed" }, + { t: 1000, kind: "all-in", detail: "all in with 81,500: doubles up (170,000)", source: "log", evidence: { outcome: "doubled" }, confidence: "confirmed" }, + { t: 1010, kind: "double-up", detail: "81,500 → 170,000 chips (2.1×)", source: "series" }, + { t: 1300, kind: "all-in", detail: "calls all in with 170,000: loses chips (120,000)", source: "frame", evidence: { outcome: "lost" }, confidence: "confirmed" }, + { t: 1400, kind: "players-left", detail: "45 players left (under 50)", source: "series", evidence: { milestone: 50, playersLeft: 45 }, confidence: "confirmed" }, + { t: 2600, kind: "final-table", detail: "9 players left", source: "series", evidence: { milestone: 9, playersLeft: 9 }, confidence: "confirmed" }, + { t: 2900, kind: "bust", detail: "out from 120,000 chips", source: "series" }, + { t: 2900, kind: "all-in", detail: "all in with 120,000: busts", source: "frame", evidence: { outcome: "busted" }, confidence: "confirmed" }, +]; +const r31scan = () => { + const sc = scan(); + sc.source.durationSeconds = 3000; + sc.derived.tournaments = [{ key: "synth main", name: "SYNTH MAIN", from: 0, to: 2930, series: { stack: [[0, 50000], [500, 80000], [1010, 170000], [1300, 120000], [2900, 0]], playersLeft: [[0, 120], [400, 100], [1400, 45], [2600, 9]] }, facts: {} }]; + sc.derived.events = R31; + return sc; +}; + +test("rankOf / compareRank: scoops (big pots, won all-ins), then milestones, swings, pots, level-ups last; confirmed first", () => { + const order = [...R31].sort(compareRank).map((e) => `${e.t} ${e.kind}`); + assert.deepEqual(order, [ + "1000 all-in", "500 big-pot", "1010 double-up", + "2900 bust", "2600 final-table", "1400 players-left", "400 players-left", + "1300 all-in", "2900 all-in", + "700 pot", + "300 level-up", "0 level-up", + ]); + assert.equal(rankOf({ kind: "buy-in" }), null); + assert.equal(titleOf(R31[5]), "All in, doubles up"); + assert.equal(titleOf(R31[2]), "Down to 100"); + assert.equal(titleOf(R31[8]), "Under 50 left"); + assert.equal(titleOf(R31[0]), "Blinds go up"); +}); + +test("framesCut: the budget is filled first-first; a window that would pass it is passed over; the overlay rides each clip", () => { + const { timeline, frameScan, seconds, skipped } = framesCut(r31scan(), { channel: "synth", video: "s1", target: 180, stats: true }); + // The all-in and the double-up (980–1035), the big pot (480–525), the bust + // (2880–2925, the busted all-in inside it for free) = 145 s; the final + // table's and the milestones' 45 s would pass 180, so the plain pot's 16 s + // and the confirmed level-up's 16 s take the rest (177 s). + assert.deepEqual(timeline.map((c) => [c.cite, c.start, c.end, c.onscreen.title]), [ + [300, 294, 310, "Blinds go up"], + [500, 480, 525, "Takes a big pot"], + [700, 694, 710, "Takes a pot"], + [1000, 980, 1035, "All in, doubles up"], + [2900, 2880, 2925, "Busts out"], + ]); + assert.equal(seconds, 177); + assert.equal(skipped, 5); + // With the stats region on, the subtitle is the event's own words. + assert.equal(timeline[3].onscreen.subtitle, "all in with 81,500: doubles up (170,000)"); + assert.deepEqual(timeline[3].frameEvents.map((e) => [e.kind, e.confidence ?? null]), [["all-in", "confirmed"], ["double-up", null]]); + // Every clip keeps its overlay points: the start, then each change inside it. + assert.deepEqual(frameScan.overlay.map((o) => o.clip), ["f01", "f02", "f03", "f04", "f05"]); + assert.deepEqual(frameScan.overlay[3].points.map((p) => [p.at, p.stack, p.playersLeft]), [[980, 80000, 100], [1010, 170000, 100]]); + // The default budget (240 s) takes the final table too. + const roomy = framesCut(r31scan(), { channel: "synth", video: "s1" }); + assert.ok(roomy.timeline.some((c) => c.cite === 2600)); + assert.ok(roomy.seconds <= 240); }); diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -19,8 +19,9 @@ // one machine renders nowhere else; // - a QR below MIN_QR_PX_PER_MODULE_720P pixels per module once the cut is // watched at 720p, or a link too long for a QR at all; -// - everything the manifest validators say -- validateThreadEntries and -// validateFlipEntries (threads.mjs, flips.mjs), validateNarration +// - everything the manifest validators say -- validateThreadEntries, +// validateFlipEntries and validateStatsEntries (threads.mjs, flips.mjs, +// stats.mjs), validateNarration // (narration.mjs), validatePodcast (build-podcast.mjs), and the cut edits, teasers, claims and posts validators // a build runs first -- so `--lint` alone reports what a build would // refuse, all at once; @@ -82,6 +83,7 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; +import { validateStatsEntries } from "./stats.mjs"; import { qrUrlFor } from "./render-cards.mjs"; import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs"; import { validatePodcast } from "./build-podcast.mjs"; @@ -224,6 +226,8 @@ export function validatorErrors(whole) { ...validatePodcast(whole), // Release 28: where a field says it was drafted, and the publish block. ...validateDrafted(whole), ...validatePublish(whole), + // Release 31: the stats region's `stats` keys and render.chrome.stats. + ...validateStatsEntries(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); diff --git a/umtool/report-to-video/stats.mjs b/umtool/report-to-video/stats.mjs @@ -0,0 +1,184 @@ +// The STATS region for the deck (release 31, lane P3): a frame scan's running +// numbers -- the stack, the stack in big blinds, players left, the level -- +// drawn in a corner of the footage box over each clip that carries them, +// step-held between the scan's points. +// +// render.chrome: "stats": { "position": "top-left", "fields": ["stack", "stackBB", "playersLeft", "level"], "name": true } +// timeline entry: "stats": false (this clip without it) | "stats": true (this clip only, no render.chrome.stats) +// manifest: "frameScan": { "overlay": [{ "clip": "f01", "points": [{ "at": <source s>, "stack", "stackBB", "playersLeft", "level", "name" }] }] } +// +// The points are frames-cut.mjs's (`umtool new --seed frames`): the stats at +// the clip's start and at every change inside it, in SOURCE seconds. The +// schedule maps them into the cut's clock (statsSchedule); chrome-stats.mjs +// draws them; the build lays the frames over the cut as it lays the stamps'. +// +// PURE, like factcheck.mjs: validation, the defaults, the schedule. No fs, no +// ffmpeg. deck.mjs imports this file -- never the other way round. + +/** Where the stats sit in the footage box. */ +export const STATS_POSITIONS = Object.freeze(["top-left", "top-right", "bottom-left", "bottom-right"]); + +/** The numbers the region may show, in the order it shows them. */ +export const STATS_FIELDS = Object.freeze(["stack", "stackBB", "playersLeft", "level"]); + +/** Each field's label over its number. */ +export const STATS_LABELS = Object.freeze({ stack: "Stack", stackBB: "Big blinds", playersLeft: "Left", level: "Level" }); + +/** + * Every stats setting and its default. `name` puts the tournament's name over + * the numbers. The default corner is the one the fact-check stamp (top-left) + * and the popup posts (top-right) leave: bottom-left. + */ +export const STATS_DEFAULTS = Object.freeze({ position: "bottom-left", fields: STATS_FIELDS, name: true }); + +/** How long the panel takes to come in and go out, in seconds. */ +export const STATS_MOTION = Object.freeze({ in: 0.3, out: 0.25 }); + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +/** The stats settings with every default filled in (the defaults when the cut sets none). */ +export function resolveStats(render) { + const s = render?.chrome?.stats; + if (!isObj(s)) return { ...STATS_DEFAULTS, fields: [...STATS_DEFAULTS.fields] }; + return { + position: s.position ?? STATS_DEFAULTS.position, + fields: Array.isArray(s.fields) ? STATS_FIELDS.filter((f) => s.fields.includes(f)) : [...STATS_DEFAULTS.fields], + name: typeof s.name === "boolean" ? s.name : STATS_DEFAULTS.name, + }; +} + +/** + * Every reason `render.chrome.stats` cannot be built, as sentences (empty: it + * can). Unknown keys are refused, as the deck's are; validateChrome calls this. + * + * @returns {string[]} + */ +export function validateStats(s, where = "render.chrome.stats") { + if (s === undefined) return []; + if (!isObj(s)) return [`${where} must be an object`]; + const errors = []; + for (const k of Object.keys(s)) { + if (!["position", "fields", "name"].includes(k)) errors.push(`${where}.${k} is not a stats setting`); + } + if (s.position !== undefined && !STATS_POSITIONS.includes(s.position)) { + errors.push(`${where}.position must be ${STATS_POSITIONS.map((p) => `"${p}"`).join(", ")}`); + } + if (s.fields !== undefined) { + if (!Array.isArray(s.fields) || !s.fields.length || !s.fields.every((f) => STATS_FIELDS.includes(f)) || new Set(s.fields).size !== s.fields.length) { + errors.push(`${where}.fields must be a list of ${STATS_FIELDS.join(", ")}, each at most once`); + } + } + if (s.name !== undefined && typeof s.name !== "boolean") errors.push(`${where}.name must be true or false`); + return errors; +} + +/** Does the cut set the region for every clip (`render.chrome.stats`)? */ +export const statsForCut = (render) => isObj(render?.chrome?.stats); + +/** Does this entry ask for the stats: a clip, `stats: true`, or the cut's setting and not `stats: false`. */ +export function statsWanted(entry, render) { + if (entry?.type !== "clip") return false; + if (entry.stats === true) return true; + return statsForCut(render) && entry.stats !== false; +} + +/** The overlay points `frameScan.overlay` holds for a clip id (sorted by `at`), or []. */ +export function overlayPointsOf(manifest, id) { + const o = (manifest?.frameScan?.overlay ?? []).find((x) => x?.clip === id); + return Array.isArray(o?.points) ? [...o.points].filter((p) => Number.isFinite(p?.at)).sort((a, b) => a.at - b.at) : []; +} + +/** + * The clips that DECLARE the region: they ask for it (statsWanted) and the + * manifest's frame scan has points for them. What the schedule draws and + * verify-build holds the frames to. + * + * @returns {string[]} + */ +export function statsClips(manifest) { + const render = manifest?.render ?? {}; + return (manifest?.timeline ?? []).filter((e) => statsWanted(e, render) && overlayPointsOf(manifest, e.id).length).map((e) => e.id); +} + +/** + * Every `stats` key in the timeline, checked: a boolean, on a clip; `true` + * only where something can draw it (the deck on) and with points to draw + * (the manifest's `frameScan.overlay` names the clip). The build refuses with + * these before it fetches; the lint says them. + * + * @returns {string[]} + */ +export function validateStatsEntries(manifest) { + const errors = []; + const render = manifest?.render ?? {}; + const deck = render.chrome?.engine === "hyperframes" && render.chrome?.layout === "deck"; + if (statsForCut(render) && !deck) errors.push("render.chrome.stats is drawn by the deck: render.chrome needs layout \"deck\""); + (manifest?.timeline ?? []).forEach((e, i) => { + if (e?.stats === undefined) return; + const where = `timeline[${i}] (${e.id ?? "?"}).stats`; + if (typeof e.stats !== "boolean") { errors.push(`${where} must be true or false`); return; } + if (e.type !== "clip") { errors.push(`${where}: only a clip carries the stats`); return; } + if (e.stats === true && !deck) errors.push(`${where}: the stats are drawn by the deck, and render.chrome is not the deck`); + if (e.stats === true && !overlayPointsOf(manifest, e.id).length) errors.push(`${where}: frameScan.overlay has no points for ${e.id}`); + }); + return errors; +} + +/** The value of each field at source second `t`: the last point at or before it (the first point's before it). */ +function valuesAt(points, t, fields) { + let cur = points[0]; + for (const p of points) { + if (p.at > t) break; + cur = p; + } + const out = {}; + for (const f of fields) out[f] = Number.isFinite(cur?.[f]) ? cur[f] : null; + return out; +} + +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** + * Where and what the region draws, in the CUT's clock. `segments` are the + * schedule's, in order, each `{ id, start, duration, sourceFrom?, points? }` + * (`sourceFrom` the source second the segment's picture starts at -- its + * play window's `from` -- and `points` its overlay points, only on a clip + * that declares the region). + * + * A clip's panel is up from its start (its incoming dissolve's middle after + * the first) to its end (the outgoing dissolve's middle before the last). + * Its STATES are the values at the picture's first source second, then at + * each point inside the clip -- a source second `t` lands at `start + (t - + * sourceFrom)` -- each held until the next. (The build snaps a clip's ends to + * a nearby silence, so a state can land up to `render.snapWindow` from its + * frame; the scan reads a frame every few seconds.) + * + * @returns {{ position: string, fields: string[], name: boolean, + * clips: Array<{ segment: string, in: number, out: number, name: string|null, + * states: Array<{ at: number, values: Record<string, number|null> }> }> } | null} + */ +export function statsSchedule({ segments, D, total, render }) { + const cfg = resolveStats(render); + const clips = []; + segments.forEach((s, i) => { + if (!s.points?.length || !Number.isFinite(s.sourceFrom)) return; + const next = segments[i + 1]; + const lo = s.start + (i > 0 ? D / 2 : 0); + const hi = next ? next.start + D / 2 : total; + if (!(hi > lo)) return; + const end = s.sourceFrom + (hi - s.start); + const states = [{ at: r3(lo), values: valuesAt(s.points, s.sourceFrom + (lo - s.start), cfg.fields) }]; + for (const p of s.points) { + if (p.at <= s.sourceFrom + (lo - s.start) || p.at >= end) continue; + const at = r3(s.start + (p.at - s.sourceFrom)); + const values = valuesAt(s.points, p.at, cfg.fields); + const last = states[states.length - 1]; + if (cfg.fields.every((f) => last.values[f] === values[f])) continue; + if (at <= last.at) last.values = values; + else states.push({ at, values }); + } + const named = s.points.find((p) => typeof p.name === "string" && p.name)?.name ?? null; + clips.push({ segment: s.id, in: r3(lo), out: r3(hi), name: cfg.name ? named : null, states }); + }); + return clips.length ? { position: cfg.position, fields: cfg.fields, name: cfg.name, clips } : null; +} diff --git a/umtool/report-to-video/stats.test.mjs b/umtool/report-to-video/stats.test.mjs @@ -0,0 +1,258 @@ +// The stats region (release 31, lane P3): stats.mjs (settings, which clips +// declare it, the schedule in the cut's clock), deck.mjs (validation, the +// schedule, the geometry), chrome-stats.mjs (the page), the overlay chain, +// and a tiny real build -- two lavfi clips beside the manifest, a stub +// renderer -- that verify-build passes, and fails loudly once the frames or +// a declared clip are missing. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + overlayPointsOf, resolveStats, statsClips, statsSchedule, statsWanted, validateStats, validateStatsEntries, +} from "./stats.mjs"; +import { deckSchedule, estimateSchedule, statsGeometry, validateChrome } from "./deck.mjs"; +import { panelSpans, statsCues, statsHtml, statsValue } from "./chrome-stats.mjs"; +import { buildVideo, chromeOverlayChain, setProgressMode, statsRegion } from "./build-video.mjs"; +import { verifyBuild } from "./verify-build.mjs"; +import { lintManifest } from "./lint.mjs"; +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const DECK = { engine: "hyperframes", layout: "deck", deck: {} }; +const render = (chrome = { ...DECK, stats: {} }, more = {}) => ({ width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, chrome, ...more }); + +// A frame scan's overlay, frames-cut's shape: source seconds. +const OVERLAY = { + overlay: [ + { clip: "c1", points: [{ at: 100, name: "SYNTH MAIN", stack: 50000, stackBB: 50, playersLeft: 120, level: 1 }, { at: 106, name: "SYNTH MAIN", stack: 80000, stackBB: 66.7, playersLeft: 120, level: 1 }] }, + { clip: "c2", points: [{ at: 400, name: "SYNTH MAIN", stack: 170000, stackBB: 106.3, playersLeft: 45, level: 4 }] }, + ], +}; +const ENTRIES = [ + { type: "clip", id: "c1", channel: "synth", video: "v1", start: 100, end: 110 }, + { type: "card", id: "k1", seconds: 3, heading: "Between" }, + { type: "clip", id: "c2", channel: "synth", video: "v1", start: 400, end: 408 }, +]; + +test("settings: defaults, validation (unknown keys and bad values refused), the deck accepts `stats`", () => { + assert.deepEqual(resolveStats(render()), { position: "bottom-left", fields: ["stack", "stackBB", "playersLeft", "level"], name: true }); + assert.deepEqual(resolveStats(render({ ...DECK, stats: { fields: ["level", "stack"], name: false } })).fields, ["stack", "level"]); + assert.deepEqual(validateStats({}), []); + assert.deepEqual(validateStats({ position: "middle", fields: ["stack", "chips"], name: "yes", colour: 1 }), [ + "render.chrome.stats.colour is not a stats setting", + 'render.chrome.stats.position must be "top-left", "top-right", "bottom-left", "bottom-right"', + "render.chrome.stats.fields must be a list of stack, stackBB, playersLeft, level, each at most once", + "render.chrome.stats.name must be true or false", + ]); + assert.deepEqual(validateChrome({ ...DECK, stats: {} }, render()), []); + assert.deepEqual(validateChrome({ ...DECK, stats: { position: "top-right" } }, render()), []); + assert.ok(validateChrome({ ...DECK, stats: [] }, render()).includes("render.chrome.stats must be an object")); +}); + +test("which clips declare it: the cut's setting, a clip's own true or false, and points to draw", () => { + const r = render(); + assert.equal(statsWanted(ENTRIES[0], r), true); + assert.equal(statsWanted(ENTRIES[1], r), false); + assert.equal(statsWanted({ ...ENTRIES[0], stats: false }, r), false); + assert.equal(statsWanted({ ...ENTRIES[0], stats: true }, render(DECK)), true); + assert.equal(statsWanted(ENTRIES[0], render(DECK)), false); + const m = { render: r, timeline: [...ENTRIES, { type: "clip", id: "c3", video: "v1", start: 0, end: 2 }], frameScan: OVERLAY }; + assert.deepEqual(statsClips(m), ["c1", "c2"]); + assert.deepEqual(overlayPointsOf(m, "c2").map((p) => p.at), [400]); + assert.deepEqual(validateStatsEntries(m), []); + // A stats key: a boolean, on a clip, true only under the deck and with points. + const bad = { + render: render({ engine: "hyperframes", layout: "deck" }), + frameScan: OVERLAY, + timeline: [{ ...ENTRIES[0], stats: "on" }, { ...ENTRIES[1], stats: true }, { type: "clip", id: "c9", video: "v1", start: 0, end: 1, stats: true }], + }; + assert.deepEqual(validateStatsEntries(bad), [ + "timeline[0] (c1).stats must be true or false", + "timeline[1] (k1).stats: only a clip carries the stats", + "timeline[2] (c9).stats: frameScan.overlay has no points for c9", + ]); + assert.deepEqual(validateStatsEntries({ render: { chrome: undefined }, timeline: [{ ...ENTRIES[0], stats: true }], frameScan: OVERLAY }), [ + "timeline[0] (c1).stats: the stats are drawn by the deck, and render.chrome is not the deck", + ]); +}); + +test("the lint says the stats keys a build would refuse", () => { + const m = { slug: "s", title: "S", render: render({ ...DECK }), frameScan: OVERLAY, timeline: [{ ...ENTRIES[0], stats: "on" }] }; + const lint = lintManifest(m, { exists: () => true }); + assert.ok(lint.errors.some((e) => /c1\)\.stats must be true or false/.test(e)), JSON.stringify(lint.errors)); +}); + +test("statsSchedule: source seconds into the cut's clock, held between points, up from mid-dissolve to mid-dissolve", () => { + const segs = [ + { id: "c1", start: 0, duration: 10, sourceFrom: 100, points: OVERLAY.overlay[0].points }, + { id: "k1", start: 9.5, duration: 3 }, + { id: "c2", start: 12, duration: 8, sourceFrom: 400, points: OVERLAY.overlay[1].points }, + ]; + const s = statsSchedule({ segments: segs, D: 0.5, total: 20, render: render() }); + assert.equal(s.position, "bottom-left"); + assert.deepEqual(s.clips.map((c) => [c.segment, c.in, c.out, c.name]), [["c1", 0, 9.75, "SYNTH MAIN"], ["c2", 12.25, 20, "SYNTH MAIN"]]); + assert.deepEqual(s.clips[0].states.map((x) => [x.at, x.values.stack, x.values.stackBB]), [[0, 50000, 50], [6, 80000, 66.7]]); + assert.deepEqual(s.clips[1].states.map((x) => [x.at, x.values.playersLeft]), [[12.25, 45]]); + // A clip whose picture starts after a point (a cut inside the extent) opens on the value held there. + const late = statsSchedule({ segments: [{ id: "c1", start: 0, duration: 4, sourceFrom: 107, points: OVERLAY.overlay[0].points }], D: 0, total: 4, render: render() }); + assert.deepEqual(late.clips[0].states, [{ at: 0, values: { stack: 80000, stackBB: 66.7, playersLeft: 120, level: 1 } }]); + // Nothing declared: no stats in the schedule. + assert.equal(statsSchedule({ segments: [{ id: "c1", start: 0, duration: 4 }], D: 0, total: 4, render: render() }), null); +}); + +test("deckSchedule / estimateSchedule carry `stats` only when a clip declares it", () => { + const est = estimateSchedule({ render: render(), timeline: ENTRIES, frameScan: OVERLAY }); + assert.deepEqual(est.stats.clips.map((c) => c.segment), ["c1", "c2"]); + // The c1 point at 106 lands 6 s into the cut (no lead-in: no cutStart). + assert.deepEqual(est.stats.clips[0].states.map((x) => x.at), [0, 6]); + const off = estimateSchedule({ render: render(DECK), timeline: ENTRIES, frameScan: OVERLAY }); + assert.equal("stats" in off, false); + const one = deckSchedule({ entries: [ENTRIES[0], { ...ENTRIES[2], stats: false }], durs: [10, 8], D: 0, render: render(), frameScan: OVERLAY }); + assert.deepEqual(one.stats.clips.map((c) => c.segment), ["c1"]); +}); + +test("the geometry: a panel in the footage box's corner, scaled with the frame", () => { + assert.deepEqual(statsGeometry(render()), { x: 201, y: 710, width: 648, height: 150 }); + assert.deepEqual(statsGeometry(render({ ...DECK, stats: { position: "top-right", name: false, fields: ["stack", "playersLeft"] } })), { x: 1371, y: 30, width: 348, height: 112 }); + const small = statsGeometry(render(undefined, { width: 1280, height: 720 })); + assert.equal(small.width, 432); + assert.equal(small.height, 100); +}); + +test("the page: one block per state, the numbers as the panel shows them, every cue stating its from", () => { + assert.equal(statsValue("stack", 41000), "41,000"); + assert.equal(statsValue("stack", 323170), "323.2K"); + assert.equal(statsValue("stack", 1250000), "1.25M"); + assert.equal(statsValue("stackBB", 66.66), "66.7"); + assert.equal(statsValue("stackBB", 202.2), "202"); + assert.equal(statsValue("playersLeft", null), "—"); + assert.deepEqual(panelSpans([{ in: 0, out: 5 }, { in: 5, out: 9 }, { in: 12, out: 14 }]), [{ in: 0, out: 9 }, { in: 12, out: 14 }]); + + const schedule = estimateSchedule({ render: render(), timeline: ENTRIES, frameScan: OVERLAY }); + const { init, cues } = statsCues(schedule); + assert.deepEqual(Object.keys(init).sort(), ["pn", "s0_0", "s0_1", "s1_0"]); + // The first state shows at the clip's in, hides as the second shows. + const s00 = cues.filter((c) => c.k === "s0_0"); + assert.deepEqual(s00.map((c) => [c.at, c.from.autoAlpha, c.to.autoAlpha]), [[0, 0, 1], [6, 1, 0]]); + for (const c of cues) assert.ok(Object.keys(c.to).every((p) => p in c.from), JSON.stringify(c)); + + const html = statsHtml(schedule, render(), { fonts: { regular: "assets/DeckSans.ttf", bold: "assets/DeckSansBold.ttf" } }); + assert.match(html, /data-composition-id="stats"/); + assert.match(html, /data-width="648" data-height="150"/); + assert.match(html, /<div class="name">SYNTH MAIN<\/div>/); + assert.match(html, /data-k="s0_1"[^>]*>.*<div class="val">80,000<\/div>.*<div class="val">66\.7<\/div>/s); + assert.match(html, /<div class="lab">Left<\/div><div class="val">45<\/div>/); + // The palette's roles, never a colour of its own for the ground or the text. + assert.match(html, /background: rgba\(18, 16, 26, 0\.84\); border-left: 5px solid #a97bff/); + assert.throws(() => statsHtml({ ...schedule, stats: undefined }, render()), /draws no clip's stats/); +}); + +test("the overlay chain lays the stats like the stamps: reinit off, rgba, shortest", () => { + const r = render(); + const region = statsRegion(r, "/x/chrome/stats-frames", { layout: undefined }); + assert.deepEqual({ ...region, frames: undefined }, { name: "stats", frames: undefined, x: 201, y: 710, width: 648, height: 150 }); + const chain = chromeOverlayChain(r, [region], "[0:v]", 1, {}); + assert.deepEqual(chain.inputs.slice(0, 2), ["-reinit_filter", "0"]); + assert.match(chain.chain, /\[1:v\]format=rgba\[hfa0\];\[0:v\]\[hfa0\]overlay=x=201:y=710:format=yuv444:shortest=1/); +}); + +const have = ["ffmpeg", "ffprobe", "magick"].every((b) => spawnSync(b, ["-version"]).status === 0); + +test("a deck build draws the stats region, verify-build holds it; a missing sequence or clip fails loudly", { skip: !have && "needs ffmpeg, ffprobe and magick" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-stats-build-")); + const env = process.env.HYPERFRAMES_BIN; + t.after(() => { + if (env === undefined) delete process.env.HYPERFRAMES_BIN; + else process.env.HYPERFRAMES_BIN = env; + rmSync(root, { recursive: true, force: true }); + }); + // A renderer that writes the frames the composition declares, as real PNGs, + // and logs each project it renders. + const stub = path.join(root, "hf-stub.mjs"); + writeFileSync(stub, `#!/usr/bin/env node +import { spawnSync } from "node:child_process"; +import { appendFileSync, copyFileSync, mkdirSync, readFileSync } from "node:fs"; +const a = process.argv.slice(2); +if (a.includes("--version")) { process.stdout.write("0.0.0-test\\n"); process.exit(0); } +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +appendFileSync(${JSON.stringify(path.join(root, "renders.log"))}, a.at(-1) + "\\n"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const w = Number((/data-width="(\\d+)"/.exec(html) ?? [0, 640])[1]); +const h = Number((/data-height="(\\d+)"/.exec(html) ?? [0, 360])[1]); +mkdirSync(out, { recursive: true }); +const one = out + "/.one.png"; +spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x112233@0.5:size=" + w + "x" + h, "-frames:v", "1", "-pix_fmt", "rgba", one]); +for (let i = 1; i <= Math.round(dur * fps); i += 1) copyFileSync(one, out + "/frame_" + String(i).padStart(6, "0") + ".png"); +`); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + + mkdirSync(path.join(root, "media"), { recursive: true }); + for (const name of ["a", "b"]) { + const r = spawnSync("ffmpeg", [ + "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=10:duration=3", + "-f", "lavfi", "-i", "sine=f=330:r=48000:d=3", "-shortest", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", + "-c:a", "aac", path.join(root, "media", `${name}.mp4`), + ]); + assert.equal(r.status, 0, String(r.stderr)); + } + const manifestPath = path.join(root, "video.manifest.json"); + const manifest = { + slug: "stats", title: "Stats", + render: { + width: 1920, height: 1080, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2, + palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, + chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { show: false } }, stats: {} }, + }, + timeline: [ + { id: "c1", type: "clip", src: "media/a.mp4", start: 0, end: 3 }, + { id: "c2", type: "clip", src: "media/b.mp4", start: 0, end: 3 }, + ], + frameScan: { + overlay: [ + { clip: "c1", points: [{ at: 0, name: "SYNTH MAIN", stack: 50000, stackBB: 50, playersLeft: 120, level: 1 }, { at: 1.5, name: "SYNTH MAIN", stack: 80000, stackBB: 66.7, playersLeft: 120, level: 1 }] }, + { clip: "c2", points: [{ at: 0, name: "SYNTH MAIN", stack: 170000, stackBB: 106.3, playersLeft: 45, level: 4 }] }, + ], + }, + }; + writeFileSync(manifestPath, JSON.stringify(manifest)); + const v = path.join(root, "out", "sourced"); + setProgressMode(() => {}); + try { + await buildVideo({ manifestPath, opts: { noNetwork: true } }); + } finally { + setProgressMode("human"); + } + const schedule = JSON.parse(readFileSync(path.join(v, "schedule.json"), "utf8")); + assert.deepEqual(schedule.stats.clips.map((c) => c.segment), ["c1", "c2"]); + assert.match(readFileSync(path.join(root, "renders.log"), "utf8"), /chrome\/stats\n/); + assert.match(readFileSync(path.join(v, "chrome", "stats", "index.html"), "utf8"), /<div class="val">80,000<\/div>/); + + const ok = await verifyBuild(manifestPath, {}); + assert.deepEqual(ok.problems, []); + assert.equal(ok.deck.stats.frames, ok.deck.expectedFrames); + assert.equal(ok.deck.stats.declared, 2); + + // The frames gone (pruned with no record of them): loud. + const prunedPath = path.join(v, "chrome", "pruned.json"); + const pruned = JSON.parse(readFileSync(prunedPath, "utf8")); + delete pruned.dirs["stats-frames"]; + writeFileSync(prunedPath, JSON.stringify(pruned)); + const noFrames = await verifyBuild(manifestPath, {}); + assert.equal(noFrames.ok, false); + assert.ok(noFrames.problems.some((p) => /stats region is declared but .*stats-frames has no frames/.test(p)), JSON.stringify(noFrames.problems)); + + // A clip that declares the stats but is not in the schedule's: loud. + const sched2 = { ...schedule, stats: { ...schedule.stats, clips: schedule.stats.clips.filter((c) => c.segment !== "c2") } }; + writeFileSync(path.join(v, "schedule.json"), JSON.stringify(sched2)); + const missing = await verifyBuild(manifestPath, {}); + assert.ok(missing.problems.some((p) => /^c2 declare the stats region but .* draws none for them/.test(p)), JSON.stringify(missing.problems)); +}); diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs @@ -20,6 +20,7 @@ import path from "node:path"; import { postsRegions, selectVariant, variantPaths } from "./build-video.mjs"; import { deckGeometry, deckOn, frameCount, postsGeometry, resolveDeck, teaserSeconds, transitionOf } from "./deck.mjs"; +import { statsClips } from "./stats.mjs"; import { frameKeyOf, framesOf } from "./prune-frames.mjs"; const execFileP = promisify(execFile); @@ -90,7 +91,11 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n // the deliverable. Both are measured against the schedule the build wrote. let deck = null; if (deckOn(manifest.render)) { - deck = await verifyDeck(path.join(root, variant), manifest.render, file, problems); + deck = await verifyDeck(path.join(root, variant), manifest.render, file, problems, manifest); + } else if (statsClips(manifest).length) { + // Only the deck draws the stats: a clip that declares them in a cut + // without it was built without them. + problems.push(`${statsClips(manifest).join(", ")} declare the stats region, but the deck is off — nothing drew them`); } const teasers = await verifyTeasers(path.join(root, variant), manifest, problems, { noXfade, since: st.mtimeMs }); @@ -107,8 +112,11 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n * When the schedule carries posts, each window's `chrome/posts-<segment>-frames` * holds that window's frame count, and each held clip's freeze is in the file. * When it stamps a claim, `chrome/stamp-frames` is as long as the deck's. + * With `manifest`, every clip that declares the stats region (stats.mjs + * `statsClips`) is in the schedule's `stats`, and `chrome/stats-frames` is as + * long as the deck's. */ -export async function verifyDeck(variantDir, render, file, problems) { +export async function verifyDeck(variantDir, render, file, problems, manifest = null) { const schedPath = path.join(variantDir, "schedule.json"); const schedule = await readFile(schedPath, "utf8").then(JSON.parse, () => null); if (!schedule || schedule.kind !== "deck") { @@ -159,6 +167,21 @@ export async function verifyDeck(variantDir, render, file, problems) { stamp = { frames: got, expectedFrames: want, stamps: schedule.factcheck.stamps.length }; if (got !== want) problems.push(`${dir} holds ${got} frames; the fact-check stamps run the whole cut, ${want}`); } + // The stats region: every clip that declares it drawn, one sequence for the + // whole cut, as long as the deck's. Loud when a declared clip is missing or + // the frames are: a cut that lost its overlay looks finished otherwise. + let stats = null; + const declared = manifest ? statsClips(manifest) : []; + if (declared.length || schedule.stats?.clips?.length) { + const drawn = new Set((schedule.stats?.clips ?? []).map((c) => c.segment)); + const missing = declared.filter((id) => !drawn.has(id)); + if (missing.length) problems.push(`${missing.join(", ")} declare the stats region but ${schedPath} draws none for them — rebuild the chrome`); + const dir = path.join(variantDir, "chrome", "stats-frames"); + const got = await countFrames(dir); + stats = { frames: got, expectedFrames: want, clips: drawn.size, declared: declared.length }; + if (got === 0) problems.push(`the stats region is declared but ${dir} has no frames — built with --no-chrome, or the region never rendered`); + else if (got !== want) problems.push(`${dir} holds ${got} frames; the stats region runs the whole cut, ${want}`); + } // The posts windows: each laid at its own second, each as long as snapWindow says. const posts = []; for (const r of postsRegions(render, variantDir, schedule)) { @@ -173,6 +196,7 @@ export async function verifyDeck(variantDir, render, file, problems) { total: schedule.total, frames, expectedFrames: want, videoFrames, segments: schedule.segments.length, ...(feed ? { feed } : {}), ...(stamp ? { stamp } : {}), + ...(stats ? { stats } : {}), ...(posts.length ? { posts } : {}), ...(holds.length ? { holds } : {}), }; @@ -319,6 +343,9 @@ async function main() { if (res.deck.feed) { console.log(` posts feed: ${res.deck.feed.frames}/${res.deck.feed.expectedFrames} frame(s), ${res.deck.feed.posts} post(s), no hold`); } + if (res.deck.stats) { + console.log(` stats: ${res.deck.stats.frames}/${res.deck.stats.expectedFrames} frame(s) over ${res.deck.stats.clips} of ${res.deck.stats.declared} declared clip(s)`); + } for (const w of res.deck.posts ?? []) { console.log(` posts on ${w.segment}: ${w.frames}/${w.expectedFrames} frame(s) at ${w.at.toFixed(3)}s`); }