commit ab178f486ecb0d309b0f87002542deeb688ac72e
parent 10060b97cb3f931498e4903c68d0ef793b352f25
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 16:24:28 -0500
umtool: the combo badge rendered -- "COMBO ×2", "×3" … popped onto the repeated attachment's corner as it starts (a slam to a 1.32× overshoot, a spring back, a shake that dies away, a hold, a fade; 2.6 s), the same markup and motion Play draws, shot frame by frame on a transparent page and laid over the post item's segment by a pass of its own (the plain segment kept beside it, so a new count re-lays only the badge); render.posts.combo's sfx plays a bundled hit or coin under it; counted over the whole cut, so --only draws the count the full build would
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 295 insertions(+), 2 deletions(-)
diff --git a/umtool/report-to-video/assets/combo/coin.wav b/umtool/report-to-video/assets/combo/coin.wav
Binary files differ.
diff --git a/umtool/report-to-video/assets/combo/hit.wav b/umtool/report-to-video/assets/combo/hit.wav
Binary files differ.
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -213,6 +213,8 @@ import {
import { snap } from "./snap.mjs";
import { buildPostSegment } from "./post-render.mjs";
import { avatarUrls } from "./post-avatars.mjs";
+import { applyPostCombo } from "./post-combo-render.mjs";
+import { projectCombos } from "./post-combo-prints.mjs";
export { snap };
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
@@ -6287,6 +6289,11 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
const entries = manifest.timeline.filter((e) => !only || e.id === only);
if (only && !entries.length) throw new Error(`no timeline entry with id ${only}`);
+ // The combo counter (post-combo.mjs): each post item's repeat of an earlier one's attachment, counted
+ // over the WHOLE cut, so an `--only` rebuild draws the count the full build would.
+ const postCombos = manifest.timeline.some((e) => e?.type === "post" && e.media?.length)
+ ? (await projectCombos(manifestDir, manifest, { channelsDir })).combos
+ : {};
// Under the deck, the box every footage segment is framed into: the posts
// feed's when this cut is a feed -- decided on the cut's WHOLE timeline, so
// an `--only` rebuild frames a clip as the full build would.
@@ -6404,6 +6411,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
avatars: avatarUrls(manifest, (src) => path.resolve(manifestDir, src)),
});
if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr });
+ // Its combo badge (post-combo-render.mjs): a pass over the segment when its attachment repeats an earlier one's.
+ if (postCombos[entry.id]) {
+ await applyPostCombo(seg, entry, {
+ combo: postCombos[entry.id], render, outDir, box: df ? df.box : { x: 0, y: 0, width: render.width, height: render.height },
+ encode: encodeArgs(render), exec: execFileP, ffmpeg: FFMPEG, emit: (ev, f) => EMIT(ev, f),
+ });
+ }
return seg;
}
if (entry.type === "scroll" || entry.type === "chart" || entry.type === "ledger") {
diff --git a/umtool/report-to-video/post-combo-render.mjs b/umtool/report-to-video/post-combo-render.mjs
@@ -0,0 +1,206 @@
+// 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/<id>.mp4 the item as the build plays it (the badge on it)
+// segments/<id>.plain.mp4 the item without it (post-render's), kept to lay a new count over
+// segments/<id>.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 { postItemPlan, postLayout, stepBoxes } from "./post-item.mjs";
+
+const HERE = path.dirname(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(entry, 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,
+ ...(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 = `<!doctype html><html><head><meta charset="utf-8"><style>html, body { margin: 0; padding: 0; width: ${region.width}px; height: ${region.height}px; overflow: hidden; background: transparent; } #wrap { position: absolute; left: ${left}px; top: ${top}px; width: ${size.width}px; height: ${size.height}px; }</style></head>
+<body><div id="wrap">${comboBadgeHtml(count, knobs, size, { font })}</div><script>
+window.setFrame = function (tr, op) { var b = document.querySelector('[data-combo-badge]'); b.style.transform = tr; b.style.opacity = String(op); };
+(document.fonts && document.fonts.ready ? document.fonts.ready : Promise.resolve()).then(function () { document.body.setAttribute('data-ready', '1'); });
+</script></body></html>`;
+ 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));
+ await writeFile(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;
+}
diff --git a/umtool/report-to-video/post-combo-render.test.mjs b/umtool/report-to-video/post-combo-render.test.mjs
@@ -0,0 +1,73 @@
+// The combo badge's pass (post-combo-render.mjs): when and where it is laid
+// (comboPlan), the encode (comboPassArgs), and the files -- the plain segment
+// kept beside it, put back when the badge goes.
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync, statSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { comboKnobs } from "./post-combo.mjs";
+import { applyPostCombo, comboPassArgs, comboPlainPath, comboPlan, comboRecordPath, comboSfxFile } from "./post-combo-render.mjs";
+
+const render = { width: 1920, height: 1080, fps: 30, palette: {} };
+const entry = (media, extra = {}) => ({ type: "post", id: "p", post: "c/1", platform: "x", text: "a few words here to read", date: "2026-11-01T00:00:00Z", media, ...extra });
+const gif = { src: "m/a.mp4", kind: "gif", seconds: 2, width: 498, height: 280 };
+const combo = (count, extra = {}) => ({ count, media: 0, show: count >= 2, knobs: comboKnobs({}), ...extra });
+
+test("the badge pops when its attachment starts, on its corner, for its 2.6 s (cut at the item's end)", () => {
+ const box = { x: 160, y: 40, width: 1600, height: 900 };
+ const one = comboPlan(entry([gif]), combo(2), { box, render });
+ assert.equal(one.at, 0, "beside the card, the attachment plays from the first frame");
+ assert.equal(one.frames, 78);
+ assert.ok(one.place.region.x + one.place.region.width <= box.width && one.place.region.x > box.width / 2, "top-right, inside the box");
+ // Narrated with the attachments after the read: it pops when the attachment does.
+ const after = entry([gif], { narration: { script: "x", takes: [{ file: "t.wav", seconds: 4 }], pick: 0, attach: "after" } });
+ const late = comboPlan(after, combo(3), { box, render });
+ assert.ok(late && late.at > 3, `after the read (${late?.at})`);
+ // Its second attachment: the step that plays it.
+ const two = comboPlan(entry([{ ...gif, src: "m/b.mp4" }, gif]), combo(2, { media: 1 }), { box, render });
+ assert.ok(two.at > 0);
+ assert.equal(comboPlan(entry([gif]), combo(1), { box, render }), null, "the first use draws none");
+ assert.equal(comboPlan(entry([gif]), { ...combo(2), show: false }, { box, render }), null);
+ // A short item cuts the badge's life.
+ const short = comboPlan(entry([gif], { hold: 1.5 }), combo(2), { box, render });
+ assert.equal(short.frames, 45);
+});
+
+test("the pass: the frames over the plain segment from the attachment's start, the sound into its mix or its audio copied", () => {
+ const a = comboPassArgs({ plain: "/s/p.plain.mp4", frames: "/c/f%04d.png", fps: 30, at: 1.5, x: 1500, y: 60, encode: ["-c:v", "libx264", "-c:a", "aac"], outPath: "/s/p.tmp.mp4" });
+ const fc = a[a.indexOf("-filter_complex") + 1];
+ assert.match(fc, /setpts=PTS-STARTPTS\+1\.5\/TB/);
+ assert.match(fc, /overlay=x=1500:y=60:eof_action=pass/);
+ assert.match(fc, /between\(t,1\.5,4\.1\)/);
+ assert.deepEqual(a.slice(a.indexOf("-map"), a.indexOf("-map") + 4), ["-map", "[v]", "-map", "0:a"]);
+ assert.deepEqual(a.slice(-3), ["-c:a", "copy", "/s/p.tmp.mp4"]);
+ const s = comboPassArgs({ plain: "p", frames: "f", fps: 30, at: 2, x: 0, y: 0, sfx: comboSfxFile("hit"), outPath: "o" });
+ const fs2 = s[s.indexOf("-filter_complex") + 1];
+ assert.match(fs2, /adelay=2000\|2000/);
+ assert.match(fs2, /amix=inputs=2:normalize=0:duration=first\[a\]/);
+ assert.ok(s.includes("[a]") && !s.includes("copy"));
+ assert.ok(existsSync(comboSfxFile("hit")) && existsSync(comboSfxFile("coin")), "the bundled sounds");
+ assert.equal(comboSfxFile("off"), null);
+});
+
+test("a badge that goes (the count fell under minCount, turned off) puts the plain segment back", async () => {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "umtool-combo-pass-"));
+ try {
+ const seg = path.join(dir, "p.mp4");
+ writeFileSync(seg, "WITH-BADGE");
+ writeFileSync(comboPlainPath(seg), "PLAIN");
+ const st = statSync(seg);
+ writeFileSync(comboRecordPath(seg), JSON.stringify({ key: "k", out: `${st.size}:${Math.round(st.mtimeMs)}` }));
+ const notes = [];
+ await applyPostCombo(seg, entry([gif]), { combo: { ...combo(2), show: false }, render, outDir: dir, box: { width: 1920, height: 1080 }, exec: async () => assert.fail("no encode"), emit: (_, f) => notes.push(f.message) });
+ assert.equal(readFileSync(seg, "utf8"), "PLAIN");
+ assert.equal(existsSync(comboRecordPath(seg)), false);
+ assert.match(notes[0], /plain segment back/);
+ // A fresh plain segment (post-render's) with no badge to lay is left alone.
+ await applyPostCombo(seg, entry([gif]), { combo: combo(1), render, outDir: dir, box: { width: 1920, height: 1080 }, exec: async () => assert.fail("no encode") });
+ assert.equal(readFileSync(seg, "utf8"), "PLAIN");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/post-combo.mjs b/umtool/report-to-video/post-combo.mjs
@@ -310,8 +310,8 @@ export const comboTransform = (f, k = 1) => `translate(${r3(f.x * k)}px, ${r3(f.
export function comboSize(count, knobs, boxHeight) {
const k = (boxHeight / 1080) * (fin(knobs?.scale) ? knobs.scale : 1);
const { label, count: n } = comboText(count, knobs);
- const N = 118 * k;
- const L = 40 * k;
+ const N = 150 * k;
+ const L = 48 * k;
const w = Math.max(label.length * 0.66 * L + 0.14 * L * label.length, n.length * 0.62 * N) + 48 * k;
const h = (label ? L * 1.1 : 0) + N * 0.98 + 30 * k;
const even = (v) => Math.max(2, Math.ceil(v / 2) * 2);