// A REEL'S OWN INTRO, and the site the outro card names (operator, 5 Nov: // "actually I want intro in the trailer too"). // // `umtool trailer --reel ` with the reel's `intro` on opened on the // master's brand intro, and refused a take whose cut had none -- the X // trailer of a cut rendered without one could not have it. Now: // // - the reel's `intro` an OBJECT (render.intro's shape: `{style, mark, // site, …}`): that intro, rendered for the reel at the take's size, fps // and encode (intro.mjs renderIntro, through its cache), whatever the // master opens on; // - `true` and the master has a brand intro: the master's own frames, as // before (the cut is byte for byte what it was); // - `true` and the master has none: the take's `render.intro` rendered for // the reel, else REEL_INTRO_DEFAULT (the dark boot with the mark on the // chime, the site found from the cut's siteOrigin). // // The outro card's brand line is that intro's site (its name, lead and accent // on the dark ground), else the site the cut's siteOrigin names, else // Archilyzer. // // Plain ESM: the CLI runs it under bare node. import path from "node:path"; import { encodeArgs } from "./build-video.mjs"; import { INTRO_BRAND_DEFAULT, introEntry, introErrors, renderIntro, resolveIntroSite } from "./intro.mjs"; /** The intro a reel gets when it asks for one and neither it nor the take names one. */ export const REEL_INTRO_DEFAULT = Object.freeze({ style: "boot-dark", mark: "chime", site: "auto" }); class ReelIntroError extends Error {} /** Does the take's cut open on a brand intro (a segment of type "intro" in its schedule)? */ export function scheduleHasIntro(schedule) { return (schedule?.segments ?? []).some((s) => s?.type === "intro" || s?.id === "brand-intro"); } const describe = (entry) => `${entry.style}${entry.mark && entry.mark !== "none" ? `, mark ${entry.mark}` : ""}${entry.site ? `, site ${entry.site.name}` : ""}, ${entry.seconds} s`; /** * Which intro the reel opens on: `{ from: "master" | "reel" | "take" | "default", entry, label }`. * `entry` is intro.mjs introEntry's (for "master", the take's own render.intro, when it reads). * * @param {{ build: { schedule: any, render: any, manifest?: any }, introSpec?: unknown, sitesDir?: string }} o */ export function reelIntroOf({ build, introSpec = null, sitesDir = undefined }) { const provenance = build.manifest?.provenance ?? null; const entryOf = (spec, what) => { const errors = introErrors(spec); if (errors.length) throw new ReelIntroError(`${what}: ${errors.join("; ")}`); const e = introEntry({ ...build.render, intro: spec }, { provenance, manifest: build.manifest ?? null, ...(sitesDir ? { sitesDir } : {}) }); if (!e) throw new ReelIntroError(`${what}: not an intro`); return e; }; if (introSpec !== null && introSpec !== undefined && introSpec !== true) { const entry = entryOf(introSpec, "the reel's intro"); return { from: /** @type {const} */ ("reel"), entry, label: `the reel's own (${describe(entry)}), rendered for it` }; } if (scheduleHasIntro(build.schedule)) { let entry = null; try { entry = build.render?.intro ? entryOf(build.render.intro, "render.intro") : null; } catch { entry = null; } return { from: /** @type {const} */ ("master"), entry, label: "the master's own brand intro" }; } if (build.render?.intro) { const entry = entryOf(build.render.intro, "the take's render.intro"); return { from: /** @type {const} */ ("take"), entry, label: `the take's render.intro (${describe(entry)}), rendered for the reel -- the master has none` }; } const entry = entryOf({ ...REEL_INTRO_DEFAULT }, "the default intro"); return { from: /** @type {const} */ ("default"), entry, label: `the default intro (${describe(entry)}), rendered for the reel -- the master has none` }; } /** * The intro rendered at the take's size, fps and encode: the cached file's path. * @param {{ entry: any, build: { render: any }, takeDir: string }} o */ export async function renderReelIntro({ entry, build, takeDir }) { const r = await renderIntro({ entry, render: build.render, encode: encodeArgs(build.render), manifestDir: takeDir, workDir: path.join(takeDir, "out", "sourced", "chrome"), }); return r.path; } /** * The outro card's brand line: `{ name, lead, ink }` -- the intro's site, else * the site the cut's siteOrigin names, else Archilyzer; its accent on the dark ground. * * @param {any} entry introEntry's, or null * @param {{ provenance?: any, sitesDir?: string }} [o] */ export async function outroBrand(entry, { provenance = null, sitesDir = undefined } = {}) { let site = entry?.site ?? null; if (!site) { try { site = resolveIntroSite("auto", { siteOrigin: provenance?.siteOrigin ?? null, ...(sitesDir ? { sitesDir } : {}) }); } catch { site = null; } } const { introAccent, introPalette } = await import("./chrome-intro.mjs"); const { brandKit } = await import("./brand.mjs"); const palette = introPalette("dark", brandKit(entry?.brand ?? INTRO_BRAND_DEFAULT)); if (!site) return { name: "Archilyzer", lead: "Archi", ink: introAccent("signal", "dark", palette).ink }; return { name: site.name, ...(site.lead ? { lead: site.lead } : {}), ink: introAccent(site.accent ?? "signal", "dark", palette).ink }; } export { ReelIntroError }; /** * The ffmpeg argv that puts a reel's intro before a finished short and its * outro card after it, in one pass (`umtool vertical`, 9:16): the intro * crossfaded into the short over `xfade` (0: a hard cut), the card faded in * over its last `fade` seconds and held (outro.mjs outroFilterParts). Pure. * * @param {{ short: string, shortSeconds: number, intro?: { file: string, seconds: number } | null, * outro?: { png: string, seconds: number, fade?: number } | null, fps: number, xfade?: number, * render?: Record, encode: string[], out: string, escape: (f: string) => string, * outroParts: (o: any) => { parts: string[], vOut: string, aOut: string } }} o */ export function wrapShortArgs({ short, shortSeconds, intro = null, outro = null, fps, xfade = 0.3, render = {}, encode, out, escape, outroParts }) { const rate = render.audioRate ?? 48000; const layout = render.audioChannels === 1 ? "mono" : "stereo"; const norm = (lab, file) => [ `movie=filename=${escape(file)}:streams=dv+da[${lab}v0][${lab}a0]`, `[${lab}v0]fps=${fps},format=yuv420p,setsar=1,settb=AVTB[${lab}v]`, `[${lab}a0]aresample=${rate},aformat=channel_layouts=${layout}[${lab}a]`, ]; const parts = [...norm("s", short)]; let v = "[sv]"; let a = "[sa]"; let seconds = shortSeconds; if (intro) { const n = Math.round(intro.seconds * fps); const d = (n / fps).toFixed(6); parts.push(...norm("i", intro.file)); parts.push(`[iv]trim=end_frame=${n},setpts=PTS-STARTPTS[ivt]`, `[ia]atrim=end=${d},asetpts=PTS-STARTPTS,apad=whole_dur=${d},atrim=end=${d}[iat]`); if (xfade > 0) { parts.push(`[ivt][sv]xfade=transition=fade:duration=${xfade.toFixed(6)}:offset=${(n / fps - xfade).toFixed(6)}[wv]`, `[iat][sa]acrossfade=d=${xfade.toFixed(6)}:c1=tri:c2=tri[wa]`); seconds = n / fps + shortSeconds - xfade; } else { parts.push(`[ivt][iat][sv][sa]concat=n=2:v=1:a=1[wv][wa]`); seconds = n / fps + shortSeconds; } v = "[wv]"; a = "[wa]"; } if (outro) { const o = outroParts({ png: outro.png, seconds: outro.seconds, fade: outro.fade, fps, cutSeconds: seconds, vIn: v, aIn: a, audioRate: rate, audioChannels: render.audioChannels ?? 2, escape }); parts.push(...o.parts); v = o.vOut; a = o.aOut; } return ["-nostdin", "-v", "error", "-y", "-filter_complex", parts.join(";"), "-map", v, "-map", a, "-map_metadata", "-1", ...encode, "-movflags", "+faststart", out]; } /** * A finished short with the reel's intro before it and its outro card after * it: the intro rendered at the short's size (1080x1920; its drawing centred * in the safe area, chrome-intro.mjs), the card drawn at it (outro.mjs, inside * the safe area), joined in one pass, written beside and renamed over `file`. * Returns what was added (`{ intro, outro }`, each null when not asked). * * @param {{ file: string, takeDir: string, render: Record, manifest?: any, introSpec?: unknown, * outro?: { title: string, text: string, image?: string | null, imageFile?: string | null, seconds: number } | null, * xfade?: number, sitesDir?: string, log?: (s: string) => void, endCard?: { qrUrl?: string | null, sources?: Array<{ date: string, label: string }> } | null }} o */ export async function wrapShort({ file, takeDir, render, manifest = null, introSpec = null, outro = null, xfade = 0.3, sitesDir = undefined, log = () => {}, endCard = null }) { if (!introSpec && !outro) return { intro: null, outro: null }; const { execFile } = await import("node:child_process"); const { promisify } = await import("node:util"); const { rename, rm } = await import("node:fs/promises"); const execFileP = promisify(execFile); const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; const { filterPath } = await import("./trailer.mjs"); const { OUTRO_FADE, outroFilterParts, renderOutroCard } = await import("./outro.mjs"); const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,nb_frames:format=duration", "-of", "json", file]); const j = JSON.parse(stdout); const W = Number(j.streams?.[0]?.width) || 1080; const H = Number(j.streams?.[0]?.height) || 1920; const fps = render.fps ?? 30; const frames = Number(j.streams?.[0]?.nb_frames); const shortSeconds = Number.isFinite(frames) && frames > 0 ? frames / fps : Number(j.format?.duration); const vr = { ...render, width: W, height: H }; // The short's intro: never the master's 16:9 frames -- the reel's own, else the take's render.intro, else the default. let ri = null; if (introSpec) ri = reelIntroOf({ build: { schedule: null, render: vr, manifest }, introSpec: introSpec === true ? null : introSpec, sitesDir }); let introFile = null; if (ri) { log(`vertical: intro ${ri.label.replace(/, rendered for (it|the reel).*$/, "")} at ${W}x${H} …`); introFile = (await renderIntro({ entry: ri.entry, render: vr, encode: encodeArgs(vr), manifestDir: takeDir, workDir: path.join(takeDir, "out", "sourced", "chrome") })).path; } let card = null; if (outro) { const brand = await outroBrand(ri?.entry ?? null, { provenance: manifest?.provenance ?? null, sitesDir }); // A 9:16 card with somewhere to go is the end card (outro.mjs): the QR, the host, the short's sources. const r = await renderOutroCard({ width: W, height: H, title: outro.title, text: outro.text, imageFile: outro.imageFile ?? null, brand, dir: path.join(takeDir, "out", "sourced", "outro"), ...(endCard && H > W ? { qrUrl: endCard.qrUrl ?? null, sources: endCard.sources ?? null } : {}), }); card = { png: r.file, seconds: outro.seconds, fade: OUTRO_FADE }; log(`vertical: outro card ${r.cached ? "(drawn before)" : "drawn"} -- "${outro.title}"`); } const tmp = path.join(path.dirname(file), `.${path.basename(file, ".mp4")}.${process.pid}.wrap.mp4`); const argv = wrapShortArgs({ short: file, shortSeconds, intro: introFile ? { file: introFile, seconds: ri.entry.seconds } : null, outro: card, fps, xfade, render: vr, encode: encodeArgs(vr), out: tmp, escape: filterPath, outroParts: outroFilterParts, }); try { await execFileP(FFMPEG, argv, { maxBuffer: 1 << 26 }); await rename(tmp, file); } finally { await rm(tmp, { force: true }); } return { intro: ri ? { from: ri.from, style: ri.entry.style, site: ri.entry.site?.name ?? null, seconds: ri.entry.seconds, file: introFile } : null, outro: card ? { title: outro.title, text: outro.text, image: outro.image ?? null, seconds: card.seconds, fade: card.fade, card: card.png } : null, }; }