Archilyzer · Source

archilyzer

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

commit 521c3fa5f777dff0ea35b768ab5b992dd1be730c
parent b5192ad09507c728468143d9f97d76ce2b6b72c1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 00:08:06 -0400

umtool: report-to-video lints before it renders, prunes the chrome's frames after the mux, never writes through a linked segment, and renders in the heavy slot

- lint.mjs (`node lint.mjs <manifest>`, `build-video.mjs --lint`): errors for
  an image src not relative to the manifest or naming no file (timeline
  images, panels, posts' shot/logo under the deck), a QR under 1.5 px/module
  at 720p or a link no QR holds, and every manifest validator (threads and
  flips included); warnings for a QR under 2.0 and a teaser line past the
  34-character house style (a title's first tier is the frame's limit,
  which validateTeasers already refuses). Every build runs it after the
  validators and before anything renders; an error refuses (--no-lint
  bypasses), `--only` lints its entry, --chapters-only is not held up.
- prune-frames.mjs: after the final mux (a full build, --chrome-only) the
  chrome/<name>-frames and chrome/work-* directories go, recorded first in
  chrome/pruned.json (frames, key); --keep-frames keeps them. Not after
  --no-chrome, not under the legacy chart band. segments/ is never touched;
  a symlink is not followed. verify-build reads a pruned sequence's count and
  key from the record, unless the cut is newer than the prune.
- --chrome-only builds a MISSING segment from the cache (skipFetch) after
  every refusal and never writes an existing one; --chrome-preview still
  refuses a missing one. An entry's rebuild first unlinks its files that are
  hard links or symlinks (detachSegmentFiles; a clip only once its source is
  in hand), and a teaser re-encode writes beside and renames over, its record
  too: another take's linked segments are never written through.
- The rendering runs (full build, --chrome-only, --chrome-preview,
  --rail-only) take the machine's heavy slot (heavy-gate.mjs over
  scripts/queue-lock.mjs withHeavy), its lock pinned to this checkout's git
  common dir; loaded by a run-time URL so the umtool bundle never sees it.
  HEAVY=0 / HEAVY_HELD pass through. compose-chrome's rendererEnv untouched.
- setProgressMode takes a function (tests read events without stdout).

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

