#!/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?, mark?, sound?, seconds?, // site?, swap?, url?, urlPlace? }) // // THE SITE. `site: "auto"` names the archive the cut cites -- the site whose // site.json `siteUrl` is the manifest's `provenance.siteOrigin` (the Huck cut: // https://jeralyzer.pages.dev, so Jeralyzer) -- and `site: ""` names one // outright; both are read here, once, from SITES_DIR (umtool/lib/paths.mjs), // into the object form `{ name, lead, accent, url }` the page draws from, so // the entry (and the cache key, through the page) carries what was drawn, not // a lookup. Nothing matched: no swap, and the intro is the plain one. // // 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 `. // 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: ""` (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, mark, size, fps, // length), the sound's bytes and the encode's parameters -- as // `/.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] [--mark none|draw|chime] [--seconds 4.18] // [--site auto||'{"name":"Jeralyzer","accent":"brass"}' [--site-origin ] // [--swap swipe-down|roll|wipe] [--url both|site|project|false] [--url-place under|replace]] // [--title T] [--line L …] [--sound | --silent] [--width 1920 --height 1080 --fps 30] --out // node intro.mjs extract-sound // `render` takes the heavy slot (heavy-gate.mjs) unless HEAVY=0. import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { readFileSync, readdirSync } from "node:fs"; 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_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_SITE_DEFAULTS, INTRO_STYLE_GROUND, INTRO_STYLE_MARK, INTRO_STYLES, INTRO_SUFFIX, INTRO_SWAPS, INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf, introSitePrefix, introUrlText, validateIntro, } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { SITES_DIR } from "../lib/paths.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { INTRO_BEATS, INTRO_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_SITE_DEFAULTS, INTRO_STYLE_GROUND, INTRO_STYLE_MARK, INTRO_STYLES, INTRO_SUFFIX, INTRO_SWAPS, INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf, introSitePrefix, introUrlText, 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 site (`render.intro.site`) // --------------------------------------------------------------------------- /** A URL's origin, lowercased, for matching a siteOrigin to a siteUrl; null for anything not http(s). */ function originOf(u) { try { const url = new URL(String(u ?? "").trim()); return /^https?:$/.test(url.protocol) ? url.origin.toLowerCase() : null; } catch { return null; } } /** One site.json read for the intro: its title, wordmark lead, accent and public URL, nothing else. */ function readSite(sitesDir, id) { let j; try { j = JSON.parse(readFileSync(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ sitesDir, id, "site.json"), "utf8")); } catch { return null; } const name = typeof j.siteTitle === "string" && j.siteTitle.trim() ? j.siteTitle.trim() : null; if (!name) return null; return { id, name, ...(typeof j.wordmarkLead === "string" && j.wordmarkLead.trim() ? { lead: j.wordmarkLead.trim() } : {}), ...(typeof j.accent === "string" && j.accent.trim() ? { accent: j.accent.trim() } : {}), ...(originOf(j.siteUrl) ? { url: introUrlText(j.siteUrl) } : {}), origin: originOf(j.siteUrl), }; } /** The site ids under `sitesDir` (each a directory with a site.json), sorted. */ function siteIds(sitesDir) { try { return readdirSync(/* turbopackIgnore: true */ sitesDir, { withFileTypes: true }) .filter((d) => d.isDirectory() && !d.name.startsWith("_") && !d.name.startsWith(".")) .map((d) => d.name) .sort(); } catch { return []; } } /** * `render.intro.site` as the page draws it: `{ name, lead?, accent?, url? }`, * or null for no swap. `auto` is the site whose siteUrl is `siteOrigin` (none: * null); an id is that site's site.json, and one that is not there is refused * by name; the object form is kept as written (its `url` without a scheme). * A site.json is read for its title, lead, accent and URL only. * * @param {unknown} site * @param {{ siteOrigin?: string | null, sitesDir?: string }} [o] * @returns {null | { id?: string, name: string, lead?: string, accent?: string, url?: string | false }} */ export function resolveIntroSite(site, { siteOrigin = null, sitesDir = SITES_DIR } = {}) { if (site === undefined || site === null || site === "none") return null; if (typeof site === "object") { const { name, lead, accent, url } = site; return { name: String(name).trim(), ...(typeof lead === "string" ? { lead: lead.trim() } : {}), ...(typeof accent === "string" ? { accent: accent.trim() } : {}), ...(url === false ? { url: false } : typeof url === "string" ? { url: introUrlText(url) } : {}), }; } const strip = (r) => { if (!r) return null; const { origin, ...rest } = r; return rest; }; if (site === "auto") { const want = originOf(siteOrigin); if (!want) return null; for (const id of siteIds(sitesDir)) { const r = readSite(sitesDir, id); if (r?.origin === want) return strip(r); } return null; } const r = readSite(sitesDir, site); if (!r) { const ids = siteIds(sitesDir); throw new Error( `render.intro.site ${JSON.stringify(site)} is not a site in ${sitesDir}` + (ids.length ? ` — one of ${ids.join(", ")}, or "auto"` : ` (no sites there) — use "auto" or {name, accent, url}`), ); } return strip(r); } const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; /** `YYYY-MM-DD` (a manifest's `generatedOn`) in words, "29 October 2026"; null for anything else. */ export function introDateWords(v) { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v ?? "")); if (!m || Number(m[2]) < 1 || Number(m[2]) > 12) return null; return `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]}`; } /** * The words an intro draws: its own `title` and `lines` when written; on * title-card, unwritten, the project's title (the manifest's `title`) and its * date in words (`generatedOn`) -- "project title + date over the brand". * A boot style draws words only when they are written. * * @param {{ style: string, title?: string, lines?: string[] }} o introOf's * @param {{ title?: unknown, generatedOn?: unknown } | null} [manifest] * @returns {{ title?: string, lines?: string[] }} */ export function introWords(o, manifest = null) { const card = o.style === "title-card"; // The manifest's title as ONE line of at most 80 characters (code points): a title written over two lines // would preview but be refused by the build's own check (introErrors) at render time. const fromManifest = card && typeof manifest?.title === "string" ? Array.from(manifest.title.replace(/\s+/g, " ").trim()).slice(0, 80).join("").trim() : ""; const title = o.title ?? (fromManifest || undefined); const date = card ? introDateWords(manifest?.generatedOn) : null; const lines = o.lines ?? (date ? [date] : undefined); return { ...(title ? { title } : {}), ...(lines && lines.length ? { lines } : {}) }; } /** * 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. * `provenance` (the manifest's) is what `site: "auto"` reads its siteOrigin from; * `manifest` (its title, its `generatedOn`) is what title-card's words default to. * * @param {any} render * @param {{ provenance?: any, sitesDir?: string, manifest?: any }} [o] */ export function introEntry(render, { provenance = null, sitesDir = SITES_DIR, manifest = null } = {}) { if (introErrors(render?.intro).length) return null; const o = introOf(render); if (!o) return null; const site = o.site ? resolveIntroSite(o.site, { siteOrigin: provenance?.siteOrigin ?? null, sitesDir }) : null; const words = introWords(o, manifest); return { type: INTRO_TYPE, id: INTRO_ID, style: o.style, ground: o.ground, mark: o.mark, seconds: o.seconds, ...(o.sound !== undefined ? { sound: o.sound } : {}), // The brand's knobs, only when set (introOf): the plain intro's entry otherwise. ...(o.brand !== undefined ? { brand: o.brand } : {}), ...(o.suffix !== undefined ? { suffix: o.suffix } : {}), ...(o.projectUrl !== undefined ? { projectUrl: o.projectUrl } : {}), // The site's swap, resolved: only when one was found, so an intro with no // site (or an "auto" that matched none) is the plain intro's entry. ...(site ? { site, swap: o.swap, url: o.url, urlPlace: o.urlPlace } : {}), // The words (title-card's, or under a boot style's wordmark): only when there are any. ...words, // A placeholder's words (umtool's Play view, the deck's table). heading: "Intro", }; } /** The object form of a resolved site (its id dropped): what the validator and the page read. */ const siteObject = (site) => { const { id, ...rest } = site; return rest; }; /** The brand kit the intro draws (`render.intro.brand`), refused by the intro's own key. */ function introKit(brandKit, id) { try { return brandKit(id); } catch (e) { throw new Error(String(e?.message ?? e).replace(/^render\.brand /, "render.intro.brand ")); } } /** * The page's site knobs from an entry: `{ site, swap, url, urlPlace }` with the * defaults filled in, or null (no site: introHtml is called exactly as before). */ export function introSiteKnobs(entry) { if (!entry?.site) return null; return { site: entry.site, swap: entry.swap ?? INTRO_SITE_DEFAULTS.swap, url: entry.url ?? INTRO_SITE_DEFAULTS.url, urlPlace: entry.urlPlace ?? INTRO_SITE_DEFAULTS.urlPlace, }; } /** 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, { sitesDir = SITES_DIR } = {}) { const entry = introEntry(manifest?.render, { provenance: manifest?.provenance ?? null, sitesDir, manifest }); 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(/* turbopackIgnore: true */ 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 `, 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(/* turbopackIgnore: true */ 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(/* turbopackIgnore: true */ env.XDG_CACHE_HOME || path.join(/* turbopackIgnore: true */ 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's page for an entry (introEntry's) at a render's size and fps: * what renderIntro renders and keys, and what umtool's Play and the Cut tab's * intro editor preview (lib/report/onscreen.mjs composeIntroPreview) -- one * call, so the preview is the page the build renders. * * @param {Record} entry * @param {Record} render */ export async function introPageHtml(entry, render, { gsapSrc } = {}) { const { introHtml } = await import("./chrome-intro.mjs"); const { brandKit } = await import("./brand.mjs"); const siteKnobs = introSiteKnobs(entry); return introHtml({ style: entry.style, ground: entry.ground, ...(entry.mark !== undefined ? { mark: entry.mark } : {}), seconds: entry.seconds, width: render.width ?? 1920, height: render.height ?? 1080, fps: render.fps ?? 30, kit: introKit(brandKit, entry.brand ?? INTRO_BRAND_DEFAULT), ...(siteKnobs ?? {}), ...(entry.suffix !== undefined ? { suffix: entry.suffix } : {}), ...(entry.projectUrl !== undefined ? { projectUrl: entry.projectUrl } : {}), ...(entry.title !== undefined ? { title: entry.title } : {}), ...(entry.lines !== undefined ? { lines: entry.lines } : {}), ...(gsapSrc ? { gsapSrc } : {}), }); } /** * The intro's page written as a project a browser can open: `dir/` * (introPageHtml's, `extraScript` before its `` -- Play's seek, the * preview's only), GSAP and, when the page draws words, their face under * `dir/assets/`. What umtool's previews serve (lib/report/onscreen.mjs * composeIntroPreview); no render. * * @param {string} dir * @param {Record} entry introEntry's * @param {Record} render * @param {{ file?: string, extraScript?: string }} [opts] * @returns {Promise<{ file: string, html: string }>} */ export async function writeIntroPage(dir, entry, render, { file = "index.html", extraScript = "" } = {}) { const { INTRO_FONT_FILE, INTRO_FONT_ASSET } = await import("./chrome-intro.mjs"); const { GSAP_FILE } = await import("./chrome-deck.mjs"); const html = await introPageHtml(entry, render); await mkdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "assets"), { recursive: true }); const gsap = path.join(/* turbopackIgnore: true */ dir, "assets", "gsap.min.js"); if (!(await exists(gsap))) await copyFile(/* turbopackIgnore: true */ GSAP_FILE, gsap); if (entry.title || entry.lines?.length) { const face = path.join(/* turbopackIgnore: true */ dir, INTRO_FONT_ASSET); if (!(await exists(face))) await copyFile(/* turbopackIgnore: true */ INTRO_FONT_FILE, face); } const at = html.lastIndexOf(""); const page = !extraScript ? html : at < 0 ? html + extraScript : `${html.slice(0, at)}${extraScript}\n ${html.slice(at)}`; const out = path.join(/* turbopackIgnore: true */ dir, file); const tmp = tmpPathFor(out); await writeFile(/* turbopackIgnore: true */ tmp, page, "utf8"); await rename(tmp, out); return { file: out, html }; } /** * 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 siteKnobs = introSiteKnobs(entry); const errors = introErrors({ style: entry.style, ground: entry.ground, seconds: entry.seconds, ...(entry.mark !== undefined ? { mark: entry.mark } : {}), ...(entry.sound !== undefined ? { sound: entry.sound } : {}), ...(entry.brand !== undefined ? { brand: entry.brand } : {}), ...(entry.suffix !== undefined ? { suffix: entry.suffix } : {}), ...(entry.projectUrl !== undefined ? { projectUrl: entry.projectUrl } : {}), ...(entry.title !== undefined ? { title: entry.title } : {}), ...(entry.lines !== undefined ? { lines: entry.lines } : {}), ...(siteKnobs ? { site: siteObject(siteKnobs.site), swap: siteKnobs.swap, urlPlace: siteKnobs.urlPlace, url: siteKnobs.url === "none" ? false : siteKnobs.url, } : {}), }); if (errors.length) throw new Error(errors.join("; ")); const { INTRO_FONT_FILE, INTRO_FONT_ASSET } = await import("./chrome-intro.mjs"); const { hyperframesCommand, frameCount } = await import("./deck.mjs"); const fps = render.fps ?? 30; const html = await introPageHtml(entry, render); const sound = introSoundPath(entry, manifestDir, standin); let soundSha = null; if (sound) { const bytes = await readFile(/* turbopackIgnore: true */ 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(/* turbopackIgnore: true */ cacheDir, `${key}.mp4`); if (await exists(cached)) return { path: cached, key, cached: true }; const t0 = Date.now(); const proj = path.join(/* turbopackIgnore: true */ workDir, `intro-${key.slice(0, 12)}`); const framesDir = path.join(/* turbopackIgnore: true */ workDir, `intro-${key.slice(0, 12)}-frames`); await rm(proj, { recursive: true, force: true }); await rm(framesDir, { recursive: true, force: true }); await mkdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ proj, "assets"), { recursive: true }); const { HF_JSON, runHyperframes } = await import("./compose-chrome.mjs"); const { GSAP_FILE } = await import("./chrome-deck.mjs"); await copyFile(/* turbopackIgnore: true */ GSAP_FILE, path.join(/* turbopackIgnore: true */ proj, "assets", "gsap.min.js")); // The words' face, when the page draws words (introHtml links it only then). if (entry.title || entry.lines?.length) await copyFile(/* turbopackIgnore: true */ INTRO_FONT_FILE, path.join(/* turbopackIgnore: true */ proj, INTRO_FONT_ASSET)); await writeFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ proj, "index.html"), html, "utf8"); await writeFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ proj, "hyperframes.json"), HF_JSON + "\n", "utf8"); await runHyperframes(hf, [ "render", "--format", "png-sequence", "--quality", "high", "--fps", String(fps), "-w", String(workers), "--no-browser-gpu", "--output", framesDir, proj, ]); const got = (await readdir(/* turbopackIgnore: true */ 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 = tmpPathFor(path.join(/* turbopackIgnore: true */ cacheDir, `.${key}`), { ext: ".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/.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(/* turbopackIgnore: true */ 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(/* turbopackIgnore: true */ 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(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), { recursive: true }); const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), `.${entry.id}`), { ext: ".mp4" }); try { await copyFile(r.path, tmp); await rename(tmp, seg); } finally { await rm(tmp, { force: true }); } const recTmp = tmpPathFor(recPath); await writeFile(/* turbopackIgnore: true */ recTmp, JSON.stringify({ key: r.key, style: entry.style, ground: entry.ground, mark: entry.mark, seconds: entry.seconds, ...(entry.site ? { site: entry.site.name, swap: entry.swap } : {}), 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 [--out ]"); const out = flag("--out") ?? INTRO_STANDIN_SOUND; await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ 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] [--mark " + INTRO_MARKS.join("|") + "]\n" + " [--seconds s] [--site auto|| [--site-origin ] [--swap " + INTRO_SWAPS.join("|") + "]\n" + " [--url " + INTRO_URLS.join("|") + "|false] [--url-place " + INTRO_URL_PLACES.join("|") + "]]\n" + " [--title T] [--line L …] [--sound | --silent] [--width 1920 --height 1080 --fps 30] --out \n" + " intro.mjs extract-sound [--out ]", ); return 2; } const out = flag("--out"); if (!out) throw new Error("render: --out is required"); const intro = { style: flag("--style"), ...(flag("--ground") ? { ground: flag("--ground") } : {}), ...(flag("--mark") ? { mark: flag("--mark") } : {}), ...(flag("--seconds") ? { seconds: Number(flag("--seconds")) } : {}), ...(flag("--site") ? { site: flag("--site").trim().startsWith("{") ? JSON.parse(flag("--site")) : flag("--site") } : {}), ...(flag("--swap") ? { swap: flag("--swap") } : {}), ...(flag("--url") ? { url: flag("--url") === "false" ? false : flag("--url") === "true" ? true : flag("--url") } : {}), ...(flag("--url-place") ? { urlPlace: flag("--url-place") } : {}), ...(flag("--title") ? { title: flag("--title") } : {}), ...(rest.includes("--line") ? { lines: rest.flatMap((a, i) => (a === "--line" && rest[i + 1] !== undefined ? [rest[i + 1]] : [])) } : {}), ...(rest.includes("--silent") ? { sound: false } : flag("--sound") ? { sound: path.resolve(/* turbopackIgnore: true */ 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, { provenance: flag("--site-origin") ? { siteOrigin: flag("--site-origin") } : null }); if (!entry) throw new Error(introErrors(intro).join("; ")); if (intro.site && intro.site !== "none" && !entry.site) console.error(`site ${JSON.stringify(intro.site)}: no site matched — the plain intro`); const { encodeArgs } = await import("./build-video.mjs"); const run = async () => { const workDir = path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ 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(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ out)), { recursive: true }); await copyFile(r.path, out); const site = entry.site ? `, site ${entry.site.name} ${entry.swap} url ${entry.url} ${entry.urlPlace}` : ""; console.log(`${entry.style} (${entry.ground}, mark ${entry.mark}${site}) -> ${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); }); }