// THE CHANNEL PROMO (lane clip-kit, slice D): the card a per-clip build ends on, promoting the streamer it was // clipped from. DATA, not a drawing: the project says who and where (`render.promo`), one template draws it in 9:16 // and 16:9, and the clip's last seconds dissolve into it. // // render.promo { name: "Some Streamer" | ["Some", "Streamer"], one or two lines (≤ 24 characters each) // url: "https://kick.com/…", the channel's page, shown host + path // qr?: "https://…" | false, the code's link (default: url); false: none // portrait?: { file: "shots/….png", box?: [x, y, w, h] }, a picture of the project's, the circle cut // from `box` (fractions; default its centre) // kicker?: "…", a small line over the name (default: none) // palette?: { ground?, ink?, accent?, link?, plate? }, the card's colours over the cut's (#rrggbb) // lead?: 4.5, fade?: 0.7, hold?: 1.5, seconds (below) // captions?: true } the captions stay over the card // clip.promo false (this clip ends without it) | { lead?, fade?, hold? } over the cut's // // THE TIMING (the operator's accepted card, 13 Nov): the card starts `lead` seconds before the clip's end and fades in // over `fade`, the clip's own sound playing on under it; then it holds `hold` seconds in silence. A still: no push, // no zoom ("the promo screen is wiggling a bit"), no slam, no sting. // // THE CARD IS ONLY portrait, name, url and code (the operator: "drop the 'clipped from the stream of' text and 'live on // kick' to really keep it minimal"). A kicker is drawn only when the project gives one. // // THE CAPTIONS stay over the card for the seconds the clip still plays under it -- X autoplays muted, and the last // words are the ones a muted viewer would lose -- moved into a band the card keeps clear (promoBand). // // THE COLOURS are the cut's palette (`render.palette`: bg → ground, fg → ink, amber (else accent) → the ring and the // name's second line), `promo.palette` over them for the card alone; the url's host in its platform's colour (Kick's // green, …) unless `palette.link` says. The faces are the repository's own (Archivo, IBM Plex Sans; fonts/). // // The card is drawn by a browser (Playwright's chromium, as a post card is) from promoCardHtml, once per key, into the // build's cards dir. PURE above renderPromoCard. import { execFile } from "node:child_process"; import { createHash, randomBytes } from "node:crypto"; import { access, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; import { FONTS_DIR } from "./brand.mjs"; const execFileP = promisify(execFile); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); const q = (v) => JSON.stringify(v); export const PROMO_KEYS = Object.freeze(["name", "url", "qr", "portrait", "kicker", "palette", "lead", "fade", "hold", "captions"]); export const PROMO_CLIP_KEYS = Object.freeze(["lead", "fade", "hold"]); export const PROMO_PALETTE_KEYS = Object.freeze(["ground", "ink", "accent", "link", "plate"]); export const PROMO_TIMING = Object.freeze({ lead: Object.freeze({ min: 1, max: 10, default: 4.5 }), fade: Object.freeze({ min: 0.2, max: 2, default: 0.7 }), hold: Object.freeze({ min: 0, max: 5, default: 1.5 }), }); export const PROMO_NAME_LINE_MAX = 24; export const PROMO_KICKER_MAX = 40; /** The clip's sound fades out over its last this-many seconds, before the card's silence. */ export const PROMO_SOUND_OUT = 0.15; /** The code's quiet zone, in modules (the QR standard's four). */ export const PROMO_QR_QUIET = 4; /** A platform's own colour, for the url's host (the operator's card: Kick's green). */ export const PROMO_LINK_COLOURS = Object.freeze({ "kick.com": "#53fc18", "twitch.tv": "#a970ff", "youtube.com": "#ff4e45", "rumble.com": "#85c742" }); const IMAGE = /\.(png|jpe?g|webp)$/i; const HEX = /^#[0-9a-fA-F]{6}$/; /** A promo's name as its lines. */ export function nameLines(name) { if (Array.isArray(name)) return name.map((s) => String(s).trim()).filter(Boolean); const s = String(name ?? "").trim(); if (!s) return []; if (s.length <= PROMO_NAME_LINE_MAX / 2 || !s.includes(" ")) return [s]; // Two lines, broken at the space nearest the middle. const mid = s.length / 2; let best = -1; for (let i = s.indexOf(" "); i >= 0; i = s.indexOf(" ", i + 1)) if (best < 0 || Math.abs(i - mid) < Math.abs(best - mid)) best = i; return [s.slice(0, best), s.slice(best + 1)]; } /** Each thing wrong with `render.promo` ([] when fine, or absent). */ export function promoErrors(v, where = "render.promo") { if (v === undefined || v === null) return []; if (!isObj(v)) return [`${where} is {name, url, qr?, portrait?, kicker?, palette?, lead?, fade?, hold?, captions?}`]; const errors = []; for (const k of Object.keys(v)) if (!PROMO_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${PROMO_KEYS.join(", ")})`); const lines = nameLines(v.name); if (!(typeof v.name === "string" || (Array.isArray(v.name) && v.name.every((s) => typeof s === "string"))) || !lines.length || lines.length > 2 || lines.some((l) => l.length > PROMO_NAME_LINE_MAX)) { errors.push(`${where}.name is the channel's name: one or two lines of at most ${PROMO_NAME_LINE_MAX} characters`); } const https = (u) => typeof u === "string" && /^https?:\/\/[^\s]+$/.test(u); if (!https(v.url)) errors.push(`${where}.url is the channel's page, an http(s) link`); if (v.qr !== undefined && v.qr !== false && !https(v.qr)) errors.push(`${where}.qr is a link (http(s)) or false (no code); absent: the url`); if (v.portrait !== undefined) { const p = v.portrait; if (!isObj(p) || typeof p.file !== "string" || !p.file.trim() || path.isAbsolute(p.file) || p.file.split(/[\\/]/).includes("..") || !IMAGE.test(p.file)) { errors.push(`${where}.portrait is {file, box?}: a .png, .jpg or .webp of the project's, by its path in it (e.g. shots/still-w01-10650_20s.png)`); } else { for (const k of Object.keys(p)) if (!["file", "box", "from"].includes(k)) errors.push(`${where}.portrait.${k} is not a key (file, box, from)`); if (p.box !== undefined && !(Array.isArray(p.box) && p.box.length === 4 && p.box.every(num) && p.box[2] > 0 && p.box[3] > 0 && p.box[0] >= 0 && p.box[1] >= 0 && p.box[0] + p.box[2] <= 1.001 && p.box[1] + p.box[3] <= 1.001)) { errors.push(`${where}.portrait.box is [x, y, w, h], fractions of the picture inside it`); } } } if (v.kicker !== undefined && !(typeof v.kicker === "string" && v.kicker.trim() && v.kicker.length <= PROMO_KICKER_MAX)) errors.push(`${where}.kicker is a line of 1 to ${PROMO_KICKER_MAX} characters`); if (v.palette !== undefined) { if (!isObj(v.palette)) errors.push(`${where}.palette is {${PROMO_PALETTE_KEYS.join(", ")}}, each #rrggbb`); else for (const [k, c] of Object.entries(v.palette)) { if (!PROMO_PALETTE_KEYS.includes(k)) errors.push(`${where}.palette.${k} is not a colour of the card (${PROMO_PALETTE_KEYS.join(", ")})`); else if (!HEX.test(String(c))) errors.push(`${where}.palette.${k} is #rrggbb`); } } errors.push(...timingErrors(v, where)); if (v.captions !== undefined && typeof v.captions !== "boolean") errors.push(`${where}.captions is true (the captions stay over the card) or false`); return errors; } function timingErrors(v, where) { const errors = []; for (const [k, b] of Object.entries(PROMO_TIMING)) { if (v[k] !== undefined && !(num(v[k]) && v[k] >= b.min && v[k] <= b.max)) errors.push(`${where}.${k} is ${b.min}–${b.max} seconds`); } const lead = v.lead ?? PROMO_TIMING.lead.default; const fade = v.fade ?? PROMO_TIMING.fade.default; if (num(lead) && num(fade) && fade > lead) errors.push(`${where}.fade (${fade} s) is longer than its lead (${lead} s): the card would still be fading in at the clip's end`); return errors; } /** Each thing wrong with a clip's `promo` ([] when fine, or absent). */ export function clipPromoErrors(v, where = "clip.promo") { if (v === undefined || v === false) return []; if (!isObj(v)) return [`${where} is false (this clip ends without the card) or {${PROMO_CLIP_KEYS.join("?, ")}?}`]; const errors = []; for (const k of Object.keys(v)) if (!PROMO_CLIP_KEYS.includes(k)) errors.push(`${where}.${k} is not a key (${PROMO_CLIP_KEYS.join(", ")})`); return [...errors, ...timingErrors(v, where)]; } /** Every reason a manifest's promo cannot be drawn ([] when fine): the cut's and each clip's. */ export function validatePromo(manifest) { const errors = promoErrors(manifest?.render?.promo); for (const e of manifest?.timeline ?? []) { if (e?.promo === undefined) continue; if (e.type !== "clip") errors.push(`timeline ${e.id ?? "?"}: promo is a clip's`); else errors.push(...clipPromoErrors(e.promo, `timeline ${e.id}.promo`)); } return errors; } /** * The promo a clip ends on: null when the cut sets none or the clip says `promo: false`; else the cut's with the * clip's timing over it and the defaults under both. `seconds` (the clip's length as it plays) holds the lead inside * it: at most the clip's length less a second (said in `note`). */ export function promoOf(entry, render, seconds = Infinity) { const p = render?.promo; if (!isObj(p) || entry?.promo === false) return null; const own = isObj(entry?.promo) ? entry.promo : {}; const t = (k) => own[k] ?? p[k] ?? PROMO_TIMING[k].default; let lead = t("lead"); let note = null; if (Number.isFinite(seconds) && lead > seconds - 1) { const was = lead; lead = Math.max(0.5, Math.round((seconds - 1) * 100) / 100); note = `its card's lead is ${was} s, longer than the clip less a second: ${lead} s`; } return { ...p, lead, fade: Math.min(t("fade"), lead), hold: t("hold"), captions: p.captions !== false, note }; } /** "#rrggbb" mixed toward another by `t` (0–1). */ export function mixHex(a, b, t) { const h = (s) => [1, 3, 5].map((i) => parseInt(String(s).slice(i, i + 2), 16)); const [x, y] = [h(a), h(b)]; return `#${x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, "0")).join("")}`; } /** A url's host's own colour (PROMO_LINK_COLOURS), else null. */ export function linkColourOf(url) { try { const host = new URL(String(url)).hostname.toLowerCase().replace(/^(?:www|m)\./, ""); for (const [h, c] of Object.entries(PROMO_LINK_COLOURS)) if (host === h || host.endsWith(`.${h}`)) return c; } catch { // not a url: no platform colour } return null; } /** The card's colours: the cut's palette, the promo's over it. */ export function promoPalette(render, promo) { const pal = isObj(render?.palette) ? render.palette : {}; const ok = (c) => (HEX.test(String(c ?? "")) ? String(c) : null); const base = { ground: ok(pal.bg) ?? "#12100c", ink: ok(pal.fg) ?? "#f6f1e6", accent: ok(pal.amber) ?? ok(pal.accent) ?? "#f2a531", }; const own = isObj(promo?.palette) ? promo.palette : {}; const out = { ...base, ...Object.fromEntries(Object.entries(own).filter(([, c]) => ok(c))) }; out.link = ok(own.link) ?? linkColourOf(promo?.url) ?? out.accent; // The code's plate: WHITE whatever the palette (a scanner wants black on white), unless the promo names one. out.plate = ok(own.plate) ?? "#ffffff"; out.lift = mixHex(out.ground, out.accent, 0.12); return out; } /** The url as the card shows it: its host (with a "/" after it) and its path, no scheme, no trailing "/". */ export function urlParts(url) { try { const u = new URL(String(url)); const host = u.hostname.replace(/^www\./, ""); const rest = `${u.pathname}${u.search}`.replace(/\/$/, "").replace(/^\//, ""); return { host: rest ? `${host}/` : host, rest }; } catch { return { host: String(url ?? ""), rest: "" }; } } /** * Where a frame of `width`×`height` keeps its captions while the card is up (px from the top: `y0`, `y1`), and the * box the card's content keeps to: in a 9:16 frame the card stands in the upper safe area (the top 8 % kept) and the * captions in a band above the bottom 20 %; in a 16:9 one the band runs along the foot. `captions: false` gives the * card the whole safe area. */ export function promoBand({ width, height, captions = true }) { const vertical = height > width; const H = height; if (vertical) { const box = { x0: Math.round(width * 0.08), x1: Math.round(width * 0.88), y0: Math.round(H * 0.08), y1: Math.round(H * (captions ? 0.6 : 0.8)) }; return { vertical, box, band: captions ? { y0: Math.round(H * 0.62), y1: Math.round(H * 0.79) } : null }; } const box = { x0: Math.round(width * 0.06), x1: Math.round(width * 0.94), y0: Math.round(H * 0.06), y1: Math.round(H * (captions ? 0.74 : 0.94)) }; return { vertical, box, band: captions ? { y0: Math.round(H * 0.78), y1: Math.round(H * 0.93) } : null }; } const esc = (s) => String(s ?? "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); const cssUrl = (u) => String(u).replace(/'/g, "%27"); /** * The card's page (PURE): portrait in its ring, the name stacked (the second line in the accent), the url (its host in * the link colour), the code on a plate -- a row in 16:9, a column in 9:16, fitted (scaled down, never up) into the * band's content box. `portraitUrl`, `qrUrl` are file urls; `fonts` the faces' file urls. * * @param {{ promo: Record, width: number, height: number, palette: ReturnType, * portraitUrl?: string | null, qrUrl?: string | null, fonts: { display: string, text: string } }} o */ export function promoCardHtml({ promo, width, height, palette, portraitUrl = null, qrUrl = null, fonts }) { const { vertical, box } = promoBand({ width, height, captions: promo.captions !== false }); const vmin = Math.min(width, height) / 100; const px = (n) => `${Math.round(n * vmin)}px`; const lines = nameLines(promo.name); const { host, rest } = urlParts(promo.url); const sz = vertical ? { f: 38, h: 18, k: 3.3, u: 5.4, q: 23, gap: 4 } : { f: 38, h: 15.5, k: 2.5, u: 4.2, q: 21, gap: 6 }; const pb = Array.isArray(promo.portrait?.box) ? promo.portrait.box : null; return `
${portraitUrl ? `
` : ""}
${promo.kicker ? `
${esc(promo.kicker)}
` : ""}

