commit e2a485d9c59443cd6b9b022208cc3b5f662b13a7
parent d3570dfa78485916b83474ab04bc03fb4d3ef9b8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 26 Oct 2026 07:48:53 -0400
Merge lane/brand-intro: a report video can open with a brand intro (render.intro), GBA-style: Archilyzer built in on the first sound, MEDIA on the chime; eight variants
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# editor/CHANGELOG.md
Diffstat:
22 files changed, 1438 insertions(+), 25 deletions(-)
diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts
@@ -169,7 +169,7 @@ test("the look ops (release 38): look, slide and room through the look's own rul
assert.match(r.applied[1]!.warnings![0]!, /the slide's knobs show once the join style is blur slide/);
assert.deepEqual(
r.refused.map((x) => x.why),
- ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur)'],
+ ["render.transition must be a number of seconds from 0 (a hard cut) to 3", '"chrome" is not a look setting (headerHeight, footerHeight, qr, transition, transitionStyle, loudness, captions, room, slide, blur, intro)'],
);
assert.equal((manifest.render as { transition: number }).transition, 0.4, "the input is not touched");
});
diff --git a/common/lib/report/intro.d.mts b/common/lib/report/intro.d.mts
@@ -0,0 +1,23 @@
+// Types for ./intro.mjs: the brand intro's rules (`render.intro`).
+
+type Render = Record<string, unknown> | null | undefined;
+
+export type IntroGround = "light" | "dark";
+export type Intro = { style: string; ground: IntroGround; sound: string | false | undefined; seconds: number };
+
+export const INTRO_STYLES: readonly string[];
+export const INTRO_GROUNDS: readonly IntroGround[];
+export const INTRO_STYLE_GROUND: Readonly<Record<string, IntroGround>>;
+export const INTRO_BEATS: Readonly<{
+ build: Readonly<{ from: number; to: number }>;
+ chime: Readonly<{ from: number; to: number }>;
+ fade: number;
+}>;
+export const INTRO_SECONDS: number;
+export const INTRO_SECONDS_MIN: number;
+export const INTRO_SECONDS_MAX: number;
+export const INTRO_ID: string;
+export function introOf(render: Render): Intro | null;
+export function introErrors(value: unknown): string[];
+export function validateIntro(manifest: unknown): string[];
+export function introPatchValue(v: unknown): unknown;
diff --git a/common/lib/report/intro.mjs b/common/lib/report/intro.mjs
@@ -0,0 +1,111 @@
+// THE BRAND INTRO'S RULES (`render.intro`): the short Archilyzer sting a cut
+// can open with -- "Archilyzer" built in on the first sound, "media" under it
+// on the chime, after the Game Boy Advance boot screen -- and the ONE set of
+// checks every writer and reader of the key runs:
+//
+// umtool's updateRender / `umtool look <p> intro=<style>` (look.mjs applyLookPatch)
+// a take's patch, the build and the lint (look.mjs validateLook)
+//
+// The picture and the sound are report-to-video's (intro.mjs, chrome-intro.mjs).
+// This file only says what the key may hold, so the editor's video assistant,
+// which cannot import umtool, refuses exactly what the build refuses.
+//
+// "render": { "intro": "boot" } the style alone
+// "render": { "intro": { "style": "boot-dark", "ground": "light",
+// "sound": "intro.wav", "seconds": 4.5 } } or its knobs
+//
+// Absent (or null): no intro, and the cut renders exactly as it did.
+//
+// PURE: no fs, no ffmpeg. Plain ESM with a .d.mts beside it.
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+/** The styles, in the order the docs and the variant renders list them. */
+export const INTRO_STYLES = Object.freeze(["boot", "boot-wipe", "boot-dark", "boot-cascade", "boot-mark"]);
+
+/** The grounds a style is drawn on. Each style has its own default (INTRO_STYLE_GROUND). */
+export const INTRO_GROUNDS = Object.freeze(["light", "dark"]);
+
+/** Each style's ground when the key names none. */
+export const INTRO_STYLE_GROUND = Object.freeze({
+ boot: "light",
+ "boot-wipe": "light",
+ "boot-dark": "dark",
+ "boot-cascade": "light",
+ "boot-mark": "dark",
+});
+
+/**
+ * The beats, in seconds from the intro's first frame: measured off the stand-in
+ * sound (the GBA boot: silence to 0.34, the build 0.34–2.32, a gap, the chime
+ * 2.78–3.94, silence to 4.18). Every style times its motion to these, so a
+ * replacement sound wants the same shape -- or these numbers moved with it.
+ */
+export const INTRO_BEATS = Object.freeze({
+ build: Object.freeze({ from: 0.34, to: 2.32 }),
+ chime: Object.freeze({ from: 2.78, to: 3.94 }),
+ /** The fade to the ground, over the intro's last this-many seconds. */
+ fade: 0.5,
+});
+
+/** The intro's length when the key names none: the stand-in sound's. */
+export const INTRO_SECONDS = 4.18;
+/** `seconds`' bounds: long enough for "media" to land and be read, short enough to stay a sting. */
+export const INTRO_SECONDS_MIN = 3.5;
+export const INTRO_SECONDS_MAX = 8;
+
+/** The intro's timeline id (its segment is segments/<id>.mp4). */
+export const INTRO_ID = "brand-intro";
+
+/**
+ * `render.intro` read: null (no intro) or `{ style, ground, sound, seconds }`
+ * with the defaults filled in. `sound` stays as written: `undefined` is the
+ * stand-in, `false` silence, a string a file (report-to-video resolves it).
+ * Assumes a key `introErrors` passes; a bad one reads as what it can.
+ * @returns {null | { style: string, ground: "light" | "dark", sound: string | false | undefined, seconds: number }}
+ */
+export function introOf(render) {
+ const v = render?.intro;
+ if (v === undefined || v === null || v === false) return null;
+ const o = typeof v === "string" ? { style: v } : isObj(v) ? v : {};
+ const style = String(o.style ?? "");
+ return {
+ style,
+ ground: o.ground === "light" || o.ground === "dark" ? o.ground : (INTRO_STYLE_GROUND[style] ?? "light"),
+ sound: o.sound === false || typeof o.sound === "string" ? o.sound : undefined,
+ seconds: Number.isFinite(o.seconds) ? o.seconds : INTRO_SECONDS,
+ };
+}
+
+const KEYS = ["style", "ground", "sound", "seconds"];
+
+/** Every reason `value` (a `render.intro`) cannot be built, as sentences naming the key. */
+export function introErrors(value) {
+ if (value === undefined || value === null) return [];
+ const o = typeof value === "string" ? { style: value } : value;
+ if (!isObj(o)) return [`render.intro must be a style name (${INTRO_STYLES.join(", ")}) or an object {style, ground?, sound?, seconds?}`];
+ const errors = [];
+ for (const k of Object.keys(o)) if (!KEYS.includes(k)) errors.push(`render.intro.${k} is not a key (${KEYS.join(", ")})`);
+ if (!INTRO_STYLES.includes(o.style)) {
+ errors.push(`render.intro.style ${JSON.stringify(o.style ?? null)} is not an intro style — one of ${INTRO_STYLES.join(", ")}`);
+ }
+ if (o.ground !== undefined && !INTRO_GROUNDS.includes(o.ground)) {
+ errors.push(`render.intro.ground must be ${INTRO_GROUNDS.join(" or ")}, got ${JSON.stringify(o.ground)}`);
+ }
+ if (o.sound !== undefined && o.sound !== false && !(typeof o.sound === "string" && o.sound.trim())) {
+ errors.push("render.intro.sound must be a sound file's path (relative to the manifest) or false (a silent intro)");
+ }
+ if (o.seconds !== undefined && !(Number.isFinite(o.seconds) && o.seconds >= INTRO_SECONDS_MIN && o.seconds <= INTRO_SECONDS_MAX)) {
+ errors.push(`render.intro.seconds must be a number from ${INTRO_SECONDS_MIN} to ${INTRO_SECONDS_MAX}`);
+ }
+ return errors;
+}
+
+/** `render.intro` of a manifest: what the build's validators and the lint call. */
+export const validateIntro = (manifest) => introErrors(manifest?.render?.intro);
+
+/**
+ * A look patch's `intro` as it is written: a bare style name stays a string
+ * (`umtool look <p> intro=boot`), an object is kept as given.
+ */
+export const introPatchValue = (v) => (typeof v === "string" ? v.trim() : v);
diff --git a/common/lib/report/look.d.mts b/common/lib/report/look.d.mts
@@ -4,7 +4,7 @@
type Manifest = { render?: Record<string, unknown> | null; timeline?: unknown[] } & Record<string, unknown>;
type Render = Record<string, unknown> | null | undefined;
-export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur";
+export type LookKey = "headerHeight" | "footerHeight" | "qr" | "transition" | "transitionStyle" | "loudness" | "captions" | "room" | "slide" | "blur" | "intro";
export const LOOK_KEYS: readonly LookKey[];
export const BAND_MAX: number;
export const TRANSITION_MAX: number;
diff --git a/common/lib/report/look.mjs b/common/lib/report/look.mjs
@@ -14,13 +14,17 @@
//
// PURE: no fs, no ffmpeg. Plain ESM with a .d.mts beside it.
+// `intro` (the brand intro, ./intro.mjs) is a look key too: a take compares
+// styles with `umtool look <p> intro=<style>`, and every writer checks it here.
+import { introPatchValue, validateIntro } from "./intro.mjs";
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const num = (v) => typeof v === "number" && Number.isFinite(v);
const q = (v) => JSON.stringify(v);
const round2 = (n) => Number(Number(n).toFixed(2));
/** The render keys the Look panel writes, in its order. */
-export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur"]);
+export const LOOK_KEYS = Object.freeze(["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro"]);
/** `headerHeight` / `footerHeight`: whole pixels, 0 (off) to this. */
export const BAND_MAX = 240;
@@ -292,7 +296,7 @@ export function validateVertical(manifest) {
export function validateLook(manifest) {
// render.room and a clip's room (release 36 lane E) are part of the look.
// render.blur (the uncensored variant's switch) is part of the look too.
- return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest), ...validateRenderBlur(manifest)];
+ return [...validateCaptions(manifest), ...validateLoudness(manifest), ...validateVertical(manifest), ...validateRoom(manifest), ...validateRenderBlur(manifest), ...validateIntro(manifest)];
}
// ---------------------------------------------------------------------------
@@ -358,6 +362,10 @@ export function applyLookPatch(manifest, patch) {
else if (v === "off") render.blur = "off";
else errors.push(`render.blur must be "on" (blur the clips that ask) or "off" (the uncensored variant)`);
break;
+ case "intro":
+ // A style name or {style, ground?, sound?, seconds?}; validateIntro (below) says what is wrong.
+ render.intro = introPatchValue(v);
+ break;
default:
// loudness, captions, room, slide: stored as given; the build's validators below say what is wrong.
render[k] = v;
diff --git a/common/lib/report/videoAssistOps.test.ts b/common/lib/report/videoAssistOps.test.ts
@@ -26,7 +26,7 @@ test("the look's rules: one patch function — keys refused, null removes, qr on
assert.deepEqual(bad.errors, validateTransitionStyle({ render: { slide: { blur: 9 } } }));
assert.deepEqual(applyLookPatch(m, { loudness: { target: -40 } }).errors, validateLook({ render: { loudness: { target: -40 } } }));
assert.deepEqual(lookErrors(m), []);
- assert.equal(LOOK_KEYS.length, 10);
+ assert.equal(LOOK_KEYS.length, 11);
});
test("the request table: every request → the model's ops → the diff lines kept and the reasons refused", () => {
diff --git a/common/package.json b/common/package.json
@@ -50,6 +50,7 @@
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
"./lib/report/look.mjs": "./lib/report/look.mjs",
+ "./lib/report/intro.mjs": "./lib/report/intro.mjs",
"./lib/report/fxParams.mjs": "./lib/report/fxParams.mjs",
"./lib/report/videoAssistOps.mjs": "./lib/report/videoAssistOps.mjs",
"./lib/report/videoAssistProposals.mjs": "./lib/report/videoAssistProposals.mjs",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -8,6 +8,7 @@
- **A download filter's `^` and `$` now anchor to the video's title.** A filter pattern was only ever matched against the title and the description joined together, where `$` means the end of the description, so a pattern that names exact titles (`^ROOSTER(123|456)$`) could never match: the h3-podcast-audio-feed channel's filter selected nothing for two days. Include and exclude now match when the pattern matches the title alone or the title and description together, as before. A pattern with no `$` at its end behaves exactly as it did. The channel's Playlist stage, the download lane, Download missing and `pnpm ops keep-videos` all use the same rule, and the Configure form's hints say so. Needs a restart of the editor.
- **`pnpm archilyzer corpus grep` searches the live corpus's transcripts from a terminal, with no editor and no index.** `--regex '<pattern>'` with `--channels a,b`, `--since YYYY-MM-DD`, `--until`, `--window 30`, `--limit N`, `--case-sensitive` and `--json`. It reads each held video's transcript the way the video page does (the cues file, else the best English caption track, en-orig before en), dates it by the video's upload date, and prints each hit's date, channel, id, start second, title and 30 seconds of text, then the videos in range that have no transcript yet. A channel whose drive is not answering is skipped and named. The MCP and the sites read only what was last published; this reads what is on disk now. It writes nothing.
- **`pnpm ops get x-session` says whether an X job would start now, and why not.** It answers the X login in use (the connected profile's cookie jar, or the browser's cookies), when the jar was last refreshed and its age in minutes, the limit (`social.x.maxCookieAgeMinutes`), whether X's cookie alert is up, `allowed`, and the refusal an X job would get. It is the same check that refuses a stale-cookie X job, so an assistant can ask before it queues an X fetch instead of finding out from a refusal. Needs a restart of the editor.
+- **A report video can open with a short Archilyzer intro.** "Archilyzer" builds in on the first sound and "MEDIA" lands under it on the chime, after the Game Boy Advance boot screen, then it fades and dissolves into the video. Five styles: `boot` (the letters tumble in large in the sites' accent colours and settle), `boot-wipe` (the word revealed left to right at an even pace), `boot-dark` (`boot` on the videos' dark ground), `boot-cascade` (the letters drop in one after another) and `boot-mark` (the mark's lines are drawn, then the word). Each is about 4 seconds, and the rest of the video starts that much later. The intro is not a chapter: the first chapter still starts at 0:00. Set it on the Build tab's **Look** panel (**Intro**), with `umtool look <project> intro=boot-dark` (`intro=` turns it off), or in a take (`--set render.intro=boot-wipe`). The sound is the GBA's own boot sound for now, a stand-in to replace before any public release; it is not in the repository, so a new checkout makes it once with `node umtool/report-to-video/intro.mjs extract-sound <the GBA startup video>`. A video without an intro builds exactly as before. Needs a restart of umtool and a rebuild of the video.
- **A tall post screenshot in the posts feed grows into the room the column has, instead of shrinking to a thumbnail.** A screenshot was capped at the height of a card of words and drawn smaller to fit it, so a post with a picture (the Huck video's "Hucks home!!!!!! God Is Good!!!") came out a narrow strip beside empty space. Now a picture cut by that cap grows, up to its own full-width height, into the room left in the column beside the card under it — that card stays on screen; only cards further down scroll out as before. A post that fits, and a card of words, are drawn as they were. Needs a restart of umtool and a rebuild of the video.
- **Every wait before the archive asks a site now varies a little, and only ever upward.** A job every 20.0 s, a page every 3.0 s or a sync at the same minute each day is a machine's beat, so each such wait is now stretched by up to a quarter of itself at random, and never shortened: every pacing number stays a minimum (Rumble's 120 s, X's 5 min, the sleep between downloads). It covers the gap between two downloads and between two jobs on one platform, yt-dlp's `--sleep-requests` and `--sleep-subtitles` (drawn once per yt-dlp run, and shown in its logged command line), the archive.org, Wayback and web-fetch gaps, the rate-limit cooldowns and the platform hold's probe, the download lane's metadata-scan batches (60 to 75 titles) and its rests, Save Page Now's and the Kick recorder's polls, and each channel's sync interval (later by at most 30 minutes, the same on every tick until it syncs, and shown so on /operations/sync). The share is **Jitter on every wait before a request** on /settings (`pacing.jitter`, default 25 %; 0 turns it off). Three waits that already varied could come out SHORTER than their minimum and no longer do: the platform cooldown (±10 %), archive.org's back-off (±20 %) and a forum's page pause (as little as 0.85 of it, under its own 5 s floor). It now lands between the pause and 1.8 times it. Four loops that asked a site with no gap at all now wait between requests: a Bluesky feed's pages (3–6 s), a Nitter timeline's pages (4 s and up), the availability check's per-video probes (3 s and up) and umtool's network clip fetches in a build with no editor (one at a time per platform, 30 s apart, Rumble 120 s). Needs a restart of the editor and of umtool.
- **The download lane's metadata scan reads 60 titles at a time and lets the downloads run in between.** A filtered channel's scan holds its platform's download queue while it runs, and the lane used to scan the whole backlog in one go: on 2026-10-25 the scan of h3-podcast's 1,163 unread titles, which started the moment the channel's download pause was lifted, held YouTube from 03:20 to 06:36 and nothing downloaded. The lane now scans 60 titles (about 10 minutes on YouTube), gives that platform 20 minutes of downloads, then scans the next 60, and its log says so: "1103 listed videos left to scan for h3-podcast; the next batch after 20 minutes of downloads." A scan that a platform stopped (a soft block, a rate limit) is still not retried until the next restart. **Run** on the metadata-scan operation still scans the whole backlog. Needs a restart of the editor.
diff --git a/umtool/.gitignore b/umtool/.gitignore
@@ -0,0 +1,4 @@
+
+# The brand intro's stand-in sound (intro.mjs extract-sound): Nintendo's GBA boot, never committed --
+# the source mirror publishes this history. Replace with our own before any public release.
+/report-to-video/assets/intro/
diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts
@@ -6,6 +6,7 @@ import { deckOn } from "umtool-report-to-video/deck";
import { validateLook } from "umtool-report-to-video/look";
import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition";
import { refuseCaller } from "@/lib/report/caller";
+import { INTRO_STYLES } from "yt-dlp-transcript-common/lib/report/intro.mjs";
export const dynamic = "force-dynamic";
@@ -16,7 +17,7 @@ export const dynamic = "force-dynamic";
// the writer (lib/report/manifest.mjs updateRender) validates with the
// build's own checks, so a look this route accepts is one the build accepts.
//
-// GET ?project=<id> { look, deck, montage, styles, keys, errors, token }
+// GET ?project=<id> { look, deck, montage, styles, introStyles, keys, errors, token }
// PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors }
// PUT { project, token, variants } render.variants, the ladder Make variants encodes
// (null: the default ladder) → { ok, variants, token }
@@ -34,6 +35,8 @@ export async function GET(request: Request) {
deck: deckOn(render),
montage: render.montage !== undefined && render.montage !== null,
styles: TRANSITION_STYLES,
+ // The brand intro's styles (render.intro), for the Look panel's Intro.
+ introStyles: INTRO_STYLES,
keys: LOOK_KEYS,
// A look somebody hand-edited into a state the build would refuse.
errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest), ...variantsProblems(render.variants)],
diff --git a/umtool/components/projects/report/LookPanel.tsx b/umtool/components/projects/report/LookPanel.tsx
@@ -22,6 +22,9 @@ import AssistBox from "./AssistBox";
// fields too, so every op the video assistant can propose is one here; the
// assistant's Ask box (AssistBox: optional, its proposals applied only on
// Apply) and Preview join sit under the fields.
+// The brand intro (render.intro, report-to-video intro.mjs): the sting the
+// cut opens with, by style; "none" is no intro. An intro written with its
+// other knobs (ground, sound, seconds) keeps them when the style changes.
type Look = {
headerHeight?: number;
@@ -34,8 +37,12 @@ type Look = {
room?: { tail?: boolean; head?: boolean; minGap?: number; maxS?: number } | null;
slide?: { travel?: number; blur?: number; grain?: number } | null;
blur?: string;
+ intro?: string | { style?: string; [k: string]: unknown } | null;
};
-type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; errors: string[]; token: string | null };
+type View = { look: Look; deck: boolean; montage: boolean; styles: string[]; introStyles?: string[]; errors: string[]; token: string | null };
+
+/** The intro's style as written: a bare name or the object's `style`; "" for none. */
+const introStyleOf = (v: Look["intro"]) => (typeof v === "string" ? v : v && typeof v === "object" ? String(v.style ?? "") : "");
const STYLE_WORDS: Record<string, string> = { fade: "crossfade", fadeblack: "dip to black", fadewhite: "dip to white", dissolve: "dissolve", blurslide: "blur slide" };
@@ -59,6 +66,7 @@ type Draft = {
smear: string;
grain: string;
blur: "on" | "off";
+ intro: string;
};
function draftOf(l: Look): Draft {
@@ -83,6 +91,7 @@ function draftOf(l: Look): Draft {
smear: String(l.slide?.blur ?? SLIDE_DEFAULTS.blur),
grain: String(l.slide?.grain ?? SLIDE_DEFAULTS.grain),
blur: l.blur === "off" ? "off" : "on",
+ intro: introStyleOf(l.intro),
};
}
@@ -130,6 +139,10 @@ function patchOf(was: Look, d: Draft, view: View): Record<string, unknown> {
}
// The blurred clips (render.blur): "on" is the default, written as no key.
if (d.blur !== (was.blur === "off" ? "off" : "on")) p.blur = d.blur === "off" ? "off" : null;
+ // The brand intro: none removes the key; a style keeps an object's other knobs.
+ if (d.intro !== introStyleOf(was.intro)) {
+ p.intro = !d.intro ? null : was.intro && typeof was.intro === "object" ? { ...was.intro, style: d.intro } : d.intro;
+ }
// The blur slide's knobs (release 38): only the ones off their defaults are written.
{
const cur = { travel: Number(d.travel), blur: Number(d.smear), grain: Number(d.grain) };
@@ -236,6 +249,16 @@ export default function LookPanel({ project }: { project: string }) {
<option value="off">uncensored</option>
</Select>
</Field>
+ <Field label="Intro" hint="the brand sting the cut opens with">
+ <Select data-look-intro="" value={draft.intro} disabled={busy} onChange={(e) => set({ intro: e.target.value })}>
+ <option value="">none</option>
+ {(view.introStyles ?? []).map((s) => (
+ <option key={s} value={s}>
+ {s}
+ </option>
+ ))}
+ </Select>
+ </Field>
{!view.montage && (
<Field label="Loudness">
<span className="flex items-center gap-1.5">
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -125,6 +125,7 @@ that mentions the seizure in question and one before it. The Marks box is on eve
| `render.chrome.deck.markerLayout` — `stagger` or `truncate` when labels crowd (default: stagger only when a label would truncate) | markers, **layout** | `deck.markerLayout=truncate` | `PUT /api/report/chrome {project, token, markerLayout}` |
| `render.chrome.deck.claims[]` — his explicit claims drawn against the record on the rail, at most 6: a `count` or a `goalpost` ([below](#claim-checks-on-the-rail)) | On-screen, **claim checks**: add a count / a goalpost, the clip picker, **use the playhead**, his words, the window's dates, the record's verdict, per, the claim; a goalpost's steps (**add a step**), each its from date and due durations; remove — the build's validator under each as it is typed | `umtool look <p> deck.claims='[…]'` (`deck.claims=` none) | `PUT /api/report/chrome {project, token, claims}` |
| `render.blur` — `off`: every clip's picture as recorded, no caption (the uncensored variant); `on` (the default) blurs the clips that ask | Build, **Look**: **Blurred clips** | `umtool look <p> blur=off` · a take: `umtool take <p> --id uncensored --set render.blur=off` | `PUT /api/report/render {project, token, patch: {blur}}` |
+| `render.intro` — the brand sting the cut opens with: a style (`boot` `boot-wipe` `boot-dark` `boot-cascade` `boot-mark`) or `{style, ground?, sound?, seconds?}`; absent is none ([report-video.md](report-video.md#the-brand-intro-renderintro)) | Build, **Look**: **Intro** | `umtool look <p> intro=boot-dark` (`intro=` none) · a take: `umtool take <p> --id intro-wipe --set render.intro=boot-wipe` | `PUT /api/report/render {project, token, patch: {intro}}` |
| `render.variants` — the ladder **Make variants** encodes: `{name, height?, crf?, maxMiB?, preset?}` (at most 12; a `maxMiB` rung takes no crf, a height there caps it); `master` is the build itself | Deliver, **Variants and sync**: Edit, Save ladder, Use the default | `umtool look <p> variants='[{"name":"master"},{"name":"720p","height":720,"crf":23}]'` | `PUT /api/report/render {project, token, variants}` |
The default ladder: `master`, `1080p` (crf 22), `720p` (crf 23), `fit24` (at most 24 MiB). `umtool look` also sets
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1401,6 +1401,80 @@ clip in the editor to frame it.
From a terminal: `node umtool/report-to-video/build-video.mjs
<project>/video.manifest.json --short <clipId>`.
+## The brand intro (`render.intro`)
+
+A cut can open with a short Archilyzer sting, after the Game Boy Advance boot
+screen: "Archilyzer" built in on the first sound, "MEDIA" landing under it on
+the chime, then a fade to the ground. One render key, absent by default (absent
+or `null` is no intro, and the cut is built exactly as before):
+
+```jsonc
+"render": { "intro": "boot" } // a style by name
+"render": { "intro": { "style": "boot-wipe", // or with its knobs:
+ "ground": "dark", // light | dark (each style has its own default)
+ "sound": "sting.wav", // a file beside the manifest; false = silent; absent = the stand-in
+ "seconds": 4.18 } } // 3.5–8, default 4.18 (the stand-in sound's length)
+```
+
+| Style | Ground | What it does |
+|---|---|---|
+| `boot` | light | The GBA's structure: the letters tumble in huge, turned and in the seven site accents, overlapping, settle into the wordmark's own colours, a shimmer passes left to right, MEDIA rises in on the chime. |
+| `boot-wipe` | light | The wordmark revealed linearly, left to right, over exactly the first sound (0.34–2.32 s), a line of the accent riding the edge; MEDIA wipes in on the chime. |
+| `boot-dark` | dark | `boot` on the report videos' own ground (`#151b20`), the accent shimmer. |
+| `boot-cascade` | light | The letters drop in one after another, evenly across the first sound, each in an accent and then the wordmark's colour; MEDIA rises in from below on the chime. |
+| `boot-mark` | dark | The whole lockup: the Found-line mark's square, then its lines drawn one after another, the wordmark sliding out of it, the shimmer, MEDIA on the chime. |
+
+`ground` overrides a style's (`{"style": "boot-wipe", "ground": "dark"}`).
+Every style is timed to the stand-in sound's measured beats
+(common/lib/report/intro.mjs `INTRO_BEATS`): silence to 0.34 s, the build
+0.34–2.32 s, the chime from 2.78 s, the fade over the last 0.5 s. A replacement
+sound wants the same shape, or those numbers moved with it. The letters are the
+lockup's own glyph paths (brands/archilyzer-media.json), not a font.
+
+**Where it goes.** `selectVariant` prepends one timeline entry, `{type:
+"intro", id: "brand-intro"}`, so the build, the deck's schedule, the chapters
+and umtool's Play view and export all see the same first segment: the cut
+grows by the intro's seconds less the join, and every entry starts that much
+later. The deck hides over it (it is full frame, like a teaser). It is not a
+chapter of its own: the first entry's chapter starts at 0 and takes it in
+(YouTube keeps no chapter under 10 s). A timeline entry of your own named
+`brand-intro` is refused.
+
+**The join.** The intro is joined to the first entry like any two segments:
+the cut's `render.transition`, a dissolve of that length by default, a clean
+cut with `transition: 0`. Its last half-second fades to its ground on its
+own, so under a dissolve the wordmark is already going as the first entry
+comes up (a 0.4 s join starts 0.1 s into the fade), and a clean cut follows
+a plain ground.
+
+**The sound is a stand-in.** With no `sound`, the intro plays the GBA boot
+sound itself, kept as `umtool/report-to-video/assets/intro/boot-standin.wav`.
+It is **not in git** (the directory is ignored): it is Nintendo's, the source
+mirror publishes this repository's history, and it is to be replaced with a
+sound of our own before any public release. A checkout makes it with
+`node umtool/report-to-video/intro.mjs extract-sound <the GBA startup mp4>`;
+until then a build with an intro and no `sound` refuses, naming that command.
+
+**Rendered once.** The intro is the same picture in every cut of a size, so it
+is rendered (HyperFrames, as the deck is) and encoded once and kept by its key
+-- the page (style, ground, size, fps, length), the sound's bytes, the encode's
+parameters and the renderer's version -- as `<key>.mp4` in
+`~/.cache/umtool/intro/` (`UMTOOL_INTRO_CACHE` moves it). Each cut copies it
+into `segments/brand-intro.mp4` with `brand-intro.intro.json` beside it; a
+build whose record names the same key does nothing, `--chrome-only` included.
+
+**Setting it.** The Build tab's **Look** panel has **Intro** (none or a
+style); from a terminal `umtool look <project> intro=boot-dark` (`intro=`
+clears it); a take compares styles with
+`umtool take <project> --id intro-wipe --label "Intro: wipe" --set render.intro=boot-wipe`.
+The validators refuse an unknown style, ground, length or key by name
+(`validateLook`, so the Look panel, `umtool look`, a take and the build all
+refuse the same thing).
+
+**Judging styles outside a cut.**
+`node umtool/report-to-video/intro.mjs render --style boot-mark [--ground light] --out x.mp4`
+renders one at 1920×1080 30 fps through the heavy slot.
+
## Room at the clips' edges, and the blur slide (release 36 lane E)
A join of `render.transition` seconds fades over the last seconds of one clip
diff --git a/umtool/e2e/clip-look.spec.ts b/umtool/e2e/clip-look.spec.ts
@@ -52,6 +52,9 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m
await page.locator("[data-look-captions]").check();
await page.locator("[data-look-label-host]").fill("The host");
await page.locator("[data-look-size]").selectOption("l");
+ // The brand intro (render.intro): a style by name.
+ await expect(page.locator("[data-look-intro]")).toHaveValue("");
+ await page.locator("[data-look-intro]").selectOption("boot-wipe");
await page.locator("[data-look-save]").click();
await expect(page.locator("[data-look-status]")).toHaveText("Saved — the next render uses it");
const r = render();
@@ -62,6 +65,7 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m
expect(r.room).toEqual({ tail: true, head: true });
expect(r.loudness).toEqual({ target: -16 });
expect(r.captions).toEqual({ style: "speakers", labels: { host: "The host" }, size: "l" });
+ expect(r.intro).toBe("boot-wipe");
expect(r.width).toBe(640);
// Read back after a reload.
await page.reload();
@@ -74,6 +78,12 @@ test("the look: the panel saves and reads back; a voice named; a short framed, m
await expect(page.locator("[data-look-loudness]")).toHaveValue("-16");
await expect(page.locator("[data-look-captions]")).toBeChecked();
await expect(page.locator("[data-look-label-host]")).toHaveValue("The host");
+ await expect(page.locator("[data-look-intro]")).toHaveValue("boot-wipe");
+ // None clears it: the cut opens as it did.
+ await page.locator("[data-look-intro]").selectOption("");
+ await page.locator("[data-look-save]").click();
+ await expect(page.locator("[data-look-status]")).toHaveText("Saved — the next render uses it");
+ expect("intro" in render()).toBe(false);
// ---- the clip editor: a voice named, the short framed --------------------
await page.goto(urls.clipEditorHref(PROJECT, { clip: "r001" }));
diff --git a/umtool/lib/report/look.test.mjs b/umtool/lib/report/look.test.mjs
@@ -46,7 +46,7 @@ const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NA
test("updateRender: the look's keys only, null removes one, the build's checks refuse a bad value", async () => {
const p = await project({ transition: 0.4, crf: 21 });
try {
- assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur"]);
+ assert.deepEqual(LOOK_KEYS, ["headerHeight", "footerHeight", "qr", "transition", "transitionStyle", "loudness", "captions", "room", "slide", "blur", "intro"]);
const token = await manifestToken(p.dir);
const r = await updateRender(p.dir, {
headerHeight: 0, footerHeight: 0, qr: false, transition: 0.5, transitionStyle: "fadeblack",
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -11,6 +11,7 @@ Two scripts and a manifest:
| `build-video.mjs` | stable | manifest → mp4. Fetches clips, snaps cuts to silence, letterboxes them into the chrome, crossfades. |
| `render-cards.mjs` | stable | draws the timeline footer and marker, plus optional card stills. Imported by `build-video.mjs`. |
| `resolve-windows.mjs` | stable | widens clip windows from cue spans to whole sentences. Run once after authoring a manifest. |
+| `intro.mjs`, `chrome-intro.mjs` | new | the brand intro (`render.intro`): the sting a cut opens with, rendered once and cached; see umtool/docs/report-video.md, "The brand intro". |
| `brand.mjs`, `brand-cards.mjs` | stable | the opt-in brand preset (`render.brand`); see [its section](#the-archilyzer-media-preset-renderbrand). |
| `montage.mjs`, `montage-styles.mjs` | stable | montage editing (`render.montage`) and its named styles; see [its section](#rendermontage--montage-editing-release-33). |
| `montage-rulings.mjs` | stable | the clip deck's rulings (`montage-rulings.json` beside the manifest), applied at render; see [its section](#montage-rulingsjson--the-clip-decks-rulings-release-34). |
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -219,6 +219,8 @@ import {
// brand BEFORE building an argument, so a manifest without one renders exactly
// as it did -- see brand.mjs.
import { FONTS_DIR, brandHeaderGeometry, brandManifest } from "./brand.mjs";
+// The brand intro (`render.intro`): the entry selectVariant prepends and its segment.
+import { buildIntroSegment, introManifest, isIntro } from "./intro.mjs";
import { markPng, renderThumbnail, THUMB_MAX_BYTES } from "./brand-cards.mjs";
// Montage editing (`render.montage`, release 33): the tight phrase cut, the
// pieces, the cut styles, the counter and the wall -- pure, in montage.mjs.
@@ -319,8 +321,10 @@ export function selectVariant(manifest, variant = DEFAULT_VARIANT) {
// A brand preset resolves here, at the one door every reader of a cut goes
// through, so the build, verify-build, compose-chrome and umtool's export
// all see the same render block and the same appended end card. No brand:
- // the object as built above.
- return brandManifest({ ...manifest, variant, timeline, ledger, ...(posts !== undefined ? { posts } : {}) });
+ // the object as built above. So does the brand intro (`render.intro`,
+ // intro.mjs): prepended here, so every reader sees the same first segment;
+ // without the key, the same object again.
+ return introManifest(brandManifest({ ...manifest, variant, timeline, ledger, ...(posts !== undefined ? { posts } : {}) }));
}
/**
@@ -955,7 +959,7 @@ export function needsFetchMessage(missing) {
// The timeline's vocabulary is OPEN; the build loop treats everything it has
// no other branch for as a clip, and so does this.
-const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger"]);
+const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro"]);
const isClipEntry = (e) => !NON_CLIP_TYPES.has(e?.type);
/**
@@ -1187,7 +1191,7 @@ const detectSilence = (file, render, scan = null) => detectSilenceWith(file, ren
// Encoder quality is manifest-driven so a cut can trade size for fidelity without
// editing this file. Defaults reproduce the original hardcoded settings exactly.
-const encodeArgs = (render) => [
+export const encodeArgs = (render) => [
"-c:v", "libx264",
"-preset", render.preset ?? "medium",
"-crf", String(render.crf ?? 20),
@@ -5011,6 +5015,18 @@ export async function fxClipWords({ entries, segments, provenance = {}, render }
return { words, clock };
}
+/**
+ * The brand intro is no chapter of its own -- YouTube keeps none under 10 s,
+ * and "Intro" is not a place anyone jumps to: the chapter after it starts at
+ * 0 and takes it in. A cut that is nothing but the intro keeps it. Pure.
+ * @param {Array<{ start: number, end: number, title: string, section?: boolean }>} chapters one per entry
+ * @param {Array<{ type?: string }>} entries
+ */
+export function foldIntroChapter(chapters, entries) {
+ if (!isIntro(entries[0]) || chapters.length < 2) return chapters;
+ return [{ ...chapters[1], start: chapters[0].start }, ...chapters.slice(2)];
+}
+
// Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`,
// seconds) -- the list out/youtube.txt's Chapters are made from -- or null
// when the cut is one segment and gets none.
@@ -5020,7 +5036,7 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance,
// than its file, and every chapter after it starts that much later.
const { starts, total } = await cutOffsets(segments, D, fps, joins);
const lines = [";FFMETADATA1", ""];
- const chapters = [];
+ const all = [];
for (let i = 0; i < entries.length; i += 1) {
// Land just PAST the crossfade, so the marker opens on the incoming clip
// rather than on the outgoing one mid-dissolve.
@@ -5029,13 +5045,16 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance,
const title = await chapterTitle(entries[i], i, provenance, { deck });
// `section`: the entry opens one of the cut's sections (a card) -- what
// out/youtube.txt's Chapters keep (youtube.mjs youtubeChapters).
- chapters.push({ start, end, title, section: entries[i]?.type === "card" });
+ all.push({ start, end, title, section: entries[i]?.type === "card" });
+ }
+ const chapters = foldIntroChapter(all, entries);
+ for (const c of chapters) {
lines.push(
"[CHAPTER]",
"TIMEBASE=1/1000",
- `START=${Math.round(start * 1000)}`,
- `END=${Math.round(end * 1000)}`,
- `title=${ffmetaEscape(title)}`,
+ `START=${Math.round(c.start * 1000)}`,
+ `END=${Math.round(c.end * 1000)}`,
+ `title=${ffmetaEscape(c.title)}`,
"",
);
}
@@ -5055,7 +5074,7 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance,
{ maxBuffer: 1 << 24 },
);
await rename(tmp, finalPath);
- EMIT("chapters", { n: entries.length, file: path.basename(metaPath) });
+ EMIT("chapters", { n: chapters.length, file: path.basename(metaPath) });
return { chapters, total };
}
@@ -5609,6 +5628,14 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
entry, render, outDir, manifest.timelineNodes, framing, narration.get(entry.id) ?? null, narrationStore,
);
}
+ // The brand intro: rendered once (cached by its key, intro.mjs) and copied
+ // in through a rename, as a teaser's segment is written.
+ if (isIntro(entry)) {
+ EMIT("card", { id: entry.id, i, n: entries.length });
+ return buildIntroSegment(entry, {
+ render, encode: encodeArgs(render), outDir, manifestDir, workers: CHROME_WORKERS, emit: (ev, f) => EMIT(ev, f),
+ });
+ }
if (entry.type !== "teaser" && entry.type !== "clip") {
await detachSegmentFiles(path.join(outDir, "segments"), entry.id);
}
@@ -5676,7 +5703,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const finalPath = dirs.final;
// A montage's wall is a segment of the cut too.
if (dirs.montage?.settings.wall) {
- if (dirs.montage.settings.wall.at === "start") entries.unshift({ ...WALL_ENTRY });
+ if (dirs.montage.settings.wall.at === "start") entries.splice(isIntro(entries[0]) ? 1 : 0, 0, { ...WALL_ENTRY });
else entries.push({ ...WALL_ENTRY });
}
const segs = entries.map((e) => path.join(outDir, "segments", `${e.id}.mp4`));
@@ -5807,7 +5834,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// 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" || (await exists(seg))) continue;
+ if (entries[i].type === "teaser" || isIntro(entries[i]) || (await exists(seg))) continue;
if (opts.chromePreview) throw new Error(`${what} needs ${seg}, which is missing — run a full build first`);
missing.push(i);
}
@@ -5847,6 +5874,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
EMIT("card", { id: e.id, i: entries.indexOf(e), n: entries.length });
await buildTeaserSegment(e, { manifestPath, render, outDir, variant, transition: D });
}
+ // So is the brand intro's (copied from its cache unless its key is the one recorded).
+ for (const [i, e] of entries.entries()) if (isIntro(e)) await buildEntrySegment(e, i);
await linkPosts();
const schedule = await writeChromeSchedule({ manifest, entries, segments: segs, D, outDir });
EMIT("chrome", { phase: "schedule", total: schedule.total, segments: schedule.segments.length });
@@ -5943,8 +5972,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
});
EMIT("segment", { id: WALL_ENTRY.id, path: seg });
if (at === "start") {
- segments.unshift(seg);
- entries.unshift({ ...WALL_ENTRY });
+ // After the brand intro, when the cut opens with one.
+ const k = isIntro(entries[0]) ? 1 : 0;
+ segments.splice(k, 0, seg);
+ entries.splice(k, 0, { ...WALL_ENTRY });
} else {
segments.push(seg);
entries.push({ ...WALL_ENTRY });
diff --git a/umtool/report-to-video/chrome-intro.mjs b/umtool/report-to-video/chrome-intro.mjs
@@ -0,0 +1,445 @@
+// The brand intro's composition (`render.intro`, intro.mjs): one full-frame
+// HyperFrames page -- "Archilyzer" built in on the first sound, "media" under
+// it on the chime, after the Game Boy Advance boot screen.
+//
+// PURE, like chrome-teaser.mjs: a style, a ground, a size and the brand kit in,
+// an HTML string out. intro.mjs writes it beside GSAP, renders it and encodes
+// the frames with the intro's sound.
+//
+// The letters are the brand's own drawing, not a font: the lockup's glyph
+// paths (brands/archilyzer-media.json, drawn by common/lib/brandMedia.ts),
+// each wrapped in its own group so it can tumble, drop or be wiped in. So the
+// intro lands on exactly the wordmark the title card, the end card and the
+// sites carry -- "Archi" heavy, "lyzer" light, MEDIA spread to its width -- and
+// no face has to load in the render browser.
+//
+// The motion is a cue list computed here (the deck's and the teaser's reason:
+// a render is a seek per frame, from parallel workers, in any order). Every
+// cue is a fromTo whose FROM is stated; the page is a dumb interpreter of
+// `introCues`, so the tests read every time it uses.
+import { INTRO_BEATS } from "yt-dlp-transcript-common/lib/report/intro.mjs";
+import { pageDuration } from "./deck.mjs";
+
+const r3 = (v) => Math.round(v * 1000) / 1000;
+
+const esc = (s) =>
+ String(s ?? "")
+ .replace(/&/g, "&")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, """);
+
+/** A small seeded PRNG (mulberry32): the tumble is the same on every seek of every render. */
+function seeded(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// The accents (common/lib/brand.ts ACCENTS, picker order): the tumble paints
+// one site's accent per letter, as the GBA's letters come in five colours.
+// Each ground takes the accent's value for it -- the on-light values are the
+// contrast-corrected ones.
+const ACCENTS = [
+ { id: "signal", dark: "#5fa8a0", light: "#2e7b73" },
+ { id: "brass", dark: "#e3b15c", light: "#95661a" },
+ { id: "vermilion", dark: "#ec7a52", light: "#b3431f" },
+ { id: "violet", dark: "#b49cf2", light: "#6a4bc4" },
+ { id: "sakura", dark: "#ee8fb5", light: "#a83a6a" },
+ { id: "blue", dark: "#74a9f2", light: "#2d5fb8" },
+ { id: "green", dark: "#7cc46a", light: "#3f7a2c" },
+];
+const accent = (id, ground) => ACCENTS.find((a) => a.id === id)[ground];
+
+/**
+ * The colours of each ground. Dark is the video preset's palette (the report
+ * videos' own); light is the sites' light base (#f3f6f7) with the dark
+ * ground's slate as the ink.
+ */
+export function introPalette(ground, kit) {
+ if (ground === "dark") {
+ return {
+ ground: kit.palette.bg, lead: kit.palette.fg, suffix: kit.palette.muted, media: kit.palette.accent,
+ dim: kit.palette.dim, lit: kit.palette.accent,
+ tumble: ACCENTS.map((a) => a.dark), shimmer: [accent("signal", "dark"), "#ffffff"],
+ // The mark's square on its own ground would vanish: a step above it
+ // (common/lib/brandMedia.ts MEDIA_FIELD_LINE, the banner's field).
+ markGround: "#1e262d",
+ };
+ }
+ return {
+ ground: "#f3f6f7", lead: kit.palette.bg, suffix: kit.palette.dim, media: accent("signal", "light"),
+ dim: "#9aa8b2", lit: accent("signal", "light"),
+ tumble: ACCENTS.map((a) => a.light), shimmer: [accent("signal", "light"), accent("violet", "light")],
+ markGround: kit.palette.bg,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The lockup, read back off the kit's SVG.
+// ---------------------------------------------------------------------------
+
+const PATH_RE = /<path transform="translate\(([-\d.]+) ([-\d.]+)\) scale\(([-\d.]+)\)" d="([^"]+)"\/>/g;
+
+/** A glyph path's extent in its own units: every absolute coordinate pair (M L Q), H's x and V's y. */
+function glyphBox(d) {
+ const xs = [];
+ const ys = [];
+ for (const m of d.matchAll(/([MLQHVZ])([^MLQHVZ]*)/g)) {
+ const nums = (m[2].match(/-?\d*\.?\d+/g) ?? []).map(Number);
+ if (m[1] === "H") xs.push(...nums);
+ else if (m[1] === "V") ys.push(...nums);
+ else for (let i = 0; i + 1 < nums.length; i += 2) { xs.push(nums[i]); ys.push(nums[i + 1]); }
+ }
+ return { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) };
+}
+
+/**
+ * The lockup's pieces in lockup units (its `px`, 100): the mark's shapes, and
+ * the letters of "Archi" (lead), "lyzer" (suffix) and "MEDIA" (media), each
+ * with its path, its transform and its box. Text x is measured from the text's
+ * own left edge (the mark sits to its left, `markRight` units).
+ */
+export function lockupParts(kit) {
+ const svg = kit.lockup.svg;
+ const groups = [...svg.matchAll(/<g fill="(#[0-9a-fA-F]{6})">(.*?)<\/g>/g)];
+ if (groups.length !== 3) throw new Error(`the brand kit's lockup has ${groups.length} glyph groups, expected 3 (lead, suffix, MEDIA)`);
+ const roles = ["lead", "suffix", "media"];
+ const letters = [];
+ let left = Infinity;
+ groups.forEach((g, gi) => {
+ for (const m of g[2].matchAll(PATH_RE)) {
+ const [tx, ty, s] = [Number(m[1]), Number(m[2]), Number(m[3])];
+ const b = glyphBox(m[4]);
+ const box = { x0: tx + s * b.x0, x1: tx + s * b.x1, y0: ty + s * b.y0, y1: ty + s * b.y1 };
+ left = Math.min(left, box.x0, tx);
+ letters.push({ role: roles[gi], tx, ty, s, d: m[4], box });
+ }
+ });
+ const shift = (l) => ({
+ ...l, tx: r3(l.tx - left), box: { ...l.box, x0: r3(l.box.x0 - left), x1: r3(l.box.x1 - left) },
+ });
+ const out = letters.map(shift);
+ const markSvg = /<svg x="([-\d.]+)" y="([-\d.]+)" width="([-\d.]+)" height="([-\d.]+)" viewBox="0 0 512 512">(.*?)<\/svg>/.exec(svg);
+ const mark = markSvg
+ ? { x: Number(markSvg[1]) - left, y: Number(markSvg[2]), size: Number(markSvg[3]), body: markSvg[5] }
+ : null;
+ const text = out.filter((l) => l.role !== "media");
+ const media = out.filter((l) => l.role === "media");
+ return {
+ letters: out,
+ mark,
+ width: r3(Math.max(...out.map((l) => l.box.x1))),
+ top: r3(Math.min(...out.map((l) => l.box.y0))),
+ bottom: r3(Math.max(...out.map((l) => l.box.y1))),
+ wordBottom: r3(Math.max(...text.map((l) => l.box.y1))),
+ mediaTop: r3(Math.min(...media.map((l) => l.box.y0))),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// The cues.
+// ---------------------------------------------------------------------------
+
+/**
+ * Everything the intro's timeline does, as data: `{ init, cues }`. Keys name
+ * elements by `data-k`: `stage` (the whole drawing: the fade), `w<i>` / `f<i>`
+ * (letter i's group -- its motion -- and its path -- its fill), `wipe` /
+ * `edge` (the wipe's clip and its leading line), `mwipe` (MEDIA's), and
+ * `m<j>` (the mark's shapes, boot-mark). Letter indexes run over the
+ * wordmark's ten letters, then MEDIA's five.
+ *
+ * Beats (INTRO_BEATS): the wordmark is built inside the first sound, MEDIA
+ * lands on the chime, and the last `fade` seconds fade to the ground.
+ */
+export function introCues({ style, ground, seconds, parts, palette }) {
+ const B = INTRO_BEATS;
+ const init = {};
+ const cues = [];
+ const cue = (k, at, dur, from, to, ease = "power2.out") => cues.push({ k, at: r3(at), dur: r3(dur), from, to, ease });
+ const word = parts.letters.filter((l) => l.role !== "media");
+ const media = parts.letters.filter((l) => l.role === "media");
+ const nW = word.length;
+ const fin = (l) => (l.role === "lead" ? palette.lead : l.role === "suffix" ? palette.suffix : palette.media);
+ const rand = seeded(0xa2c41);
+ const motion = style === "boot-dark" ? "boot" : style;
+ const build = B.build;
+ const chime = B.chime.from;
+
+ // Every letter at rest, in its colour, unless the style says otherwise.
+ parts.letters.forEach((l, i) => {
+ init[`w${i}`] = { x: 0, y: 0, rotation: 0, scale: 1, opacity: 1, transformOrigin: "50% 50%" };
+ init[`f${i}`] = { fill: fin(l) };
+ });
+ init.stage = { opacity: 1 };
+
+ // MEDIA, on the chime: each letter rises a little into place, one after
+ // another, in the accent -- the same in every style but the wipe's.
+ const mediaIn = (lift = 26) => {
+ media.forEach((l, j) => {
+ const i = nW + j;
+ init[`w${i}`] = { ...init[`w${i}`], opacity: 0, y: lift };
+ cue(`w${i}`, chime + j * 0.035, 0.34, { opacity: 0, y: lift }, { opacity: 1, y: 0 }, "power3.out");
+ });
+ };
+ // The shimmer: a colour passing across the wordmark, letter by letter, left
+ // to right -- the GBA's pink-to-purple sweep, in the brand's accents.
+ const shimmer = (from, step) => {
+ word.forEach((l, i) => {
+ const at = from + i * step;
+ cue(`f${i}`, at, 0.12, { fill: fin(l) }, { fill: palette.shimmer[0] }, "sine.inOut");
+ cue(`f${i}`, at + 0.12, 0.12, { fill: palette.shimmer[0] }, { fill: palette.shimmer[1] }, "sine.inOut");
+ cue(`f${i}`, at + 0.24, 0.3, { fill: palette.shimmer[1] }, { fill: fin(l) }, "sine.out");
+ });
+ };
+
+ if (motion === "boot") {
+ // The tumble: each letter comes in huge, turned and in a site's accent,
+ // from up and to the right, overlapping the ones before it, and settles
+ // into place; then into the wordmark's own colours, then the shimmer.
+ const step = 0.08;
+ const fly = 0.8;
+ word.forEach((l, i) => {
+ const at = build.from + i * step;
+ const from = {
+ x: r3(220 + (nW - i) * 18 + rand() * 120), y: r3(-170 - rand() * 120), rotation: r3((rand() - 0.5) * 80),
+ scale: r3(4.2 + rand() * 2.2), opacity: 0,
+ };
+ init[`w${i}`] = { ...from, transformOrigin: "50% 50%" };
+ const color = palette.tumble[(i * 3) % palette.tumble.length];
+ init[`f${i}`] = { fill: color };
+ cue(`w${i}`, at, 0.1, { opacity: 0 }, { opacity: 0.9 }, "none");
+ cue(`w${i}`, at, fly, { x: from.x, y: from.y, rotation: from.rotation, scale: from.scale }, { x: 0, y: 0, rotation: 0, scale: 1 }, "power2.out");
+ cue(`w${i}`, at + fly * 0.5, fly * 0.5, { opacity: 0.9 }, { opacity: 1 }, "none");
+ cue(`f${i}`, at + fly * 0.75, 0.38, { fill: color }, { fill: fin(l) }, "sine.inOut");
+ });
+ shimmer(1.95, 0.05);
+ mediaIn();
+ } else if (motion === "boot-cascade") {
+ // One letter after another, evenly across the build: each drops in from
+ // above in its accent and lands with a small settle, then takes the
+ // wordmark's colour.
+ const step = (build.to - 0.42 - build.from) / (nW - 1);
+ word.forEach((l, i) => {
+ const at = build.from + i * step;
+ const color = palette.tumble[(i * 3) % palette.tumble.length];
+ init[`w${i}`] = { ...init[`w${i}`], y: -230, opacity: 0 };
+ init[`f${i}`] = { fill: color };
+ cue(`w${i}`, at, 0.1, { opacity: 0 }, { opacity: 1 }, "none");
+ cue(`w${i}`, at, 0.42, { y: -230 }, { y: 0 }, "back.out(1.7)");
+ cue(`f${i}`, at + 0.36, 0.34, { fill: color }, { fill: fin(l) }, "sine.inOut");
+ });
+ media.forEach((l, j) => {
+ const i = nW + j;
+ // From below, against the wordmark's fall: a drop from above would
+ // pass through the letters already standing.
+ init[`w${i}`] = { ...init[`w${i}`], opacity: 0, y: 70 };
+ cue(`w${i}`, chime + j * 0.05, 0.12, { opacity: 0 }, { opacity: 1 }, "none");
+ cue(`w${i}`, chime + j * 0.05, 0.4, { y: 70 }, { y: 0 }, "back.out(1.7)");
+ });
+ } else if (motion === "boot-wipe") {
+ // Linear, left to right, over the whole first sound: the wordmark in its
+ // own colours behind a clip that opens at a constant rate, a line of the
+ // accent riding its edge. MEDIA wipes in the same way, quickly, on the chime.
+ const x0 = -4;
+ const x1 = parts.width + 4;
+ init.wipe = { attr: { width: 0 } };
+ cue("wipe", build.from, build.to - build.from, { attr: { width: 0 } }, { attr: { width: x1 - x0 } }, "none");
+ // The edge's line over the letters, its glow under them (a light over the
+ // glyphs would wash out the letter being revealed).
+ for (const k of ["edge", "glow"]) {
+ init[k] = { x: x0, opacity: 0 };
+ cue(k, build.from, build.to - build.from, { x: x0 }, { x: x1 }, "none");
+ cue(k, build.from, 0.12, { opacity: 0 }, { opacity: 1 }, "none");
+ cue(k, build.to - 0.05, 0.3, { opacity: 1 }, { opacity: 0 }, "power1.out");
+ }
+ init.mwipe = { attr: { width: 0 } };
+ cue("mwipe", chime, 0.36, { attr: { width: 0 } }, { attr: { width: x1 - x0 } }, "power2.out");
+ shimmer(build.to + 0.04, 0.03);
+ } else if (motion === "boot-mark") {
+ // The mark first: its found lines drawn left to right one after another
+ // (the accent one with its arrow), then the wordmark slides out of it,
+ // then the shimmer, and MEDIA on the chime.
+ const bars = parts.markShapes ?? [];
+ bars.forEach((s, j) => {
+ if (s.kind === "ground") {
+ init[`m${j}`] = { scale: 0.82, opacity: 0, transformOrigin: "50% 50%" };
+ cue(`m${j}`, build.from, 0.45, { scale: 0.82, opacity: 0 }, { scale: 1, opacity: 1 }, "power3.out");
+ return;
+ }
+ const at = build.from + 0.12 * j;
+ if (s.kind === "arrow") {
+ init[`m${j}`] = { scale: 0, opacity: 0, transformOrigin: "0% 50%" };
+ cue(`m${j}`, at, 0.3, { scale: 0, opacity: 0 }, { scale: 1, opacity: 1 }, "back.out(2)");
+ } else {
+ init[`m${j}`] = { scaleX: 0, transformOrigin: "0% 50%" };
+ cue(`m${j}`, at, 0.5, { scaleX: 0 }, { scaleX: 1 }, "power3.out");
+ }
+ });
+ word.forEach((l, i) => {
+ const at = 1.0 + i * 0.07;
+ init[`w${i}`] = { ...init[`w${i}`], x: -40, opacity: 0 };
+ cue(`w${i}`, at, 0.5, { x: -40, opacity: 0 }, { x: 0, opacity: 1 }, "power3.out");
+ });
+ shimmer(1.9, 0.04);
+ mediaIn();
+ } else {
+ throw new Error(`no intro style "${style}"`);
+ }
+
+ // The fade to the ground, over the last beat.
+ cue("stage", seconds - B.fade, B.fade, { opacity: 1 }, { opacity: 0 }, "power1.in");
+ return { init, cues: cues.sort((a, b) => a.at - b.at || a.k.localeCompare(b.k)) };
+}
+
+// ---------------------------------------------------------------------------
+// The page.
+// ---------------------------------------------------------------------------
+
+/** The mark's shapes (boot-mark), each with the origin it grows from, in lockup units. */
+function markShapes(mark) {
+ if (!mark) return [];
+ const k = mark.size / 512;
+ const shapes = [];
+ for (const m of mark.body.matchAll(/<(rect|polygon)([^>]*)\/>/g)) {
+ const a = Object.fromEntries([...m[2].matchAll(/(\w+)="([^"]*)"/g)].map((x) => [x[1], x[2]]));
+ if (m[1] === "rect" && Number(a.width) === 512) {
+ shapes.push({ kind: "ground", fill: a.fill, el: `<rect width="512" height="512" rx="${a.rx ?? 0}"/>`, origin: "256 256" });
+ continue;
+ }
+ if (m[1] === "polygon") {
+ const pts = a.points.split(/\s+/).map((p) => p.split(",").map(Number));
+ const ox = Math.min(...pts.map((p) => p[0]));
+ const oy = pts.reduce((s, p) => s + p[1], 0) / pts.length;
+ shapes.push({ kind: "arrow", fill: a.fill, el: `<polygon points="${a.points}"/>`, origin: `${r3(ox)} ${r3(oy)}` });
+ continue;
+ }
+ const x = Number(a.x);
+ const y = Number(a.y) + Number(a.height) / 2;
+ shapes.push({
+ kind: "bar", fill: a.fill,
+ el: `<rect x="${a.x}" y="${a.y}" width="${a.width}" height="${a.height}" rx="${a.rx ?? 0}"/>`, origin: `${r3(x)} ${r3(y)}`,
+ });
+ }
+ return shapes.map((s) => ({ ...s, k }));
+}
+
+/**
+ * The intro's page.
+ * @param {{ style: string, ground: "light" | "dark", seconds: number, width?: number, height?: number, fps?: number,
+ * kit: any, gsapSrc?: string }} o
+ */
+export function introHtml({ style, ground, seconds, width = 1920, height = 1080, fps = 30, kit, gsapSrc = "assets/gsap.min.js" }) {
+ const W = width;
+ const H = height;
+ const palette = introPalette(ground, kit);
+ const parts = lockupParts(kit);
+ const withMark = style === "boot-mark";
+ const shapes = withMark ? markShapes(parts.mark) : [];
+ // The drawing's extent in lockup units, and the scale that sets it in the
+ // frame: the wordmark ~61% of the width (the lockup with its mark ~70%).
+ const x0 = withMark ? parts.mark.x : 0;
+ const x1 = parts.width;
+ const y0 = Math.min(parts.top, withMark ? parts.mark.y : Infinity);
+ const y1 = Math.max(parts.bottom, withMark ? parts.mark.y + parts.mark.size : -Infinity);
+ const k = r3((W * (withMark ? 0.7 : 0.61)) / (x1 - x0));
+ const ox = r3(W / 2 - ((x0 + x1) / 2) * k);
+ const oy = r3(H / 2 - ((y0 + y1) / 2) * k);
+ const { init, cues } = introCues({ style, ground, seconds, parts: { ...parts, markShapes: shapes }, palette });
+ const dur = pageDuration(seconds, fps);
+
+ const nW = parts.letters.filter((l) => l.role !== "media").length;
+ const glyph = (l, i) =>
+ `<g data-k="w${i}"><path data-k="f${i}" transform="translate(${l.tx} ${l.ty}) scale(${l.s})" d="${l.d}"/></g>`;
+ const wordGlyphs = parts.letters.slice(0, nW).map(glyph).join("\n ");
+ const mediaGlyphs = parts.letters.slice(nW).map((l, j) => glyph(l, nW + j)).join("\n ");
+ const wiped = style === "boot-wipe";
+ const pad = 40;
+ const wordClip = wiped
+ ? `<clipPath id="intro-wipe"><rect data-k="wipe" x="-4" y="${r3(parts.top - pad)}" width="0" height="${r3(parts.wordBottom - parts.top + 2 * pad)}"/></clipPath>
+ <clipPath id="intro-mwipe"><rect data-k="mwipe" x="-4" y="${r3(parts.mediaTop - pad)}" width="0" height="${r3(parts.bottom - parts.mediaTop + 2 * pad)}"/></clipPath>`
+ : "";
+ const markEls = withMark
+ ? `<g transform="translate(${parts.mark.x} ${parts.mark.y}) scale(${r3(parts.mark.size / 512)})">
+ ${shapes.map((s, j) => `<g data-k="m${j}" fill="${s.kind === "ground" ? palette.markGround : s.fill}">${s.el}</g>`).join("\n ")}
+ </g>`
+ : "";
+ const edgeH = r3(parts.wordBottom - parts.top + 24);
+ const data = { init, cues };
+ const json = JSON.stringify(data).replace(/</g, "\\u003c");
+
+ return `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=${W}, height=${H}" />
+ <script src="${esc(gsapSrc)}"></script>
+ <style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ html, body { width: ${W}px; height: ${H}px; overflow: hidden; background: ${palette.ground}; }
+ #root { position: relative; width: ${W}px; height: ${H}px; overflow: hidden; }
+ #intro-clip { position: absolute; left: 0; top: 0; width: ${W}px; height: ${H}px; overflow: hidden; background: ${palette.ground}; }
+ svg { position: absolute; left: 0; top: 0; }
+ </style>
+ </head>
+ <body>
+ <div id="root" data-composition-id="intro" data-start="0" data-duration="${dur}"
+ data-width="${W}" data-height="${H}" data-style="${esc(style)}" data-ground="${esc(ground)}">
+ <div id="intro-clip" class="clip" data-start="0" data-duration="${dur}" data-track-index="1">
+ <svg width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg">
+ <defs>
+ ${wordClip}
+ <linearGradient id="intro-edge" x1="0" x2="1" y1="0" y2="0">
+ <stop offset="0" stop-color="${palette.lit}" stop-opacity="0"/>
+ <stop offset="0.7" stop-color="${palette.lit}" stop-opacity="0.35"/>
+ <stop offset="1" stop-color="${palette.lit}" stop-opacity="1"/>
+ </linearGradient>
+ </defs>
+ <rect width="${W}" height="${H}" fill="${palette.ground}"/>
+ <g data-k="stage">
+ <g transform="translate(${ox} ${oy}) scale(${k})">
+ ${markEls}
+ ${wiped ? `<g data-k="glow"><rect x="-70" y="${r3(parts.top - 12)}" width="70" height="${edgeH}" fill="url(#intro-edge)" opacity="0.22"/></g>
+ ` : ""}<g${wiped ? ' clip-path="url(#intro-wipe)"' : ""}>
+ ${wordGlyphs}
+ </g>${wiped ? `
+ <g data-k="edge"><rect x="-3" y="${r3(parts.top - 12)}" width="6" height="${edgeH}" rx="3" fill="${palette.lit}"/></g>` : ""}
+ <g${wiped ? ' clip-path="url(#intro-mwipe)"' : ""}>
+ ${mediaGlyphs}
+ </g>
+ </g>
+ </g>
+ </svg>
+ </div>
+ </div>
+
+ <script id="intro-data" type="application/json">${json}</script>
+ <script>
+ const D = JSON.parse(document.getElementById("intro-data").textContent);
+ const byK = {};
+ for (const el of document.querySelectorAll("[data-k]")) byK[el.dataset.k] = el;
+ // t = 0, then the cues: every one states its from, so any seek from
+ // anywhere lands on the same pixels.
+ for (const k of Object.keys(D.init)) if (byK[k]) gsap.set(byK[k], D.init[k]);
+ const tl = gsap.timeline({ paused: true });
+ for (const c of D.cues) {
+ const el = byK[c.k];
+ if (!el) continue;
+ tl.fromTo(el, c.from, { ...c.to, duration: c.dur, ease: c.ease, immediateRender: false }, c.at);
+ }
+ // The timeline is as long as the page, whatever the last cue is.
+ tl.set({}, {}, ${dur});
+ window.__timelines = window.__timelines || {};
+ window.__timelines["intro"] = tl;
+ const still = new URLSearchParams(location.search).get("still");
+ if (still !== null) tl.seek(Number(still), false);
+ </script>
+ </body>
+</html>
+`;
+}
diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs
@@ -584,7 +584,7 @@ export async function qrPngsFor(urls, render, size, assetsDir) {
// Regions.
// ---------------------------------------------------------------------------
-const HF_JSON = JSON.stringify(
+export const HF_JSON = JSON.stringify(
{ $schema: "https://hyperframes.heygen.com/schema/hyperframes.json", paths: { blocks: "compositions", assets: "assets" } },
null,
2,
@@ -863,7 +863,7 @@ export function rendererEnv(env = process.env) {
return rest;
}
-function runRenderer(cmd, args) {
+export function runRenderer(cmd, args) {
return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: rendererEnv() });
let tail = "";
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -16,6 +16,7 @@
// build-video.mjs or compose-chrome.mjs instead.
import { createHash } from "node:crypto";
import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
+import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs";
import { attributionParts, deckSubtitle } from "./attribution.mjs";
import {
@@ -963,6 +964,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render))
return Math.max(1, to - from);
}
if (entry.type === "image") return Number(entry.seconds ?? 4);
+ // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default).
+ if (entry.type === "intro") return Number(entry.seconds ?? INTRO_SECONDS);
// A teaser's dip makes its segment longer by the dissolve and the black (`teaserLead`).
if (entry.type === "teaser") return teaserSeconds(entry, D, render.fps ?? 30);
// A narrated card's `"auto"` is its words' length, estimated until a build measures it.
@@ -1006,7 +1009,8 @@ export function isMultiChannel(entries, provenance = {}) {
/** Is the deck hidden over this segment? */
export function hidesDeck(entry, deck) {
- if (entry.type === "teaser") return true;
+ // A teaser and the brand intro are full frame: never framed into the footage box.
+ if (entry.type === "teaser" || entry.type === "intro") return true;
return deck.overCards === "hide" && CARD_TYPES.includes(entry.type);
}
diff --git a/umtool/report-to-video/intro.mjs b/umtool/report-to-video/intro.mjs
@@ -0,0 +1,357 @@
+#!/usr/bin/env node
+// THE BRAND INTRO (`render.intro`): the short Archilyzer sting a cut opens
+// with -- "Archilyzer" built in on the first sound, "media" beneath it on the
+// chime, after the Game Boy Advance boot screen.
+//
+// "render": { "intro": "boot" } (or { style, ground?, sound?, seconds? })
+//
+// Absent or null: no intro, and the cut is built exactly as before -- the
+// timeline is not touched (introManifest returns the manifest itself).
+//
+// WHERE IT GOES. selectVariant (build-video.mjs) prepends one timeline entry,
+// `{ type: "intro", id: "brand-intro", … }`, so every reader of a cut -- the
+// build, the schedule and the deck, the chapters, umtool's Play view and
+// export -- sees the same first segment, `seconds` long, and everything after
+// it starts that much later (less the join). The deck hides over it (full
+// frame, like a teaser). The chapters fold it into the first entry's: a 4 s
+// chapter is not one YouTube keeps.
+//
+// THE JOIN. The intro is joined to the first entry like any two segments: the
+// cut's own `render.transition` -- a dissolve of that length by default, a
+// clean cut with `transition: 0`. The intro's last half-second fades to its
+// ground on its own, so under a dissolve the wordmark is already going as the
+// first entry comes up (the two overlap: a 0.4 s join starts 0.1 s into the
+// fade), and with a clean cut the entry follows a plain ground.
+//
+// THE SOUND. `sound` absent is the STAND-IN: the GBA boot sound itself,
+// extracted once into assets/intro/boot-standin.wav by
+// `node umtool/report-to-video/intro.mjs extract-sound <the GBA startup mp4>`.
+// It is NOT in git (assets/intro/ is ignored): it is Nintendo's, the source
+// mirror publishes this repository's history, and it is to be replaced with a
+// sound of our own before any public release. `sound: "<file>"` (relative to
+// the manifest) is that replacement; `sound: false` is a silent intro.
+//
+// THE CACHE. The intro is the same picture in every cut of a size, so it is
+// rendered once and kept by its key -- the page (style, ground, size, fps,
+// length), the sound's bytes and the encode's parameters -- as
+// `<cache>/<key>.mp4` (UMTOOL_INTRO_CACHE, default ~/.cache/umtool/intro), and
+// copied into each cut's segments/brand-intro.mp4 with a record beside it
+// (`brand-intro.intro.json`). A cut whose record names the key builds nothing.
+//
+// On the CLI (variants for judging, outside any cut):
+// node intro.mjs render --style boot [--ground light|dark] [--seconds 4.18]
+// [--sound <wav> | --silent] [--width 1920 --height 1080 --fps 30] --out <file.mp4>
+// node intro.mjs extract-sound <reference.mp4>
+// `render` takes the heavy slot (heavy-gate.mjs) unless HEAVY=0.
+
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import { copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { promisify } from "node:util";
+
+import {
+ INTRO_BEATS, INTRO_GROUNDS, INTRO_ID, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_STYLE_GROUND, INTRO_STYLES,
+ introErrors, introOf, validateIntro,
+} from "yt-dlp-transcript-common/lib/report/intro.mjs";
+
+export {
+ INTRO_BEATS, INTRO_GROUNDS, INTRO_ID, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_STYLE_GROUND, INTRO_STYLES,
+ introErrors, introOf, validateIntro,
+};
+
+const execFileP = promisify(execFile);
+const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url));
+const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg";
+
+/** The stand-in sound (the GBA boot's): extracted by `intro.mjs extract-sound`, never committed. */
+export const INTRO_STANDIN_SOUND = path.join(/* turbopackIgnore: true */ HERE, "assets", "intro", "boot-standin.wav");
+
+/** The intro's timeline type. */
+export const INTRO_TYPE = "intro";
+
+const sha256 = (b) => createHash("sha256").update(b).digest("hex");
+
+/**
+ * The timeline entry `render.intro` adds, or null for none. A key that does
+ * not validate adds nothing here: the build's validators refuse it by name.
+ */
+export function introEntry(render) {
+ if (introErrors(render?.intro).length) return null;
+ const o = introOf(render);
+ if (!o) return null;
+ return {
+ type: INTRO_TYPE, id: INTRO_ID, style: o.style, ground: o.ground, seconds: o.seconds,
+ ...(o.sound !== undefined ? { sound: o.sound } : {}),
+ // A placeholder's words (umtool's Play view, the deck's table).
+ heading: "Intro",
+ };
+}
+
+/** Is this timeline entry the brand intro? */
+export const isIntro = (entry) => entry?.type === INTRO_TYPE;
+
+/**
+ * The manifest a cut with an intro is built from: its intro first. No intro
+ * (or one the validators will refuse): the SAME object, so nothing
+ * downstream can tell a manifest without the key from before it existed.
+ */
+export function introManifest(manifest) {
+ const entry = introEntry(manifest?.render);
+ if (!entry) return manifest;
+ const timeline = manifest.timeline ?? [];
+ if (timeline.some(isIntro)) return manifest;
+ if (timeline.some((e) => e?.id === INTRO_ID)) {
+ throw new Error(`render.intro opens the cut with an entry with id "${INTRO_ID}", and the timeline already has one — rename it`);
+ }
+ return { ...manifest, timeline: [entry, ...timeline] };
+}
+
+/**
+ * The intro's sound file, absolute, or null for a silent intro. `sound`
+ * absent is the stand-in (INTRO_STANDIN_SOUND); a path is the manifest's.
+ */
+export function introSoundPath(entry, manifestDir = process.cwd(), standin = INTRO_STANDIN_SOUND) {
+ if (entry.sound === false) return null;
+ if (typeof entry.sound === "string") return path.resolve(manifestDir, entry.sound);
+ return standin;
+}
+
+/** Why a missing sound file cannot be the intro's sound, with the way to make it. */
+export function missingSoundMessage(file, standin = INTRO_STANDIN_SOUND) {
+ if (file === standin) {
+ return (
+ `render.intro: the stand-in sound ${file} is not here (it is not in git) — extract it with ` +
+ "`node umtool/report-to-video/intro.mjs extract-sound <the GBA startup mp4>`, or give render.intro a `sound` " +
+ "of your own, or `sound: false` for a silent intro"
+ );
+ }
+ return `render.intro.sound: ${file} is not there`;
+}
+
+/**
+ * The intro's sound as a filtergraph fragment to `[ia]`: input 1 resampled
+ * to the cut's rate and layout and cut or padded to exactly `seconds` (a
+ * sound longer than the intro is faded over its last 80 ms there), or
+ * digital silence with no file.
+ */
+export function introAudioGraph({ seconds, render, hasSound, soundSeconds = null }) {
+ const rate = render.audioRate ?? 48000;
+ const layout = render.audioChannels === 1 ? "mono" : "stereo";
+ const s = Number(seconds.toFixed(6));
+ const tail = `atrim=end=${s},apad=whole_dur=${s},asetpts=PTS-STARTPTS[ia]`;
+ if (!hasSound) return `anullsrc=channel_layout=${layout}:sample_rate=${rate},${tail}`;
+ const fade = soundSeconds !== null && soundSeconds > s + 1e-3 ? `afade=t=out:st=${Number((s - 0.08).toFixed(3))}:d=0.08,` : "";
+ return `[1:a]aresample=${rate},aformat=channel_layouts=${layout},${fade}${tail}`;
+}
+
+/** The intro's encode: its frames, its sound, the cut's encode parameters (`encode`, build-video's encodeArgs). */
+export function introEncodeArgs({ framesDir, sound, seconds, render, encode, audio, outPath }) {
+ return [
+ "-nostdin", "-v", "error", "-y",
+ "-framerate", String(render.fps), "-reinit_filter", "0", "-start_number", "1",
+ "-i", path.join(framesDir, "frame_%06d.png"),
+ ...(sound ? ["-i", sound] : []),
+ "-filter_complex", `[0:v]format=rgba,fps=${render.fps},setsar=1[iv];${audio}`,
+ "-map", "[iv]", "-map", "[ia]",
+ ...encode,
+ "-frames:v", String(Math.round(seconds * render.fps)),
+ "-shortest",
+ outPath,
+ ];
+}
+
+/**
+ * The intro's key: its page (which is the style, the ground, the size, the
+ * fps and the length, drawn), its sound's bytes (null: silent), the encode's
+ * parameters and the renderer's version. Two cuts with the same key share one render.
+ */
+export function introKey({ html, soundSha = null, encode = [], fps, frames, version = null }) {
+ return sha256(JSON.stringify({ v: 1, html: sha256(html), sound: soundSha, encode, fps, frames, version }));
+}
+
+/** Where rendered intros are kept: UMTOOL_INTRO_CACHE, else ~/.cache/umtool/intro (XDG_CACHE_HOME honoured). */
+export function introCacheDir(env = process.env) {
+ if (env.UMTOOL_INTRO_CACHE) return path.resolve(env.UMTOOL_INTRO_CACHE);
+ return path.join(env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "umtool", "intro");
+}
+
+/** The record beside an intro segment: the key it was copied from. */
+export const introRecordPath = (seg) => seg.replace(/\.mp4$/, ".intro.json");
+
+const exists = (p) => stat(p).then(() => true, () => false);
+
+async function probeSeconds(file) {
+ const { stdout } = await execFileP(process.env.FFPROBE_BIN ?? "ffprobe", [
+ "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file,
+ ]);
+ return Number(stdout.trim());
+}
+
+/**
+ * The intro rendered and encoded at this cut's size, fps and encode, from
+ * the cache when it is there: `{ path, key, cached }`. `workDir` holds the
+ * page and its frames while it renders (both removed once encoded).
+ *
+ * @param {{ entry: any, render: any, encode: string[], manifestDir?: string, workDir: string,
+ * cacheDir?: string, workers?: number, emit?: (ev: string, f: object) => void, standin?: string }} o
+ */
+export async function renderIntro({ entry, render, encode, manifestDir = process.cwd(), workDir, cacheDir = introCacheDir(), workers = 4, emit = () => {}, standin = INTRO_STANDIN_SOUND }) {
+ const errors = introErrors({ style: entry.style, ground: entry.ground, seconds: entry.seconds, ...(entry.sound !== undefined ? { sound: entry.sound } : {}) });
+ if (errors.length) throw new Error(errors.join("; "));
+ const { introHtml } = await import("./chrome-intro.mjs");
+ const { brandKit } = await import("./brand.mjs");
+ const { hyperframesCommand, frameCount } = await import("./deck.mjs");
+ const W = render.width ?? 1920;
+ const H = render.height ?? 1080;
+ const fps = render.fps ?? 30;
+ const html = introHtml({ style: entry.style, ground: entry.ground, seconds: entry.seconds, width: W, height: H, fps, kit: brandKit("archilyzer-media") });
+ const sound = introSoundPath(entry, manifestDir, standin);
+ let soundSha = null;
+ if (sound) {
+ const bytes = await readFile(sound).catch(() => null);
+ if (!bytes) throw new Error(missingSoundMessage(sound, standin));
+ soundSha = sha256(bytes);
+ }
+ const frames = frameCount(entry.seconds, fps);
+ const hf = hyperframesCommand(process.env);
+ const key = introKey({ html, soundSha, encode, fps, frames, version: hf.version });
+ const cached = path.join(cacheDir, `${key}.mp4`);
+ if (await exists(cached)) return { path: cached, key, cached: true };
+
+ const t0 = Date.now();
+ const proj = path.join(workDir, `intro-${key.slice(0, 12)}`);
+ const framesDir = path.join(workDir, `intro-${key.slice(0, 12)}-frames`);
+ await rm(proj, { recursive: true, force: true });
+ await rm(framesDir, { recursive: true, force: true });
+ await mkdir(path.join(proj, "assets"), { recursive: true });
+ const { HF_JSON, runRenderer } = await import("./compose-chrome.mjs");
+ const { GSAP_FILE } = await import("./chrome-deck.mjs");
+ await copyFile(GSAP_FILE, path.join(proj, "assets", "gsap.min.js"));
+ await writeFile(path.join(proj, "index.html"), html, "utf8");
+ await writeFile(path.join(proj, "hyperframes.json"), HF_JSON + "\n", "utf8");
+ await runRenderer(hf.cmd, [
+ ...hf.args, "render", "--format", "png-sequence", "--quality", "high", "--fps", String(fps),
+ "-w", String(workers), "--no-browser-gpu", "--output", framesDir, proj,
+ ]);
+ const got = (await readdir(framesDir).catch(() => [])).filter((f) => /^frame_\d+\.png$/.test(f)).length;
+ if (got !== frames) throw new Error(`the intro render wrote ${got} frames to ${framesDir}, expected ${frames} (${entry.seconds}s at ${fps} fps)`);
+ emit("chrome", { phase: "render", region: "intro", frames, key, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)) });
+
+ const audio = introAudioGraph({
+ seconds: entry.seconds, render, hasSound: !!sound, soundSeconds: sound ? await probeSeconds(sound) : null,
+ });
+ await mkdir(cacheDir, { recursive: true });
+ const tmp = path.join(cacheDir, `.${key}.${process.pid}.tmp.mp4`);
+ try {
+ await execFileP(FFMPEG, introEncodeArgs({ framesDir, sound, seconds: entry.seconds, render, encode, audio, outPath: tmp }), { maxBuffer: 1 << 26 });
+ await rename(tmp, cached);
+ } finally {
+ await rm(tmp, { force: true });
+ await rm(framesDir, { recursive: true, force: true });
+ await rm(proj, { recursive: true, force: true });
+ }
+ return { path: cached, key, cached: false };
+}
+
+/**
+ * The cut's intro segment, segments/<INTRO_ID>.mp4: copied from the rendered
+ * intro unless the record beside it already names the same key. Written
+ * beside and renamed over, as a teaser's is (the file may be a hard link to
+ * another take's segment).
+ */
+export async function buildIntroSegment(entry, { render, encode, outDir, manifestDir, workers = 4, emit = () => {}, cacheDir = introCacheDir(), standin = INTRO_STANDIN_SOUND }) {
+ const seg = path.join(outDir, "segments", `${entry.id}.mp4`);
+ const recPath = introRecordPath(seg);
+ const r = await renderIntro({ entry, render, encode, manifestDir, workDir: path.join(outDir, "chrome"), cacheDir, workers, emit, standin });
+ const rec = await readFile(recPath, "utf8").then(JSON.parse, () => null);
+ if (rec?.key === r.key && (await exists(seg))) {
+ emit("note", { id: entry.id, message: `${entry.id}: intro segment unchanged (key ${r.key.slice(0, 12)})` });
+ return seg;
+ }
+ await mkdir(path.dirname(seg), { recursive: true });
+ const tmp = path.join(path.dirname(seg), `.${entry.id}.${process.pid}.tmp.mp4`);
+ try {
+ await copyFile(r.path, tmp);
+ await rename(tmp, seg);
+ } finally {
+ await rm(tmp, { force: true });
+ }
+ const recTmp = `${recPath}.${process.pid}.tmp`;
+ await writeFile(recTmp, JSON.stringify({ key: r.key, style: entry.style, ground: entry.ground, seconds: entry.seconds, cached: r.cached }) + "\n");
+ await rename(recTmp, recPath);
+ if (r.cached) emit("note", { id: entry.id, message: `${entry.id}: intro from the cache (key ${r.key.slice(0, 12)})` });
+ return seg;
+}
+
+/** `extract-sound`: the reference's first INTRO_SECONDS as the stand-in WAV (48 kHz stereo, 16-bit). */
+export function extractSoundArgs(reference, out = INTRO_STANDIN_SOUND) {
+ return ["-nostdin", "-v", "error", "-y", "-i", reference, "-vn", "-t", String(INTRO_SECONDS), "-ar", "48000", "-ac", "2", "-c:a", "pcm_s16le", out];
+}
+
+/** The standalone render's parameters: a 1920x1080 30 fps cut's, as scaffolded (crf 20, medium). */
+export const STANDALONE_RENDER = Object.freeze({ width: 1920, height: 1080, fps: 30, audioRate: 48000, audioChannels: 2 });
+
+async function main(argv) {
+ const [cmd, ...rest] = argv;
+ const flag = (n) => {
+ const i = rest.indexOf(n);
+ return i >= 0 ? rest[i + 1] : undefined;
+ };
+ if (cmd === "extract-sound") {
+ const ref = rest.find((a) => !a.startsWith("--"));
+ if (!ref) throw new Error("usage: intro.mjs extract-sound <reference.mp4> [--out <wav>]");
+ const out = flag("--out") ?? INTRO_STANDIN_SOUND;
+ await mkdir(path.dirname(out), { recursive: true });
+ await execFileP(FFMPEG, extractSoundArgs(ref, out));
+ console.log(`stand-in sound -> ${out}`);
+ return 0;
+ }
+ if (cmd !== "render") {
+ console.error(
+ "usage: intro.mjs render --style <" + INTRO_STYLES.join("|") + "> [--ground light|dark] [--seconds s]\n" +
+ " [--sound <wav> | --silent] [--width 1920 --height 1080 --fps 30] --out <file.mp4>\n" +
+ " intro.mjs extract-sound <reference.mp4> [--out <wav>]",
+ );
+ return 2;
+ }
+ const out = flag("--out");
+ if (!out) throw new Error("render: --out <file.mp4> is required");
+ const intro = {
+ style: flag("--style"),
+ ...(flag("--ground") ? { ground: flag("--ground") } : {}),
+ ...(flag("--seconds") ? { seconds: Number(flag("--seconds")) } : {}),
+ ...(rest.includes("--silent") ? { sound: false } : flag("--sound") ? { sound: path.resolve(flag("--sound")) } : {}),
+ };
+ const render = {
+ ...STANDALONE_RENDER,
+ ...(flag("--width") ? { width: Number(flag("--width")) } : {}),
+ ...(flag("--height") ? { height: Number(flag("--height")) } : {}),
+ ...(flag("--fps") ? { fps: Number(flag("--fps")) } : {}),
+ intro,
+ };
+ const entry = introEntry(render);
+ if (!entry) throw new Error(introErrors(intro).join("; "));
+ const { encodeArgs } = await import("./build-video.mjs");
+ const run = async () => {
+ const workDir = path.join(path.dirname(path.resolve(out)), ".intro-work");
+ const r = await renderIntro({ entry, render, encode: encodeArgs(render), workDir, emit: (ev, f) => console.error(`${ev}: ${JSON.stringify(f)}`) });
+ await rm(workDir, { recursive: true, force: true });
+ await mkdir(path.dirname(path.resolve(out)), { recursive: true });
+ await copyFile(r.path, out);
+ console.log(`${entry.style} (${entry.ground}) -> ${out}${r.cached ? " (cached)" : ""} key ${r.key.slice(0, 12)}`);
+ };
+ const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href;
+ const { withRenderSlot } = await import(/* webpackIgnore: true */ gate);
+ await withRenderSlot(["intro.mjs", ...argv], run);
+ return 0;
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
+ main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
+ console.error(e?.message ?? e);
+ process.exit(1);
+ });
+}
diff --git a/umtool/report-to-video/intro.test.mjs b/umtool/report-to-video/intro.test.mjs
@@ -0,0 +1,316 @@
+// Tests for the brand intro (`render.intro`, intro.mjs + chrome-intro.mjs +
+// common/lib/report/intro.mjs): the key's validation, the entry selectVariant
+// prepends and what it does to the cut's clock, the chapters, the beats the
+// page times to, and the cache key the render is kept by.
+//
+// The pixels are judged by eye: ~/reports/archilyzer-intro/variants.
+//
+// Run with: node --test umtool/report-to-video/intro.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { mkdir } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import {
+ INTRO_BEATS, INTRO_ID, INTRO_SECONDS, INTRO_STANDIN_SOUND, INTRO_STYLES, buildIntroSegment, introAudioGraph,
+ introEncodeArgs, introEntry, introErrors, introKey, introManifest, introOf, introRecordPath, introSoundPath,
+ missingSoundMessage, validateIntro,
+} from "./intro.mjs";
+import { introCues, introHtml, introPalette, lockupParts } from "./chrome-intro.mjs";
+import { brandKit } from "./brand.mjs";
+import { encodeArgs, foldIntroChapter, selectVariant } from "./build-video.mjs";
+import { estimateSchedule, estimatedDuration, frameCount, hidesDeck, hyperframesCommand, resolveDeck, scheduleFrom } from "./deck.mjs";
+import { LOOK_KEYS, applyLookPatch, validateLook } from "yt-dlp-transcript-common/lib/report/look.mjs";
+import { mergePatch, patchFromSets } from "../lib/report/takeMaker.mjs";
+
+const kit = brandKit("archilyzer-media");
+const RENDER = { width: 1920, height: 1080, fps: 30, audioRate: 48000, audioChannels: 2, transition: 0.5 };
+const TIMELINE = [
+ { id: "title", type: "card", seconds: 5 },
+ { id: "c1", type: "clip", video: "v1", start: 10, end: 22 },
+ { id: "c2", type: "card", seconds: 4 },
+];
+const cut = (render) => ({ slug: "t", render: { ...RENDER, ...render }, timeline: TIMELINE.map((e) => ({ ...e })) });
+
+// ---------------------------------------------------------------------------
+// Validation
+// ---------------------------------------------------------------------------
+
+test("render.intro: a style name or {style, ground, sound, seconds}; absent and null are no intro", () => {
+ assert.deepEqual(introErrors(undefined), []);
+ assert.deepEqual(introErrors(null), []);
+ for (const s of INTRO_STYLES) {
+ assert.deepEqual(introErrors(s), [], s);
+ assert.deepEqual(introErrors({ style: s, ground: "dark", sound: false, seconds: 5 }), [], s);
+ }
+ assert.deepEqual(introErrors({ style: "boot", sound: "intro.wav" }), []);
+ assert.equal(introOf({}), null);
+ assert.equal(introOf({ intro: null }), null);
+ assert.deepEqual(introOf({ intro: "boot" }), { style: "boot", ground: "light", sound: undefined, seconds: INTRO_SECONDS });
+ assert.equal(introOf({ intro: "boot-dark" }).ground, "dark");
+ assert.equal(introOf({ intro: "boot-mark" }).ground, "dark");
+ assert.equal(introOf({ intro: { style: "boot-dark", ground: "light" } }).ground, "light", "a ground named beats the style's");
+});
+
+test("render.intro: an unknown style is refused by name, with the styles listed", () => {
+ const [e] = introErrors("gameboy");
+ assert.match(e, /render\.intro\.style "gameboy" is not an intro style/);
+ for (const s of INTRO_STYLES) assert.ok(e.includes(s), s);
+ assert.match(introErrors({ ground: "dark" })[0], /style null is not an intro style/);
+});
+
+test("render.intro: a bad ground, sound, length or key is refused, each by its name", () => {
+ assert.match(introErrors({ style: "boot", ground: "grey" }).join(), /render\.intro\.ground must be light or dark/);
+ assert.match(introErrors({ style: "boot", sound: 3 }).join(), /render\.intro\.sound must be/);
+ assert.match(introErrors({ style: "boot", sound: "" }).join(), /render\.intro\.sound must be/);
+ assert.match(introErrors({ style: "boot", seconds: 2 }).join(), /render\.intro\.seconds must be a number from 3\.5 to 8/);
+ assert.match(introErrors({ style: "boot", seconds: 30 }).join(), /render\.intro\.seconds/);
+ assert.match(introErrors({ style: "boot", colour: "red" }).join(), /render\.intro\.colour is not a key/);
+ assert.match(introErrors(7).join(), /must be a style name/);
+});
+
+test("render.intro is a look key: the build's validateLook refuses a bad one, the look patch writes and clears it", () => {
+ assert.ok(LOOK_KEYS.includes("intro"));
+ assert.deepEqual(validateLook(cut({ intro: "boot" })), []);
+ assert.match(validateLook(cut({ intro: "nope" })).join(), /not an intro style/);
+ assert.deepEqual(validateIntro(cut({})), []);
+ // `umtool look <p> intro=boot-wipe` arrives as the text "boot-wipe".
+ const on = applyLookPatch(cut({}), { intro: "boot-wipe" });
+ assert.deepEqual(on.errors, []);
+ assert.equal(on.render.intro, "boot-wipe");
+ // `intro=` (null) clears it: the default, no intro.
+ const off = applyLookPatch(cut({ intro: "boot" }), { intro: null });
+ assert.deepEqual(off.errors, []);
+ assert.equal("intro" in off.render, false);
+ const obj = applyLookPatch(cut({}), { intro: { style: "boot-cascade", ground: "dark" } });
+ assert.deepEqual(obj.render.intro, { style: "boot-cascade", ground: "dark" });
+ const bad = applyLookPatch(cut({}), { intro: "boot-tetris" });
+ assert.match(bad.errors.join(), /render\.intro\.style "boot-tetris" is not an intro style/);
+});
+
+test("a take compares intros: --set render.intro=<style> patches the cut, and null takes it off again", () => {
+ const patch = patchFromSets(["render.intro=boot-wipe"]);
+ assert.deepEqual(patch, { render: { intro: "boot-wipe" } });
+ const take = mergePatch(cut({}), patch);
+ assert.deepEqual(validateLook(take), []);
+ assert.equal(selectVariant(take).timeline[0].style, "boot-wipe");
+ const off = mergePatch(cut({ intro: "boot" }), { render: { intro: null } });
+ assert.equal(selectVariant(off).timeline[0].id, "title");
+});
+
+// ---------------------------------------------------------------------------
+// The entry and the cut's clock
+// ---------------------------------------------------------------------------
+
+test("no render.intro: selectVariant's timeline is the manifest's, entry for entry (introManifest returns the same object)", () => {
+ const m = cut({});
+ assert.equal(introManifest(m), m);
+ const sel = selectVariant(m);
+ assert.deepEqual(sel.timeline.map((e) => e.id), TIMELINE.map((e) => e.id));
+ // An intro the validators refuse adds nothing either (the build refuses it by name).
+ assert.equal(introManifest(cut({ intro: "nope" })).timeline.length, TIMELINE.length);
+});
+
+test("render.intro: selectVariant opens the cut with the intro entry, everything else after it in order", () => {
+ const sel = selectVariant(cut({ intro: { style: "boot-dark", seconds: 4.5 } }));
+ assert.deepEqual(sel.timeline.map((e) => e.id), [INTRO_ID, ...TIMELINE.map((e) => e.id)]);
+ assert.deepEqual(sel.timeline[0], { type: "intro", id: INTRO_ID, style: "boot-dark", ground: "dark", seconds: 4.5, heading: "Intro" });
+ // A second pass (a reader that selects a selected cut) does not add a second intro.
+ assert.equal(introManifest(sel).timeline.filter((e) => e.type === "intro").length, 1);
+ assert.equal(introEntry({ intro: { style: "boot", sound: false } }).sound, false);
+});
+
+test("render.intro: an entry already named brand-intro is refused, naming the id", () => {
+ const m = cut({ intro: "boot" });
+ m.timeline.push({ id: INTRO_ID, type: "card", seconds: 3 });
+ assert.throws(() => selectVariant(m), /already has one — rename it/);
+});
+
+test("the intro adds its seconds to the cut, less the join, and every other entry starts that much later", () => {
+ for (const D of [0.5, 0]) {
+ const without = selectVariant(cut({ transition: D }));
+ const withIt = selectVariant(cut({ transition: D, intro: "boot" }));
+ const durs0 = without.timeline.map((e) => estimatedDuration(e, without.render, D));
+ const durs1 = withIt.timeline.map((e) => estimatedDuration(e, withIt.render, D));
+ assert.equal(durs1[0], INTRO_SECONDS);
+ assert.deepEqual(durs1.slice(1), durs0);
+ const a = scheduleFrom(durs0, D);
+ const b = scheduleFrom(durs1, D);
+ const grow = INTRO_SECONDS - D;
+ assert.ok(Math.abs(b.total - (a.total + grow)) < 1e-9, `D=${D}: ${b.total} vs ${a.total} + ${grow}`);
+ assert.equal(b.starts[0], 0);
+ a.starts.forEach((s, i) => assert.ok(Math.abs(b.starts[i + 1] - (s + grow)) < 1e-9, `D=${D} entry ${i}`));
+ }
+});
+
+test("under the deck the intro is full frame: the deck hides over it, and the schedule shifts the rest", () => {
+ const chrome = { engine: "hyperframes", layout: "deck" };
+ assert.equal(hidesDeck({ type: "intro" }, resolveDeck({ chrome })), true);
+ const without = estimateSchedule(selectVariant(cut({ chrome })));
+ const withIt = estimateSchedule(selectVariant(cut({ chrome, intro: "boot-mark" })));
+ assert.equal(withIt.segments.length, without.segments.length + 1);
+ assert.equal(withIt.segments[0].id, INTRO_ID);
+ assert.equal(withIt.segments[0].hideDeck, true);
+ const grow = INTRO_SECONDS - 0.5;
+ assert.ok(Math.abs(withIt.total - (without.total + grow)) < 1e-6);
+ without.segments.forEach((s, i) => {
+ assert.equal(withIt.segments[i + 1].id, s.id);
+ assert.ok(Math.abs(withIt.segments[i + 1].start - (s.start + grow)) < 1e-6, s.id);
+ });
+});
+
+test("the chapters fold the intro into the first entry's, which starts at 0", () => {
+ const entries = [{ type: "intro" }, { type: "card" }, { type: "clip" }];
+ const chapters = [
+ { start: 0, end: 4.18, title: "Intro" },
+ { start: 3.68, end: 9, title: "Title", section: true },
+ { start: 9, end: 20, title: "Clip" },
+ ];
+ assert.deepEqual(foldIntroChapter(chapters, entries), [
+ { start: 0, end: 9, title: "Title", section: true },
+ { start: 9, end: 20, title: "Clip" },
+ ]);
+ // No intro: the same list.
+ const rest = chapters.slice(1);
+ assert.equal(foldIntroChapter(rest, entries.slice(1)), rest);
+});
+
+// ---------------------------------------------------------------------------
+// The page: the lockup and the beats
+// ---------------------------------------------------------------------------
+
+test("the lockup's letters come off the brand kit: Archi, lyzer and MEDIA, MEDIA under the wordmark", () => {
+ const p = lockupParts(kit);
+ assert.deepEqual(p.letters.map((l) => l.role).join(","), [..."lllll", ..."sssss", ..."mmmmm"].map((c) => ({ l: "lead", s: "suffix", m: "media" })[c]).join(","));
+ assert.ok(p.mediaTop > p.wordBottom - 1, "MEDIA sits under the wordmark");
+ assert.ok(p.letters[0].box.x0 >= 0 && p.letters[0].box.x0 < 5, "measured from the text's own left edge");
+ assert.ok(p.mark && p.mark.x < 0, "the mark sits to the text's left");
+});
+
+test("every style times its motion to the beats: the wordmark inside the first sound, MEDIA on the chime, the fade last", () => {
+ const p = lockupParts(kit);
+ for (const style of INTRO_STYLES) {
+ for (const ground of ["light", "dark"]) {
+ const { cues } = introCues({ style, ground, seconds: INTRO_SECONDS, parts: { ...p, markShapes: [] }, palette: introPalette(ground, kit) });
+ const media = new Set([10, 11, 12, 13, 14].map((i) => `w${i}`));
+ const mediaIn = cues.filter((c) => media.has(c.k) || c.k === "mwipe");
+ assert.ok(mediaIn.length, `${style}: MEDIA comes in`);
+ for (const c of mediaIn) assert.ok(c.at >= INTRO_BEATS.chime.from - 1e-9, `${style}: MEDIA at ${c.at}, before the chime`);
+ const word = cues.filter((c) => /^w\d$/.test(c.k) || c.k === "wipe");
+ assert.ok(word.length, `${style}: the wordmark moves`);
+ for (const c of word) {
+ assert.ok(c.at >= INTRO_BEATS.build.from - 1e-9, `${style}: ${c.k} starts at ${c.at}, before the sound`);
+ assert.ok(c.at + c.dur <= INTRO_BEATS.build.to + 0.05, `${style}: ${c.k} lands at ${c.at + c.dur}, after the build`);
+ }
+ const fade = cues.find((c) => c.k === "stage");
+ assert.equal(fade.at, Number((INTRO_SECONDS - INTRO_BEATS.fade).toFixed(3)));
+ assert.equal(fade.to.opacity, 0);
+ // Seek-safe: every cue states where it starts.
+ for (const c of cues) assert.ok(c.from && Object.keys(c.from).length, `${style}: ${c.k} at ${c.at} has a from`);
+ }
+ }
+});
+
+test("boot-wipe reveals the wordmark linearly, left to right, over exactly the first sound", () => {
+ const p = lockupParts(kit);
+ const { cues, init } = introCues({ style: "boot-wipe", ground: "light", seconds: INTRO_SECONDS, parts: p, palette: introPalette("light", kit) });
+ const wipe = cues.find((c) => c.k === "wipe");
+ assert.equal(wipe.ease, "none");
+ assert.equal(wipe.at, INTRO_BEATS.build.from);
+ assert.equal(Number((wipe.at + wipe.dur).toFixed(3)), INTRO_BEATS.build.to);
+ assert.equal(init.wipe.attr.width, 0);
+ assert.ok(wipe.to.attr.width > p.width);
+});
+
+test("boot-cascade drops the letters one after another, evenly", () => {
+ const p = lockupParts(kit);
+ const { cues } = introCues({ style: "boot-cascade", ground: "light", seconds: INTRO_SECONDS, parts: p, palette: introPalette("light", kit) });
+ const drops = [...Array(10).keys()].map((i) => cues.find((c) => c.k === `w${i}` && c.from.y !== undefined).at);
+ const gaps = drops.slice(1).map((t, i) => Number((t - drops[i]).toFixed(3)));
+ assert.ok(gaps.every((g) => Math.abs(g - gaps[0]) <= 0.002), `even: ${gaps}`);
+});
+
+test("the page: one full-frame composition of the intro's length, its colours the ground's", () => {
+ const html = introHtml({ style: "boot-dark", ground: "dark", seconds: INTRO_SECONDS, kit });
+ assert.match(html, /data-composition-id="intro" data-start="0" data-duration="4\.1666"/);
+ assert.match(html, /data-width="1920" data-height="1080"/);
+ assert.ok(html.includes(kit.palette.bg), "the dark ground is the video palette's");
+ assert.match(introHtml({ style: "boot", ground: "light", seconds: INTRO_SECONDS, kit }), /background: #f3f6f7/);
+ assert.match(html, /window\.__timelines\["intro"\] = tl/);
+});
+
+// ---------------------------------------------------------------------------
+// The sound, the encode and the cache key
+// ---------------------------------------------------------------------------
+
+test("the sound: absent is the stand-in, a path is the manifest's, false is silence", () => {
+ assert.equal(introSoundPath({ }, "/m"), INTRO_STANDIN_SOUND);
+ assert.equal(introSoundPath({ sound: "a/b.wav" }, "/m"), "/m/a/b.wav");
+ assert.equal(introSoundPath({ sound: false }, "/m"), null);
+ assert.match(missingSoundMessage(INTRO_STANDIN_SOUND), /extract-sound/);
+ assert.match(introAudioGraph({ seconds: 4.18, render: RENDER, hasSound: false }), /^anullsrc=channel_layout=stereo:sample_rate=48000,atrim=end=4\.18,apad=whole_dur=4\.18/);
+ const g = introAudioGraph({ seconds: 4, render: RENDER, hasSound: true, soundSeconds: 4.18 });
+ assert.match(g, /^\[1:a\]aresample=48000,aformat=channel_layouts=stereo,afade=t=out:st=3\.92:d=0\.08,atrim=end=4,/);
+ assert.doesNotMatch(introAudioGraph({ seconds: 4.18, render: RENDER, hasSound: true, soundSeconds: 4.18 }), /afade/);
+ const args = introEncodeArgs({ framesDir: "/f", sound: "/s.wav", seconds: 4.18, render: RENDER, encode: encodeArgs(RENDER), audio: g, outPath: "/o.mp4" });
+ assert.deepEqual(args.slice(args.indexOf("-frames:v"), args.indexOf("-frames:v") + 2), ["-frames:v", "125"]);
+ assert.ok(args.includes("/s.wav"));
+});
+
+test("the cache key: the same intro is the same key; style, ground, size, fps, length, sound or encode change it", () => {
+ const key = ({ style = "boot", ground = "light", width = 1920, height = 1080, fps = 30, seconds = INTRO_SECONDS, soundSha = "s1", crf = 20 } = {}) =>
+ introKey({
+ html: introHtml({ style, ground, seconds, width, height, fps, kit }), soundSha,
+ encode: encodeArgs({ ...RENDER, fps, crf }), fps, frames: frameCount(seconds, fps), version: "hf",
+ });
+ const base = key();
+ assert.match(base, /^[0-9a-f]{64}$/);
+ assert.equal(key(), base);
+ const changed = [
+ key({ style: "boot-wipe" }), key({ ground: "dark" }), key({ width: 1280, height: 720 }), key({ fps: 60 }),
+ key({ seconds: 5 }), key({ soundSha: "s2" }), key({ soundSha: null }), key({ crf: 23 }),
+ ];
+ for (const k of changed) assert.notEqual(k, base);
+ assert.equal(new Set(changed).size, changed.length);
+});
+
+test("rendered once: a cached intro is copied into the cut's segment, and a second build finds it unchanged", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "intro-"));
+ try {
+ const cacheDir = path.join(dir, "cache");
+ const outDir = path.join(dir, "out");
+ await mkdir(cacheDir, { recursive: true });
+ const entry = introEntry({ intro: { style: "boot", sound: false } });
+ const encode = encodeArgs(RENDER);
+ const html = introHtml({ style: "boot", ground: "light", seconds: entry.seconds, width: 1920, height: 1080, fps: 30, kit });
+ const k = introKey({ html, soundSha: null, encode, fps: 30, frames: frameCount(entry.seconds, 30), version: hyperframesCommand(process.env).version });
+ writeFileSync(path.join(cacheDir, `${k}.mp4`), "the rendered intro");
+ const notes = [];
+ const emit = (ev, f) => notes.push(f.message ?? ev);
+ const seg = await buildIntroSegment(entry, { render: RENDER, encode, outDir, manifestDir: dir, cacheDir, emit });
+ assert.equal(seg, path.join(outDir, "segments", `${INTRO_ID}.mp4`));
+ assert.equal(readFileSync(seg, "utf8"), "the rendered intro");
+ assert.equal(JSON.parse(readFileSync(introRecordPath(seg), "utf8")).key, k);
+ assert.match(notes.join("\n"), /intro from the cache/);
+ await buildIntroSegment(entry, { render: RENDER, encode, outDir, manifestDir: dir, cacheDir, emit });
+ assert.match(notes.at(-1), /intro segment unchanged/);
+ assert.ok(!existsSync(path.join(outDir, "chrome", `intro-${k.slice(0, 12)}`)), "nothing was rendered");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("a missing stand-in sound refuses the intro with the command that makes it", async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), "intro-"));
+ try {
+ const entry = introEntry({ intro: "boot" });
+ await assert.rejects(
+ buildIntroSegment(entry, { render: RENDER, encode: encodeArgs(RENDER), outDir: dir, cacheDir: dir, standin: path.join(dir, "none.wav") }),
+ /stand-in sound .* is not here .*extract-sound/,
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});