Diffstat:
Meditor/CHANGELOG.md | 4++++
Mumtool/report-to-video/README.md | 29++++++++++++++++++++++++++---
Mumtool/report-to-video/build-video.mjs | 291+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Aumtool/report-to-video/heavy-gate.mjs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/heavy-gate.test.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/lint.mjs | 315+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/lint.test.mjs | 272+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 2++
Aumtool/report-to-video/prune-frames.mjs | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/prune-frames.test.mjs | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/segment-links.test.mjs | 249+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/verify-build.mjs | 16++++++++--------
12 files changed, 1614 insertions(+), 68 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog ## [Unreleased] +- **A report video is linted before it renders.** `node umtool/report-to-video/lint.mjs <manifest>` (or `build-video.mjs <manifest> --lint`) lists what a render would get wrong and exits 1 on an error: a picture whose `src` is not a path relative to the manifest, or names no file there (a timeline image, its panels, a post's shot or logo); a QR under 1.5 px per module once the cut is watched at 720p, or a link too long for any QR; and everything the manifest validators refuse, threads and flips included. A QR under 2.0 px per module and a teaser line past the 34-character house style are warnings. Every build runs the same lint before it renders anything: an error refuses it (`--no-lint` builds anyway), a warning is a note, and `--only <id>` lints that entry alone. +- **A report video's build deletes the chrome's frames once the cut is muxed.** A build, or `--chrome-only`, now removes `out/<variant>/chrome/<name>-frames` and the renderer's `chrome/work-*` after the final mux (1–2 GB a take), and records each sequence's frame count and key in `chrome/pruned.json`, which `verify-build.mjs` reads in their place. `--keep-frames` keeps them. `segments/` is never touched. +- **A take can re-lay its chrome over another take's segments without touching them.** `--chrome-only` builds a segment that is missing from what is cached, where it used to refuse, and never writes a segment that exists. Rebuilding an entry (`--only <id>`, a full build, a teaser whose words changed) first unlinks that entry's files that are hard links or symlinks, then writes new files, so another take's segments linked into `segments/` are never written through. +- **A report render waits for the machine's heavy slot, and a clip fetch waits for its editor job.** `build-video.mjs` takes the heavy slot (the one `pnpm heavy` and e2e use: one heavy job at a time, above the memory floor) for a full build, `--chrome-only`, `--chrome-preview` and `--rail-only`. A fetch, `--only`, `--chapters-only` and `--thumbnail` do not take it, and `HEAVY=0` bypasses it. `fetch-via-editor.mjs` no longer gives up after 10 minutes (6 hours for `--all`): it waits as long as the job does, prints the job's place in the editor's queue when it changes, retries polls the editor drops, and stops on Ctrl-C (exit 130) while the job keeps running on the editor. - **An X fetch with a `limit` stops at that many posts.** "Fetch posts" with `limit` (`pnpm ops fetch-posts {"limit": 400}`) on a gallery-dl X channel read the whole history instead — a new channel walked 3,803 posts under the rate limit and held the platform queue for hours — because the cap counted media files, which a metadata-only read has almost none of. It now caps the posts themselves. - **A home seeder of last resort, behind a VPN.** `archilyzer seed` seeds the playable torrents of the sites named in the new `settings.seeder` (`sites`, `trackers`, `maxUploadKiBps`, `maxConnections`, `pollSeconds`, `standbyAfterSeconds`, `bindInterface`; SETTINGS.md) to desktop clients over TCP and to browsers over WebRTC — but each torrent only while no other seeder has it: other seeders seen on every poll for `standbyAfterSeconds` puts that torrent on standby (it stops announcing and closes its peers, keeping the data), and it comes back at once when a leecher is waiting with no other source, or after the same window with no other seeder. Every change is logged with its reason. No DHT, no local discovery, no UPnP. `archilyzer tracker` is a self-hosted HTTP + WebSocket tracker that tracks only those torrents. `docker-compose.seeder.yml` (profile `seeder`) runs both inside a WireGuard container's network namespace (gluetun, its firewall always on), so a tunnel that is down means no network, never the home connection; the WireGuard config is yours (`SEEDER_WG_CONF`, required, mounted read-only). `archilyzer doctor` compares the seeder's egress address with the host's and fails when they are the same; it says "seeder not configured" until `seeder.sites` names a site. - **Saved videos can be made browser-playable, with a torrent each.** `pnpm ops prepare-playable` (`POST /api/ops/prepare-playable`) and `archilyzer media playable <slug>` remux each of a channel's saved containers — without re-encoding (`-c copy`) — into an mp4 with its index in front, or a webm when it already is one (VP9/AV1 with Opus), drop subtitles, metadata and chapters, and make one single-file torrent of the copy: named `<id>.<ext>`, no web seed, no comment, no "created by", 256 KiB–1 MiB pieces. They go to `playable/<slug>/<id>/` beside the saved-video store, listed in `playable/<slug>/playable.json` with each infohash. `"trackers"` is the announce list written into each torrent (none by default); it is not part of the infohash, so the same torrent can be announced elsewhere later. A video already prepared from the same source (by sha256) is skipped, so a re-run is a no-op; a codec a browser cannot play without re-encoding (HEVC, MPEG-4 Part 2) is listed and left alone. diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -114,6 +114,24 @@ Everything is cached by content, so iteration is cheap: by any cached file that **contains** it, a nudge inside the existing pad costs nothing at all. Only a window that escapes every cached file downloads again. - **Preview one entry** — `--only <id>` builds a single segment and stops. +- **Lint first** — `--lint` (or `node lint.mjs <manifest>`) says what a render + would get wrong and stops: a picture whose `src` is not a path relative to the + manifest or names no file, a QR under 1.5 px per module once the cut is + watched at 720p (errors), a QR under 2.0 or a teaser line past the 34-character + house style (warnings), and everything the manifest validators refuse. Every + build runs the same lint before it renders anything — an error refuses it + (`--no-lint` builds anyway), a warning is a note. `--only` lints its entry. +- **Disk** — after the final mux a build (and `--chrome-only`) prunes the + chrome's frame sequences, `out/<variant>/chrome/<name>-frames` and the renderer's + `chrome/work-*` — 1–2 GB a take — and records each one's frame count and key + in `chrome/pruned.json`, which `verify-build` reads in their place. + `--keep-frames` keeps them (a later `--chrome-only` then reuses a render whose + key did not change). `segments/` is never touched. +- **The heavy slot** — a run that renders the cut (a full build, + `--chrome-only`, `--chrome-preview`, `--rail-only`) takes the machine's heavy + slot first (`scripts/queue-lock.mjs`, the one `pnpm heavy` and e2e take): one + heavy job at a time, above the memory floor. A fetch, `--only`, the chapters + and the thumbnail do not. `HEAVY=0` bypasses it. - **Work offline** — `--skip-fetch` fails loudly instead of downloading, so you can confirm you are working entirely from cache. `--no-network` is the stronger form: every clip's source is found on disk **before** anything is @@ -1654,9 +1672,14 @@ node umtool/report-to-video/compose-chrome.mjs <manifest.json> [--region chart|d - **`--chrome-only`** — re-lay the deck over the segments already on disk: re-probe, rewrite the schedule, recompose (re-render only if the key - changed), re-concat with the overlay, re-mux the chapters. **No segment is - rebuilt and nothing is fetched.** The driver labels this "re-render - on-screen". + changed), re-concat with the overlay, re-mux the chapters. **No segment on + disk is rebuilt or written, and nothing is fetched**: a segment that is + MISSING is built from what is cached (as `--skip-fetch` would), so a take can + hard-link another take's `segments/*` into its own out dir and re-lay its + chrome over them. Any rebuild of an entry (`--only`, a full build, a teaser + whose words changed) first unlinks that entry's files that are links, and + writes files of its own: the other take's are never written through. The + driver labels this "re-render on-screen". - **`--no-chrome`** — the deck's framing with no overlay: a fast picture check of the letterboxing, with nothing composed or rendered. Holds and footage moves are part of the CUT, not the chrome, so `--no-chrome` still applies diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -49,6 +49,11 @@ // --audio-fallback With --no-network or --skip-fetch: play such a clip from // its sound under a poster instead (logged audio-fallback) // --only <id> Build a single entry's segment and stop (for iterating) +// --lint Lint the manifest (lint.mjs) and stop: every warning and +// error, exit 1 on an error. Every build runs the same lint +// after its validators and before it renders anything: an +// error refuses it, a warning is a note. +// --no-lint Build without the lint (an old manifest it refuses) // --no-xfade Hard cuts instead of crossfades (much faster; concat copy) // --progress ndjson One JSON event per line instead of prose (for umtool) // --continue-on-error Record a failed entry and carry on, instead of aborting @@ -72,7 +77,20 @@ // --chrome-only Re-lay the deck over the segments already on disk: re-probe, // rewrite the schedule, recompose (re-render only when the key // changed), re-concat with the overlay, re-mux the chapters. -// No segment is rebuilt, nothing is fetched. +// A segment ON DISK is never rebuilt or written (it may be a +// hard link to another take's), and nothing is fetched: a +// segment that is MISSING is built, from what is cached (as +// --skip-fetch would). A teaser's is chrome, rebuilt when its +// words change -- into a new file, never through a link. +// --keep-frames Keep chrome/<name>-frames and chrome/work-* after the final mux. +// By default a build or --chrome-only that muxed the final +// file prunes them (prune-frames.mjs; chrome/pruned.json +// records what went): 1-2 GB a take, which only a later +// --chrome-only would reuse. segments/ is never touched. +// +// The rendering runs (a full build, --chrome-only, --chrome-preview, --rail-only) +// take the machine's heavy slot first (heavy-gate.mjs, scripts/queue-lock.mjs): +// one heavy job at a time, above the memory floor. HEAVY=0 bypasses it. // --no-chrome The deck's framing without the overlay (a fast picture check) // --chrome-preview <at> <dur> Render only that window of the deck and write // out/<variant>/<slug>.preview.mp4 of it, from the cached @@ -83,8 +101,9 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { promisify } from "node:util"; -import { mkdir, writeFile, readFile, access, readdir, rename, rm, stat } from "node:fs/promises"; +import { mkdir, writeFile, readFile, access, readdir, rename, rm, stat, lstat, unlink } from "node:fs/promises"; import path from "node:path"; +import { pathToFileURL } from "node:url"; import { renderCard, renderFooterAssets, renderRailAssets, renderScrollCard, renderChartCard, @@ -115,6 +134,9 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; +// The lint a build runs before it renders, and the prune after its final mux. +import { lintManifest, lintManifestFile } from "./lint.mjs"; +import { pruneChromeFrames } from "./prune-frames.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. import { platformArgsForUrl } from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; @@ -417,6 +439,13 @@ let EMIT = (ev, fields = {}) => { }; export function setProgressMode(mode) { + // A function receives each event as an object (`{ ev, ...fields }`): a test + // reads the events without taking over stdout, which the test runner's own + // reporter writes to. + if (typeof mode === "function") { + EMIT = (ev, fields = {}) => mode({ ev, ...fields }); + return; + } EMIT = mode === "ndjson" ? (ev, fields = {}) => process.stdout.write(JSON.stringify({ ev, ...fields }) + "\n") @@ -1027,6 +1056,10 @@ const encodeArgsVideoOnly = (render) => [ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, provenance, framing = null) { const outDir = dirs.dir; const { path: raw, fetchStart, scan } = await fetchClip(entry, meta, render, dirs.local, opts); + // Its source in hand, and only then: a link to another take's files is + // unlinked before anything is written (detachSegmentFiles), so a clip whose + // source cannot be had leaves this take's segment as it was. + await detachSegmentFiles(path.join(outDir, "segments"), entry.id); const seg = path.join(outDir, "segments", `${entry.id}.mp4`); const pal = render.palette; const { width, height } = render; @@ -1284,6 +1317,39 @@ async function buildClipSegment(entry, meta, render, dirs, opts, chrome, nodes, return seg; } +/** + * The files an entry's segment build writes in `segments/`: the picture and + * the records beside it. + */ +export const SEGMENT_FILE_SUFFIXES = Object.freeze([".mp4", ".cut.json", ".teaser.json", ".quote.txt", ".attrib.txt", ".channel.txt"]); + +/** + * Before an entry's segment is rebuilt: each of its files in `segDir` that is + * a link -- a hard link (more than one name) or a symlink, i.e. another + * take's, linked in to re-lay chrome over it -- is unlinked, so the build + * writes a file of this take's own instead of writing through the link. The + * other take's file is untouched; a file with one name is left for the build + * to overwrite, as it always was. Returns the names unlinked. + */ +export async function detachSegmentFiles(segDir, id) { + const gone = []; + for (const suffix of SEGMENT_FILE_SUFFIXES) { + const p = path.join(segDir, `${id}${suffix}`); + const st = await lstat(p).catch(() => null); + if (!st || !(st.isSymbolicLink() || (st.isFile() && st.nlink > 1))) continue; + await unlink(p); + gone.push(path.basename(p)); + } + return gone; +} + +/** Write `text` to `file` through a rename: a link at `file` is replaced, never written through. */ +async function replaceFile(file, text) { + const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`); + await writeFile(tmp, text, "utf8"); + await rename(tmp, file); +} + /** Beside `segments/<id>.mp4`: `<id>.cut.json`, the source seconds it was cut from. */ export const cutRecordPath = (seg) => seg.replace(/\.mp4$/, ".cut.json"); @@ -1534,10 +1600,20 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir, EMIT("note", { id: entry.id, message: `${entry.id}: teaser segment unchanged (key ${key.slice(0, 12)})` }); return seg; } - await execFileP(FFMPEG, teaserEncodeArgs({ framesDir: r.frames, seconds, render, audio, outPath: seg }), { maxBuffer: 1 << 26 }); + // Encoded beside it and renamed over it, and so is its record: the segment + // on disk may be a hard link to another take's (linked in to re-lay chrome + // over it), and a rename replaces this take's name without writing a byte of + // the other take's file. + const tmp = path.join(path.dirname(seg), `.${entry.id}.${process.pid}.tmp.mp4`); + try { + await execFileP(FFMPEG, teaserEncodeArgs({ framesDir: r.frames, seconds, render, audio, outPath: tmp }), { maxBuffer: 1 << 26 }); + await rename(tmp, seg); + } finally { + await rm(tmp, { force: true }); + } // `transition` is the cut's as built (0 under --no-xfade): a dip's lead // counts it, and verify-build reads it back from here. - await writeFile(recPath, JSON.stringify({ key, frames: r.key, hits: hits.length, transition }) + "\n", "utf8"); + await replaceFile(recPath, JSON.stringify({ key, frames: r.key, hits: hits.length, transition }) + "\n"); return seg; } @@ -3944,6 +4020,14 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const errors = validatePosts(whole.posts, whole.timeline ?? [], whole.render); if (errors.length) throw new Error(`posts: ${errors.join("; ")}`); } + // The lint (lint.mjs): what a render would get wrong that no validator + // refuses -- a picture that is not beside the manifest, a QR too small to + // scan at 720p, a teaser line over house style. The validators above have + // spoken already; `--only` lints its one entry. Enforced below, once the runs + // that render nothing (a bench fetch, the thumbnail) are out of the way. + const lint = opts.noLint + ? { errors: [], warnings: [] } + : lintManifest(manifest, { manifestDir, whole, only: only ?? null, validators: false }); // Where each post's QR goes: its page on the archive (`posts.links` // "archive", the default), which needs the archive channel that keeps it. @@ -4055,6 +4139,15 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly return { out: r.out, failures: [] }; } + // The lint's errors refuse every run that renders, before it renders (the + // chapters alone are a remux of what is there). Its warnings are notes. + if (!opts.chaptersOnly) { + for (const w of lint.warnings) EMIT("note", { message: `lint: ${w}` }); + if (lint.errors.length) { + throw new Error(`lint: ${lint.errors.join("; ")} — --lint lists them; --no-lint builds anyway`); + } + } + // `--no-network`: every clip's source is found on disk BEFORE anything is // rendered, and a build that would have to fetch even one is refused here, // naming each -- not twenty minutes in, at the first one. (The runs that @@ -4107,6 +4200,71 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly const failures = []; const D = opts.noXfade || (render.transition ?? 0.5) === 0 ? 0 : render.transition ?? 0.5; + + // One entry's segment, by its kind: the build's loop below, `--only`, and a + // segment `--chrome-only` finds MISSING (with `o` = skipFetch). Before an + // entry is written, its files in segments/ that are links (another take's, + // linked in to re-lay chrome over it) are unlinked, so the build writes + // files of this take's own and the other take's stay as they are: here for + // the kinds made from the manifest alone, in buildClipSegment once a clip's + // source is in hand. A teaser checks its own record first and writes a new + // file only when its render changed (buildTeaserSegment). Returns the + // segment's path. + const buildEntrySegment = async (entry, i, o = opts) => { + if (entry.type !== "teaser" && entry.type !== "clip") { + await detachSegmentFiles(path.join(outDir, "segments"), entry.id); + } + if (entry.type === "card") { + EMIT("card", { id: entry.id, i, n: entries.length }); + return buildCardSegment(entry, render, outDir, manifest.timelineNodes, framing); + } + if (entry.type === "teaser") { + EMIT("card", { id: entry.id, i, n: entries.length }); + return buildTeaserSegment(entry, { manifestPath, render, outDir, variant, transition: D }); + } + if (entry.type === "image") { + // `card`, not a new event name: umtool's activity feed and build chain + // key off this one to mean "a segment that needs no network", and a + // third word there would show as an unknown step rather than as work. + EMIT("card", { id: entry.id, i, n: entries.length }); + return buildImageSegment(entry, render, outDir, chrome, provenance, manifestDir, framing); + } + if (entry.type === "scroll" || entry.type === "chart" || entry.type === "ledger") { + EMIT("card", { id: entry.id, i, n: entries.length }); + if (!manifest.ledger?.length) + throw new Error(`${entry.id} is type:${entry.type} but the manifest has no ledger[]`); + return entry.type === "scroll" + ? buildScrollSegment(entry, render, outDir, manifest.ledger) + : entry.type === "chart" + ? buildChartSegment(entry, render, outDir, manifest.ledger) + : buildLedgerSegment(entry, render, outDir, manifest.ledger, availability); + } + const meta = await clipMeta(entry, provenance); + EMIT("clip", { + id: entry.id, i, n: entries.length, video: clipLabel(entry), + section: entry.section, sectionEnter: !!entry.sectionEnter, + }); + return buildClipSegment(entry, meta, render, dirs, o, chrome, manifest.timelineNodes, provenance, framing); + }; + + // After the final mux: the chrome's frame sequences go (prune-frames.mjs), + // unless --keep-frames -- `chrome/<name>-frames` and `chrome/work-*` only, never + // a segment. Not under the legacy chart band (`hyper`), whose frames are an + // input made outside the build, nor after `--no-chrome`, which rendered no + // chrome and leaves the last render's frames for a `--chrome-only`. + const pruneFrames = async () => { + if (opts.keepFrames || hyper || (deck && opts.noChrome)) return; + const p = await pruneChromeFrames(outDir); + if (p.sequences.length || p.work.length) { + EMIT("note", { + message: + `pruned ${p.sequences.length} frame sequence(s)` + + (p.work.length ? ` and ${p.work.length} renderer work dir(s)` : "") + + `, ${(p.bytes / (1 << 20)).toFixed(0)} MiB (chrome/pruned.json records them; --keep-frames keeps them)`, + }); + } + }; + // Where the cut dips to black (a teaser's `dip`), in its frames: for the // passes that lay the picture's last layer over an already joined base. // (The crossfade's own encode finds them from its joins.) @@ -4177,21 +4335,40 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly if (opts.noChrome) throw new Error(`${what} and --no-chrome contradict each other`); if (only) throw new Error(`${what} lays the deck over the whole cut; --only does not apply`); const segs = entries.map((e) => path.join(outDir, "segments", `${e.id}.mp4`)); - // Every refusal before any render: a teaser's segment is built below, so - // only the others must be on disk already. + // A teaser's segment is built below. Any other that is missing: a preview + // refuses (it shows a window of what is there); --chrome-only builds it, + // after every refusal, from what is cached -- never fetching, and never + // writing a segment that IS there (a take may hard-link another take's + // segments in, and writing one would write the other take's file). + const missing = []; for (const [i, seg] of segs.entries()) { - if (entries[i].type === "teaser") continue; - if (!(await exists(seg))) - throw new Error(`${what} needs ${seg}, which is missing — run a full build first`); + if (entries[i].type === "teaser" || (await exists(seg))) continue; + if (opts.chromePreview) throw new Error(`${what} needs ${seg}, which is missing — run a full build first`); + missing.push(i); } // Segments framed for another layout (the posts feed switched on or off // since they were built) cannot take this cut's chrome: refused, by name. - // A teaser is full frame, so its record is not read for this. + // A teaser is full frame, so its record is not read for this; a missing + // segment is built for this cut's layout below. { - const records = await Promise.all(segs.map((sg) => readCutRecord(sg))); - const problems = framingProblems({ entries, records, render, want: framing }); + const present = entries.map((_, i) => i).filter((i) => !missing.includes(i)); + const records = await Promise.all(present.map((i) => readCutRecord(segs[i]))); + const problems = framingProblems({ entries: present.map((i) => entries[i]), records, render, want: framing }); if (problems.length) throw new Error(`${what}: ${problems.join("; ")}`); } + for (const i of missing) { + const e = entries[i]; + EMIT("note", { message: `${what}: ${e.id}'s segment is missing — building it from what is cached` }); + try { + await buildEntrySegment(e, i, { ...opts, skipFetch: true }); + } catch (err) { + throw new Error( + `${what} could not build the missing ${e.id} from the cache: ${err?.message ?? err} — ` + + `run --only ${e.id}, or a full build`, + ); + } + EMIT("segment", { id: e.id, path: segs[i] }); + } // A teaser's segment is chrome too -- graphics made from the manifest's // words, nothing fetched -- so it is (re)built here: re-rendered and // re-encoded only when its words, motion or sound changed. @@ -4249,6 +4426,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly await assertConcatLength(dirs.final, schedule.total, render.fps, "deck build"); // The overlay re-encodes, so the chapters on the previous final are gone. if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins); + await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; } @@ -4257,43 +4435,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly for (let i = 0; i < entries.length; i += 1) { const entry = entries[i]; try { - if (entry.type === "card") { - EMIT("card", { id: entry.id, i, n: entries.length }); - segments.push(await buildCardSegment(entry, render, outDir, manifest.timelineNodes, framing)); - } else if (entry.type === "teaser") { - EMIT("card", { id: entry.id, i, n: entries.length }); - segments.push(await buildTeaserSegment(entry, { manifestPath, render, outDir, variant, transition: D })); - } else if (entry.type === "image") { - // `card`, not a new event name: umtool's activity feed and build chain - // key off this one to mean "a segment that needs no network", and a - // third word there would show as an unknown step rather than as work. - EMIT("card", { id: entry.id, i, n: entries.length }); - segments.push( - await buildImageSegment(entry, render, outDir, chrome, provenance, manifestDir, framing), - ); - } else if (entry.type === "scroll" || entry.type === "chart" || entry.type === "ledger") { - EMIT("card", { id: entry.id, i, n: entries.length }); - if (!manifest.ledger?.length) - throw new Error(`${entry.id} is type:${entry.type} but the manifest has no ledger[]`); - segments.push( - entry.type === "scroll" - ? await buildScrollSegment(entry, render, outDir, manifest.ledger) - : entry.type === "chart" - ? await buildChartSegment(entry, render, outDir, manifest.ledger) - : await buildLedgerSegment(entry, render, outDir, manifest.ledger, availability), - ); - } else { - const meta = await clipMeta(entry, provenance); - EMIT("clip", { - id: entry.id, i, n: entries.length, video: clipLabel(entry), - section: entry.section, sectionEnter: !!entry.sectionEnter, - }); - segments.push( - await buildClipSegment( - entry, meta, render, dirs, opts, chrome, manifest.timelineNodes, provenance, framing, - ), - ); - } + segments.push(await buildEntrySegment(entry, i)); EMIT("segment", { id: entry.id, path: segments[segments.length - 1] }); } catch (err) { // Without --continue-on-error a dead source at entry 14 of 19 throws away @@ -4415,6 +4557,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly EMIT("note", { message: `thumbnail not made: ${err?.message ?? err}` }), ); } + await pruneFrames(); const { stdout } = await execFileP(FFPROBE, [ "-v", "error", "-show_entries", "format=duration,size", @@ -4517,6 +4660,28 @@ export function chromeFlags(argv) { return out; } +/** + * Does this run take the machine's heavy slot (heavy-gate.mjs)? Every run that + * renders the cut does -- a full build, --chrome-only, --chrome-preview, + * --rail-only, a --no-chrome build. A fetch, one `--only` segment, the + * chapters and the thumbnail do not. + */ +export function takesHeavySlot({ opts = {}, only = null, fetchOnly = null } = {}) { + return !fetchOnly && !only && !opts.chaptersOnly && !opts.thumbnailOnly; +} + +// heavy-gate.mjs's withRenderSlot, loaded by a URL made at run time: the +// umtool app imports this file, and the gate (and the checkout's +// scripts/queue-lock.mjs behind it) must never reach its bundle. Only main() +// asks, and main() runs only when this file is argv[1] (the guard at the +// bottom), so the gate is argv[1]'s neighbour. No path op on a value the +// bundler would trace (scripts/next-build-trace.test.mjs). +async function renderSlot() { + const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href; + const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); + return withRenderSlot; +} + async function main() { const argv = process.argv.slice(2); const manifestPath = argv.find((a) => !a.startsWith("--")); @@ -4527,7 +4692,8 @@ async function main() { " [--pad <s>] [--pad-before <s>] [--pad-after <s>] [--skip-fetch] [--no-network] [--audio-fallback] [--no-xfade] [--no-chapters] [--chapters-only]\n" + " [--progress ndjson] [--continue-on-error] [--no-reuse]\n" + " [--no-rail] [--rail-only] [--preview <start> <dur>]\n" + - " [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] (render.chrome, the deck)\n" + + " [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" + + " [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" + " [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" + " [--thumbnail] (render.brand only: out/<slug>.thumbnail.png and stop)", ); @@ -4561,6 +4727,8 @@ async function main() { resolveSiteIds: argv.includes("--resolve-site-ids"), cueSource: flag("--cue-source"), thumbnailOnly: argv.includes("--thumbnail"), + keepFrames: argv.includes("--keep-frames"), + noLint: argv.includes("--no-lint"), }; try { Object.assign(opts, chromeFlags(argv)); @@ -4578,13 +4746,22 @@ async function main() { } } - const { failures } = await buildVideo({ - manifestPath, - opts, - out: flag("--out"), - only: flag("--only"), - fetchOnly: flag("--fetch-only"), - }); + // The lint alone: every warning and error, exit 1 on an error. + if (argv.includes("--lint")) { + const lint = await lintManifestFile(manifestPath, { variant: opts.variant, only: flag("--only") ?? null }); + for (const w of lint.warnings) EMIT("note", { message: `lint: ${w}` }); + for (const e of lint.errors) EMIT("note", { message: `lint ERROR: ${e}` }); + EMIT("note", { message: `lint: ${lint.errors.length} error(s), ${lint.warnings.length} warning(s)` }); + EMIT("done", { out: null, lint: { errors: lint.errors, warnings: lint.warnings } }); + process.exit(lint.errors.length ? 1 : 0); + } + + const only = flag("--only"); + const fetchOnly = flag("--fetch-only"); + const build = () => buildVideo({ manifestPath, opts, out: flag("--out"), only, fetchOnly }); + const { failures } = takesHeavySlot({ opts, only, fetchOnly }) + ? await (await renderSlot())(["build-video", ...argv], build) + : await build(); // Non-zero on a partial run, so a caller that ignores the events still learns // the build did not produce what was asked for. if (failures.length) process.exit(1); diff --git a/umtool/report-to-video/heavy-gate.mjs b/umtool/report-to-video/heavy-gate.mjs @@ -0,0 +1,70 @@ +// THE HEAVY SLOT, for a render (scripts/queue-lock.mjs, `pnpm heavy`). +// +// A render of the cut -- the segments' encodes, the deck's HyperFrames +// render, the overlay pass -- is one heavy job machine-wide, started only +// above the memory floor, like an e2e run or a `next build` (two OOMs took the +// desktop session down, 2026-10-08). build-video's CLI runs its rendering +// runs through `withRenderSlot`; a fetch, the lint, `--only`, the chapters and +// the thumbnail do not take it. +// +// Loaded only by build-video's CLI, by a path built at run time, never by the +// umtool app that imports build-video.mjs: queue-lock.mjs is a CLI of the +// checkout, not a module of the bundle. +// +// THE LOCK FILE. queue-lock finds its lock in the git common dir of the +// process's cwd. A render's cwd is usually a report workspace -- outside the +// checkout, or a repository of its own -- whose lock no e2e run or build would +// ever see. So unless HEAVY_LOCK_FILE is set, it is pinned here to the one in +// THIS checkout's git common dir, the file every other heavy entry point +// takes. HEAVY=0 bypasses the slot and the floor; HEAVY_HELD (set inside the +// slot, e.g. under an e2e run or `pnpm heavy -- …`) passes straight through. + +import { execFileSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +/** This checkout's root: two levels above this file (umtool/report-to-video/). */ +export function checkoutRoot() { + return path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)), "..", ".."); +} + +/** The heavy slot's lock file for this checkout, or null outside a git checkout. */ +export function heavyLockFile(root = checkoutRoot()) { + try { + const common = execFileSync("git", ["-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"], { + encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], + }).trim(); + return common ? path.join(/* turbopackIgnore: true */ common, "heavy-queue.lock") : null; + } catch { + return null; + } +} + +/** + * Run `fn` in the heavy slot. `cmd` names the work to anyone waiting behind + * it. With no gate to load (a copy of the directory without the checkout's + * scripts/), says so and runs: the slot is a safety net, not a correctness lock. + * + * @template T + * @param {string[]} cmd + * @param {() => Promise<T>} fn + * @param {{ env?: NodeJS.ProcessEnv, root?: string, say?: (line: string) => void }} [opts] + * @returns {Promise<T>} + */ +export async function withRenderSlot(cmd, fn, { env = process.env, root = checkoutRoot(), say } = {}) { + const note = say ?? ((line) => process.stderr.write(`${line}\n`)); + if (env.HEAVY === "0" || env.HEAVY_HELD) return fn(); + let gate; + try { + const file = path.join(/* turbopackIgnore: true */ root, "scripts", "queue-lock.mjs"); + gate = await import(/* webpackIgnore: true */ pathToFileURL(file).href); + } catch (err) { + note(`heavy: no heavy-slot gate in this checkout (${err?.message ?? err}) — rendering without it`); + return fn(); + } + if (!env.HEAVY_LOCK_FILE) { + const lock = heavyLockFile(root); + if (lock) env.HEAVY_LOCK_FILE = lock; + } + return gate.withHeavy({ cmd }, fn); +} diff --git a/umtool/report-to-video/heavy-gate.test.mjs b/umtool/report-to-video/heavy-gate.test.mjs @@ -0,0 +1,117 @@ +// The heavy slot for a render (heavy-gate.mjs) and which build-video runs +// take it (takesHeavySlot). +// +// The real machine-wide lock is never taken here: every run that reaches the +// gate names its own HEAVY_LOCK_FILE in a temp dir, with the floor at 0. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { checkoutRoot, heavyLockFile, withRenderSlot } from "./heavy-gate.mjs"; +import { takesHeavySlot } from "./build-video.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +/** Run `fn` with process.env patched, restoring every key after. */ +async function withEnv(patch, fn) { + const saved = Object.fromEntries(Object.keys(patch).map((k) => [k, process.env[k]])); + for (const [k, v] of Object.entries(patch)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + try { + return await fn(); + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } +} + +test("which runs take the slot: every one that renders the cut, never a fetch, --only, the chapters or the thumbnail", () => { + assert.equal(takesHeavySlot({ opts: {} }), true, "a full build"); + assert.equal(takesHeavySlot({ opts: { chromeOnly: true } }), true); + assert.equal(takesHeavySlot({ opts: { chromePreview: { at: 0, dur: 2 } } }), true); + assert.equal(takesHeavySlot({ opts: { railOnly: true } }), true); + assert.equal(takesHeavySlot({ opts: { noChrome: true } }), true); + assert.equal(takesHeavySlot({ opts: {}, fetchOnly: "c1" }), false); + assert.equal(takesHeavySlot({ opts: {}, only: "c1" }), false); + assert.equal(takesHeavySlot({ opts: { chaptersOnly: true } }), false); + assert.equal(takesHeavySlot({ opts: { thumbnailOnly: true } }), false); +}); + +test("the checkout's own lock file: beside the e2e queue's, in its git common dir", () => { + assert.equal(checkoutRoot(), path.resolve(HERE, "..", "..")); + const lock = heavyLockFile(); + assert.ok(lock, "this checkout is a git checkout"); + assert.equal(path.basename(lock), "heavy-queue.lock"); + assert.ok(existsSync(path.dirname(lock)), lock); + assert.equal(heavyLockFile(path.join(tmpdir(), "not-a-checkout-" + process.pid)), null); +}); + +test("HEAVY=0 and HEAVY_HELD pass straight through; no gate in the checkout renders with a note", async () => { + const ran = []; + await withEnv({ HEAVY: "0", HEAVY_HELD: undefined }, () => withRenderSlot(["x"], async () => ran.push("bypass"))); + await withEnv({ HEAVY: undefined, HEAVY_HELD: "1" }, () => withRenderSlot(["x"], async () => ran.push("held"))); + const notes = []; + const root = mkdtempSync(path.join(tmpdir(), "rtv-nogate-")); + try { + await withEnv({ HEAVY: undefined, HEAVY_HELD: undefined }, () => + withRenderSlot(["x"], async () => ran.push("nogate"), { root, say: (l) => notes.push(l) }), + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } + assert.deepEqual(ran, ["bypass", "held", "nogate"]); + assert.match(notes[0], /^heavy: no heavy-slot gate in this checkout .* — rendering without it$/); +}); + +test("a render runs inside the slot: the lock is taken, HEAVY_HELD is set for what it starts, and both are let go", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "rtv-heavy-")); + const lock = path.join(dir, "heavy-queue.lock"); + try { + const seen = await withEnv( + { HEAVY: undefined, HEAVY_HELD: undefined, HEAVY_LOCK_FILE: lock, HEAVY_MIN_FREE_MB: "0" }, + async () => { + const inside = await withRenderSlot(["build-video", "m.json"], async () => ({ + held: process.env.HEAVY_HELD, + lockExists: existsSync(lock), + holder: existsSync(`${lock}.holder.json`), + })); + return { inside, after: process.env.HEAVY_HELD, lockFile: process.env.HEAVY_LOCK_FILE }; + }, + ); + assert.deepEqual(seen.inside, { held: "1", lockExists: true, holder: true }); + assert.equal(seen.after, undefined); + assert.equal(seen.lockFile, lock, "a HEAVY_LOCK_FILE already set is kept"); + assert.equal(existsSync(`${lock}.holder.json`), false, "the holder file goes with the slot"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("with no HEAVY_LOCK_FILE the lock is pinned to the checkout's git common dir, not the cwd's", async () => { + const { execFileSync } = await import("node:child_process"); + const { copyFileSync, mkdirSync } = await import("node:fs"); + // A stand-in checkout: a git repo carrying the real gate. + const repo = mkdtempSync(path.join(tmpdir(), "rtv-heavy-repo-")); + try { + execFileSync("git", ["init", "-q", repo]); + mkdirSync(path.join(repo, "scripts")); + copyFileSync(path.join(checkoutRoot(), "scripts", "queue-lock.mjs"), path.join(repo, "scripts", "queue-lock.mjs")); + const lock = path.join(repo, ".git", "heavy-queue.lock"); + const seen = await withEnv( + { HEAVY: undefined, HEAVY_HELD: undefined, HEAVY_LOCK_FILE: undefined, HEAVY_MIN_FREE_MB: "0" }, + () => withRenderSlot(["build-video"], async () => ({ file: process.env.HEAVY_LOCK_FILE, exists: existsSync(lock) }), { root: repo }), + ); + assert.deepEqual(seen, { file: lock, exists: true }); + } finally { + rmSync(repo, { recursive: true, force: true }); + } +}); diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -0,0 +1,315 @@ +#!/usr/bin/env node +// THE MANIFEST LINT — what a render would get wrong that no validator refuses, +// said before a single frame is drawn. +// +// node umtool/report-to-video/lint.mjs <manifest.json> [--variant sourced|full] [--json] +// node umtool/report-to-video/build-video.mjs <manifest.json> --lint [--variant …] +// +// Both print every warning and error and exit 1 on an error. A build runs the +// same lint after its validators and before anything renders: its errors +// refuse the build, its warnings are notes. A run that renders nothing (a +// bench fetch, the thumbnail, --chapters-only) is not held up by it, and +// `--only <id>` lints that one entry. +// +// ERRORS +// - an image whose `src` is not relative to the manifest (absolute, or `~`) +// or names no file beside it: a timeline `image` entry's `src`, each of its +// `panels[].src`, and under the deck a post's `shot` and `logo`. The +// manifest is checked in beside its pictures, and a path that resolves on +// 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), 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. +// WARNINGS +// - a teaser line over TEASER_HOUSE_CHARS -- an overline's or a kicker's +// first tier, or any line's break: house style, not a fit. (A title's +// first tier is held to the same 34 by the frame itself, TEASER_LIMITS.fit, +// and validateTeasers refuses it.) +// - a QR under WARN_QR_PX_PER_MODULE_720P pixels per module at 720p: it +// scans on a good screen with a steady hand, not reliably. +// +// THE QR ARITHMETIC. A QR's side is (17 + 4·version) modules plus its quiet +// zone on each side (`render.qr.quiet`, 3 as qrencode is run here). The +// version is the smallest that holds the link in byte mode at the ECC level +// (`render.qr.ecc`, M) -- qrencode may pick a denser mode for part of a URL, +// so this errs towards a bigger symbol, the safe side for a lint. The deck's +// and the posts' codes are resized to their `size`, quiet zone included +// (compose-chrome qrPng), on a `render.height`-px frame: at 720p that is +// size·720/height px over the modules. The rail's tile is resized to +// `rail.qrSize` the same way. The corner code of a cut without the deck is +// qrencode's own `scale` px per module, unresized. +// +// THE LINKS, AS FAR AS THEY ARE KNOWN BEFORE THE BUILD. A deck QR under +// `qr.links: "original"` needs the record's page, which the build reads; the +// lint measures the archive link instead. A post's archive page needs the +// archive channel the build's resolver finds (post-links.mjs); until then the +// lint measures the longer of the post's own url and its archive page under +// the manifest's channel slug, the build's two outcomes. +// +// Pure but for the existence of an image file (`exists`, injectable). + +import { existsSync } from "node:fs"; +import path from "node:path"; +import { + deckOn, deckQrUrl, postArchiveUrl, postNativeId, postQrUrl, resolveDeck, teaserLines, + validateCutEdits, validatePosts, validateTeasers, +} from "./deck.mjs"; +import { validateClaims } from "./factcheck.mjs"; +import { validateThreadEntries } from "./threads.mjs"; +import { validateFlipEntries } from "./flips.mjs"; +import { qrUrlFor } from "./render-cards.mjs"; + +export const TEASER_HOUSE_CHARS = 34; +export const MIN_QR_PX_PER_MODULE_720P = 1.5; +export const WARN_QR_PX_PER_MODULE_720P = 2.0; + +// Byte-mode capacity (bytes) per version 1-20, at L / M / Q / H (ISO/IEC 18004). +const BYTE_CAPACITY = { + L: [17, 32, 53, 78, 106, 134, 154, 192, 230, 271, 321, 367, 425, 458, 520, 586, 644, 718, 792, 858], + M: [14, 26, 42, 62, 84, 106, 122, 152, 180, 213, 251, 287, 331, 362, 412, 450, 504, 560, 624, 666], + Q: [11, 20, 32, 46, 60, 74, 86, 108, 130, 151, 177, 203, 241, 258, 292, 322, 364, 394, 442, 482], + H: [7, 14, 24, 34, 44, 58, 64, 84, 98, 119, 137, 155, 177, 194, 220, 250, 280, 310, 338, 382], +}; + +/** The smallest QR version holding `text` in byte mode at `ecc`, or null past version 20. */ +export function qrVersion(text, ecc = "M") { + const bytes = Buffer.byteLength(String(text), "utf8"); + const caps = BYTE_CAPACITY[String(ecc).toUpperCase()] ?? BYTE_CAPACITY.M; + const i = caps.findIndex((c) => c >= bytes); + return i < 0 ? null : i + 1; +} + +/** A QR's side in modules, quiet zone included. */ +export function qrModules(version, quiet = 3) { + return 17 + 4 * version + 2 * quiet; +} + +/** Pixels per module once a `px`-wide code on a `height`-px frame is watched at 720p. */ +export function pxPerModuleAt720(px, modules, height = 1080) { + return (px * (720 / height)) / modules; +} + +// A post's QR link at its LONGEST: under "archive" with no channel resolved +// yet, the build will draw either its archive page or, when the archive does +// not have it, its own url. +function postQrUrlForLint(post, provenance, links) { + const known = postQrUrl(post, provenance, { links }); + if (links === "original" || post.siteUrl || post.siteChannel) return known; + const origin = typeof provenance?.siteOrigin === "string" ? provenance.siteOrigin.trim() : ""; + const id = postNativeId(post); + if (!origin || !id) return known; + const archive = postArchiveUrl(origin, provenance.channelSlug ?? "channel", id); + return !known || archive.length > String(known).length ? archive : known; +} + +/** + * Every QR the cut will draw, as `{ where, url, px, perModule }` -- `px` the + * drawn width on the frame, or null for the corner code, which is `perModule` + * native pixels per module, unresized. + * + * @param {any} manifest a cut, as selectVariant returns it + * @param {{ only?: string|null }} [opts] + */ +export function qrsOf(manifest, { only = null } = {}) { + const render = manifest.render ?? {}; + const provenance = manifest.provenance ?? {}; + const timeline = (manifest.timeline ?? []).filter((e) => e && (!only || e.id === only)); + const out = []; + if (deckOn(render)) { + const d = resolveDeck(render); + if (d.qr?.show) { + for (const e of timeline) { + const url = deckQrUrl(e, provenance, { links: d.qr.links }); + if (url) out.push({ where: `timeline ${e.id} (the deck's QR)`, url, px: Number(d.qr.size) }); + } + } + if (d.posts?.show && Array.isArray(manifest.posts)) { + for (const p of manifest.posts) { + if (!p || (only && p.attachTo !== only)) continue; + const url = postQrUrlForLint(p, provenance, d.posts.links); + if (url) out.push({ where: `posts ${p.id ?? "?"} (its QR)`, url, px: Number(d.posts.qrSize) }); + } + } + return out; + } + if (render.qr === false) return out; + if (render.rail) { + // The rail's foot: a tile per entry (a card's is the sweep's link), the + // code resized to rail.qrSize. + const px = Number(render.rail.qrSize ?? 132); + for (const e of timeline) { + const url = qrUrlFor(e, provenance); + if (url) out.push({ where: `timeline ${e.id} (its rail QR)`, url, px }); + } + return out; + } + // The corner code: a clip's (its citeUrl, else its moment on the archive; + // none for a `src` clip without a citeUrl), and a still's citeUrl. + const scale = Number(render.qr?.scale ?? 4); + for (const e of timeline) { + let url = null; + if (e.type === "clip") { + if (e.src != null && !e.citeUrl) continue; + url = e.citeUrl ?? + `${provenance.siteOrigin}/?v=${encodeURIComponent(`${e.channel ?? provenance.channelSlug}/${e.video}`)}&t=${Math.floor(e.start)}`; + } else if (e.type === "image" && e.citeUrl) { + url = e.citeUrl; + } + if (url) out.push({ where: `timeline ${e.id} (its corner QR)`, url, px: null, perModule: scale }); + } + return out; +} + +/** + * Every picture the cut reads from beside the manifest, as `{ where, src }`. + * Posts' shots and logos only under the deck, the one place posts are drawn. + */ +export function imageSrcsOf(manifest, { only = null } = {}) { + const out = []; + for (const e of manifest.timeline ?? []) { + if (e?.type !== "image" || (only && e.id !== only)) continue; + if (typeof e.src === "string") out.push({ where: `timeline ${e.id}`, src: e.src }); + if (Array.isArray(e.panels)) { + e.panels.forEach((p, i) => { + if (typeof p?.src === "string") out.push({ where: `timeline ${e.id}.panels[${i}]`, src: p.src }); + }); + } + } + if (deckOn(manifest.render) && Array.isArray(manifest.posts)) { + for (const p of manifest.posts) { + if (!p || (only && p.attachTo !== only)) continue; + for (const key of ["shot", "logo"]) { + if (typeof p[key] === "string" && p[key]) out.push({ where: `posts ${p.id ?? "?"}.${key}`, src: p[key] }); + } + } + } + return out; +} + +/** The validators a build runs before it renders, as one list of sentences. */ +export function validatorErrors(whole) { + const errors = [ + ...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), + ...validateThreadEntries(whole), ...validateFlipEntries(whole), + ]; + if (deckOn(whole.render)) { + errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); + } + return errors; +} + +/** + * The lint of one cut. + * + * @param {any} manifest the cut, as selectVariant returns it + * @param {{ manifestDir?: string, whole?: any, exists?: (p: string) => boolean, + * only?: string|null, validators?: boolean }} [opts] + * `whole` is the manifest as written (what the validators read); + * `validators: false` leaves them out (a build has run them already); + * `only` lints one timeline entry (and the posts attached to it). + * @returns {{ errors: string[], warnings: string[] }} + */ +export function lintManifest(manifest, { + manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, +} = {}) { + const errors = []; + const warnings = []; + const render = manifest.render ?? {}; + const height = Number(render.height) || 1080; + + for (const { where, src } of imageSrcsOf(manifest, { only })) { + if (path.isAbsolute(src) || src.startsWith("~")) { + errors.push(`${where}: the image "${src}" must be a path relative to the manifest (it is checked in beside its pictures)`); + } else if (manifestDir && !exists(path.resolve(manifestDir, src))) { + errors.push(`${where}: the image "${src}" names no file beside the manifest`); + } + } + + for (const e of manifest.timeline ?? []) { + if (e?.type !== "teaser" || (only && e.id !== only)) continue; + teaserLines(e).forEach((l, i) => { + // A TITLE's first tier past it does not fit the frame at all, which + // validateTeasers refuses; the house style speaks for the other tiers. + for (const [part, text] of [["", l.role === "title" ? null : l.head], [" break", l.sub]]) { + if (text && text.length > TEASER_HOUSE_CHARS) { + warnings.push( + `timeline ${e.id}.lines[${i}]${part} "${text}" is ${text.length} characters; house style is at most ${TEASER_HOUSE_CHARS}`, + ); + } + } + }); + } + + const ecc = render.qr?.ecc ?? "M"; + const quiet = Number(render.qr?.quiet ?? 3); + for (const q of qrsOf(manifest, { only })) { + const version = qrVersion(q.url, ecc); + if (version === null) { + errors.push(`${q.where}: its link is ${Buffer.byteLength(q.url)} bytes, too long for a scannable QR (${q.url.slice(0, 80)}…)`); + continue; + } + const modules = qrModules(version, quiet); + const per = q.px === null ? q.perModule * (720 / height) : pxPerModuleAt720(q.px, modules, height); + const what = + `${q.where}: ${per.toFixed(2)} px per module at 720p ` + + `(${q.px === null ? `scale ${q.perModule}` : `${q.px} px`} on a ${height}p frame, a version-${version} code, ${modules} modules)`; + if (per < MIN_QR_PX_PER_MODULE_720P) { + errors.push(`${what} — too small to scan; make it larger or the link shorter (at least ${MIN_QR_PX_PER_MODULE_720P})`); + } else if (per < WARN_QR_PX_PER_MODULE_720P) { + warnings.push(`${what} — scans only on a good screen; ${WARN_QR_PX_PER_MODULE_720P} is comfortable`); + } + } + + if (validators && !only) errors.push(...validatorErrors(whole)); + return { errors, warnings }; +} + +/** + * Lint a manifest file: read it, select the cut, lint it. A validator that + * throws (a malformed manifest) is an error, not a crash. + * + * @returns {Promise<{ errors: string[], warnings: string[], variant: string }>} + */ +export async function lintManifestFile(manifestPath, { variant = "sourced", only = null } = {}) { + const { readFile } = await import("node:fs/promises"); + const { selectVariant } = await import("./build-video.mjs"); + const whole = JSON.parse(await readFile(manifestPath, "utf8")); + const manifestDir = path.dirname(path.resolve(manifestPath)); + try { + const manifest = selectVariant(whole, variant); + return { ...lintManifest(manifest, { manifestDir, whole, only }), variant }; + } catch (err) { + return { errors: [err?.message ?? String(err)], warnings: [], variant }; + } +} + +/** The lint's lines, as `--lint` and this file's CLI print them. */ +export function lintReport({ errors, warnings }) { + return [ + ...warnings.map((w) => `warning: ${w}`), + ...errors.map((e) => `ERROR: ${e}`), + `${errors.length} error(s), ${warnings.length} warning(s)`, + ]; +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const argv = process.argv.slice(2); + const flag = (n) => { const i = argv.indexOf(n); return i < 0 ? undefined : argv[i + 1]; }; + const valued = new Set(["--variant"]); + const manifestPath = argv.find((a, i) => !a.startsWith("--") && !valued.has(argv[i - 1])); + if (!manifestPath) { + console.error("usage: lint.mjs <manifest.json> [--variant sourced|full] [--json]"); + process.exit(2); + } + lintManifestFile(manifestPath, { variant: flag("--variant") ?? "sourced" }).then((r) => { + if (argv.includes("--json")) console.log(JSON.stringify(r, null, 2)); + else for (const line of lintReport(r)) console.log(line); + process.exit(r.errors.length ? 1 : 0); + }, (err) => { + console.error(err?.message ?? err); + process.exit(1); + }); +} diff --git a/umtool/report-to-video/lint.test.mjs b/umtool/report-to-video/lint.test.mjs @@ -0,0 +1,272 @@ +// The manifest lint (lint.mjs): its QR arithmetic, each rule's severity, the +// validators it folds in, `--only`, its two command lines, and the build's +// refusal before anything renders. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + MIN_QR_PX_PER_MODULE_720P, TEASER_HOUSE_CHARS, WARN_QR_PX_PER_MODULE_720P, + imageSrcsOf, lintManifest, lintManifestFile, pxPerModuleAt720, qrModules, qrsOf, qrVersion, +} from "./lint.mjs"; +import { buildVideo } from "./build-video.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const PROV = { siteOrigin: "https://example.test", channelSlug: "chan" }; +const BASE = { width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE }; +const DECK = { ...BASE, chrome: { engine: "hyperframes", layout: "deck", deck: {} } }; +const all = () => true; + +test("the QR arithmetic: version by byte capacity, modules with the quiet zone, px per module at 720p", () => { + assert.equal(qrVersion("x".repeat(14), "M"), 1); + assert.equal(qrVersion("x".repeat(15), "M"), 2); + assert.equal(qrVersion("x".repeat(62), "M"), 4); + assert.equal(qrVersion("x".repeat(63), "M"), 5); + assert.equal(qrVersion("x".repeat(17), "L"), 1); + assert.equal(qrVersion("x".repeat(667), "M"), null, "past version 20 is not a scannable code"); + assert.equal(qrModules(1, 3), 27); + assert.equal(qrModules(5, 3), 43); + assert.equal(qrModules(5, 0), 37); + // 150 px on a 1080p frame is 100 px at 720p; over 50 modules, 2. + assert.equal(pxPerModuleAt720(150, 50, 1080), 2); + assert.equal(pxPerModuleAt720(100, 50, 720), 2); +}); + +test("a teaser line over house style is a WARNING, never an error; at the limit it says nothing", () => { + const ok = "x".repeat(TEASER_HOUSE_CHARS); + const long = "y".repeat(TEASER_HOUSE_CHARS + 1); + // Three rows: an overline, a title, a kicker (deck.mjs teaserLines). + const m = { + render: BASE, provenance: PROV, + timeline: [ + { id: "t1", type: "teaser", lines: [long, ok, { text: `Kicker ${long}`, break: long }] }, + { id: "t2", type: "teaser", lines: [ok, "Short title", ok] }, + ], + }; + const r = lintManifest(m, { exists: all }); + assert.deepEqual(r.errors, [], "the validators accept every line: each fits the frame"); + assert.equal(r.warnings.length, 2, r.warnings.join("\n")); + assert.match(r.warnings[0], /^timeline t1\.lines\[0\] "y{35}" is 35 characters; house style is at most 34$/); + assert.match(r.warnings[1], /^timeline t1\.lines\[2\] break "y{35}" is 35 characters/); + // A TITLE past 34 does not fit the frame: the validator's error, said once. + const title = lintManifest({ ...m, timeline: [{ id: "t3", type: "teaser", lines: ["Soon", long] }] }, { exists: all }); + assert.deepEqual(title.warnings, []); + assert.equal(title.errors.length, 1); + assert.match(title.errors[0], /at most 34 fit the frame as the title/); +}); + +test("an image src that is not relative to the manifest, or names no file, is an ERROR", () => { + const m = { + render: { ...BASE, qr: false }, provenance: PROV, + timeline: [ + { id: "abs", type: "image", src: "/somewhere/else/shot.png", seconds: 4 }, + { id: "home", type: "image", src: "~/shot.png", seconds: 4 }, + { id: "gone", type: "image", src: "stills/missing.png", seconds: 4 }, + { id: "here", type: "image", src: "stills/here.png", seconds: 4 }, + { id: "row", type: "image", seconds: 4, panels: [{ src: "stills/here.png" }, { src: "/abs/b.png" }] }, + ], + }; + const exists = (p) => p === path.resolve("/m", "stills/here.png"); + const r = lintManifest(m, { manifestDir: "/m", exists, validators: false }); + assert.equal(r.errors.length, 4, r.errors.join("\n")); + assert.match(r.errors[0], /^timeline abs: the image "\/somewhere\/else\/shot\.png" must be a path relative to the manifest/); + assert.match(r.errors[1], /^timeline home: the image "~\/shot\.png" must be a path relative/); + assert.match(r.errors[2], /^timeline gone: the image "stills\/missing\.png" names no file beside the manifest/); + assert.match(r.errors[3], /^timeline row\.panels\[1\]: .* must be a path relative/); + assert.deepEqual(r.warnings, []); +}); + +test("under the deck a post's shot and logo are pictures beside the manifest too", () => { + const m = { + render: DECK, provenance: PROV, + timeline: [{ id: "c1", type: "clip", video: "v", start: 0, end: 5 }], + posts: [{ id: "p1", attachTo: "c1", shot: "/abs/p.png", logo: "logos/l.png", url: "https://bsky.app/profile/a/post/abc" }], + }; + assert.deepEqual(imageSrcsOf(m).map((s) => s.where), ["posts p1.shot", "posts p1.logo"]); + const r = lintManifest(m, { manifestDir: "/m", exists: all, validators: false }); + assert.equal(r.errors.filter((e) => /posts p1\.shot/.test(e)).length, 1); + assert.equal(r.errors.filter((e) => /posts p1\.logo/.test(e)).length, 0); + // Without the deck no post is drawn, so none is read. + assert.deepEqual(imageSrcsOf({ ...m, render: BASE }), []); +}); + +test("a QR below 1.5 px/module at 720p is an ERROR, below 2.0 a WARNING, at 2.0 nothing", () => { + assert.equal(MIN_QR_PX_PER_MODULE_720P, 1.5); + assert.equal(WARN_QR_PX_PER_MODULE_720P, 2.0); + const clip = (id, citeUrl) => ({ id, type: "clip", video: "v", start: 0, end: 5, citeUrl }); + // The corner code (no deck): qrencode's scale, unresized. + const corner = (scale, height = 1080) => lintManifest( + { render: { ...BASE, height, qr: { scale } }, provenance: PROV, timeline: [clip("c1", "https://e.test/a")] }, + { exists: all, validators: false }, + ); + assert.match(corner(2).errors[0] ?? "", /timeline c1 \(its corner QR\): 1\.33 px per module at 720p .* too small to scan/); + assert.match(corner(2, 900).warnings[0] ?? "", /1\.60 px per module at 720p .* scans only on a good screen/); + assert.deepEqual(corner(2, 900).errors, []); + assert.deepEqual(corner(3), { errors: [], warnings: [] }); + + // The deck's code: resized to qr.size, quiet zone included. A 62-byte link + // is a version-4 code, 39 modules: 80 px on 1080p is 1.37 per module, an + // error; 100 px is 1.71, a warning; 120 px is 2.05, fine. + const url62 = `https://e.test/${"a".repeat(62 - 15)}`; + assert.equal(url62.length, 62); + const deck = (size) => lintManifest( + { render: { ...DECK, chrome: { ...DECK.chrome, deck: { qr: { size } } } }, provenance: PROV, timeline: [clip("c1", url62)] }, + { exists: all, validators: false }, + ); + assert.match(deck(80).errors[0] ?? "", /timeline c1 \(the deck's QR\): 1\.37 px per module at 720p \(80 px on a 1080p frame, a version-4 code, 39 modules\)/); + assert.match(deck(100).warnings[0] ?? "", /1\.71 px per module/); + assert.deepEqual(deck(100).errors, []); + assert.deepEqual(deck(120), { errors: [], warnings: [] }); + + // A link no QR can hold. + const huge = lintManifest( + { render: BASE, provenance: PROV, timeline: [clip("c1", `https://e.test/${"z".repeat(700)}`)] }, + { exists: all, validators: false }, + ); + assert.match(huge.errors[0], /too long for a scannable QR/); +}); + +test("which codes a cut draws: the deck's (none for a card), a post's at its longest, the rail's, the corner's", () => { + const timeline = [ + { id: "c1", type: "clip", video: "v1", start: 12.7, end: 20 }, + { id: "k1", type: "card", seconds: 3 }, + { id: "s1", type: "clip", src: "media/local.mp4" }, + { id: "i1", type: "image", src: "a.png", citeUrl: "https://e.test/i1" }, + ]; + const deckQrs = qrsOf({ render: DECK, provenance: PROV, timeline }); + assert.deepEqual(deckQrs.map((q) => [q.where, q.url, q.px]), [ + ["timeline c1 (the deck's QR)", "https://example.test/?v=chan%2Fv1&t=12", 150], + ["timeline i1 (the deck's QR)", "https://e.test/i1", 150], + ]); + // A post under "archive" with no channel resolved yet: the longer of its + // url and its archive page under the manifest's channel. + const post = { id: "p1", attachTo: "c1", url: "https://bsky.app/profile/a/post/abc" }; + const [pq] = qrsOf({ render: DECK, provenance: PROV, timeline, posts: [post] }).filter((q) => q.where.startsWith("posts")); + assert.equal(pq.url, "https://example.test/?v=chan%2Fabc&vm=post"); + assert.equal(pq.px, 120); + // The corner code: clips with a moment, stills with a citeUrl. + assert.deepEqual(qrsOf({ render: BASE, provenance: PROV, timeline }).map((q) => q.where), [ + "timeline c1 (its corner QR)", "timeline i1 (its corner QR)", + ]); + // The rail draws one per entry, resized to rail.qrSize; `qr: false` none. + const rail = qrsOf({ render: { ...BASE, rail: { qrSize: 132 } }, provenance: { ...PROV, qrLink: "https://e.test/q" }, timeline }); + assert.ok(rail.every((q) => q.px === 132)); + assert.deepEqual(qrsOf({ render: { ...BASE, qr: false }, provenance: PROV, timeline }), []); +}); + +test("the threads and flips validators are part of the lint (and stay out when a build has run them)", () => { + const m = { + render: { ...BASE, qr: false, chrome: { flips: { pairs: [{ id: "p1", then: { entry: "nope" }, now: { entry: "c1" } }] } } }, + provenance: PROV, + timeline: [{ id: "c1", type: "clip", video: "v", start: 0, end: 5, thread: "t-unknown" }], + }; + const r = lintManifest(m, { exists: all }); + assert.ok(r.errors.some((e) => /timeline\[0\] \(c1\)\.thread t-unknown is not in render\.chrome\.threads\.list/.test(e)), r.errors.join("\n")); + assert.ok(r.errors.some((e) => /render\.chrome\.flips\.pairs\[0\] \(p1\)\.then\.entry nope is not in the timeline/.test(e)), r.errors.join("\n")); + assert.deepEqual(lintManifest(m, { exists: all, validators: false }).errors, []); +}); + +test("--only lints its one entry", () => { + const m = { + render: { ...BASE, qr: false }, provenance: PROV, + timeline: [ + { id: "bad", type: "image", src: "/abs/a.png", seconds: 4 }, + { id: "good", type: "image", src: "b.png", seconds: 4 }, + { id: "t1", type: "teaser", lines: ["z".repeat(40), "Soon"] }, + ], + }; + assert.equal(lintManifest(m, { exists: all, only: "good" }).errors.length, 0); + assert.equal(lintManifest(m, { exists: all, only: "good" }).warnings.length, 0); + assert.equal(lintManifest(m, { exists: all, only: "bad" }).errors.length, 1); + assert.equal(lintManifest(m, { exists: all, only: "t1" }).warnings.length, 1); +}); + +// ---- the command lines and the build --------------------------------------------- + +function project(manifest) { + const dir = mkdtempSync(path.join(tmpdir(), "rtv-lint-")); + mkdirSync(path.join(dir, "stills"), { recursive: true }); + writeFileSync(path.join(dir, "stills", "ok.png"), ""); + const manifestPath = path.join(dir, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify(manifest)); + return { dir, manifestPath, done: () => rmSync(dir, { recursive: true, force: true }) }; +} + +const run = (args) => new Promise((resolve) => { + execFile(process.execPath, args, { env: { ...process.env, HEAVY: "0" } }, (err, stdout, stderr) => { + resolve({ code: err ? err.code : 0, stdout, stderr }); + }); +}); + +const BAD = { + slug: "lint-demo", title: "Lint demo", provenance: PROV, + render: { ...BASE, qr: false }, + timeline: [ + { id: "i1", type: "image", src: "/elsewhere/shot.png", seconds: 4 }, + { id: "i2", type: "image", src: "stills/ok.png", seconds: 4 }, + { id: "t1", type: "teaser", lines: ["An overline well past the house style", "Soon"] }, + ], +}; + +test("lint.mjs and build-video.mjs --lint print every warning and error and exit 1 on an error", async () => { + const bad = project(BAD); + const good = project({ ...BAD, timeline: BAD.timeline.slice(1) }); + try { + const a = await run([path.join(HERE, "lint.mjs"), bad.manifestPath]); + assert.equal(a.code, 1); + assert.match(a.stdout, /^warning: timeline t1\.lines\[0\] .* house style is at most 34$/m); + assert.match(a.stdout, /^ERROR: timeline i1: the image "\/elsewhere\/shot\.png" must be a path relative to the manifest/m); + assert.match(a.stdout, /^1 error\(s\), 1 warning\(s\)$/m); + const json = await run([path.join(HERE, "lint.mjs"), bad.manifestPath, "--json"]); + assert.equal(JSON.parse(json.stdout).errors.length, 1); + + const b = await run([path.join(HERE, "build-video.mjs"), bad.manifestPath, "--lint"]); + assert.equal(b.code, 1); + assert.match(b.stdout, /^lint ERROR: timeline i1: /m); + assert.match(b.stdout, /^lint: timeline t1\.lines\[0\] /m); + const nd = await run([path.join(HERE, "build-video.mjs"), bad.manifestPath, "--lint", "--progress", "ndjson"]); + const done = nd.stdout.trim().split("\n").map((l) => JSON.parse(l)).find((e) => e.ev === "done"); + assert.equal(done.lint.errors.length, 1); + assert.equal(done.lint.warnings.length, 1); + + // A warning alone is not a failure. + const c = await run([path.join(HERE, "lint.mjs"), good.manifestPath]); + assert.equal(c.code, 0, c.stdout); + assert.match(c.stdout, /^0 error\(s\), 1 warning\(s\)$/m); + const r = await lintManifestFile(good.manifestPath); + assert.deepEqual(r.errors, []); + assert.equal(r.variant, "sourced"); + } finally { + bad.done(); + good.done(); + } +}); + +test("a build refuses a lint error before it renders anything; --no-lint builds past it", async () => { + const p = project(BAD); + try { + await assert.rejects( + buildVideo({ manifestPath: p.manifestPath, opts: {} }), + /^Error: lint: timeline i1: the image "\/elsewhere\/shot\.png" must be a path relative .* — --lint lists them; --no-lint builds anyway$/, + ); + // Past the lint the image itself is looked for -- and is not there. + await assert.rejects( + buildVideo({ manifestPath: p.manifestPath, opts: { noLint: true }, only: "i1" }), + (err) => !/^lint:/.test(err.message) && /no image at \/elsewhere\/shot\.png/.test(err.message), + ); + // `--only` lints its one entry: the good still is not held up by the bad one. + await assert.rejects( + buildVideo({ manifestPath: p.manifestPath, opts: {}, only: "i1" }), + /^Error: lint: timeline i1/, + ); + } finally { + p.done(); + } +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -26,10 +26,12 @@ "./deck": "./deck.mjs", "./factcheck": "./factcheck.mjs", "./ledger-totals": "./ledger-totals.mjs", + "./lint": "./lint.mjs", "./local-media": "./local-media.mjs", "./mute": "./mute.mjs", "./package.json": "./package.json", "./post-links": "./post-links.mjs", + "./prune-frames": "./prune-frames.mjs", "./render-cards": "./render-cards.mjs", "./resolve-windows": "./resolve-windows.mjs", "./shoot-page": "./shoot-page.mjs", diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -0,0 +1,113 @@ +// PRUNING THE CHROME'S FRAMES once the cut is muxed. +// +// The deck, the feed, the stamps, the threads, each posts window and each +// teaser render a PNG sequence into `<variant>/chrome/<name>-frames` -- one to +// two GB a take -- and the renderer can leave a `chrome/work-*` directory +// behind a render it did not finish. Once the final file is muxed none of it is +// read again by that cut; the cost of keeping it is only that the NEXT +// `--chrome-only` reuses a render whose key did not change instead of +// rendering it again. Several takes of that size filled /home (2026-10-09). +// So a build prunes them after its final mux, unless `--keep-frames` +// (build-video.mjs says which runs prune). +// +// WHAT IS TOUCHED, AND NOTHING ELSE: the DIRECTORIES `chrome/<name>-frames` and +// `chrome/work-*`. Never `segments/` -- a take re-lays its chrome over ANOTHER +// take's segments by hard-linking them in, and a prune that reached them would +// take the other take's footage with it -- never the compositions +// (`chrome/deck/`, `chrome/posts-<id>/`), the cards, the QRs, the schedule or +// the joins' caches. A symlink named like one is not followed or removed. +// +// What was pruned is written down first, in `chrome/pruned.json`: each +// sequence's frame count and render key, as of this prune (a sequence a later +// build renders again is counted on disk; the record only answers for one that +// is gone). verify-build reads a pruned sequence's count and key from there, so +// a verified cut stays verifiable. + +import { lstat, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const PRUNED_RECORD = "pruned.json"; +const FRAME_RE = /^frame_\d+\.png$/; + +/** Is this `chrome/` entry one a prune removes? A real directory, named for it. */ +export function isPrunable(dirent) { + return dirent.isDirectory() && (dirent.name.endsWith("-frames") || dirent.name.startsWith("work-")); +} + +async function dirBytes(dir) { + let total = 0; + const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); + for (const e of entries) { + const p = path.join(dir, e.name); + if (e.isDirectory()) total += await dirBytes(p); + else total += (await lstat(p).catch(() => null))?.size ?? 0; + } + return total; +} + +async function readRecord(chromeDir) { + return readFile(path.join(chromeDir, PRUNED_RECORD), "utf8").then( + (s) => JSON.parse(s), + () => null, + ); +} + +/** + * Remove `<variantDir>/chrome/<name>-frames` and `chrome/work-*`, recording each + * sequence's frame count and key first. Returns what went and how much. + * + * @returns {Promise<{ sequences: string[], work: string[], bytes: number }>} + */ +export async function pruneChromeFrames(variantDir, { now = () => new Date() } = {}) { + const chromeDir = path.join(variantDir, "chrome"); + const entries = (await readdir(chromeDir, { withFileTypes: true }).catch(() => [])).filter(isPrunable); + const sequences = entries.filter((e) => e.name.endsWith("-frames")).map((e) => e.name).sort(); + const work = entries.filter((e) => !e.name.endsWith("-frames")).map((e) => e.name).sort(); + if (!sequences.length && !work.length) return { sequences, work, bytes: 0 }; + + const dirs = {}; + let bytes = 0; + for (const name of sequences) { + const dir = path.join(chromeDir, name); + const files = await readdir(dir).catch(() => []); + const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); + dirs[name] = { frames: files.filter((f) => FRAME_RE.test(f)).length, key }; + } + for (const name of [...sequences, ...work]) bytes += await dirBytes(path.join(chromeDir, name)); + const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; + const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); + await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); + await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); + for (const name of [...sequences, ...work]) { + await rm(path.join(chromeDir, name), { recursive: true, force: true }); + } + return { sequences, work, bytes }; +} + +// The record's entry for a pruned sequence -- unless the cut was written AFTER +// the prune (`since`: the final file's mtime in ms), which means a later build +// that rendered no chrome (`--no-chrome`) made it, and the record is not about +// the file being verified. +async function recorded(dir, since) { + const rec = await readRecord(path.dirname(dir)); + if (!rec) return null; + if (since != null && !(Date.parse(rec.prunedAt) >= since - 2000)) return null; + return rec.dirs?.[path.basename(dir)] ?? null; +} + +/** + * A sequence's frame count: counted on disk, or -- when it was pruned after + * the mux -- what the prune recorded. 0 when neither knows it. + */ +export async function framesOf(dir, { since = null } = {}) { + const files = await readdir(dir).catch(() => null); + if (files) return files.filter((f) => FRAME_RE.test(f)).length; + return Number((await recorded(dir, since))?.frames ?? 0); +} + +/** A sequence's render key: its `.key`, or the one the prune recorded; null when neither. */ +export async function frameKeyOf(dir, { since = null } = {}) { + const files = await readdir(dir).catch(() => null); + if (files) return readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); + return (await recorded(dir, since))?.key ?? null; +} diff --git a/umtool/report-to-video/prune-frames.test.mjs b/umtool/report-to-video/prune-frames.test.mjs @@ -0,0 +1,204 @@ +// Pruning the chrome's frames after the final mux (prune-frames.mjs): what it +// removes (chrome/*-frames and chrome/work-* directories, nothing else -- never +// segments/, never through a symlink), what it records, how verify-build reads +// the record, and a real build that prunes -- and keeps with --keep-frames. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { PRUNED_RECORD, frameKeyOf, framesOf, pruneChromeFrames } from "./prune-frames.mjs"; +import { verifyBuild, verifyTeasers } from "./verify-build.mjs"; +import { buildVideo, setProgressMode } from "./build-video.mjs"; +import { frameCount, teaserSeconds } from "./deck.mjs"; +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; + +const have = ["ffmpeg", "ffprobe", "magick"].every((b) => spawnSync(b, ["-version"]).status === 0); + +function frames(dir, n, key) { + mkdirSync(dir, { recursive: true }); + for (let i = 1; i <= n; i += 1) writeFileSync(path.join(dir, `frame_${String(i).padStart(6, "0")}.png`), "x"); + if (key) writeFileSync(path.join(dir, ".key"), `${key}\n`); +} + +test("pruneChromeFrames removes chrome/*-frames and chrome/work-* only, and records each sequence first", async () => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-prune-")); + try { + const v = path.join(root, "out", "sourced"); + const chrome = path.join(v, "chrome"); + frames(path.join(chrome, "deck-frames"), 5, "deck-key"); + frames(path.join(chrome, "teaser-t1-frames"), 3, "teaser-key"); + frames(path.join(chrome, "deck-from2-frames"), 2, null); + mkdirSync(path.join(chrome, "work-abc123", "deep"), { recursive: true }); + writeFileSync(path.join(chrome, "work-abc123", "deep", "partial.png"), "y"); + // What stays: the compositions, a file named like a sequence, and a + // SYMLINK named like one -- neither followed nor removed. + mkdirSync(path.join(chrome, "deck", "assets"), { recursive: true }); + writeFileSync(path.join(chrome, "deck", "index.html"), "<html>"); + writeFileSync(path.join(chrome, "notes-frames"), "a file, not a sequence"); + const elsewhere = path.join(root, "elsewhere-frames"); + frames(elsewhere, 2, "theirs"); + symlinkSync(elsewhere, path.join(chrome, "linked-frames")); + // segments/: a segment hard-linked from another take. + const other = path.join(root, "other-take"); + mkdirSync(other); + writeFileSync(path.join(other, "c1.mp4"), "another take's footage"); + mkdirSync(path.join(v, "segments")); + linkSync(path.join(other, "c1.mp4"), path.join(v, "segments", "c1.mp4")); + writeFileSync(path.join(v, "schedule.json"), "{}"); + + const at = new Date("2026-10-10T01:02:03.000Z"); + const r = await pruneChromeFrames(v, { now: () => at }); + assert.deepEqual(r.sequences, ["deck-frames", "deck-from2-frames", "teaser-t1-frames"]); + assert.deepEqual(r.work, ["work-abc123"]); + assert.ok(r.bytes >= 5 + 3 + 2 + 1); + + assert.deepEqual(readdirSync(chrome).sort(), ["deck", "linked-frames", "notes-frames", PRUNED_RECORD].sort()); + assert.equal(readFileSync(path.join(chrome, "deck", "index.html"), "utf8"), "<html>"); + assert.equal(readdirSync(elsewhere).length, 3, "a symlinked directory's contents are untouched"); + assert.equal(readFileSync(path.join(v, "segments", "c1.mp4"), "utf8"), "another take's footage"); + assert.equal(statSync(path.join(other, "c1.mp4")).nlink, 2, "segments/ is never touched"); + assert.ok(existsSync(path.join(v, "schedule.json"))); + + const rec = JSON.parse(readFileSync(path.join(chrome, PRUNED_RECORD), "utf8")); + assert.equal(rec.format, "umtool-pruned-frames"); + assert.equal(rec.prunedAt, at.toISOString()); + assert.deepEqual(rec.dirs, { + "deck-frames": { frames: 5, key: "deck-key" }, + "deck-from2-frames": { frames: 2, key: null }, + "teaser-t1-frames": { frames: 3, key: "teaser-key" }, + }); + + // A second prune with nothing to prune changes nothing. + assert.deepEqual(await pruneChromeFrames(v), { sequences: [], work: [], bytes: 0 }); + assert.equal(JSON.parse(readFileSync(path.join(chrome, PRUNED_RECORD), "utf8")).prunedAt, at.toISOString()); + // No chrome/ at all: nothing to do. + assert.deepEqual(await pruneChromeFrames(path.join(root, "nothing")), { sequences: [], work: [], bytes: 0 }); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("framesOf / frameKeyOf: on disk first; a pruned sequence from the record -- unless the cut is newer than the prune", async () => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-prune-read-")); + try { + const chrome = path.join(root, "chrome"); + frames(path.join(chrome, "deck-frames"), 4, "k4"); + assert.equal(await framesOf(path.join(chrome, "deck-frames")), 4); + assert.equal(await frameKeyOf(path.join(chrome, "deck-frames")), "k4"); + const at = Date.parse("2026-10-10T00:00:00.000Z"); + await pruneChromeFrames(root, { now: () => new Date(at) }); + const dir = path.join(chrome, "deck-frames"); + assert.equal(await framesOf(dir), 4); + assert.equal(await frameKeyOf(dir), "k4"); + // The final file written before (or as) the prune ran: the record is about it. + assert.equal(await framesOf(dir, { since: at - 60_000 }), 4); + // Written after it (a later --no-chrome build): the record is not. + assert.equal(await framesOf(dir, { since: at + 60_000 }), 0); + assert.equal(await frameKeyOf(dir, { since: at + 60_000 }), null); + // A sequence a later build rendered again is counted on disk, not recorded. + frames(dir, 6, "k6"); + assert.equal(await framesOf(dir), 6); + assert.equal(await frameKeyOf(dir), "k6"); + // Never recorded at all: 0 and null. + assert.equal(await framesOf(path.join(chrome, "stamp-frames")), 0); + assert.equal(await frameKeyOf(path.join(chrome, "stamp-frames")), null); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("verify-build reads a pruned teaser's frames and key from the record", async () => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-prune-verify-")); + try { + const v = path.join(root, "out", "sourced"); + const entry = { id: "t1", type: "teaser", lines: ["Soon", "Later"] }; + const manifest = { render: { fps: 10, transition: 0 }, timeline: [entry] }; + const want = frameCount(teaserSeconds(entry, 0, 10), 10); + frames(path.join(v, "chrome", "teaser-t1-frames"), want, "tk"); + mkdirSync(path.join(v, "segments"), { recursive: true }); + writeFileSync(path.join(v, "segments", "t1.teaser.json"), JSON.stringify({ key: "seg", frames: "tk", hits: 0, transition: 0 })); + const at = Date.parse("2026-10-10T00:00:00.000Z"); + await pruneChromeFrames(v, { now: () => new Date(at) }); + + const ok = []; + await verifyTeasers(v, manifest, ok, { noXfade: true, since: at - 1000 }); + assert.deepEqual(ok, []); + // A cut written after the prune is not vouched for by it. + const later = []; + await verifyTeasers(v, manifest, later, { noXfade: true, since: at + 60_000 }); + assert.match(later.join("\n"), /teaser-t1-frames holds 0 frames; the teaser t1 is \d+/); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a build prunes the frames it rendered after the final mux, verify-build still passes; --keep-frames keeps them", { skip: !have && "needs ffmpeg, ffprobe and magick" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-prune-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. + const stub = path.join(root, "hf-stub.mjs"); + writeFileSync(stub, `#!/usr/bin/env node +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdirSync, readFileSync } from "node:fs"; +const a = process.argv.slice(2); +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const 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:size=" + w + "x" + h, "-frames:v", "1", 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; + + const manifestPath = path.join(root, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify({ + slug: "prune", title: "Prune", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { + width: 1920, height: 1080, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2, + palette: { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }, + fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, qr: false, + }, + timeline: [{ id: "t1", type: "teaser", lines: ["Soon", "Later"] }], + })); + const v = path.join(root, "out", "sourced"); + const framesDir = path.join(v, "chrome", "teaser-t1-frames"); + const events = []; + setProgressMode((e) => events.push(e)); + try { + // --keep-frames: the sequence stays, nothing is recorded. + await buildVideo({ manifestPath, opts: { keepFrames: true } }); + assert.ok(readdirSync(framesDir).some((f) => /^frame_\d+\.png$/.test(f))); + assert.equal(existsSync(path.join(v, "chrome", PRUNED_RECORD)), false); + + // The default: pruned after the mux, said in a note, and recorded. + const want = readdirSync(framesDir).filter((f) => /^frame_\d+\.png$/.test(f)).length; + const seg = statSync(path.join(v, "segments", "t1.mp4")); + await buildVideo({ manifestPath, opts: {} }); + assert.equal(existsSync(framesDir), false); + assert.ok(events.some((e) => e.ev === "note" && /^pruned 1 frame sequence\(s\), \d+ MiB \(chrome\/pruned\.json records them; --keep-frames keeps them\)$/.test(e.message))); + const rec = JSON.parse(readFileSync(path.join(v, "chrome", PRUNED_RECORD), "utf8")); + assert.equal(rec.dirs["teaser-t1-frames"].frames, want); + // The segment is the one the first build made (its record matched). + assert.equal(statSync(path.join(v, "segments", "t1.mp4")).ino, seg.ino); + } finally { + setProgressMode("human"); + } + const verified = await verifyBuild(manifestPath, {}); + assert.deepEqual(verified.problems, []); + assert.equal(verified.ok, true); +}); diff --git a/umtool/report-to-video/segment-links.test.mjs b/umtool/report-to-video/segment-links.test.mjs @@ -0,0 +1,249 @@ +// A take that re-lays its chrome over ANOTHER take's segments: it hard-links +// `out/sourced/segments/*` into its own out dir and runs `--chrome-only`. +// +// - `--chrome-only` builds a segment that is MISSING (from what is cached) +// and never writes one that EXISTS: the other take's file keeps its inode, +// its bytes, its mtime and its second name; +// - `--only <id>` and a teaser re-encoded for changed words write a file of +// this take's own, and leave the other take's alone; +// - detachSegmentFiles unlinks only links (a hard link, a symlink), never a +// file with one name, and only an entry's own files. +// +// Real encodes, kept tiny; the deck's renderer is a stub. Skipped without +// ffmpeg/ffprobe. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { chmodSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { buildTeaserSegment, buildVideo, detachSegmentFiles, segmentFraming, setProgressMode } from "./build-video.mjs"; +import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; + +const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +// The deck is drawn on a 1920x1080 frame (what its default panel fits). +const 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: {} }, +}; +const PROV = { siteOrigin: "https://example.test", channelSlug: "chan" }; + +const ff = (args) => { + const r = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", ...args]); + assert.equal(r.status, 0, String(r.stderr)); +}; +const sha = (p) => createHash("sha256").update(readFileSync(p)).digest("hex"); +const fingerprint = (p) => { + const st = statSync(p); + return { ino: st.ino, nlink: st.nlink, size: st.size, mtimeMs: st.mtimeMs, sha: sha(p) }; +}; + +/** + * Two takes. A: a built image segment `i1` (and its framing record). B: the + * same manifest plus a second still `i2`, with A's `i1` files hard-linked into + * its segments/ and `i2` never built. + */ +function twoTakes(root) { + const a = path.join(root, "take-a"); + const b = path.join(root, "take-b"); + const aSegs = path.join(a, "out", "sourced", "segments"); + const bSegs = path.join(b, "out", "sourced", "segments"); + for (const d of [aSegs, bSegs, path.join(b, "stills")]) mkdirSync(d, { recursive: true }); + ff(["-f", "lavfi", "-i", "color=c=0x334455:size=320x180", "-frames:v", "1", path.join(b, "stills", "one.png")]); + ff(["-f", "lavfi", "-i", "color=c=0x554433:size=320x180", "-frames:v", "1", path.join(b, "stills", "two.png")]); + // A's segment: a second of picture and silence, as a still's segment is. + ff([ + "-f", "lavfi", "-i", "color=c=0x223344:size=320x180:rate=10:duration=1", + "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000", + "-t", "1", "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(aSegs, "i1.mp4"), + ]); + writeFileSync(path.join(aSegs, "i1.cut.json"), JSON.stringify({ version: 1, id: "i1", framing: segmentFraming(RENDER) }) + "\n"); + for (const f of ["i1.mp4", "i1.cut.json"]) linkSync(path.join(aSegs, f), path.join(bSegs, f)); + const manifestPath = path.join(b, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify({ + slug: "links", title: "Links", provenance: PROV, render: RENDER, + timeline: [ + { id: "i1", type: "image", src: "stills/one.png", seconds: 1 }, + { id: "i2", type: "image", src: "stills/two.png", seconds: 1 }, + ], + })); + return { a, b, aSegs, bSegs, manifestPath }; +} + +// The build's events, read off its progress hook; a failure is returned, not thrown. +async function quietly(fn) { + const events = []; + setProgressMode((e) => events.push(e)); + try { + return { result: await fn().catch((err) => ({ err })), events }; + } finally { + setProgressMode("human"); + } +} + +test("--chrome-only builds a MISSING segment from the cache and never writes an EXISTING hard-linked one", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-links-")); + 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 }); + }); + const { aSegs, bSegs, manifestPath } = twoTakes(root); + // The renderer refuses: the run stops at the deck's render, after every + // segment it was going to build is built -- which is all this test reads. + const stub = path.join(root, "hf-refuses.sh"); + writeFileSync(stub, "#!/bin/sh\nexit 1\n"); + chmodSync(stub, 0o755); + process.env.HYPERFRAMES_BIN = stub; + + const before = fingerprint(path.join(aSegs, "i1.mp4")); + const beforeRec = fingerprint(path.join(aSegs, "i1.cut.json")); + assert.equal(before.nlink, 2, "A's segment has B's second name"); + + const { result, events } = await quietly(() => buildVideo({ manifestPath, opts: { chromeOnly: true } })); + assert.ok(result?.err, "the stub renderer stops the run"); + assert.ok(events.some((e) => e.ev === "chrome" && e.phase === "schedule"), `stopped past the schedule: ${result.err.message}`); + + // The missing one was built, as a file of B's own, for this cut's layout. + assert.ok(events.some((e) => e.ev === "note" && /--chrome-only: i2's segment is missing — building it from what is cached/.test(e.message))); + assert.ok(events.some((e) => e.ev === "segment" && e.id === "i2")); + const built = statSync(path.join(bSegs, "i2.mp4")); + assert.ok(built.size > 0); + assert.equal(built.nlink, 1); + assert.deepEqual(JSON.parse(readFileSync(path.join(bSegs, "i2.cut.json"), "utf8")).framing, segmentFraming(RENDER)); + assert.equal(existsSync(path.join(aSegs, "i2.mp4")), false); + + // The existing one: not a byte, not a name, not a timestamp changed. + assert.deepEqual(fingerprint(path.join(aSegs, "i1.mp4")), before); + assert.deepEqual(fingerprint(path.join(aSegs, "i1.cut.json")), beforeRec); + assert.equal(statSync(path.join(bSegs, "i1.mp4")).ino, before.ino, "B still names A's file: nothing was rebuilt in its place"); + // Nothing was built for i1. + assert.equal(events.some((e) => e.ev === "segment" && e.id === "i1"), false); +}); + +test("--chrome-preview still refuses a missing segment, by name", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-links-pv-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const { bSegs, manifestPath } = twoTakes(root); + const { result } = await quietly(() => buildVideo({ manifestPath, opts: { chromePreview: { at: 0, dur: 1 } } })); + assert.match(String(result?.err?.message), /--chrome-preview needs .*i2\.mp4, which is missing — run a full build first/); + assert.equal(existsSync(path.join(bSegs, "i2.mp4")), false); +}); + +test("--only <id> still builds that one segment -- as this take's own file, the other take's untouched", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-links-only-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const { aSegs, bSegs, manifestPath } = twoTakes(root); + const before = fingerprint(path.join(aSegs, "i1.mp4")); + const beforeRec = fingerprint(path.join(aSegs, "i1.cut.json")); + + const { result } = await quietly(() => buildVideo({ manifestPath, opts: {}, only: "i1" })); + assert.equal(result.err, undefined, result.err?.message); + assert.equal(result.out, path.join(bSegs, "i1.mp4")); + + const mine = statSync(path.join(bSegs, "i1.mp4")); + assert.notEqual(mine.ino, before.ino); + assert.equal(mine.nlink, 1); + assert.equal(statSync(path.join(bSegs, "i1.cut.json")).nlink, 1); + // A's: the same bytes and inode; one name now, its own. + const after = fingerprint(path.join(aSegs, "i1.mp4")); + assert.deepEqual({ ...after, nlink: 2 }, before); + assert.equal(after.nlink, 1); + assert.equal(fingerprint(path.join(aSegs, "i1.cut.json")).sha, beforeRec.sha); +}); + +test("a teaser re-encoded for changed words replaces a hard-linked segment instead of writing through it", { skip: !have && "needs ffmpeg and ffprobe" }, async (t) => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-links-teaser-")); + 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 (real PNGs, + // so the encode can read them), as the e2e fixture's stub does. + const stub = path.join(root, "hf-stub.mjs"); + writeFileSync(stub, `#!/usr/bin/env node +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdirSync, readFileSync } from "node:fs"; +const a = process.argv.slice(2); +const out = a[a.indexOf("--output") + 1]; +const fps = Number(a[a.indexOf("--fps") + 1]); +const html = readFileSync(a.at(-1) + "/index.html", "utf8"); +const dur = Number(/data-composition-id="[^"]*"[^>]*data-duration="([\\d.]+)"/.exec(html)[1]); +const w = Number((/data-width="(\\d+)"/.exec(html) ?? [0, 1920])[1]); +const h = Number((/data-height="(\\d+)"/.exec(html) ?? [0, 1080])[1]); +mkdirSync(out, { recursive: true }); +const one = out + "/.one.png"; +spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x112233:size=" + w + "x" + h, "-frames:v", "1", 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; + + const a = path.join(root, "take-a", "out", "sourced", "segments"); + const bDir = path.join(root, "take-b"); + const b = path.join(bDir, "out", "sourced", "segments"); + mkdirSync(a, { recursive: true }); + mkdirSync(b, { recursive: true }); + // A's teaser segment and its record, linked into B. B's words differ, so + // its key does not match A's record and the teaser is encoded again. + writeFileSync(path.join(a, "t1.mp4"), "take A's teaser"); + writeFileSync(path.join(a, "t1.teaser.json"), JSON.stringify({ key: "a-key", frames: "a-frames", hits: 0, transition: 0 }) + "\n"); + for (const f of ["t1.mp4", "t1.teaser.json"]) linkSync(path.join(a, f), path.join(b, f)); + const manifestPath = path.join(bDir, "video.manifest.json"); + const entry = { id: "t1", type: "teaser", lines: ["Take B", "Soon"] }; + const render = { ...RENDER, chrome: undefined }; + writeFileSync(manifestPath, JSON.stringify({ slug: "teaser", title: "T", provenance: PROV, render, timeline: [entry] })); + + const { result } = await quietly(() => + buildTeaserSegment(entry, { manifestPath, render, outDir: path.join(bDir, "out", "sourced"), variant: "sourced", transition: 0 }), + ); + assert.equal(result?.err, undefined, result?.err?.message); + // A's files: as they were, one name each now. + assert.equal(readFileSync(path.join(a, "t1.mp4"), "utf8"), "take A's teaser"); + assert.equal(JSON.parse(readFileSync(path.join(a, "t1.teaser.json"), "utf8")).key, "a-key"); + assert.equal(statSync(path.join(a, "t1.mp4")).nlink, 1); + // B's: a new segment and record of its own, and no temp file left beside them. + assert.notEqual(statSync(path.join(b, "t1.mp4")).ino, statSync(path.join(a, "t1.mp4")).ino); + assert.ok(statSync(path.join(b, "t1.mp4")).size > 1000); + assert.notEqual(JSON.parse(readFileSync(path.join(b, "t1.teaser.json"), "utf8")).key, "a-key"); + const { readdirSync } = await import("node:fs"); + assert.deepEqual(readdirSync(b).sort(), ["t1.mp4", "t1.teaser.json"]); +}); + +test("detachSegmentFiles: unlinks an entry's linked files (hard or symbolic), never a file with one name", () => { + const root = mkdtempSync(path.join(tmpdir(), "rtv-detach-")); + try { + const other = path.join(root, "other"); + const segs = path.join(root, "segs"); + mkdirSync(other); + mkdirSync(segs); + writeFileSync(path.join(other, "c1.mp4"), "other take's picture"); + writeFileSync(path.join(other, "c1.attrib.txt"), "other take's line"); + linkSync(path.join(other, "c1.mp4"), path.join(segs, "c1.mp4")); + symlinkSync(path.join(other, "c1.attrib.txt"), path.join(segs, "c1.attrib.txt")); + writeFileSync(path.join(segs, "c1.cut.json"), "mine"); + writeFileSync(path.join(other, "c10.mp4"), "x"); + linkSync(path.join(other, "c10.mp4"), path.join(segs, "c10.mp4")); + return detachSegmentFiles(segs, "c1").then((gone) => { + assert.deepEqual(gone.sort(), ["c1.attrib.txt", "c1.mp4"]); + assert.equal(existsSync(path.join(segs, "c1.mp4")), false); + assert.equal(existsSync(path.join(segs, "c1.attrib.txt")), false); + assert.equal(readFileSync(path.join(segs, "c1.cut.json"), "utf8"), "mine", "a file with one name stays"); + assert.equal(readFileSync(path.join(other, "c1.mp4"), "utf8"), "other take's picture"); + assert.equal(readFileSync(path.join(other, "c1.attrib.txt"), "utf8"), "other take's line"); + assert.equal(statSync(path.join(segs, "c10.mp4")).nlink, 2, "another entry's files are not this entry's"); + }).finally(() => rmSync(root, { recursive: true, force: true })); + } catch (err) { + rmSync(root, { recursive: true, force: true }); + throw err; + } +}); 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 { frameKeyOf, framesOf } from "./prune-frames.mjs"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; @@ -90,7 +91,7 @@ export async function verifyBuild(manifestPath, { outDir, variant = "sourced", n if (deckOn(manifest.render)) { deck = await verifyDeck(path.join(root, variant), manifest.render, file, problems); } - const teasers = await verifyTeasers(path.join(root, variant), manifest, problems, { noXfade }); + const teasers = await verifyTeasers(path.join(root, variant), manifest, problems, { noXfade, since: st.mtimeMs }); return { ok: problems.length === 0, variant, file, duration, chapters, entries, size: st.size, deck, @@ -117,10 +118,9 @@ export async function verifyDeck(variantDir, render, file, problems) { const fps = Number(schedule.fps ?? render.fps); const want = frameCount(schedule.total, fps); const framesDir = path.join(variantDir, "chrome", "deck-frames"); - const countFrames = (dir) => readdir(dir).then( - (fs) => fs.filter((f) => /^frame_\d+\.png$/.test(f)).length, - () => 0, - ); + // On disk, or -- pruned after the mux (prune-frames.mjs) -- as recorded. + const since = (await stat(file).catch(() => null))?.mtimeMs ?? null; + const countFrames = (dir) => framesOf(dir, { since }); const frames = await countFrames(framesDir); if (frames === 0) { problems.push(`the deck is on but ${framesDir} has no frames — built with --no-chrome?`); @@ -183,7 +183,7 @@ export async function verifyDeck(variantDir, render, file, problems) { * record beside its segment (`<id>.teaser.json`) names those frames' key -- a * segment encoded from an older render (changed words) fails here. */ -export async function verifyTeasers(variantDir, manifest, problems, { noXfade = false } = {}) { +export async function verifyTeasers(variantDir, manifest, problems, { noXfade = false, since = null } = {}) { const fps = Number(manifest.render?.fps ?? 30); // A dip's lead counts the cut's transition AS BUILT: the one the teaser's // record names, else the one the build measured (its schedule, under the @@ -194,13 +194,13 @@ export async function verifyTeasers(variantDir, manifest, problems, { noXfade = for (const e of manifest.timeline ?? []) { if (e.type !== "teaser") continue; const dir = path.join(variantDir, "chrome", `teaser-${e.id}-frames`); - const frames = await readdir(dir).then((fs) => fs.filter((f) => /^frame_\d+\.png$/.test(f)).length, () => 0); + const frames = await framesOf(dir, { since }); const seg = path.join(variantDir, "segments", `${e.id}.mp4`); const rec = await readFile(seg.replace(/\.mp4$/, ".teaser.json"), "utf8").then(JSON.parse, () => null); const D = Number.isFinite(rec?.transition) ? rec.transition : cutD; const seconds = teaserSeconds(e, D, fps); const want = frameCount(seconds, fps); - const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); + const key = await frameKeyOf(dir, { since }); if (frames !== want) problems.push(`${dir} holds ${frames} frames; the teaser ${e.id} is ${want} (${seconds}s at ${fps} fps)`); if (!rec) problems.push(`the teaser ${e.id} has no record beside ${seg} — rebuild it`); else if (key && rec.frames !== key) problems.push(`the teaser ${e.id}'s segment was encoded from another render of it — rebuild it`);