// The combo counter (post-combo.mjs, post-combo-prints.mjs): the three tiers // of "the same attachment", the count in the cut's order, minCount, an item's // badge off, the motion, the knobs' validators. import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { COMBO_DEFAULTS, COMBO_TIMING, audioSame, comboBadgeHtml, comboCounts, comboFrame, comboKnobs, comboPlace, comboStart, linkTier, printSimilarity, repeatGroups, validatePostCombo, validatePostComboRender, validatePostCombos, xMediaIdOf, } from "./post-combo.mjs"; import { attachmentPrints, energyPrint, projectCombos } from "./post-combo-prints.mjs"; const item = (id, src, extra = {}) => ({ type: "post", id, post: `chan/${id}`, date: `2026-11-0${id.length % 9}T00:00:00.000Z`, text: "", platform: "x", media: [{ src, kind: "gif", seconds: 2 }], ...extra }); test("the X media id comes from the capture's url: video, GIF, thumb and picture; anything else is none", () => { assert.equal(xMediaIdOf("https://video.twimg.com/amplify_video/2117250894920396961/vid/avc1/720x1280/a.mp4?tag=14"), "amplify_video/2117250894920396961"); assert.equal(xMediaIdOf("https://video.twimg.com/ext_tw_video/1999/pu/vid/x.mp4"), "ext_tw_video/1999"); assert.equal(xMediaIdOf("https://video.twimg.com/tweet_video/HWCOFy3bwAAsJJS.mp4"), "tweet_video/HWCOFy3bwAAsJJS"); assert.equal(xMediaIdOf("https://pbs.twimg.com/tweet_video_thumb/HWCOFy3bwAAsJJS.jpg"), "tweet_video/HWCOFy3bwAAsJJS"); assert.equal(xMediaIdOf("https://pbs.twimg.com/media/HWEqGNfWYAAbqx_?format=jpg&name=small"), "media/HWEqGNfWYAAbqx_"); assert.equal(xMediaIdOf("https://example.com/amplify_video/1/x.mp4"), null); assert.equal(xMediaIdOf(null), null); assert.equal(xMediaIdOf("not a url"), null); }); test("tier by tier: the media id first, then the bytes, then (asked for) the sound -- the strongest agreeing tier names the link", () => { const a = { mediaId: "amplify_video/1", sha256: "aa" }; assert.equal(linkTier(a, { mediaId: "amplify_video/1", sha256: "bb" }), "media-id"); // A GIF X re-uploads has a new id each time: its bytes are what match. assert.equal(linkTier({ mediaId: "tweet_video/A", sha256: "cc" }, { mediaId: "tweet_video/B", sha256: "cc" }), "sha256"); assert.equal(linkTier({ mediaId: "tweet_video/A", sha256: "cc" }, { mediaId: "tweet_video/B", sha256: "cc" }, ["media-id"]), null); const fp = (words) => ({ kind: "chromaprint", bits: 32, words, seconds: 10 }); const words = Array.from({ length: 40 }, (_, i) => (i * 2654435761) >>> 0); const near = words.map((w, i) => (i % 5 === 0 ? (w ^ 0b111) >>> 0 : w)); assert.equal(linkTier({ sha256: "x", audio: fp(words) }, { sha256: "y", audio: fp(near) }), null, "the sound is opt-in"); assert.equal(linkTier({ sha256: "x", audio: fp(words) }, { sha256: "y", audio: fp(near) }, ["media-id", "sha256", "audio"]), "audio"); // The same print shifted (a clip trimmed by a frame) still matches; a different length does not. assert.ok(printSimilarity(fp(words), fp(words.slice(3))) > 0.99); assert.equal(audioSame(fp(words), { ...fp(words), seconds: 14 }), false); assert.equal(audioSame(fp(words), fp(words.map((w) => (~w) >>> 0))), false); }); test("the repeat groups are in the cut's order, one use per item, each numbered and linked by its tier", () => { const timeline = [ item("p1", "posts-media/a/1/1_1.mp4"), { type: "clip", id: "c1" }, item("p2", "posts-media/a/2/2_1.mp4"), item("p3", "posts-media/a/3/3_1.mp4"), item("p4", "posts-media/a/4/4_1.mp4"), { ...item("p5", "posts-media/a/5/5_1.mp4"), media: [{ src: "x/5a.mp4", kind: "gif", seconds: 2 }, { src: "x/5b.mp4", kind: "gif", seconds: 2 }] }, item("p6", "posts-media/a/6/6_1.mp4", { media: undefined }), ]; const prints = { "p1:0": { mediaId: "tweet_video/A", sha256: "S" }, "p2:0": { mediaId: "tweet_video/B", sha256: "T" }, "p3:0": { mediaId: "tweet_video/C", sha256: "S" }, "p4:0": { mediaId: "tweet_video/A", sha256: "Q" }, // The same attachment twice in one item is one use. "p5:0": { sha256: "T" }, "p5:1": { sha256: "T" }, }; const groups = repeatGroups(timeline, (id, i) => prints[`${id}:${i}`]); assert.deepEqual(groups.map((g) => [g.key, g.members.map((m) => `${m.id}#${m.n}:${m.tier ?? "-"}`)]), [ ["g1", ["p1#1:-", "p3#2:sha256", "p4#3:media-id"]], ["g2", ["p2#1:-", "p5#2:sha256"]], ]); assert.deepEqual(groups[0].tiers, ["media-id", "sha256"]); // Moved in the cut, the numbers follow the cut, not the dates. const moved = [timeline[4], timeline[0], timeline[3], timeline[2], timeline[5]]; assert.deepEqual(repeatGroups(moved, (id, i) => prints[`${id}:${i}`])[0].members.map((m) => `${m.id}#${m.n}`), ["p4#1", "p1#2", "p3#3"]); }); test("the count: ×2 from the second use; minCount raises the first badge; an item's badge off still counts", () => { const timeline = [item("a", "m/a.mp4"), item("b", "m/b.mp4"), item("c", "m/c.mp4"), item("d", "m/d.mp4")]; const all = () => ({ sha256: "same" }); const groups = repeatGroups(timeline, all); let combos = comboCounts(timeline, groups, {}); assert.deepEqual(Object.fromEntries(Object.entries(combos).map(([id, c]) => [id, `${c.count}${c.show ? "!" : ""}`])), { a: "1", b: "2!", c: "3!", d: "4!" }); combos = comboCounts(timeline, groups, { posts: { combo: { minCount: 3 } } }); assert.deepEqual(Object.values(combos).map((c) => c.show), [false, false, true, true]); // b's badge off: c is still ×3 (the viewer saw b), only b draws none. const off = timeline.map((e) => (e.id === "b" ? { ...e, combo: false } : e)); combos = comboCounts(off, repeatGroups(off, all), {}); assert.deepEqual(Object.values(combos).map((c) => `${c.count}${c.show ? "!" : ""}`), ["1", "2", "3!", "4!"]); // The cut's off: none drawn, the counts kept. combos = comboCounts(timeline, groups, { posts: { combo: { on: false } } }); assert.deepEqual(Object.values(combos).map((c) => c.show), [false, false, false, false]); // An item's own overrides ride on the cut's. const own = timeline.map((e) => (e.id === "c" ? { ...e, combo: { label: "HIT", color: "#22ccff" } } : e)); const c = comboCounts(own, repeatGroups(own, all), { posts: { combo: { scale: 1.5 } } }).c; assert.deepEqual([c.knobs.label, c.knobs.color, c.knobs.scale, c.knobs.position], ["HIT", "#22ccff", 1.5, "top-right"]); }); test("the badge pops when its attachment's step starts, and moves: slam, overshoot, spring, shake, hold, fade", () => { const plan = { steps: [{ kind: "image", at: 0, items: [{ i: 0 }] }, { kind: "video", at: 3.5, items: [{ i: 1 }] }] }; assert.equal(comboStart(plan, 1), 3.5); assert.equal(comboStart(plan, 0), 0); assert.equal(comboStart(plan, 2), null); assert.equal(comboFrame(-0.01), null); assert.equal(comboFrame(COMBO_TIMING.end), null); const f0 = comboFrame(0); assert.ok(f0 && f0.scale < 0.5 && f0.opacity === 0); const peak = comboFrame(COMBO_TIMING.pop); assert.ok(peak.scale > 1.3, `the overshoot (${peak.scale})`); const dips = []; for (let t = COMBO_TIMING.pop; t < COMBO_TIMING.settle; t += 0.01) dips.push(comboFrame(t).scale); assert.ok(Math.min(...dips) < 0.9, "it springs back under its size"); const rest = comboFrame(1.5); assert.deepEqual(rest, { scale: 1, x: 0, y: 0, rotate: -7, opacity: 1 }); assert.equal(comboFrame(1.5, { mirror: true }).rotate, 7); const shaking = comboFrame(0.2); assert.ok(Math.abs(shaking.x) > 0 || Math.abs(shaking.y) > 0); const fading = comboFrame(2.4); assert.ok(fading.opacity > 0 && fading.opacity < 1 && fading.scale > 1); }); test("the badge sits on the attachment's corner, inside the box; its markup carries the count and the label", () => { const box = { width: 1920, height: 1080 }; const media = { x: 900, y: 100, width: 960, height: 540 }; const k = comboKnobs({}); const p = comboPlace(3, k, media, box); assert.ok(p.center.x > media.x + media.width / 2 && p.center.y < media.y + media.height / 2, "top-right"); assert.ok(p.region.x >= 0 && p.region.x + p.region.width <= box.width + 1); assert.ok(p.region.width >= p.size.width * 1.3 && p.region.height >= p.size.height * 1.3, "room for the overshoot"); assert.equal(p.mirror, false); const left = comboPlace(3, { ...k, position: "bottom-left" }, media, box); assert.ok(left.center.x < media.x + media.width / 2 && left.center.y > media.y + media.height / 2 && left.mirror); // A corner off the box's edge is pulled in. const edge = comboPlace(3, k, { x: 1500, y: 0, width: 420, height: 300 }, box); assert.ok(edge.center.x + edge.size.width / 2 <= box.width && edge.center.y - edge.size.height / 2 >= 0); assert.ok(comboPlace(3, { ...k, scale: 2 }, media, box).size.width > p.size.width * 1.8); const html = comboBadgeHtml(3, k, p.size, { font: "file:///f/Bold.ttf" }); assert.match(html, /data-combo-badge="3"/); assert.match(html, />COMBO×3" }, p.size), /<b>/); }); test("the knobs are refused in the build's words", () => { assert.deepEqual(validatePostComboRender({}), []); assert.deepEqual(validatePostComboRender({ posts: { combo: { ...COMBO_DEFAULTS, sfx: "hit", match: "audio" } } }), []); const bad = validatePostComboRender({ posts: { combo: { on: "yes", position: "middle", color: "red", scale: 9, sfx: "boom", minCount: 1, match: "pixels", size: 2 }, other: 1 } }); for (const want of ["render.posts.other", ".on must", ".position must", ".color must", ".scale must", ".sfx must", ".minCount must", ".match must", ".size is not"]) { assert.ok(bad.some((e) => e.includes(want)), `${want} in ${bad.join(" | ")}`); } assert.deepEqual(validatePostCombo({ id: "p", combo: false }), []); assert.deepEqual(validatePostCombo({ id: "p", combo: { on: false, label: "HIT" } }), []); assert.match(validatePostCombo({ id: "p", combo: { minCount: 3 } })[0], /minCount is not a combo knob/); assert.match(validatePostCombo({ id: "p", combo: true })[0], /must be false/); assert.match(validatePostCombo({ id: "p", combo: { label: "x".repeat(17) } })[0], /at most 16/); assert.equal(validatePostCombos({ render: { posts: { combo: { on: 1 } } }, timeline: [{ type: "post", id: "p", combo: 2 }, { type: "clip", id: "c", combo: 2 }] }).length, 2); }); // --------------------------------------------------------------------------- // The prints, off disk // --------------------------------------------------------------------------- const ff = (args) => { const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]); if (r.status !== 0) throw new Error(String(r.stderr)); }; function project() { const root = mkdtempSync(path.join(os.tmpdir(), "umtool-combo-")); const dir = path.join(root, "proj"); const channels = path.join(root, "channels"); return { root, dir, channels, done: () => rmSync(root, { recursive: true, force: true }) }; } test("the prints: the media id and sha256 from the capture (the project's copy, else the corpus's), else the file hashed; cached", async () => { const p = project(); try { const put = (rel, body) => { mkdirSync(path.dirname(path.join(p.dir, rel)), { recursive: true }); writeFileSync(path.join(p.dir, rel), body); }; // 1 and 3: the same bytes, different X ids (a GIF re-uploaded); 2: other bytes; 4: like 1, no capture anywhere. put("posts-media/ch/1/1_1.mp4", "SAME-BYTES"); put("posts-media/ch/2/2_1.mp4", "OTHER"); put("posts-media/ch-replies/3/3_1.mp4", "SAME-BYTES"); put("posts-media/ch/4/4_1.mp4", "SAME-BYTES"); const sha = execFileSync("sha256sum", [path.join(p.dir, "posts-media/ch/1/1_1.mp4")], { encoding: "utf8" }).split(" ")[0]; // 1's record copied into the project (posts add does); 3's only in the corpus, under the replies channel. writeFileSync(path.join(p.dir, "posts-media/ch/1/capture.json"), JSON.stringify({ media: [{ name: "1_1.mp4", bytes: 10, sha256: sha, url: "https://video.twimg.com/tweet_video/AAA.mp4" }] })); mkdirSync(path.join(p.channels, "ch-replies", "posts-media", "3"), { recursive: true }); writeFileSync(path.join(p.channels, "ch-replies", "posts-media", "3", "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", bytes: 10, sha256: sha, url: "https://video.twimg.com/tweet_video/BBB.mp4" }] })); // 2's record lies about its bytes (a file replaced since): it is hashed, not trusted. writeFileSync(path.join(p.dir, "posts-media/ch/2/capture.json"), JSON.stringify({ media: [{ name: "2_1.mp4", bytes: 999, sha256: sha, url: "https://video.twimg.com/amplify_video/22/x.mp4" }] })); const manifest = { render: {}, timeline: [ item("p1", "posts-media/ch/1/1_1.mp4", { post: "ch/1" }), item("p2", "posts-media/ch/2/2_1.mp4", { post: "ch/2" }), item("p3", "posts-media/ch-replies/3/3_1.mp4", { post: "ch/3" }), item("p4", "posts-media/ch/4/4_1.mp4", { post: "ch/4" }), item("p5", "posts-media/ch/5/gone.mp4", { post: "ch/5" }), ], }; const cacheDir = path.join(p.root, "cache"); const prints = await attachmentPrints(manifest, p.dir, { channelsDir: p.channels, cacheDir }); assert.deepEqual(prints["p1:0"], { mediaId: "tweet_video/AAA", sha256: sha, via: "capture" }); assert.deepEqual(prints["p3:0"], { mediaId: "tweet_video/BBB", sha256: sha, via: "capture" }); assert.equal(prints["p2:0"].via, "hashed"); assert.notEqual(prints["p2:0"].sha256, sha); assert.equal(prints["p2:0"].mediaId, "amplify_video/22"); assert.deepEqual(prints["p4:0"], { mediaId: null, sha256: sha, via: "hashed" }); assert.equal(prints["p5:0"], undefined, "a file not on disk has no print"); const r = await projectCombos(p.dir, manifest, { channelsDir: p.channels, cacheDir }); assert.deepEqual(r.groups.map((g) => g.members.map((m) => `${m.id}#${m.n}`)), [["p1#1", "p3#2", "p4#3"]]); assert.equal(r.combos.p4.count, 3); assert.equal(r.combos.p2, undefined); // id-only: the GIF's new ids do not match. assert.deepEqual((await projectCombos(p.dir, manifest, { channelsDir: p.channels, cacheDir, match: "id" })).groups, []); // Cached: a second look reads the cache (a hash that would fail is never run). const again = await attachmentPrints(manifest, p.dir, { channelsDir: p.channels, cacheDir: path.join(p.root, "cache") }); assert.equal(again["p4:0"].sha256, sha); } finally { p.done(); } }); test("the sound's print: the same clip re-encoded matches, another sound does not; the coarse hash when there is no fpcalc", async () => { const p = project(); try { mkdirSync(p.dir, { recursive: true }); const a = path.join(p.dir, "a.mp4"); const b = path.join(p.dir, "b.mp4"); const c = path.join(p.dir, "c.mp4"); const src = "aevalsrc=0.6*sin(2*PI*(220+180*sin(2*PI*0.7*t))*t)*(0.5+0.5*sin(2*PI*1.3*t)):s=44100:d=6"; ff(["-f", "lavfi", "-i", "color=c=black:s=64x64:d=6", "-f", "lavfi", "-i", src, "-shortest", "-c:v", "libx264", "-c:a", "aac", "-b:a", "128k", a]); ff(["-i", a, "-c:v", "libx264", "-crf", "35", "-c:a", "aac", "-b:a", "64k", b]); ff(["-f", "lavfi", "-i", "color=c=black:s=64x64:d=6", "-f", "lavfi", "-i", "anoisesrc=d=6:c=pink:a=0.4", "-shortest", "-c:v", "libx264", "-c:a", "aac", c]); const vid = (id, src2) => ({ type: "post", id, text: "", date: "2026-11-01T00:00:00Z", media: [{ src: src2, kind: "video", seconds: 6, audio: true }] }); const manifest = { render: { posts: { combo: { match: "audio" } } }, timeline: [vid("a", "a.mp4"), vid("b", "b.mp4"), vid("c", "c.mp4")] }; const r = await projectCombos(p.dir, manifest, { cacheDir: null }); assert.deepEqual(r.groups.map((g) => g.members.map((m) => `${m.id}:${m.tier ?? "-"}`)), [["a:-", "b:audio"]]); assert.notEqual(r.prints["a:0"].sha256, r.prints["b:0"].sha256); // No fpcalc: ffmpeg's energy hash still tells the two sounds apart. const noFp = await projectCombos(p.dir, manifest, { cacheDir: null, audioPrint: (f) => import("./post-combo-prints.mjs").then((m) => m.audioPrintOf(f, { fpcalc: "/nonexistent/fpcalc" })) }); assert.equal(noFp.prints["a:0"].audio.kind, "energy"); assert.deepEqual(noFp.groups.map((g) => g.members.map((m) => m.id)), [["a", "b"]]); assert.equal(energyPrint(Buffer.alloc(16000 * 2)), null, "silence has no print"); } finally { p.done(); } }); test("render.posts is shared: the combo validator leaves redact and slurs to post-redact.mjs (a cut with redacted words built again)", () => { assert.deepEqual(validatePostComboRender({ posts: { redact: [{ term: "Someone" }], slurs: { on: true }, combo: { on: true } } }), []); assert.match(validatePostComboRender({ posts: { comb: {} } }).join(" "), /render\.posts\.comb is not a knob/); // Every module's key under render.posts passes this one (the progress bar's failed every cut that had it, 4 Nov). assert.deepEqual(validatePostComboRender({ posts: { progress: "auto", clock: { on: true }, panel: {}, join: {}, linkVisit: {}, threadMap: {}, scene: {} } }), []); });