${lines.map((l, i) => `${esc(l)}`).join("")}

${esc(host)}${esc(rest)}
${qrUrl ? `
` : ""}
`; } /** * The card's key: everything drawn (the page's inputs, the portrait's and the code's bytes, the size). */ export function promoCardKey({ html, portraitSha = null, qrText = null, width, height }) { return createHash("sha256").update(JSON.stringify({ v: 1, html, portraitSha, qrText, width, height })).digest("hex").slice(0, 20); } /** The faces the card is drawn in (the repository's own). */ export const PROMO_FONTS = Object.freeze({ display: path.join(/* turbopackIgnore: true */ FONTS_DIR, "Archivo[wdth,wght].ttf"), text: path.join(/* turbopackIgnore: true */ FONTS_DIR, "IBMPlexSans[wdth,wght].ttf") }); const exists = (p) => access(/* turbopackIgnore: true */ p).then(() => true, () => false); /** * Draw the card at `width`×`height`: `/promo-.png` (kept: the same card is not drawn again). The portrait is * read from `manifestDir`; the code drawn by qrencode. Returns `{file, key, cached, scale}`. * * @param {{ promo: Record, render: Record, width: number, height: number, dir: string, * manifestDir: string, loadChromium?: () => Promise }} o */ export async function renderPromoCard({ promo, render, width, height, dir, manifestDir, loadChromium = null }) { await mkdir(/* turbopackIgnore: true */ dir, { recursive: true }); const palette = promoPalette(render, promo); const portraitFile = promo.portrait?.file ? path.resolve(/* turbopackIgnore: true */ manifestDir, promo.portrait.file) : null; const portraitBytes = portraitFile ? await readFile(/* turbopackIgnore: true */ portraitFile).catch(() => null) : null; if (portraitFile && !portraitBytes) throw new Error(`render.promo.portrait ${promo.portrait.file}: not a file of the project`); const portraitSha = portraitBytes ? createHash("sha256").update(portraitBytes).digest("hex") : null; const qrText = promo.qr === false ? null : (promo.qr ?? promo.url); const fonts = { display: pathToFileURL(PROMO_FONTS.display).href, text: pathToFileURL(PROMO_FONTS.text).href }; // The page's own text with placeholder urls: the key reads what is drawn, not where this run keeps its files. const stable = promoCardHtml({ promo, width, height, palette, portraitUrl: portraitFile ? "portrait" : null, qrUrl: qrText ? "qr" : null, fonts: { display: "display", text: "text" } }); const key = promoCardKey({ html: stable, portraitSha, qrText, width, height }); const file = path.join(/* turbopackIgnore: true */ dir, `promo-${key}.png`); const meta = `${file}.json`; if ((await exists(file)) && (await exists(meta))) return { file, key, cached: true, ...JSON.parse(await readFile(/* turbopackIgnore: true */ meta, "utf8")) }; // Its own work dir per call (two draws of one card at once -- the page asks for both shapes together -- never share one). const work = path.join(/* turbopackIgnore: true */ dir, `.promo-${key}-${process.pid}-${randomBytes(4).toString("hex")}`); await mkdir(/* turbopackIgnore: true */ work, { recursive: true }); try { let qrUrl = null; if (qrText) { const qrPng = path.join(/* turbopackIgnore: true */ work, "qr.png"); // A real quiet zone: four modules of white inside the plate (the code's own margin), the plate's corners round. await execFileP(process.env.QRENCODE_BIN ?? "qrencode", ["-o", qrPng, "-s", "10", "-m", String(PROMO_QR_QUIET), "-l", "M", "--", qrText]); qrUrl = pathToFileURL(qrPng).href; } let portraitUrl = null; if (portraitBytes) { const ext = path.extname(portraitFile).toLowerCase(); const copy = path.join(/* turbopackIgnore: true */ work, `portrait${ext}`); await writeFile(/* turbopackIgnore: true */ copy, portraitBytes); portraitUrl = pathToFileURL(copy).href; } const html = promoCardHtml({ promo, width, height, palette, portraitUrl, qrUrl, fonts }); const page = path.join(/* turbopackIgnore: true */ work, "card.html"); await writeFile(/* turbopackIgnore: true */ page, html, "utf8"); const chromium = await (loadChromium ?? (await import("./post-render.mjs")).loadChromium)(); const browser = await chromium.launch({ headless: true }); let scale = 1; try { const ctx = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const p = await ctx.newPage(); await p.goto(pathToFileURL(page).href, { waitUntil: "load" }); await p.waitForSelector("body[data-promo-ready='1']", { timeout: 15000 }); scale = Number(await p.evaluate(() => document.body.dataset.promoScale)) || 1; const tmp = path.join(/* turbopackIgnore: true */ work, "card.png"); await p.screenshot({ path: tmp, clip: { x: 0, y: 0, width, height } }); await rename(/* turbopackIgnore: true */ tmp, file); } finally { await browser.close(); } const metaTmp = path.join(/* turbopackIgnore: true */ work, "meta.json"); await writeFile(/* turbopackIgnore: true */ metaTmp, JSON.stringify({ scale }) + "\n"); await rename(/* turbopackIgnore: true */ metaTmp, meta); return { file, key, cached: false, scale }; } finally { await rm(/* turbopackIgnore: true */ work, { recursive: true, force: true }); } } /** * The filtergraph parts that end a segment on the card (PURE): the picture `vIn` held `hold` seconds past its end * (its last frame cloned), the card (input `cardIdx`, a looped still) faded in from `seconds - lead` over `fade` and * laid over it; the sound `aIn` faded out over its last PROMO_SOUND_OUT seconds and silence for the hold. Returns the * parts and the pads they end on. */ export function promoFilterParts({ vIn, aIn, cardIdx, seconds, lead, fade, hold, fps }) { const at = Math.max(0, seconds - lead); const f = (n) => Number(n).toFixed(3); return { parts: [ `${vIn}tpad=stop_mode=clone:stop_duration=${f(hold)}[pmv]`, `[${cardIdx}:v]fps=${fps},format=rgba,fade=t=in:st=0:d=${f(fade)}:alpha=1,setpts=PTS+${f(at)}/TB[pmc]`, `[pmv][pmc]overlay=0:0:eof_action=pass:enable='gte(t,${f(at)})':format=auto[pmo]`, `${aIn}afade=t=out:st=${f(Math.max(0, seconds - PROMO_SOUND_OUT))}:d=${f(PROMO_SOUND_OUT)},apad=pad_dur=${f(hold)}[pma]`, ], v: "[pmo]", a: "[pma]", seconds: seconds + hold, at, }; } /** The card's input: the still looped for as long as it is up (its lead and its hold, a frame more). */ export const promoCardInput = ({ file, lead, hold, fps }) => ["-loop", "1", "-framerate", String(fps), "-t", (lead + hold + 1 / fps).toFixed(3), "-i", file];