// THE COMBO BADGE, RENDERED (post-combo.mjs): a pass over a post item's // finished segment (post-render.mjs builds it, untouched by this) that lays // the badge's frames over the attachment's corner from the moment the // attachment starts, and its sound, when one is asked for, into the mix. // // The frames are the SAME markup Play draws (comboBadgeHtml), moved by the // same motion (comboFrame), shot by a browser on a transparent page, one PNG // per frame of the badge's 2.6 s (a frame that equals the one before is a // copy, not a shot). A separate pass, so the badge's count can change -- an // item earlier in the cut gains the attachment -- without the card being // drawn again: // // segments/.mp4 the item as the build plays it (the badge on it) // segments/.plain.mp4 the item without it (post-render's), kept to lay a new count over // segments/.combo.json what the badge was laid from (the key), and which file is which // // applyPostCombo(seg, ctx) the pass (or nothing: no combo on this item) // comboPassArgs(...) its ffmpeg argv, PURE (the tests read it) import { createHash } from "node:crypto"; import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { COMBO_TIMING, comboBadgeHtml, comboFrame, comboPlace, comboStart, comboTransform } from "./post-combo.mjs"; import { panelEntry, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; import { LIMITED_RANGE } from "./color-range.mjs"; import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); /** A bundled sound's file (`sfx`: hit, coin), or null for `off`. */ export const comboSfxFile = (name) => (name && name !== "off" ? path.join(/* turbopackIgnore: true */ HERE, "assets", "combo", `${name}.wav`) : null); export const comboRecordPath = (seg) => seg.replace(/\.mp4$/, ".combo.json"); export const comboPlainPath = (seg) => seg.replace(/\.mp4$/, ".plain.mp4"); /** * WHERE AND WHEN, pure: the badge for item `entry` with `combo` (comboCounts' * `{ count, media, knobs, show }`) in a box of `box` (`{ x?, y?, width, * height }`, the footage box in the frame): `{ at, place, frames }` -- the * item second it pops, its place (comboPlace, in the box's px), the frame * count -- or null when it draws none (off, under minCount, its attachment * never plays). */ export function comboPlan(entry, combo, { box, render }) { if (!combo?.show) return null; const plan = postItemPlan(entry, render); const at = comboStart(plan, combo.media); if (at === null || at >= plan.total - 0.05) return null; const step = plan.steps.find((s) => s.items.some((m) => m.i === combo.media)); const layout = postLayout(panelEntry(entry, render), box); if (!layout.slot) return null; const boxes = stepBoxes(step, layout.slot); const mb = boxes[step.items.findIndex((m) => m.i === combo.media)] ?? boxes[0]; const place = comboPlace(combo.count, combo.knobs, mb, box); const fps = render.fps ?? 30; // The badge's life, cut at the item's end. const frames = Math.max(1, Math.ceil(Math.min(COMBO_TIMING.end, plan.total - at) * fps)); return { at, place, frames, total: plan.total }; } /** * The pass, pure: the plain segment, the badge's frames from `at` at * (`x`, `y`) of the frame, the sound (`sfx`, a file) at `at` into its mix -- * else its audio copied as it is. * * @returns {string[]} */ export function comboPassArgs({ plain, frames, fps, at, x, y, sfx = null, encode = [], audioRate = 48000, outPath }) { const end = at + COMBO_TIMING.end; const parts = [ `[1:v]format=rgba,setpts=PTS-STARTPTS+${num(at)}/TB[cb]`, `[0:v][cb]overlay=x=${Math.round(x)}:y=${Math.round(y)}:eof_action=pass:format=auto:enable='between(t,${num(at)},${num(end)})',format=yuv420p[v]`, ]; const inputs = ["-i", plain, "-framerate", String(fps), "-i", frames]; if (sfx) { inputs.push("-i", sfx); const ms = Math.round(at * 1000); parts.push(`[2:a]aresample=${audioRate},aformat=channel_layouts=stereo,volume=0.8,adelay=${ms}|${ms}[sx]`, `[0:a][sx]amix=inputs=2:normalize=0:duration=first[a]`); } return [ "-nostdin", "-v", "error", "-y", ...inputs, "-filter_complex", parts.join(";"), "-map", "[v]", "-map", sfx ? "[a]" : "0:a", ...encode, // Limited range, as the item under it (color-range.mjs). ...LIMITED_RANGE, ...(sfx ? [] : ["-c:a", "copy"]), outPath, ]; } async function loadChromium() { const mod = await import("@playwright/test"); const chromium = mod.chromium ?? mod.default?.chromium; if (!chromium) throw new Error("Playwright loaded but has no chromium export"); return chromium; } /** * Shoot the badge's frames into `dir` (`f0000.png` …): a transparent page * the region's size, the badge centred where it sits, each frame's motion * set and shot. Returns the pattern ffmpeg reads. */ export async function shootComboFrames({ count, knobs, place, frames, fps, dir, font = "" }) { await rm(dir, { recursive: true, force: true }); await mkdir(dir, { recursive: true }); const { region, size, center, mirror } = place; const k = size.k; const left = r3(center.x - region.x - size.width / 2); const top = r3(center.y - region.y - size.height / 2); const html = `
${comboBadgeHtml(count, knobs, size, { font })}
`; const page0 = path.join(dir, "badge.html"); await writeFile(page0, html, "utf8"); const chromium = await loadChromium(); const browser = await chromium.launch({ headless: true }); try { const ctx = await browser.newContext({ viewport: { width: region.width, height: region.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" }); const page = await ctx.newPage(); await page.goto(pathToFileURL(page0).href, { waitUntil: "load" }); await page.waitForSelector("body[data-ready='1']", { timeout: 15000 }); let last = null; let lastFile = null; for (let f = 0; f < frames; f += 1) { const fr = comboFrame(f / fps, { mirror }) ?? { scale: 1, x: 0, y: 0, rotate: 0, opacity: 0 }; const tr = comboTransform(fr, k); const file = path.join(dir, `f${String(f).padStart(4, "0")}.png`); const sig = `${tr}|${fr.opacity}`; if (sig === last && lastFile) await copyFile(lastFile, file); else { await page.evaluate(([t, o]) => /** @type {any} */ (window).setFrame(t, o), [tr, fr.opacity]); await page.screenshot({ path: file, omitBackground: true, clip: { x: 0, y: 0, width: region.width, height: region.height } }); last = sig; lastFile = file; } } await ctx.close(); } finally { await browser.close(); } return path.join(dir, "f%04d.png"); } const sigOf = (st) => (st ? `${st.size}:${Math.round(st.mtimeMs)}` : null); /** * THE PASS over post item `entry`'s segment `seg`. `ctx`: `{ combo, render, * outDir, box, encode, exec, ffmpeg, emit }` -- the item's combo * (comboCounts'), the footage box in the frame (`x`, `y`, `width`, * `height`). Returns `seg` (the badge on it, or none to lay). */ export async function applyPostCombo(seg, entry, { combo, render, outDir, box, encode = [], exec, ffmpeg = "ffmpeg", emit = () => {} }) { const record = comboRecordPath(seg); const plainFile = comboPlainPath(seg); const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null); const st = await stat(seg).catch(() => null); if (!st) return seg; // Is `seg` our badge's output (the post item unchanged since), or post-render's plain one? const ours = !!had && had.out === sigOf(st) && !!(await stat(plainFile).catch(() => null)); const cp = comboPlan(entry, combo, { box, render }); if (!cp) { // No badge now: the plain one back. if (ours) { await rename(plainFile, seg); await rm(record, { force: true }); emit("note", { message: `${entry.id}: combo badge off — its plain segment back` }); } return seg; } const post = await readFile(seg.replace(/\.mp4$/, ".post.json"), "utf8").then((t) => JSON.parse(t)?.key ?? null, () => null); const sfx = comboSfxFile(combo.knobs.sfx); const key = createHash("sha256") .update(JSON.stringify({ v: 1, post, count: combo.count, knobs: combo.knobs, place: cp.place, at: cp.at, frames: cp.frames, box, fps: render.fps, encode, font: render.fontBold ?? null, sfx: sfx ? combo.knobs.sfx : null })) .digest("hex"); if (ours && had.key === key) { emit("note", { message: `${entry.id}: combo ×${combo.count} unchanged — kept` }); return seg; } if (!ours) await rename(seg, plainFile); const dir = path.join(outDir, "cards", `post-${entry.id}`, "combo"); const frames = await shootComboFrames({ count: combo.count, knobs: combo.knobs, place: cp.place, frames: cp.frames, fps: render.fps ?? 30, dir, font: render.fontBold ? pathToFileURL(render.fontBold).href : "", }); const tmp = seg.replace(/\.mp4$/, ".combo-tmp.mp4"); const argv = comboPassArgs({ plain: plainFile, frames, fps: render.fps ?? 30, at: cp.at, x: (box.x ?? 0) + cp.place.region.x, y: (box.y ?? 0) + cp.place.region.y, sfx, encode, audioRate: render.audioRate ?? 48000, outPath: tmp, }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { // The plain segment stands, as if there were no badge: the build goes on and says so. await rename(plainFile, seg).catch(() => {}); const detail = String(err?.stderr ?? "").trim() || err?.message || String(err); throw new Error(`${entry.id}: ffmpeg failed laying the combo badge\n${detail}`); } await rename(tmp, seg); const out = sigOf(await stat(seg)); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. await writeFileAtomic(record, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); emit("note", { message: `${entry.id}: combo ×${combo.count} at ${cp.at.toFixed(2)} s${sfx ? ` (sfx ${combo.knobs.sfx})` : ""}` }); return seg; }