Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit d5ce1d357d545144dacce730955fb43f125a274a
parent 0c202936be657594085ee46aa10a61219d29df96
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue,  3 Nov 2026 17:45:55 -0500

Merge lane/combo-counter: a reused attachment pops a COMBO ×N badge on its card in cut order -- matched by X media id, then sha256, then (opt-in) an audio print; laid over the finished segment (over read-follow, the zoom and a censor blur); Play and the bench; posts repeats, posts combo, posts attach

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/post-combo/route.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 5+++++
Mumtool/components/projects/PostBench.tsx | 23++++++++++++++++++++++-
Mumtool/components/projects/PostBenchPage.tsx | 8+++++++-
Aumtool/components/projects/PostComboPanel.tsx | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/review/ComboBadge.tsx | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 20+++++++++++++++++++-
Mumtool/docs/cli.md | 3+++
Mumtool/docs/knobs.md | 26++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/post-combo-fixture.mjs | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/post-combo.spec.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playView.mjs | 9++++++++-
Aumtool/lib/report/postComboCli.mjs | 287+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postComboCli.test.mjs | 127+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 5+++++
Aumtool/report-to-video/assets/combo/coin.wav | 0
Aumtool/report-to-video/assets/combo/hit.wav | 0
Mumtool/report-to-video/build-video.mjs | 14++++++++++++++
Mumtool/report-to-video/lint.mjs | 3+++
Mumtool/report-to-video/package.json | 3+++
Aumtool/report-to-video/post-combo-prints.mjs | 224+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-combo-render.mjs | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-combo-render.test.mjs | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-combo.mjs | 439+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-combo.test.mjs | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
28 files changed, 2323 insertions(+), 4 deletions(-)

diff --git a/umtool/app/api/report/post-combo/route.ts b/umtool/app/api/report/post-combo/route.ts @@ -0,0 +1,72 @@ +import { readFile } from "node:fs/promises"; +import { COMBO_SFX } from "umtool-report-to-video/post-combo"; +import { projectCombos } from "umtool-report-to-video/post-combo-prints"; +import { comboSfxFile } from "umtool-report-to-video/post-combo-render"; +import { channelsDirFor } from "@/lib/projects/report.mjs"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, updatePostCombo, updatePostComboRender } from "@/lib/report/manifest.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// THE COMBO COUNTER (report-to-video/post-combo.mjs; umtool/docs/knobs.md, "The +// combo counter"): the cut's repeated attachments, the badge's sounds, and its +// writers -- what the post bench's combo panel and Play draw with. +// +// GET ?project { match, groups, combos }: each repeat, each item's count +// GET ?sfx=hit|coin a bundled sound (Play plays it as the badge pops) +// POST {project, op: "set", id, combo, token} an item's: false (no badge, still counted), null (the cut's), {knobs} +// POST {project, op: "cut", patch, token} the cut's: render.posts.combo (a key null: the default) + +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const sfx = q.get("sfx"); + if (sfx) { + if (!COMBO_SFX.includes(sfx) || sfx === "off") return new Response("no such sound", { status: 404 }); + const body = await readFile(comboSfxFile(sfx) as string).catch(() => null); + if (!body) return new Response("the sound is not on disk", { status: 404 }); + return new Response(new Uint8Array(body), { headers: { "content-type": "audio/wav", "cache-control": "max-age=3600" } }); + } + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const m = r.manifest as Record<string, unknown>; + const { match, groups, combos } = await projectCombos(r.project.dir, m, { channelsDir: channelsDirFor(r.project.dir, m) }); + return Response.json({ match, groups, combos }, { headers: noStore }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); + } +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/post-combo"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const token = body.token === undefined || body.token === null ? null : String(body.token); + try { + if (body.op === "set") { + const value = body.combo === false ? false : body.combo === null || body.combo === undefined ? null : (body.combo as Record<string, unknown>); + const { result, editNotes } = await withEditNotes(r.project, () => updatePostCombo(r.project.dir, String(body.id ?? ""), value, { token })); + return Response.json({ ok: true, entry: result.entry, combo: result.combo, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "cut") { + const { result, editNotes } = await withEditNotes(r.project, () => updatePostComboRender(r.project.dir, (body.patch ?? {}) as Record<string, unknown>, { token })); + return Response.json({ ok: true, combo: result.combo, token: result.token, editNotes }, { headers: noStore }); + } + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + return Response.json({ error: "op is set or cut" }, { status: 400 }); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -116,6 +116,8 @@ // fit <project> --all | <item>… narrated posts' videos cut to their best part // avatar <project> <handle> <image> | avatars <project> the authors' pictures // redact <project> ls | add "<term>" [--substring] | remove <n> words blanked from what is published +// repeats <project> [--match id|file|audio] · combo <project> [<item>] k=v|off the combo counter +// attach <project> [<item>…|--all] a capture's media onto post items that carry none // umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel import process from "node:process"; import { @@ -1039,6 +1041,9 @@ function usage() { " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards", " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from", " what is published (a bar on the card, left out of a synthesized read); the data never rewritten", + " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)", + " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (the cut's, one item's)", + " umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto post items that carry none", " umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>", " the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;", " Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's", diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -11,6 +11,9 @@ import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import BlurBoxPad from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; +import PostComboPanel from "./PostComboPanel"; +import ComboBadge, { type ComboInfo } from "./review/ComboBadge"; +import { liveCombo } from "umtool-report-to-video/post-combo"; import PostZoomPanel from "./PostZoomPanel"; import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom"; @@ -53,7 +56,7 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [ ]; export default function PostBench({ - project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, + project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, }: { project: string; entry: Entry; @@ -66,6 +69,8 @@ export default function PostBench({ fromPlay: boolean; /** The cut's render block (its `postNarration` knobs). */ render?: Record<string, unknown>; + /** Its combo (post-combo.mjs): the attachment the cut plays again here, its count, its group. */ + combo?: ComboInfo | null; }) { const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); @@ -253,6 +258,7 @@ export default function PostBench({ </div> <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}> <PostItemPlayer project={project} entry={entry} plan={plan} box={box} s={s} playing={playing} cardKey={token} /> + <ComboBadge project={project} entry={entry} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} /> </div> <div className="flex items-center gap-2 text-[12px]"> <button type="button" className={btn} data-post-bench-play="" onClick={() => (s >= total ? (setS(0), setPlaying(true)) : setPlaying((p) => !p))}> @@ -372,6 +378,21 @@ export default function PostBench({ </label> </section> + {combo && ( + <PostComboPanel + project={project} + entry={entry} + token={token} + combo={combo} + render={render} + onEntry={(e, t) => { + setEntry(e as Entry); + setSaved(e as Entry); + setToken(t); + }} + /> + )} + {contexts.map(({ key, label, ref, set }) => { const para = typeof ref.paraphrase === "string" ? ref.paraphrase : ""; return ( diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -1,13 +1,15 @@ import { notFound } from "next/navigation"; import AppShell from "@/components/shell/AppShell"; import PostBench from "./PostBench"; -import { readManifest } from "@/lib/projects/report.mjs"; +import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { projectHref, playHref } from "@/lib/hrefs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; import { postItemPlan } from "umtool-report-to-video/post-item"; +import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import type { ProjectRef } from "@/lib/project-types"; import type { PostPlan } from "./review/PostItemPlayer"; +import type { ComboInfo } from "./review/ComboBadge"; // THE POST BENCH (report-to-video/post-item.mjs; knobs.md, "A post item"): one // post item of the cut on its own -- its card and attachments played on the @@ -30,6 +32,9 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj const neighbours = tl.filter((e) => e?.type === "post").map((e) => e.id); const k = neighbours.indexOf(id); const fromPlay = search.from === "play"; + // Its combo (post-combo.mjs): counted over the whole cut, as the build counts it. + const combos = (await projectCombos(project.dir, m, { channelsDir: channelsDirFor(project.dir, m) }).catch(() => ({ combos: {} }))).combos as Record<string, ComboInfo>; + const combo = combos[id] ?? null; const back = fromPlay ? playHref(project.id, { clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); return ( <div className="flex h-full flex-col"> @@ -46,6 +51,7 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj box={{ width: box.width, height: box.height }} plan={postItemPlan(entry, render) as unknown as PostPlan} render={render} + combo={combo} back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }} prev={k > 0 ? neighbours[k - 1] : null} next={k < neighbours.length - 1 ? neighbours[k + 1] : null} diff --git a/umtool/components/projects/PostComboPanel.tsx b/umtool/components/projects/PostComboPanel.tsx @@ -0,0 +1,93 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import { postBenchHref } from "@/lib/hrefs"; +import { comboKnobs } from "umtool-report-to-video/post-combo"; +import type { ComboInfo } from "./review/ComboBadge"; + +// --------------------------------------------------------------------------- +// THE POST BENCH's COMBO PANEL (report-to-video/post-combo.mjs; knobs.md, "The +// combo counter"): when this item's attachment is one other items of the cut +// play too -- its repeat group in the cut's order (each post's date, the tier +// that matched, a link to its bench), which use this is, and the badge on THIS +// item turned off or on: one write (updatePostCombo, POST /api/report/post-combo +// {op: "set"}), the writer `umtool posts combo <p> <item> off|on` runs. An item +// with its badge off still counts: the next use is still ×(n+1). +// --------------------------------------------------------------------------- + +const TIER: Record<string, string> = { "media-id": "the same X media", sha256: "the same file", audio: "the same sound" }; + +export default function PostComboPanel({ + project, entry, token, combo, render, onEntry, +}: { + project: string; + entry: Record<string, unknown> & { id: string; combo?: unknown }; + token: string | null; + combo: ComboInfo; + render: Record<string, unknown>; + onEntry: (entry: Record<string, unknown> & { id: string }, token: string | null) => void; +}) { + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + // The box follows the click at once; the write's answer settles it (a refusal puts it back). + const [pending, setPending] = useState<boolean | null>(null); + const cut = comboKnobs(render); + const off = entry.combo === false; + const members = combo.members ?? []; + const set = async (on: boolean) => { + setError(null); + setBusy(true); + setPending(on); + const res = await fetch("/api/report/post-combo", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, op: "set", id: entry.id, combo: on ? null : false, token }), + }); + const j = (await res.json().catch(() => ({}))) as { entry?: Record<string, unknown> & { id: string }; token?: string; error?: string; errors?: string[] }; + setBusy(false); + setPending(null); + if (!res.ok || !j.entry) { + setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); + return; + } + onEntry(j.entry, j.token ?? null); + }; + return ( + <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-bench-combo={combo.count}> + <h2 className="micro mb-2"> + combo · attachment {combo.media + 1} · use {combo.count} of {members.length} + </h2> + <ol className="m-0 list-none space-y-0.5 p-0 text-[12px]" data-post-bench-combo-group={combo.group ?? ""}> + {members.map((m) => ( + <li key={m.id} className="flex items-baseline gap-2" data-post-bench-combo-member={m.id} aria-current={m.id === entry.id ? "true" : undefined}> + <span className="w-8 font-mono tabular-nums">{m.n >= Math.max(2, cut.minCount) ? `×${m.n}` : m.n}</span> + {m.id === entry.id ? ( + <b>{m.id}</b> + ) : ( + <Link href={postBenchHref(project, m.id)} className="ink-link"> + {m.id} + </Link> + )} + <span className="text-text-2">{typeof m.date === "string" ? m.date.slice(0, 10) : ""}</span> + <span className="ml-auto text-text-2">{m.tier ? TIER[m.tier] ?? m.tier : "first"}</span> + </li> + ))} + </ol> + <label className="mt-2 flex items-center gap-2"> + <input type="checkbox" checked={pending ?? !off} disabled={busy} onChange={(e) => void set(e.target.checked)} data-post-bench-combo-toggle="" /> + the badge on this item + </label> + <p className="m-0 mt-1 text-[11.5px] text-text-2" data-post-bench-combo-note=""> + {cut.on === false + ? "the cut's combo badge is off (umtool posts combo <p> on=on)" + : combo.count < Math.max(2, cut.minCount) + ? `the first use${combo.count > 1 ? "s" : ""} draw${combo.count > 1 ? "" : "s"} none: the badge from ×${cut.minCount}` + : off + ? "off here: it still counts, the next use stays ×" + (combo.count + 1) + : `“${String(combo.knobs?.label ?? cut.label)} ×${combo.count}” pops as the attachment starts`} + </p> + {error && <p className="m-0 mt-1 text-[var(--color-blocking,#c33)]" data-post-bench-combo-error="">{error}</p>} + </section> + ); +} diff --git a/umtool/components/projects/review/ComboBadge.tsx b/umtool/components/projects/review/ComboBadge.tsx @@ -0,0 +1,111 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState } from "react"; +import { comboBadgeHtml, comboFrame, comboPlace, comboStart, comboTransform } from "umtool-report-to-video/post-combo"; +import { postLayout, stepBoxes } from "umtool-report-to-video/post-item"; +import type { PostPlan } from "./PostItemPlayer"; + +// --------------------------------------------------------------------------- +// THE COMBO BADGE, PLAYED (report-to-video/post-combo.mjs; knobs.md, "The combo +// counter"): over a post item that repeats an earlier item's attachment, +// "COMBO ×<n>" pops onto that attachment's corner as it starts -- the build's +// own markup (comboBadgeHtml), moved by the build's own motion (comboFrame) on +// the item's clock, in the box's px scaled to the player. Laid beside the +// PostItemPlayer (Play the cut, the post bench), never inside it. Its sound, +// when the cut asks for one, plays as it pops while playing. +// --------------------------------------------------------------------------- + +export type ComboInfo = { + count: number; + media: number; + show: boolean; + knobs: Record<string, unknown> & { sfx?: string }; + group?: string; + tier?: string | null; + members?: Array<{ id: string; i: number; n: number; post: string | null; date: string | null; tier: string | null }>; +}; + +type Box = { width: number; height: number }; + +export default function ComboBadge({ + project, entry, plan, combo, box, s, playing, +}: { + project: string; + entry: Record<string, unknown> & { id: string }; + plan: PostPlan; + combo: ComboInfo | null | undefined; + box: Box; + /** The item's own second. */ + s: number; + playing: boolean; +}) { + const wrap = useRef<HTMLDivElement | null>(null); + const [scale, setScale] = useState(0); + useEffect(() => { + const node = wrap.current; + if (!node) return; + const ro = new ResizeObserver(([e]) => setScale(e.contentRect.width / box.width)); + ro.observe(node); + return () => ro.disconnect(); + }, [box.width]); + const geo = useMemo(() => { + if (!combo?.show) return null; + const at = comboStart(plan, combo.media); + const step = plan.steps.find((st) => st.items.some((m) => m.i === combo.media)); + const layout = postLayout(entry, box); + if (at === null || !step || !layout.slot) return null; + const boxes = stepBoxes(step, layout.slot) as Array<{ x: number; y: number; width: number; height: number }>; + const mb = boxes[step.items.findIndex((m) => m.i === combo.media)] ?? boxes[0]; + const place = comboPlace(combo.count, combo.knobs, mb, box); + const font = `/api/report/post-item?project=${encodeURIComponent(project)}&font=bold`; + return { at, place, html: comboBadgeHtml(combo.count, combo.knobs, place.size, { font }) }; + }, [combo, plan, entry, box, project]); + const frame = geo ? comboFrame(s - geo.at, { mirror: geo.place.mirror }) : null; + // Its sound, as it pops while playing (not when scrubbed onto). + const sfx = typeof combo?.knobs?.sfx === "string" && combo.knobs.sfx !== "off" ? combo.knobs.sfx : null; + const audio = useRef<HTMLAudioElement | null>(null); + const up = !!frame; + const was = useRef(false); + useEffect(() => { + const a = audio.current; + if (up && !was.current && playing && a && geo && s - geo.at < 0.3) { + a.currentTime = 0; + void a.play().catch(() => {}); + } + was.current = up; + }, [up, playing, geo, s]); + if (!combo) return null; + const size = geo?.place.size; + return ( + <div + ref={wrap} + data-post-combo={combo.count} + data-post-combo-show={combo.show ? "1" : "0"} + data-post-combo-up={up ? "1" : "0"} + data-post-combo-at={geo ? String(geo.at) : undefined} + className="pointer-events-none absolute inset-0 overflow-hidden" + > + {sfx && ( + // eslint-disable-next-line jsx-a11y/media-has-caption + <audio ref={audio} src={`/api/report/post-combo?sfx=${encodeURIComponent(sfx)}`} preload="auto" data-post-combo-sfx={sfx} /> + )} + {geo && size && frame && scale > 0 && ( + <div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}> + <div + style={{ + position: "absolute", + left: geo.place.center.x - size.width / 2, + top: geo.place.center.y - size.height / 2, + width: size.width, + height: size.height, + transform: comboTransform(frame, size.k), + transformOrigin: "50% 50%", + opacity: frame.opacity, + }} + dangerouslySetInnerHTML={{ __html: geo.html }} + /> + </div> + )} + </div> + ); +} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -28,6 +28,7 @@ import { useCutApp } from "../cutApp/CutApp"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; import AddPost from "./AddPost"; import PostItemPlayer, { type PostPlan } from "./PostItemPlayer"; +import ComboBadge, { type ComboInfo } from "./ComboBadge"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -121,6 +122,8 @@ export type PlayEntry = { /** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */ post?: Record<string, unknown> & { id: string }; postPlan?: PostPlan; + /** Its combo badge (post-combo.mjs): the attachment it repeats, its count, the knobs. */ + postCombo?: ComboInfo; }; export type PlayViewData = { @@ -848,6 +851,20 @@ export default function PlayCut({ published={asPublished} /> ) : null; + // A post item that repeats an earlier one's attachment: its combo badge, beside the player. + const comboBadge = (box2: { width: number; height: number }) => + postNow?.entry.postCombo ? ( + <ComboBadge + key={`combo-${postNow.item.id}`} + project={project} + entry={postNow.entry.post!} + plan={postNow.entry.postPlan!} + combo={postNow.entry.postCombo} + box={box2} + s={Math.max(0, t - postNow.item.start)} + playing={ui.playing && !ui.waiting} + /> + ) : null; const placeholderCard = placeholder ? ( <div data-play-placeholder={placeholder.kind} @@ -998,6 +1015,7 @@ export default function PlayCut({ {postNow && rect && ( <div className="absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H), background: bg }}> {postPlayer({ width: box.width, height: box.height })} + {comboBadge({ width: box.width, height: box.height })} </div> )} {placeholderCard} @@ -1015,7 +1033,7 @@ export default function PlayCut({ ) : ( <div className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain"> {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)} - {postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}</div>} + {postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>} {placeholderCard} </div> )} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -89,6 +89,9 @@ Inbox cannot disagree about what is wrong with one. | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | | `posts redact <project> ls \| add "<term>" [--substring] [--note "…"] \| remove <n> [--json]` | **REDACTED WORDS** ([knobs.md](knobs.md#redacted-words-blanked-from-what-is-published)): the project's list (`render.posts.redact`, `updatePostRedact`) of words or phrases blanked from everything the cut publishes -- a solid bar on the rendered card, left out of a synthesized read, a post's chapter line and an attachment's captions; matched without case, as whole words (`--substring`: inside words too), a phrase across any spaces or punctuation. The posts' words and the scripts are never rewritten. `ls` numbers the terms as `remove` takes them, and counts the corpus's (`transcripts/redactions.json`) and the posts marked up in the cut's channels (`posts-markup.json`). A term already listed is refused (**exit 1**) | | `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) | +| `posts repeats <project> [--match id\|file\|audio] [--json]` | the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only | +| `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words | +| `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -750,6 +750,32 @@ the card live on the same states the build shoots. | `follow` on a post item — `false` (off on this post), or `{on, dim, ease}` over the cut's | post bench, **read-follow**: the cut's / on / off, **dim**, **ease** (saved with the bench's other knobs) | `umtool posts set-item <p> <item> follow=off` (`follow=on`, `follow=auto`: the cut's) · `follow.dim=0.7 follow.ease=0.4` | `POST /api/report/post-item {project, op: "set", id, patch: {follow}, token}` (an object merges; `null` clears) | | the block map — each block of the card's words, its text, the part that reads it, its start on the item's clock | post bench, **read-follow**: the map's rows (click one: the playhead at its start; the one being read is marked) | — (`postItemPlan(entry, render).follow`) | — | +## The combo counter + +A post item that plays an attachment an earlier post item of the cut already played gets a fighting-game badge, +**COMBO ×2**, **×3** …, popped onto that attachment's corner as it starts ([report-video.md](report-video.md#the-combo-counter): +what counts as the same attachment, the count, the motion). Render, Play and the post bench draw it. The cut's knobs are +`render.posts.combo` (`updatePostComboRender`), an item's its `combo` (`updatePostCombo`; `lib/report/manifest.mjs`), refused +in the build's words (`validatePostCombos`). `k=` (empty) takes the default (the cut's) again. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| `render.posts.combo.on` — the badge at all (default on) | — | `umtool posts combo <p> on=off` (`on=on`) | `POST /api/report/post-combo {project, op: "cut", patch: {on}, token}` | +| `render.posts.combo.label` — the word over the count (≤ 16 characters, default `COMBO`; `""` the count alone) | — | `label=HIT` | same, `patch: {label}` | +| `render.posts.combo.position` — the attachment's corner it pops on: `top-right` (default) · `top-left` · `bottom-right` · `bottom-left` · `center` | — | `position=top-left` | same | +| `render.posts.combo.color` — the count's fill, `#rrggbb` (default `#ffcf33`), running to a hot red | — | `color=#22ccff` | same | +| `render.posts.combo.scale` — its size, 0.4–2.5 (default 1: a 150 px count in a 1080 frame) | — | `scale=1.4` | same | +| `render.posts.combo.sfx` — a bundled sound as it pops: `off` (default) · `hit` · `coin` (the render's mix; Play plays it as it pops while playing) | — | `sfx=hit` | same; the sound `GET /api/report/post-combo?sfx=hit` | +| `render.posts.combo.minCount` — the first use that draws it, 2–20 (default 2: ×2 on) | — | `minCount=3` | same | +| `render.posts.combo.match` — how deep "the same attachment" goes: `id` (the X media id) · `file` (+ the sha256; default) · `audio` (+ the sound's fingerprint) | — | `match=audio` | same | +| `combo` — one post item's: `false` draws no badge on it (it STILL counts: the next use stays ×(n+1)); an object overrides `on`, `label`, `position`, `color`, `scale`, `sfx` for it | post bench, **combo**: its repeat group in the cut's order (each post's date, the tier that matched, its bench), which use this is, **the badge on this item** | `umtool posts combo <p> <item> off` (`on`/`auto`: the cut's) · `… <item> label=HIT color=#22ccff` | `POST /api/report/post-combo {project, op: "set", id, combo: false \| null \| {…}, token}` | + +| | In umtool | From a terminal | Route | +|---|---|---|---| +| the repeats: each attachment played more than once, its posts in the cut's order with their dates, the tier that matched (`X media id`, `same file`, `same sound`) and the badge each draws; a post whose capture holds the same file but whose entry carries none, marked | the post bench's **combo** block (this item's group) | `umtool posts repeats <p> [--match id\|file\|audio] [--json]` | `GET /api/report/post-combo?project` | +| attach what a capture holds to a post item that carries none (captured after it went in): its media copied in and set, nothing else of the entry changed; then it plays and counts | — | `umtool posts attach <p> <item>… \| --all [--dry-run]` | — | +| the badge on the item's clock | Play the cut, the post bench (the player) | the build: `segments/<id>.mp4` (the plain one `<id>.plain.mp4`, the record `<id>.combo.json`) | — | + ## The source backlog (Sources · Prioritize · Re-sweep when complete) The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -762,6 +762,61 @@ at their peak). **Play** sets the same states on its card page each tick; the po when (click: the playhead there), the one being read marked — and the post's knobs ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)). +### The combo counter + +When a post item's attachment is one an EARLIER post item of the cut already played — +the same reaction video answering a third person — a fighting-game badge pops onto +that attachment's corner as it starts: **COMBO ×2**, **×3** … (operator, 3 Nov: *"an +effect that shows a combo counter or something when he uses the same video to reply +to someone"*). `report-to-video/post-combo.mjs` is the rule (pure), +`post-combo-prints.mjs` reads what each attachment is, `post-combo-render.mjs` lays +the badge in the build, `components/projects/review/ComboBadge.tsx` in Play and the +post bench. + +**The same attachment**, in order of trust: the X **media id** in the capture's source +url (`amplify_video/<id>`, `ext_tw_video/<id>`, `tweet_video/<id>`, pbs `media/<id>`; +the record is the project's `posts-media/<slug>/<postId>/capture.json`, else the +corpus's), else the file's **sha256** (the capture's, trusted when its `bytes` match the +project's copy; else the copy hashed), else — `match: "audio"` — the **sound**: its +fingerprint (chromaprint's `fpcalc -raw`, else a coarse ffmpeg energy hash) alike and +its length within 0.3 s. Any one tier links two; X gives a re-uploaded GIF a new id +every time, so its bytes are what match. Each file's print is cached by path, size and +mtime (`UMTOOL_PRINTS_CACHE`, default `~/.cache/umtool/media-prints`). + +**The count** is the use's number in the cut's ORDER (the timeline's post items), not +by date: moved, the numbers follow. The badge shows from `minCount` (default 2). An +item with `combo: false` draws none and STILL counts — the viewer saw it, so the next +use stays ×(n+1). It is counted over the whole cut, so an `--only` rebuild draws the +count the full build would. + +**The motion** (2.6 s from the attachment's start, cut at the item's end): a slam in +from 0.3× to a 1.32× overshoot in 0.12 s, a spring back through 0.86× to rest, a shake +that dies away by 0.56 s, tilted 7° (the other way on a left corner), held, then faded +out over 0.4 s growing to 1.12×. The badge is a heavy face skewed, the count filled +from `color` to a hot red with a dark outline and a red under-shadow, the label over it. + +**The build** draws the item's segment as it always did (`post-render.mjs`), then a +pass of its own lays the badge's frames — the same markup Play draws, moved by the same +`comboFrame`, shot frame by frame on a transparent page — over the attachment's corner, +and the `sfx` (a bundled `hit` or `coin`) into its mix. The plain segment is kept as +`segments/<id>.plain.mp4`: a new count re-lays only the badge; a badge that goes puts +it back. `segments/<id>.combo.json` records what it was laid from. + +```jsonc +"render": { "posts": { "combo": { + "on": true, "label": "COMBO", "position": "top-right", "color": "#ffcf33", + "scale": 1, "sfx": "off", "minCount": 2, "match": "file" } } }, +"timeline": [ { "type": "post", "id": "p-…", "combo": false }, … ] // or { "label": "HIT", … } +``` + +`umtool posts repeats <p>` lists every repeated attachment with its posts in the cut's +order, their dates, the tier that matched and the badge each draws — and a post whose +CAPTURE holds the same file while its entry carries no attachment (captured after it +went in: it draws nothing and does not count until it plays the attachment). +`umtool posts attach <p> <item>… | --all` brings such a capture's media in -- copied +and measured as `posts reel` would have made it, nothing else of the entry changed -- +and from then it plays and counts. + ## The on-screen deck (`render.chrome`) Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -55,6 +55,7 @@ import { makeReelFixture } from "./reel-fixture.mjs"; import { makeIntakeFixture } from "./intake-fixture.mjs"; import { makePostItemsFixture } from "./post-items-fixture.mjs"; import { makePostNarrationFixture } from "./post-narration-fixture.mjs"; +import { makePostComboFixture } from "./post-combo-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1913,6 +1914,8 @@ makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: pat makePostItemsFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Narrated post items (report-to-video/post-narration.mjs): a take read over a video, four pictures cycling (post-narration.spec.ts). makePostNarrationFixture({ reports, deckManifest }); +// The combo counter (report-to-video/post-combo.mjs): one GIF answering three people (post-combo.spec.ts). +makePostComboFixture({ reports, channels: CHANNELS, deckManifest }); // Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut, // undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1 // window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it). diff --git a/umtool/e2e/fixtures/post-combo-fixture.mjs b/umtool/e2e/fixtures/post-combo-fixture.mjs @@ -0,0 +1,62 @@ +// THE COMBO COUNTER (report-to-video/post-combo.mjs): a posts cut where the +// same reaction GIF answers three people (post-combo.spec.ts). +// +// post-combo-fixture p-c1 the GIF's first use (no badge) +// p-txt words only, between them +// p-c2 the same bytes, another X id (re-uploaded): ×2 +// p-c3 again, its capture only in the corpus: ×3 +// p-oth another GIF (no repeat) +// the deck on. Each GIF is 2 s of testsrc, silent, as X +// serves a GIF. WRITES its manifest (the bench's +// toggle): the spec puts it back before each test. +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; + +const ff = (args) => { + const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]); + if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`); +}; + +export const COMBO_CHANNEL = "combochan-x"; + +/** @param {{ reports: string, channels: string, deckManifest: Function }} o */ +export function makePostComboFixture({ reports, channels, deckManifest }) { + const name = "post-combo-fixture"; + const dir = path.join(reports, name); + const media = path.join(dir, "posts-media", COMBO_CHANNEL); + for (const id of ["1", "3", "4", "5"]) mkdirSync(path.join(media, id), { recursive: true }); + const gif = path.join(media, "1", "1_1.mp4"); + ff(["-f", "lavfi", "-i", "testsrc=size=498x280:rate=25:duration=2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", gif]); + ff(["-f", "lavfi", "-i", "testsrc2=size=498x280:rate=25:duration=2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", path.join(media, "5", "5_1.mp4")]); + copyFileSync(gif, path.join(media, "3", "3_1.mp4")); + copyFileSync(gif, path.join(media, "4", "4_1.mp4")); + const bytes = readFileSync(gif); + const sha = createHash("sha256").update(bytes).digest("hex"); + // The captures' records: p-c1's and p-c2's copied into the project; p-c3's only in the corpus. + writeFileSync(path.join(media, "1", "capture.json"), JSON.stringify({ version: 1, id: "1", media: [{ name: "1_1.mp4", bytes: bytes.length, sha256: sha, url: "https://video.twimg.com/tweet_video/AAAA.mp4" }] })); + writeFileSync(path.join(media, "3", "capture.json"), JSON.stringify({ version: 1, id: "3", media: [{ name: "3_1.mp4", bytes: bytes.length, sha256: sha, url: "https://video.twimg.com/tweet_video/BBBB.mp4" }] })); + const cap4 = path.join(channels, COMBO_CHANNEL, "posts-media", "4"); + mkdirSync(cap4, { recursive: true }); + writeFileSync(path.join(cap4, "capture.json"), JSON.stringify({ version: 1, id: "4", media: [{ name: "4_1.mp4", bytes: bytes.length, sha256: sha, url: "https://video.twimg.com/tweet_video/CCCC.mp4" }] })); + const at = (d) => `2026-11-0${d}T10:00:00.000Z`; + const base = (id, day, text, o = {}) => ({ + type: "post", id, post: `${COMBO_CHANNEL}/${id.replace(/^p-c?/, "")}`, platform: "x", author: "Combo Subject", handle: "combosubject", + date: at(day), text, url: `https://x.com/combosubject/status/${id}`, engagement: { likes: 3 }, subjects: ["combosubject"], ...o, + }); + const g = (id) => [{ src: `posts-media/${COMBO_CHANNEL}/${id}/${id}_1.mp4`, kind: "gif", seconds: 2, width: 498, height: 280 }]; + const timeline = [ + base("p-c1", 1, "Me, every time.", { post: `${COMBO_CHANNEL}/1`, media: g("1") }), + base("p-txt", 1, "Words only, between the replies.", { post: `${COMBO_CHANNEL}/2` }), + base("p-c2", 2, "Again.", { post: `${COMBO_CHANNEL}/3`, media: g("3") }), + base("p-c3", 3, "And again.", { post: `${COMBO_CHANNEL}/4`, media: g("4") }), + base("p-oth", 3, "Something else.", { post: `${COMBO_CHANNEL}/5`, media: g("5") }), + ]; + const m = deckManifest(name, "The Combo Fixture", timeline); + m.provenance = { ...m.provenance, channelSlug: COMBO_CHANNEL, channelsDir: path.relative(dir, channels) }; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { dir }; +} diff --git a/umtool/e2e/post-combo.spec.ts b/umtool/e2e/post-combo.spec.ts @@ -0,0 +1,108 @@ +import { test, expect, type Page } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THE COMBO COUNTER (report-to-video/post-combo.mjs; knobs.md, "The combo +// counter"): one reaction GIF answering three people. Fixture: +// e2e/fixtures/post-combo-fixture.mjs -- p-c1 (its first use), p-txt (words), +// p-c2 (the same bytes re-uploaded: ×2), p-c3 (again, its capture in the +// corpus only: ×3), p-oth (another GIF). Each item is its 3 s read, its GIF +// beside the card from the first frame: the badge pops at the item's 0 s. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const DIR = path.join(FIXTURE, "reports", "post-combo-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-combo-fixture"; +const SHOTS = process.env.POST_COMBO_SHOTS ?? null; + +type Entry = { id: string; type: string; combo?: unknown }; +const timeline = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline; +const umtool = (args: string[]) => + execFileSync("node", ["bin/umtool.mjs", ...args], { + cwd: path.join(HERE, ".."), + encoding: "utf8", + env: { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_PRINTS_CACHE: path.join(FIXTURE, "cache", "media-prints"), UMTOOL_MEDIA_DIR: "" }, + }); + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); +}); + +const root = (page: Page) => page.locator("[data-play-cut]"); + +test("Play shows the combo: none on the first use, ×2 then ×3 as the repeated GIF starts", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-c1" })); + await expect(root(page)).toHaveAttribute("data-play-item", "p-c1"); + await expect(page.locator('[data-post-play="p-c1"]')).toBeVisible(); + // The first use counts, and draws nothing. + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo", "1"); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-show", "0"); + await expect(page.locator("[data-combo-badge]")).toHaveCount(0); + + // The second use: the badge is up from the attachment's start (the item's 0 s: beside the card, the GIF plays from the first frame). + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-c2" })); + await expect(root(page)).toHaveAttribute("data-play-item", "p-c2"); + const badge = page.locator("[data-post-combo]"); + await expect(badge).toHaveAttribute("data-post-combo", "2"); + await expect(badge).toHaveAttribute("data-post-combo-show", "1"); + await expect(badge).toHaveAttribute("data-post-combo-at", "0"); + await expect(badge).toHaveAttribute("data-post-combo-up", "1"); + await page.locator("[data-play-toggle]").click(); + // Popped: scaled up and opaque. + await expect.poll(async () => Number(await page.locator('[data-combo-badge="2"]').evaluate((el) => getComputedStyle(el.parentElement as HTMLElement).opacity)), { timeout: 10_000 }).toBeGreaterThan(0.9); + await expect(page.locator('[data-combo-badge="2"]')).toContainText("COMBO"); + await expect(page.locator('[data-combo-badge="2"]')).toContainText("×2"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-combo-play-x2.png") }); + // Played on into the third use: ×3, from its start. + await expect(root(page)).toHaveAttribute("data-play-item", "p-c3", { timeout: 15_000 }); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo", "3"); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-up", "1"); + await expect(page.locator('[data-combo-badge="3"]')).toContainText("×3"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-combo-play-x3.png") }); + // p-oth repeats nothing. + await expect(root(page)).toHaveAttribute("data-play-item", "p-oth", { timeout: 15_000 }); + await expect(page.locator("[data-post-combo]")).toHaveCount(0); + await page.locator("[data-play-toggle]").click(); +}); + +test("the post bench lists the repeat group and turns the badge off for one item (it still counts); posts repeats agrees", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.postBenchHref(PROJECT, "p-c3")); + const panel = page.locator('[data-post-bench-combo="3"]'); + await expect(panel).toBeVisible(); + expect(await panel.locator("[data-post-bench-combo-member]").evaluateAll((els) => els.map((e) => e.getAttribute("data-post-bench-combo-member")))).toEqual(["p-c1", "p-c2", "p-c3"]); + await expect(panel.locator('[data-post-bench-combo-member="p-c2"]')).toContainText("the same file"); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-show", "1"); + // On the item's clock: up from the GIF's start for its 2.6 s, gone before the item's 3 s end. + const scrub = page.locator("[data-post-bench-scrub]"); + await scrub.fill("1"); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-up", "1"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-combo-bench.png") }); + await scrub.fill("2.8"); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-up", "0"); + await expect(page.locator("[data-combo-badge]")).toHaveCount(0); + await panel.locator("[data-post-bench-combo-toggle]").uncheck(); + await expect(panel.locator("[data-post-bench-combo-note]")).toContainText("still counts"); + await expect.poll(() => timeline().find((e) => e.id === "p-c3")?.combo).toBe(false); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-show", "0"); + await expect(page.locator("[data-combo-badge]")).toHaveCount(0); + const rep = JSON.parse(umtool(["posts", "repeats", PROJECT, "--json"])) as { groups: { members: { id: string; badge: number | null; show: boolean; tier: string | null }[] }[] }; + expect(rep.groups).toHaveLength(1); + expect(rep.groups[0].members.map((m) => `${m.id}:${m.badge}:${m.show ? "shown" : "-"}:${m.tier ?? "first"}`)).toEqual(["p-c1:1:-:first", "p-c2:2:shown:sha256", "p-c3:3:-:sha256"]); + // On again: the item takes the cut's badge. + await panel.locator("[data-post-bench-combo-toggle]").check(); + await expect.poll(() => "combo" in (timeline().find((e) => e.id === "p-c3") ?? {})).toBe(false); + await expect(page.locator("[data-post-combo]")).toHaveAttribute("data-post-combo-show", "1"); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -67,6 +67,7 @@ import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFo import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs"; import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; +import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, validatePostCombo, validatePostComboRender } from "umtool-report-to-video/post-combo"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; @@ -2453,6 +2454,102 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { }); } +// ---- the combo counter (report-to-video/post-combo.mjs) -------------------- + +/** + * A POST ITEM's COMBO BADGE (`combo`; `umtool posts combo <p> <item> …`, the + * post bench's **combo badge**): `false` draws none on this item (it still + * counts), `null` takes the cut's again, an object sets this item's + * overrides (COMBO_ITEM_KEYS; a key null is the cut's again; none left: the + * cut's). Validated with the build's check. + * + * @param {string} dir + * @param {string} id + * @param {false | null | Record<string, any>} value + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostCombo(dir, id, value, { token = null } = {}) { + if (value !== false && value !== null && !isObj(value)) throw new Error("a post item's combo is false (no badge), null (the cut's) or an object of knobs"); + if (isObj(value)) for (const k of Object.keys(value)) if (!COMBO_ITEM_KEYS.includes(k)) throw new Error(`${k} is not a post item's combo knob (${COMBO_ITEM_KEYS.join(", ")})`); + return structural(dir, "post-combo", token, (m) => { + const i = entryIndex(m.timeline, id); + const e = m.timeline[i]; + if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`); + if (value === false) e.combo = false; + else if (value === null) delete e.combo; + else { + const c = isObj(e.combo) ? e.combo : {}; + for (const [k, v] of Object.entries(value)) { + if (v === null || v === undefined) delete c[k]; + else c[k] = typeof v === "number" ? round2(v) : v; + } + if (Object.keys(c).length) e.combo = c; + else delete e.combo; + } + const errors = validatePostCombo(e); + if (errors.length) throw new StructureRefused(errors); + return { id, at: i, entry: e, combo: e.combo ?? null }; + }); +} + +/** + * THE CUT's COMBO KNOBS (`render.posts.combo`; `umtool posts combo <p> k=v …`): + * each key one of COMBO_DEFAULTS', null back to the default. Validated with + * the build's check. + * + * @param {string} dir + * @param {Record<string, any>} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostComboRender(dir, patch, { token = null } = {}) { + if (!isObj(patch) || !Object.keys(patch).length) throw new Error("nothing to set"); + for (const k of Object.keys(patch)) if (!(k in COMBO_DEFAULTS)) throw new Error(`${k} is not a combo knob (${Object.keys(COMBO_DEFAULTS).join(", ")})`); + return structural(dir, "post-combo-cut", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + const c = isObj(posts.combo) ? posts.combo : {}; + for (const [k, v] of Object.entries(patch)) { + if (v === null || v === undefined) delete c[k]; + else c[k] = typeof v === "number" && k !== "minCount" ? round2(v) : v; + } + if (Object.keys(c).length) posts.combo = c; + else delete posts.combo; + if (Object.keys(posts).length) m.render.posts = posts; + else delete m.render.posts; + const errors = validatePostComboRender(m.render); + if (errors.length) throw new StructureRefused(errors); + return { combo: m.render.posts?.combo ?? null }; + }); +} + +/** + * ATTACH A CAPTURE's MEDIA to post items that carry none (`umtool posts + * attach`): `patches` is `{ <id>: media[] }`, each list already copied into + * the project; an item that has an attachment by now is left as it is. One + * write (one undo point), refused whole in the build's words. + * + * @param {string} dir + * @param {Record<string, Array<Record<string, any>>>} patches + * @param {{ token?: string | null }} [opts] + */ +export async function attachPostMedia(dir, patches, { token = null } = {}) { + if (!isObj(patches) || !Object.keys(patches).length) throw new Error("nothing to attach"); + return structural(dir, "post-attach", token, (m) => { + const ids = []; + for (const [id, media] of Object.entries(patches)) { + const e = m.timeline[entryIndex(m.timeline, id)]; + if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`); + if (Array.isArray(e.media) && e.media.length) continue; + if (!Array.isArray(media) || !media.length) continue; + e.media = structuredClone(media); + const errors = validatePostItem(e); + if (errors.length) throw new StructureRefused(errors); + ids.push(id); + } + return { ids }; + }); +} + // ---- the authors' pictures (report-to-video/post-avatars.mjs) -------------- /** diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -11,7 +11,7 @@ import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck"; import { resolveFactcheck } from "umtool-report-to-video/factcheck"; -import { clipDateKey, readManifest } from "../projects/report.mjs"; +import { channelsDirFor, clipDateKey, readManifest } from "../projects/report.mjs"; import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; import { postDay, postItemPlan } from "umtool-report-to-video/post-item"; @@ -20,6 +20,7 @@ import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; import { sectionModel } from "./sectionEdit.mjs"; import { manifestToken } from "./manifest.mjs"; +import { projectCombos } from "umtool-report-to-video/post-combo-prints"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); @@ -149,6 +150,12 @@ export async function playView(project, { take = null, bare = false } = {}) { }; }), ); + // The combo counter (post-combo.mjs): a post item that repeats an earlier one's attachment carries its badge + // (`postCombo`: its count, which attachment, the knobs, whether it shows), counted over the cut played. + if (entries.some((e) => e.type === "post")) { + const { combos } = await projectCombos(project.dir, selected, { channelsDir: channelsDirFor(project.dir, base) }).catch(() => ({ combos: {} })); + for (const e of entries) if (e.type === "post" && combos[e.id]) Object.assign(e, { postCombo: combos[e.id] }); + } // The counter (the deck's tally): each stamp's landing second and count on // the estimate's clock, and each verdict's word -- the reel strip's // staircase before (or without) the chrome's own schedule. diff --git a/umtool/lib/report/postComboCli.mjs b/umtool/lib/report/postComboCli.mjs @@ -0,0 +1,287 @@ +// `umtool posts repeats` / `umtool posts combo` (report-to-video/post-combo.mjs): +// the COMBO COUNTER from a terminal -- which attachments the cut plays more +// than once, and the badge's knobs. +// +// umtool posts repeats <project> [--match id|file|audio] [--json] +// umtool posts combo <project> [k=v …] [--json] the cut's (render.posts.combo) +// umtool posts combo <project> <item> off|on|auto|k=v … [--json] one item's (`combo`) +// +// `repeats` lists each repeated attachment with its posts in the cut's order +// (their dates, the tier that matched) and the badge each draws; a post item +// whose CAPTURE holds the same file but whose entry carries no attachment (it +// was captured after it went in) is listed too, marked, with how to bring it +// in -- it draws no badge and does not count until it plays the attachment. +// +// Plain ESM: the CLI runs it under bare node. +import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, comboKnobs, repeatGroups } from "umtool-report-to-video/post-combo"; +import { captureOnlyMedia, projectCombos } from "umtool-report-to-video/post-combo-prints"; +import { channelsDirFor, readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { copyFile, mkdir, realpath, stat } from "node:fs/promises"; +import path from "node:path"; +import { attachPostMedia, manifestToken, updatePostCombo, updatePostComboRender } from "./manifest.mjs"; +import { mediaKindOf, probeMediaFile } from "./postReel.mjs"; + +export class ComboError extends Error {} + +export const REPEATS_USAGE = [ + "usage: umtool posts repeats <project> [--match id|file|audio] [--json]", + " every attachment the cut's post items play more than once, its posts in the cut's order (dates, the tier", + " that matched: the X media id, the file's sha256, or -- --match audio -- the sound's fingerprint), and the", + " combo badge each draws (×2 from the second use; render.posts.combo). A post whose capture holds the same", + " file but whose entry has no attachment yet is listed too, marked: it counts once it plays it.", + " umtool posts combo <project> [on=on|off] [label=COMBO] [position=top-right|top-left|bottom-right|bottom-left|center]", + " [color=#rrggbb] [scale=0.4-2.5] [sfx=off|hit|coin] [minCount=2-20] [match=id|file|audio] [--json]", + " the cut's badge (render.posts.combo; k= back to the default); no knobs prints them.", + " umtool posts combo <project> <item> off|on|auto [label=…] [position=…] [color=…] [scale=…] [sfx=…] [--json]", + " one post item's: off draws no badge on it (it still counts), on/auto the cut's again; its own label, …", + " umtool posts attach <project> [<item> … | --all] [--dry-run] [--json]", + " a post item with no attachment whose capture holds one (captured after it went in): its media copied in and", + " set, as posts reel would have made it -- nothing else of the entry changes. One write (one undo point).", +].join("\n"); + +const OFF = new Set(["off", "no", "false", "0"]); +const ON = new Set(["on", "yes", "true", "1"]); + +/** `k=v` words into a combo patch (null: the default / the cut's). */ +export function comboPatchOf(pairs, { item = false } = {}) { + const keys = item ? COMBO_ITEM_KEYS : Object.keys(COMBO_DEFAULTS); + /** @type {Record<string, any>} */ + const out = {}; + for (const pair of pairs) { + const eq = pair.indexOf("="); + if (eq < 1) throw new ComboError(`${pair}: a knob is key=value`); + const k = pair.slice(0, eq); + const raw = pair.slice(eq + 1); + if (!keys.includes(k)) throw new ComboError(`${k}= is not a ${item ? "post item's " : ""}combo knob (${keys.join(", ")})`); + if (raw === "") out[k] = null; + else if (k === "on") { + if (!ON.has(raw.toLowerCase()) && !OFF.has(raw.toLowerCase())) throw new ComboError("on= takes on or off"); + out.on = ON.has(raw.toLowerCase()); + } else if (k === "scale" || k === "minCount") { + const v = Number(raw); + if (!Number.isFinite(v)) throw new ComboError(`${k}= takes a number`); + out[k] = v; + } else out[k] = raw; + } + return out; +} + +async function projectOf(projectArg, root) { + const { resolveProject } = await import("../projects/core.mjs"); + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new ComboError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new ComboError(`no project matches "${projectArg}"`); + return r.project; +} + +/** + * THE REPEATS VIEW: the cut's groups with the capture-only posts folded in. + * + * @param {{ id: string, dir: string }} project + * @param {{ match?: string | null, cacheDir?: string | null, channelsDir?: string | null }} [o] + */ +export async function repeatsView(project, { match = null, cacheDir = undefined, channelsDir = null } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new ComboError(`${project.id} has no manifest`); + const corpus = channelsDir ?? channelsDirFor(project.dir, manifest); + const opts = { channelsDir: corpus, ...(match ? { match } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) }; + const cut = await projectCombos(project.dir, manifest, opts); + // The posts whose capture has a file their entry does not carry: in the cut's order, as if they played it. + const captured = await captureOnlyMedia(manifest, { channelsDir: corpus }); + const tl = (manifest.timeline ?? []).map((e) => (captured[e?.id] ? { ...e, media: captured[e.id].map((m) => ({ src: `@capture/${m.slug}/${m.name}`, kind: "capture" })) } : e)); + const prints = (id, i) => (captured[id] ? { mediaId: captured[id][i]?.mediaId ?? null, sha256: captured[id][i]?.sha256 ?? null } : cut.prints[`${id}:${i}`]); + const all = repeatGroups(tl, prints, { match: cut.match }); + const byId = new Map((manifest.timeline ?? []).map((e) => [e?.id, e])); + const ids = (manifest.timeline ?? []).map((e) => e?.id); + const afterOf = (id) => (ids.indexOf(id) > 0 ? ids[ids.indexOf(id) - 1] : "-"); + const groups = all.map((g) => { + const first = g.members.find((m) => !captured[m.id]) ?? g.members[0]; + const att = byId.get(first.id)?.media?.[first.i]; + return { + key: g.key, + tiers: g.tiers, + kind: att?.kind ?? "?", + src: att?.src ?? first.src, + members: g.members.map((m) => { + const c = cut.combos[m.id]; + const cap = captured[m.id]?.[m.i]; + return { + id: m.id, n: m.n, post: m.post, date: m.date, tier: m.tier, attached: !cap, + ...(cap ? { capture: `${cap.slug}/posts-media/${String(m.post ?? "").split("/")[1] ?? ""}/${cap.name}`, captureSlug: cap.slug, after: afterOf(m.id) } : {}), + badge: c && c.media === m.i ? c.count : null, show: !!(c && c.media === m.i && c.show), + }; + }), + }; + }).filter((g) => g.members.some((m) => m.attached)); + groups.forEach((g, k) => (g.key = `g${k + 1}`)); + return { project: project.id, match: cut.match, knobs: comboKnobs(manifest.render), groups, combos: cut.combos }; +} + +const TIER_WORDS = { "media-id": "X media id", sha256: "same file", audio: "same sound" }; +const MATCH_WORDS = { id: "the X media id", file: "the X media id, then the file's bytes", audio: "the X media id, the bytes, then the sound" }; + +/** Copy a capture's file into the project (never through a link out of it); the same size already there is left. */ +async function copyIn(projectDir, from, rel) { + const to = path.join(projectDir, ...rel.split("/")); + const [a, b] = await Promise.all([stat(from).catch(() => null), stat(to).catch(() => null)]); + if (a && b && a.size === b.size) return; + await mkdir(path.dirname(to), { recursive: true }); + const [real, proj] = await Promise.all([realpath(path.dirname(to)), realpath(projectDir)]); + if (real !== proj && !real.startsWith(proj + path.sep)) throw new Error(`${path.dirname(rel)} leads out of the project (a link) — not copying through it`); + await copyFile(from, to); +} + +/** + * ATTACH WHAT THE CAPTURES HOLD (`umtool posts attach`): each post item with no + * attachment whose capture has one (captured after it went in) gets its media + * as `posts reel` would have made it -- the files copied into the project's + * posts-media/, measured -- and nothing else of the entry changes (its + * paraphrases, narration, knobs kept). One write. `ids` narrows it. + * + * @param {{ id: string, dir: string }} project + * @param {{ ids?: string[] | null, dryRun?: boolean, channelsDir?: string | null }} [o] + */ +export async function attachFromCaptures(project, { ids = null, dryRun = false, channelsDir = null } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new ComboError(`${project.id} has no manifest`); + const corpus = channelsDir ?? channelsDirFor(project.dir, manifest); + const captured = await captureOnlyMedia(manifest, { channelsDir: corpus }); + const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; + const want = ids ? ids.map((r) => tl.find((e) => e?.type === "post" && (e.id === r || String(e.post ?? "").split("/")[1] === r))?.id ?? r) : null; + if (want) for (const id of want) if (!tl.some((e) => e?.id === id && e.type === "post")) throw new ComboError(`no post item ${id} in ${project.id}`); + const patches = {}; + const plan = []; + for (const [id, list] of Object.entries(captured)) { + if (want && !want.includes(id)) continue; + const postId = String(tl.find((e) => e?.id === id)?.post ?? "").split("/")[1]; + const media = []; + for (const m of list) { + const from = path.join(corpus, m.slug, "posts-media", postId, m.name); + if (!(await stat(from).catch(() => null))) continue; + const rel = `posts-media/${m.slug}/${postId}/${m.name}`; + const probe = await probeMediaFile(from); + const kind = mediaKindOf(m.name, m.url, probe); + const item = { + src: rel, kind, + ...(probe.width ? { width: probe.width } : {}), + ...(probe.height ? { height: probe.height } : {}), + ...(kind !== "image" && probe.seconds ? { seconds: probe.seconds } : {}), + ...(kind === "video" ? { audio: probe.audio === true } : {}), + }; + // A timed attachment that could not be measured cannot be planned. + if (kind !== "image" && !Number.isFinite(item.seconds)) continue; + media.push({ item, from }); + } + if (!media.length) continue; + patches[id] = media.map((x) => x.item); + plan.push({ id, media: media.map((x) => ({ src: x.item.src, kind: x.item.kind, from: x.from })) }); + } + if (dryRun || !plan.length) return { dryRun, attached: plan, result: null, editNotes: null }; + for (const p of plan) for (const m of p.media) await copyIn(project.dir, m.from, m.src); + const { result, editNotes } = await withEditNotes(project, async () => attachPostMedia(project.dir, patches, { token: await manifestToken(project.dir) })); + return { dryRun, attached: plan.filter((p) => result.ids.includes(p.id)), result, editNotes }; +} + +/** The repeats view as lines. */ +export function repeatsLines(v) { + const out = []; + const shown = v.groups.filter((g) => g.members.filter((m) => m.attached).length >= 2); + out.push(`${shown.length} attachment(s) played more than once in ${v.project} (matched by ${MATCH_WORDS[v.match] ?? v.match}; the badge ${v.knobs.on === false ? "OFF for the cut" : `from ×${v.knobs.minCount}`})`); + for (const g of v.groups) { + const uses = g.members.filter((m) => m.attached).length; + out.push(` ${g.key} ${uses}× ${g.kind} ${g.src}${g.members.length > uses ? ` (+${g.members.length - uses} not attached yet)` : ""}`); + for (const m of g.members) { + const day = typeof m.date === "string" ? m.date.slice(0, 10) : "?"; + const badge = !m.attached ? " - " : m.badge && m.badge >= 2 ? (m.show ? `×${m.badge}`.padEnd(5) : `(×${m.badge})`.padEnd(5)) : " 1 "; + const how = m.tier ? TIER_WORDS[m.tier] ?? m.tier : "first"; + out.push(` ${badge} ${m.id} ${day} ${m.post ?? ""} [${how}]${m.attached ? "" : ` NOT ATTACHED: its capture ${m.capture} is the same file`}`); + } + } + const missing = v.groups.flatMap((g) => g.members.filter((m) => !m.attached)); + if (missing.length) { + out.push(` ${missing.length} post(s) above carry no attachment in the cut (captured after they went in); each counts once it plays it:`); + out.push(` umtool posts attach ${v.project} ${missing.map((m) => m.id).join(" ")} (their capture's media, nothing else of the entry changed)`); + } + return out; +} + +/** + * @param {"repeats" | "combo"} verb + * @param {string[]} words the words after the verb (project first) + * @param {Map<string, string | true>} flags + * @param {{ root: string, json: boolean, out: (s: string) => void, err: (s: string) => void }} o + */ +export async function comboCommand(verb, words, flags, o) { + try { + return await comboRun(verb, words, flags, o); + } catch (e) { + if (!(e instanceof ComboError)) throw e; + o.err(`umtool posts ${verb}: ${e.message}`); + return 2; + } +} + +async function comboRun(verb, words, flags, { root, json, out, err }) { + const [projectArg, ...rest] = words; + if (!projectArg || flags.has("--help")) { + err(REPEATS_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + if (verb === "attach") { + const items = rest.filter((w) => !w.startsWith("--")); + if (!items.length && !flags.has("--all")) throw new ComboError("name the items to attach, or --all"); + const r = await attachFromCaptures(project, { ids: items.length ? items : null, dryRun: flags.has("--dry-run") }); + if (json) out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2)); + else { + out(`${r.dryRun ? "would attach" : "attached"} the capture's media to ${r.attached.length} post item(s) in ${project.id}`); + for (const a of r.attached) out(` ${a.id} ${a.media.map((m) => `${m.kind} ${m.src}`).join(", ")}`); + if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`); + } + return 0; + } + if (verb === "repeats") { + const m = flags.get("--match"); + if (m !== undefined && !["id", "file", "audio"].includes(String(m))) throw new ComboError("--match takes id, file or audio"); + const v = await repeatsView(project, { match: m === undefined ? null : String(m) }); + out(json ? JSON.stringify({ ok: true, ...v }, null, 2) : repeatsLines(v).join("\n")); + return 0; + } + // combo: the cut's (no item), or one item's. + const manifest = await readManifest(project.dir); + if (!manifest) throw new ComboError(`${project.id} has no manifest`); + const isPair = (w) => w.includes("="); + if (!rest.length || isPair(rest[0])) { + if (!rest.length) { + const k = comboKnobs(manifest.render); + out(json ? JSON.stringify({ ok: true, combo: manifest.render?.posts?.combo ?? null, knobs: k }, null, 2) : `the cut's combo badge: ${Object.entries(k).map(([a, b]) => `${a}=${b}`).join(" ")}`); + return 0; + } + const patch = comboPatchOf(rest); + const { result, editNotes } = await withEditNotes(project, async () => updatePostComboRender(project.dir, patch, { token: await manifestToken(project.dir) })); + out(json ? JSON.stringify({ ok: true, combo: result.combo, token: result.token, editNotes }, null, 2) : `the cut's combo badge: ${JSON.stringify(result.combo ?? "the defaults")}`); + return 0; + } + const [ref, ...pairs] = rest; + const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; + const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref)); + if (!hit) throw new ComboError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + let value; + const word = pairs.length === 1 && !isPair(pairs[0]) ? pairs[0].toLowerCase() : null; + if (!pairs.length) { + out(json ? JSON.stringify({ ok: true, id: hit.id, combo: hit.combo ?? null, knobs: comboKnobs(manifest.render, hit) }, null, 2) : `${hit.id}: ${hit.combo === false ? "no badge (off)" : hit.combo ? JSON.stringify(hit.combo) : "the cut's badge"}`); + return 0; + } + if (word !== null) { + if (OFF.has(word)) value = false; + else if (ON.has(word) || word === "auto") value = hit.combo === false || !hit.combo ? null : { on: null }; + else throw new ComboError(`${pairs[0]}: off, on, auto or key=value`); + } else { + if (pairs.some((p) => !isPair(p))) throw new ComboError("off / on go alone; knobs are key=value"); + value = comboPatchOf(pairs, { item: true }); + } + const { result, editNotes } = await withEditNotes(project, async () => updatePostCombo(project.dir, hit.id, value, { token: await manifestToken(project.dir) })); + out(json ? JSON.stringify({ ok: true, id: hit.id, combo: result.combo, token: result.token, editNotes }, null, 2) : `${hit.id}: ${result.combo === false ? "no badge on this item (it still counts)" : result.combo ? `its own: ${JSON.stringify(result.combo)}` : "the cut's badge"}`); + return 0; +} diff --git a/umtool/lib/report/postComboCli.test.mjs b/umtool/lib/report/postComboCli.test.mjs @@ -0,0 +1,127 @@ +// `umtool posts repeats` / `posts combo` (postComboCli.mjs) and their writers +// (manifest.mjs updatePostCombo, updatePostComboRender): the repeats listed in +// the cut's order with the capture-only posts marked; an item's badge off and +// on; the cut's knobs set, refused in the build's words. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postsCommand } from "./postsCli.mjs"; +import { repeatsView } from "./postComboCli.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-combo-")); +after(() => rm(ROOT, { recursive: true, force: true })); +process.env.UMTOOL_PRINTS_CACHE = path.join(ROOT, "cache"); +const CH = path.join(ROOT, "channels"); +const REPORTS = path.join(ROOT, "reports"); + +const post = (id, media) => ({ + type: "post", id: `p-${id}`, post: `obv-x/${id}`, platform: "x", author: "Mr. Obvious", handle: "ObviousRises", date: `2026-11-0${id}T10:00:00.000Z`, text: `post ${id}`, + ...(media ? { media: [{ src: `posts-media/obv-x/${id}/${id}_1.mp4`, kind: "gif", seconds: 2, width: 498, height: 280 }] } : {}), +}); + +async function project(name) { + const dir = path.join(REPORTS, name); + for (const id of ["1", "2", "4"]) { + await mkdir(path.join(dir, "posts-media", "obv-x", id), { recursive: true }); + await writeFile(path.join(dir, "posts-media", "obv-x", id, `${id}_1.mp4`), id === "4" ? "ANOTHER" : "THE-SAME-GIF"); + } + // 3 went in before its capture: no attachment in the cut, the same file in the corpus (the replies channel, which 4 comes from). + await mkdir(path.join(CH, "obv-x-replies", "posts-media", "3"), { recursive: true }); + const { createHash } = await import("node:crypto"); + const sha = createHash("sha256").update("THE-SAME-GIF").digest("hex"); + await writeFile(path.join(CH, "obv-x-replies", "posts-media", "3", "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", bytes: 12, sha256: sha, url: "https://video.twimg.com/tweet_video/C.mp4" }] })); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "obv-x", channelsDir: CH }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, + timeline: [post("1", true), { type: "clip", id: "c01", video: "v1", start: 1, end: 3 }, post("2", true), { ...post("3", false), post: "obv-x/3" }, { ...post("4", true), post: "obv-x-replies/4" }, { ...post("5", true), media: [{ src: "posts-media/obv-x/1/1_1.mp4", kind: "gif", seconds: 2 }] }], + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const run = async (args) => { + const out = []; + const err = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => out.push(s), err: (s) => err.push(s) }); + return { code, out: out.join("\n"), err: err.join("\n") }; +}; + +test("posts repeats: the attachment's posts in the cut's order, the badges they draw, and the post whose capture has it", async () => { + const p = await project("rep"); + const v = await repeatsView(p); + assert.equal(v.groups.length, 1); + assert.deepEqual(v.groups[0].members.map((m) => `${m.id}:${m.attached ? (m.badge ?? 1) : "-"}`), ["p-1:1", "p-2:2", "p-3:-", "p-5:3"]); + const three = v.groups[0].members.find((m) => m.id === "p-3"); + assert.equal(three.captureSlug, "obv-x-replies"); + assert.equal(three.after, "p-2"); + const r = await run(["repeats", "rep"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /1 attachment\(s\) played more than once/); + assert.match(r.out, /×3\s+p-5/); + assert.match(r.out, /NOT ATTACHED: its capture obv-x-replies\/posts-media\/3\/3_1\.mp4/); + assert.match(r.out, /umtool posts attach rep p-3/); + const j = JSON.parse((await run(["repeats", "rep", "--json", "--match", "id"])).out); + assert.equal(j.match, "id"); + assert.equal(j.groups.length, 0, "the GIF's ids differ: by id alone, no repeat"); + assert.equal((await run(["repeats", "rep", "--match", "pixels"])).code, 2); +}); + +test("posts combo: an item's badge off (it still counts) and back; the cut's knobs set and refused in the build's words", async () => { + const p = await project("knobs"); + let r = await run(["combo", "knobs", "p-2", "off"]); + assert.equal(r.code, 0, r.err); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-2").combo, false); + let v = await repeatsView(p); + assert.deepEqual(v.groups[0].members.filter((m) => m.attached).map((m) => `${m.id}:${m.badge}${m.show ? "!" : ""}`), ["p-1:1", "p-2:2", "p-5:3!"]); + r = await run(["combo", "knobs", "p-2", "on"]); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-2").combo, undefined); + r = await run(["combo", "knobs", "p-5", "label=HIT", "color=#22ccff"]); + assert.deepEqual((await manifest(p)).timeline.find((e) => e.id === "p-5").combo, { label: "HIT", color: "#22ccff" }); + r = await run(["combo", "knobs", "p-5", "label="]); + assert.deepEqual((await manifest(p)).timeline.find((e) => e.id === "p-5").combo, { color: "#22ccff" }); + // The cut's. + r = await run(["combo", "knobs", "minCount=3", "sfx=hit", "scale=1.5"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual((await manifest(p)).render.posts, { combo: { minCount: 3, sfx: "hit", scale: 1.5 } }); + v = await repeatsView(p); + assert.deepEqual(v.groups[0].members.filter((m) => m.attached).map((m) => m.show), [false, false, true]); + r = await run(["combo", "knobs", "sfx=boom"]); + assert.equal(r.code, 1); + assert.match(r.err, /render\.posts\.combo\.sfx must be one of off, hit, coin/); + r = await run(["combo", "knobs", "minCount=", "sfx=", "scale="]); + assert.equal((await manifest(p)).render.posts, undefined, "back to the defaults: no key left"); + assert.equal((await run(["combo", "knobs", "p-9", "off"])).code, 2); + assert.equal((await run(["combo", "knobs", "p-5", "minCount=3"])).code, 2, "minCount is the cut's"); + r = await run(["combo", "knobs"]); + assert.match(r.out, /label=COMBO/); +}); + +test("posts attach: the capture's media onto the item that carries none, nothing else of it changed; then it counts", async () => { + const p = await project("att"); + // A real GIF in the corpus capture (it must measure), the same bytes as the cut's p-1/p-2. + const { execFileSync } = await import("node:child_process"); + const { createHash } = await import("node:crypto"); + const capDir = path.join(CH, "obv-x-replies", "posts-media", "3"); + const gif = path.join(capDir, "3_1.mp4"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-an", gif]); + const body = await readFile(gif); + for (const id of ["1", "2"]) await writeFile(path.join(p.dir, "posts-media", "obv-x", id, `${id}_1.mp4`), body); + await writeFile(path.join(capDir, "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", bytes: body.length, sha256: createHash("sha256").update(body).digest("hex"), url: "https://video.twimg.com/tweet_video/C.mp4" }] })); + const m0 = await manifest(p); + m0.timeline.find((e) => e.id === "p-3").quoted = { text: "kept", paraphrase: "kept too" }; + await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(m0, null, 2)); + const dry = JSON.parse((await run(["attach", "att", "--all", "--dry-run", "--json"])).out); + assert.deepEqual(dry.attached.map((a) => a.id), ["p-3"]); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-3").media, undefined, "a dry run writes nothing"); + const r = await run(["attach", "att", "p-3"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /attached the capture's media to 1 post item/); + const e = (await manifest(p)).timeline.find((x) => x.id === "p-3"); + assert.equal(e.media[0].src, "posts-media/obv-x-replies/3/3_1.mp4"); + assert.equal(e.media[0].kind, "gif", "a tweet_video is a GIF X serves as a silent mp4"); + assert.deepEqual(e.quoted, { text: "kept", paraphrase: "kept too" }); + const v = await repeatsView(p); + assert.deepEqual(v.groups[0].members.map((m) => `${m.id}:${m.attached ? m.badge : "-"}`), ["p-1:1", "p-2:2", "p-3:3", "p-5:4"]); + assert.equal((await run(["attach", "att"])).code, 2, "names the items, or --all"); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -91,6 +91,9 @@ export const POSTS_USAGE = [ " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", " none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.", + " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)", + " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (umtool posts repeats --help)", + " umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto items that carry none", ].join("\n"); const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]); @@ -397,6 +400,8 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con if (verb === "avatar" && projectArg && !flags.has("--help")) return await avatarCommand(projectArg, words.slice(2), { root, json, out }); if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out }); if (verb === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out }); + // The combo counter (postComboCli.mjs): the attachments played more than once, the badge's knobs. + if (verb === "repeats" || verb === "combo" || verb === "attach") return await (await import("./postComboCli.mjs")).comboCommand(verb, words.slice(1), flags, { root, json, out, err }); if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); return 2; 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 @@ -215,6 +215,8 @@ import { buildPostSegment } from "./post-render.mjs"; import { readPostRedaction } from "./post-redact-files.mjs"; import { dropMarks, redactEntry } from "./post-redact.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"; @@ -6300,6 +6302,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. @@ -6418,6 +6425,13 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly redaction: POST_REDACTION, }); 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/lint.mjs b/umtool/report-to-video/lint.mjs @@ -88,6 +88,7 @@ import { postItemFiles, validatePostItems } from "./post-item.mjs"; import { wordZoomTimes } from "./word-zoom.mjs"; import { postAvatarFiles, validatePostAvatars } from "./post-avatars.mjs"; import { validatePostNarrationRender } from "./post-narration.mjs"; +import { validatePostCombos } from "./post-combo.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -331,6 +332,8 @@ export function validatorErrors(whole) { ...validatePostAvatars(whole), // A narrated post item's mix (post-narration.mjs): the cut's knobs. ...validatePostNarrationRender(whole.render), + // The combo counter (post-combo.mjs): render.posts.combo and each post item's `combo`. + ...validatePostCombos(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -61,6 +61,9 @@ "./pauses": "./pauses.mjs", "./post-links": "./post-links.mjs", "./post-avatars": "./post-avatars.mjs", + "./post-combo": "./post-combo.mjs", + "./post-combo-prints": "./post-combo-prints.mjs", + "./post-combo-render": "./post-combo-render.mjs", "./post-item": "./post-item.mjs", "./post-narration": "./post-narration.mjs", "./post-censor": "./post-censor.mjs", diff --git a/umtool/report-to-video/post-combo-prints.mjs b/umtool/report-to-video/post-combo-prints.mjs @@ -0,0 +1,224 @@ +// THE COMBO COUNTER's PRINTS (post-combo.mjs): what each post item's +// attachment IS, read from disk -- its X media id and sha256 from the +// capture's record (capture.json, the project's copy beside the file, else +// the corpus's `channels/<slug>/posts-media/<postId>/`), the file hashed when +// no record vouches for it, and (opt-in) its sound's fingerprint. Each +// file's print is CACHED by its path, size and mtime: in memory, and on disk +// under UMTOOL_PRINTS_CACHE (default ~/.cache/umtool/media-prints), so a +// second look at a cut hashes nothing. +// +// attachmentPrints(manifest, dir, o) { "<itemId>:<i>": print } +// projectCombos(dir, manifest, o) the groups and each item's combo (post-combo.mjs), one call +// +// Plain ESM, node only: the build, the CLI and umtool's server import it. +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createReadStream } from "node:fs"; +import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { COMBO_DEFAULTS, comboCounts, comboItems, comboKnobs, repeatGroups, tiersOf, xMediaIdOf } from "./post-combo.mjs"; + +const execFileP = promisify(execFile); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** Where the prints are kept: UMTOOL_PRINTS_CACHE, else ~/.cache/umtool/media-prints (XDG_CACHE_HOME honoured). */ +export function printsCacheDir(env = process.env) { + if (env.UMTOOL_PRINTS_CACHE) return env.UMTOOL_PRINTS_CACHE; + return path.join(/* turbopackIgnore: true */ env.XDG_CACHE_HOME || path.join(/* turbopackIgnore: true */ os.homedir(), ".cache"), "umtool", "media-prints"); +} + +const memo = new Map(); +const MEMO_MAX = 4000; + +/** A file's cached print fields (`sha256`, `audio`), keyed by its path and signature. */ +async function cached(file, sig, cacheDir, field, make) { + // No cache asked for (null): made every time. + if (cacheDir === null) return make(); + const key = createHash("sha1").update(file).digest("hex"); + let rec = memo.get(key); + if (!rec || rec.sig !== sig) { + rec = cacheDir ? await readFile(path.join(cacheDir, `${key}.json`), "utf8").then((t) => JSON.parse(t), () => null) : null; + if (!rec || rec.sig !== sig) rec = { sig, file }; + } + if (!(field in rec)) { + rec[field] = await make(); + if (cacheDir) { + await mkdir(cacheDir, { recursive: true }).catch(() => {}); + const tmp = path.join(cacheDir, `.${key}.${process.pid}.tmp`); + await writeFile(tmp, JSON.stringify(rec), "utf8").then(() => rename(tmp, path.join(cacheDir, `${key}.json`)), () => {}); + } + } + if (memo.size >= MEMO_MAX) memo.delete(memo.keys().next().value); + memo.set(key, rec); + return rec[field]; +} + +/** A file's sha256, streamed. */ +export function sha256File(file) { + return new Promise((resolve, reject) => { + const h = createHash("sha256"); + createReadStream(file).on("data", (b) => h.update(b)).on("end", () => resolve(h.digest("hex"))).on("error", reject); + }); +} + +/** + * The sound's fingerprint: chromaprint's raw print (`fpcalc -raw`, its first + * 30 s), else the coarse hash -- ffmpeg's 8 kHz mono, each 1/8 s its energy + * and its zero crossings against the one before (2 bits), 16 steps to a word. + * Null for a file with no sound, or when neither tool runs. + * + * @returns {Promise<{ kind: "chromaprint"|"energy", bits: number, words: number[], seconds: number } | null>} + */ +export async function audioPrintOf(file, { fpcalc = process.env.FPCALC_BIN ?? "fpcalc", ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", exec = execFileP } = {}) { + try { + const r = await exec(fpcalc, ["-raw", "-json", "-length", "30", file], { maxBuffer: 1 << 24 }); + const j = JSON.parse(String(r.stdout)); + if (Array.isArray(j?.fingerprint) && j.fingerprint.length) return { kind: "chromaprint", bits: 32, words: j.fingerprint.map((v) => v >>> 0), seconds: Number(j.duration) || 0 }; + } catch { + // no fpcalc, or no sound it can read: the coarse hash + } + try { + const r = await exec(ffmpeg, ["-nostdin", "-v", "error", "-t", "30", "-i", file, "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { encoding: "buffer", maxBuffer: 1 << 26 }); + return energyPrint(Buffer.from(r.stdout)); + } catch { + return null; + } +} + +/** The coarse hash of 8 kHz mono s16le samples (audioPrintOf's fallback), pure. Null when silent or too short. */ +export function energyPrint(buf, rate = 8000) { + const n = Math.floor(buf.length / 2); + const block = Math.round(rate / 8); + const blocks = Math.floor(n / block); + if (blocks < 4) return null; + const e = []; + const z = []; + for (let b = 0; b < blocks; b += 1) { + let s = 0; + let c = 0; + let prev = 0; + for (let i = 0; i < block; i += 1) { + const v = buf.readInt16LE((b * block + i) * 2); + s += v * v; + if (i && (v >= 0) !== (prev >= 0)) c += 1; + prev = v; + } + e.push(Math.sqrt(s / block)); + z.push(c); + } + if (Math.max(...e) < 30) return null; + const bitsOut = []; + for (let b = 1; b < blocks; b += 1) bitsOut.push(e[b] > e[b - 1] ? 1 : 0, z[b] > z[b - 1] ? 1 : 0); + const words = []; + for (let i = 0; i + 16 <= bitsOut.length; i += 16) { + let w = 0; + for (let j = 0; j < 16; j += 1) w = (w << 1) | bitsOut[i + j]; + words.push(w >>> 0); + } + return words.length ? { kind: "energy", bits: 16, words, seconds: n / rate } : null; +} + +/** The capture record a project file came from: beside it in the project, else the corpus's (`posts-media/<slug>/<postId>/<name>`). */ +async function captureRecordOf(dir, src, entry, channelsDir) { + const name = path.basename(src); + const m = /^posts-media\/([^/]+)\/([^/]+)\/[^/]+$/.exec(src); + const tries = [path.join(dir, path.dirname(src), "capture.json")]; + if (channelsDir && m) tries.push(path.join(channelsDir, m[1], "posts-media", m[2], "capture.json")); + const [slug, postId] = typeof entry?.post === "string" ? entry.post.split("/") : []; + if (channelsDir && slug && postId && !(m && m[1] === slug && m[2] === postId)) tries.push(path.join(channelsDir, slug, "posts-media", postId, "capture.json")); + for (const f of tries) { + const cap = await readFile(f, "utf8").then((t) => JSON.parse(t), () => null); + const rec = Array.isArray(cap?.media) ? cap.media.find((x) => x?.name === name) : null; + if (rec) return rec; + } + return null; +} + +/** + * EVERY ATTACHMENT's PRINT in the cut: `{ "<itemId>:<i>": { mediaId, sha256, + * audio?, via } }` -- the media id from the capture's url, the sha256 from its + * record when the bytes agree (`via: "capture"`), else the file's own (`via: + * "hashed"`), the sound's print when `match` is "audio" and it is a video with + * sound. A file not on disk has no print (it cannot be told apart). + * + * @param {Record<string, any>} manifest + * @param {string} dir the project's folder (the manifest's) + * @param {{ channelsDir?: string|null, match?: string, cacheDir?: string|null, audioPrint?: typeof audioPrintOf }} [o] + */ +export async function attachmentPrints(manifest, dir, { channelsDir = null, match = null, cacheDir = printsCacheDir(), audioPrint = audioPrintOf } = {}) { + const tiers = tiersOf(match ?? comboKnobs(manifest?.render).match ?? COMBO_DEFAULTS.match); + const out = {}; + for (const e of comboItems(manifest?.timeline)) { + for (const [i, m] of e.media.entries()) { + if (!isObj(m) || typeof m.src !== "string") continue; + const file = path.resolve(dir, m.src); + const st = await stat(file).catch(() => null); + if (!st?.isFile()) continue; + const sig = `${st.size}|${Math.round(st.mtimeMs)}`; + const rec = await captureRecordOf(dir, m.src, e, channelsDir); + const p = { mediaId: xMediaIdOf(rec?.url), sha256: null, via: null }; + if (tiers.includes("sha256")) { + if (typeof rec?.sha256 === "string" && /^[0-9a-f]{64}$/.test(rec.sha256) && rec.bytes === st.size) { + p.sha256 = rec.sha256; + p.via = "capture"; + } else { + p.sha256 = await cached(file, sig, cacheDir, "sha256", () => sha256File(file)); + p.via = "hashed"; + } + } + if (tiers.includes("audio") && m.kind === "video" && m.audio !== false) { + p.audio = await cached(file, sig, cacheDir, "audio", () => audioPrint(file)); + } + out[`${e.id}:${i}`] = p; + } + } + return out; +} + +/** + * THE CUT's COMBOS in one call: the repeat groups (post-combo.mjs + * repeatGroups) over the prints, and each item's combo (comboCounts). + * + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {{ channelsDir?: string|null, match?: string|null, cacheDir?: string|null, audioPrint?: typeof audioPrintOf }} [o] + */ +export async function projectCombos(dir, manifest, o = {}) { + const match = o.match ?? comboKnobs(manifest?.render).match; + const prints = await attachmentPrints(manifest, dir, { ...o, match }); + const groups = repeatGroups(manifest?.timeline, (id, i) => prints[`${id}:${i}`], { match }); + return { match, groups, combos: comboCounts(manifest?.timeline, groups, manifest?.render), prints }; +} + +/** + * THE REPEATS THE CUT DOES NOT SHOW YET: a post item with no attachment in + * the cut whose capture holds one (captured after the item went in -- its + * media was never copied). Its capture is looked for under its own channel, + * then every channel the cut's posts come from (a reply captured under the + * replies channel). `{ <itemId>: [{ name, slug, mediaId, sha256, url }] }`. + * + * @param {Record<string, any>} manifest + * @param {{ channelsDir?: string|null }} [o] + */ +export async function captureOnlyMedia(manifest, { channelsDir = null } = {}) { + if (!channelsDir) return {}; + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter(Boolean))]; + const out = {}; + for (const e of tl) { + if (e?.type !== "post" || typeof e.post !== "string" || (Array.isArray(e.media) && e.media.length)) continue; + const [own, postId] = e.post.split("/"); + if (!own || !postId) continue; + for (const slug of [own, ...channels.filter((c) => c !== own)]) { + const dirOf = path.join(channelsDir, slug, "posts-media", postId); + const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null); + const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : []; + if (!media.length) continue; + out[e.id] = media.map((m) => ({ name: m.name, slug, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null })); + break; + } + } + return out; +} 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(/* 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(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(/* turbopackIgnore: true */ 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 @@ -0,0 +1,439 @@ +// THE COMBO COUNTER (umtool/docs/report-video.md, "The combo counter"): when a +// post item's attachment is one an EARLIER item of the cut already played -- +// the same reaction video answering a third person -- a fighting-game badge +// pops onto the card as that attachment starts: "COMBO ×2", "×3", … (operator, +// 3 Nov: "an effect that shows a combo counter or something when he uses the +// same video to reply to someone"). +// +// WHAT IS A REPEAT. Two attachments are the same when they share, in order of +// trust: +// +// media-id X's own id for the media, from the capture's source url +// (`amplify_video/<id>`, `ext_tw_video/<id>`, `tweet_video/<id>`, +// pbs `media/<id>`) -- the same upload, attached again +// sha256 the file's bytes (capture.json's `media[i].sha256`, trusted when +// its `bytes` match the project's copy; else the copy hashed) +// audio (opt-in, `match: "audio"`) the sound's fingerprint and its length +// (chromaprint's fpcalc, else a coarse energy hash by ffmpeg): the +// same clip re-encoded +// +// Any one tier links two attachments; the links make the groups (a GIF X +// re-uploads gets a new id every time, and its bytes are what match). The +// prints are read by post-combo-prints.mjs; everything here is PURE -- the +// build, Play, the bench and `umtool posts repeats` read the same rules. +// +// THE COUNT is the use's number in the cut's ORDER (the timeline's, post items +// only): the 2nd use is ×2. An item that turns its badge off (`combo: false`) +// still counts -- the viewer saw the attachment -- its own badge is not drawn. +// The badge shows from `minCount` (default 2). +// +// render.posts.combo = { on, label, position, color, scale, sfx, minCount, match } +// timeline[i].combo = false | { on?, label?, position?, color?, scale?, sfx? } + +/** The cut's knobs (render.posts.combo) and their defaults. */ +export const COMBO_DEFAULTS = Object.freeze({ + on: true, + label: "COMBO", + position: "top-right", + color: "#ffcf33", + scale: 1, + sfx: "off", + minCount: 2, + match: "file", +}); +export const COMBO_POSITIONS = Object.freeze(["top-right", "top-left", "bottom-right", "bottom-left", "center"]); +/** The bundled sounds (assets/combo/<name>.wav), and `off`. */ +export const COMBO_SFX = Object.freeze(["off", "hit", "coin"]); +/** How deep the match goes: `id` the media id alone, `file` + the bytes, `audio` + the sound. */ +export const COMBO_MATCH = Object.freeze(["id", "file", "audio"]); +export const COMBO_TIERS = Object.freeze(["media-id", "sha256", "audio"]); +export const COMBO_LABEL_MAX = 16; +export const COMBO_SCALE = Object.freeze({ min: 0.4, max: 2.5 }); +export const COMBO_MIN_COUNT = Object.freeze({ min: 2, max: 20 }); +/** The knobs a post item may override (minCount and match are the cut's). */ +export const COMBO_ITEM_KEYS = Object.freeze(["on", "label", "position", "color", "scale", "sfx"]); + +/** + * THE MOTION, in seconds from the attachment's start: a slam in from small to + * an OVERSHOOT (1.32×), a spring back through 0.86× to rest, a shake that dies + * away, the hold, then a fade out growing a little. + */ +export const COMBO_TIMING = Object.freeze({ fadeIn: 0.06, pop: 0.12, settle: 0.34, shake: 0.56, out: 2.2, end: 2.6 }); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000 + 0; +const HEX_RE = /^#[0-9a-fA-F]{6}$/; + +// --------------------------------------------------------------------------- +// The media id (tier 1) +// --------------------------------------------------------------------------- + +/** + * X's id for a media url, `<kind>/<id>` (`amplify_video/2117…`, + * `tweet_video/HWCOFy3bwAAsJJS`, `media/HWEqGNfWYAAbqx_`), or null. + */ +export function xMediaIdOf(url) { + if (typeof url !== "string" || !url) return null; + let u; + try { + u = new URL(url); + } catch { + return null; + } + if (!/(^|\.)twimg\.com$/.test(u.hostname)) return null; + const v = /^\/(amplify_video|ext_tw_video|tweet_video)\/([A-Za-z0-9_-]+)/.exec(u.pathname); + if (v) return `${v[1]}/${v[2]}`; + const thumb = /^\/(amplify_video_thumb|ext_tw_video_thumb|tweet_video_thumb)\/([A-Za-z0-9_-]+)/.exec(u.pathname); + if (thumb) return `${thumb[1].replace(/_thumb$/, "")}/${thumb[2]}`; + const pic = /^\/media\/([A-Za-z0-9_-]+)/.exec(u.pathname); + return pic ? `media/${pic[1]}` : null; +} + +// --------------------------------------------------------------------------- +// The audio print (tier 3): compared pure +// --------------------------------------------------------------------------- + +const popcount = (x) => { + let v = x >>> 0; + v -= (v >>> 1) & 0x55555555; + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24; +}; + +/** + * How alike two audio prints are, 0-1: the best share of equal bits over + * small shifts of one against the other (`bits` per word: 32 for chromaprint, + * the energy hash's own). Null when they overlap too little to say. + * + * @param {{ words: number[], bits?: number }} a + * @param {{ words: number[], bits?: number }} b + */ +export function printSimilarity(a, b, o = {}) { + const x = Array.isArray(a?.words) ? a.words : []; + const y = Array.isArray(b?.words) ? b.words : []; + const bits = a?.bits ?? 32; + // About a second of overlap either way: chromaprint's word is ~0.12 s, the energy hash's 1 s. + const { maxShift = bits >= 32 ? 8 : 1, minOverlap = bits >= 32 ? 8 : 3 } = o; + let best = null; + for (let o = -maxShift; o <= maxShift; o += 1) { + let same = 0; + let n = 0; + for (let i = Math.max(0, -o); i < x.length && i + o < y.length; i += 1) { + same += bits - popcount((x[i] ^ y[i + o]) & (bits >= 32 ? 0xffffffff : (1 << bits) - 1)); + n += 1; + } + if (n < minOverlap) continue; + const s = same / (n * bits); + if (best === null || s > best) best = s; + } + return best; +} + +/** The share of bits two prints must agree on to be the same sound (chromaprint's; the coarse hash's is its own). */ +export const AUDIO_MATCH = Object.freeze({ chromaprint: 0.85, energy: 0.8 }); + +/** Two attachments' sounds the same: the prints alike and the lengths within 0.3 s (or 3%). */ +export function audioSame(a, b) { + if (!isObj(a) || !isObj(b) || a.kind !== b.kind) return false; + if (fin(a.seconds) && fin(b.seconds) && Math.abs(a.seconds - b.seconds) > Math.max(0.3, 0.03 * Math.max(a.seconds, b.seconds))) return false; + const s = printSimilarity(a, b); + return s !== null && s >= (AUDIO_MATCH[a.kind] ?? 0.85); +} + +// --------------------------------------------------------------------------- +// The groups and the count +// --------------------------------------------------------------------------- + +/** The post items of a timeline in its order, with an attachment. */ +export const comboItems = (timeline) => (Array.isArray(timeline) ? timeline : []).filter((e) => isObj(e) && e.type === "post" && typeof e.id === "string" && Array.isArray(e.media) && e.media.length); + +/** The tiers a `match` uses. */ +export const tiersOf = (match) => (match === "id" ? ["media-id"] : match === "audio" ? ["media-id", "sha256", "audio"] : ["media-id", "sha256"]); + +/** The strongest tier on which two prints agree, or null. */ +export function linkTier(p, q, tiers = tiersOf("file")) { + if (!isObj(p) || !isObj(q)) return null; + if (tiers.includes("media-id") && p.mediaId && p.mediaId === q.mediaId) return "media-id"; + if (tiers.includes("sha256") && p.sha256 && p.sha256 === q.sha256) return "sha256"; + if (tiers.includes("audio") && p.audio && q.audio && audioSame(p.audio, q.audio)) return "audio"; + return null; +} + +/** + * THE REPEAT GROUPS, pure: every attachment that another item of the cut + * also plays. `prints(itemId, i)` is attachment i's print (`{ mediaId?, + * sha256?, audio? }`, post-combo-prints.mjs). Each group's members are in + * the cut's order, one per item (an item with the attachment twice is one + * use), numbered from 1, each with the strongest tier linking it to an + * earlier member (`tier`, null for the first). + * + * @param {Array<Record<string, any>>} timeline + * @param {(id: string, i: number) => Record<string, any> | null | undefined} prints + * @param {{ match?: string }} [o] + * @returns {Array<{ key: string, tiers: string[], members: Array<{ id: string, i: number, n: number, post: string|null, date: string|null, tier: string|null }> }>} + */ +export function repeatGroups(timeline, prints, { match = COMBO_DEFAULTS.match } = {}) { + const tiers = tiersOf(match); + const items = comboItems(timeline); + const atts = []; + items.forEach((e, order) => e.media.forEach((m, i) => atts.push({ id: e.id, i, order, entry: e, p: prints(e.id, i) ?? null }))); + // Union-find over the attachments: any tier links two. + const up = atts.map((_, k) => k); + const find = (k) => (up[k] === k ? k : (up[k] = find(up[k]))); + for (let a = 0; a < atts.length; a += 1) { + for (let b = a + 1; b < atts.length; b += 1) { + if (atts[a].id === atts[b].id && atts[a].i === atts[b].i) continue; + if (linkTier(atts[a].p, atts[b].p, tiers)) up[find(b)] = find(a); + } + } + const byRoot = new Map(); + atts.forEach((x, k) => { + const r = find(k); + if (!byRoot.has(r)) byRoot.set(r, []); + byRoot.get(r).push(x); + }); + const groups = []; + for (const list of byRoot.values()) { + // One use per item: its first attachment in the group. + const seen = new Set(); + const uses = list.sort((a, b) => a.order - b.order || a.i - b.i).filter((x) => (seen.has(x.id) ? false : seen.add(x.id))); + if (uses.length < 2) continue; + const members = uses.map((x, n) => { + let tier = null; + for (let j = 0; j < n; j += 1) { + const t = linkTier(x.p, uses[j].p, tiers); + if (t && (tier === null || COMBO_TIERS.indexOf(t) < COMBO_TIERS.indexOf(tier))) tier = t; + } + // Linked only through a later member (a chain): the weakest tier of the group says how. + return { id: x.id, i: x.i, n: n + 1, post: typeof x.entry.post === "string" ? x.entry.post : null, date: typeof x.entry.date === "string" ? x.entry.date : null, tier, src: typeof x.entry.media[x.i]?.src === "string" ? x.entry.media[x.i].src : null }; + }); + const tiersUsed = [...new Set(members.map((m) => m.tier).filter(Boolean))].sort((a, b) => COMBO_TIERS.indexOf(a) - COMBO_TIERS.indexOf(b)); + groups.push({ key: "", tiers: tiersUsed, members }); + } + groups.sort((a, b) => items.findIndex((e) => e.id === a.members[0].id) - items.findIndex((e) => e.id === b.members[0].id)); + groups.forEach((g, k) => (g.key = `g${k + 1}`)); + return groups; +} + +/** + * The cut's knobs with every default filled in (render.posts.combo), and an + * item's overrides on top (`combo: false` is `{ on: false }`). + */ +export function comboKnobs(render, entry = null) { + const r = isObj(render?.posts) && isObj(render.posts.combo) ? render.posts.combo : {}; + const own = entry?.combo === false ? { on: false } : isObj(entry?.combo) ? entry.combo : {}; + const pick = Object.fromEntries(COMBO_ITEM_KEYS.filter((k) => own[k] !== undefined).map((k) => [k, own[k]])); + return { ...COMBO_DEFAULTS, ...r, ...pick }; +} + +/** Whether use `count` of item `entry` draws its badge: the cut's on, the item's own, count ≥ minCount. */ +export function comboShow(count, render, entry = null) { + const cut = comboKnobs(render); + return cut.on !== false && comboKnobs(render, entry).on !== false && count >= Math.max(COMBO_MIN_COUNT.min, cut.minCount); +} + +/** + * The combo of an item as it stands NOW (the bench: its `combo` edited, not + * yet saved): its count and attachment as counted, its knobs and `show` read + * again from `render` and `entry`. + */ +export const liveCombo = (combo, render, entry) => (combo ? { ...combo, knobs: comboKnobs(render, entry), show: comboShow(combo.count, render, entry) } : null); + +/** + * EACH ITEM's COMBO, pure: `{ [itemId]: { count, media, group, show, knobs, + * members } }` for every item in a repeat group -- `count` its use's number, + * `media` the attachment it repeats (the first of its attachments with an + * earlier use; else its first in a group), `show` whether its badge is drawn + * (the cut's `on`, the item's own, count ≥ minCount). + */ +export function comboCounts(timeline, groups, render = undefined) { + const out = {}; + const byId = new Map((Array.isArray(timeline) ? timeline : []).filter(isObj).map((e) => [e.id, e])); + // The item's repeat: an attachment with an earlier use before one that is a first, then the lower index. + const better = (m, had) => (m.n >= 2) !== (had.count >= 2) ? m.n >= 2 : m.i < had.media; + for (const g of groups) { + for (const m of g.members) { + const had = out[m.id]; + if (had && !better(m, had)) continue; + const entry = byId.get(m.id); + const knobs = comboKnobs(render, entry); + out[m.id] = { + count: m.n, + media: m.i, + group: g.key, + tier: m.tier, + show: comboShow(m.n, render, entry), + knobs, + members: g.members.map(({ id, i, n, post, date, tier }) => ({ id, i, n, post, date, tier })), + }; + } + } + return out; +} + +/** The text a badge draws: its label and "×<count>". */ +export const comboText = (count, knobs = COMBO_DEFAULTS) => ({ label: String(knobs.label ?? COMBO_DEFAULTS.label), count: `×${count}` }); + +/** When the badge pops, on the item's clock: the start of the step that plays attachment `media` (null: it never plays). */ +export function comboStart(plan, media) { + const st = (Array.isArray(plan?.steps) ? plan.steps : []).find((s) => (s.items ?? []).some((m) => m.i === media)); + return st && fin(st.at) ? r3(st.at) : null; +} + +// --------------------------------------------------------------------------- +// The motion +// --------------------------------------------------------------------------- + +const easeOutCubic = (u) => 1 - (1 - u) ** 3; + +/** + * The badge at `t` seconds after it pops, pure: `{ scale, x, y, rotate, + * opacity }` (x, y px of a 1080-high frame, before `k`; rotate degrees), or + * null when it is not up. `mirror` tilts it the other way (a left corner). + */ +export function comboFrame(t, { mirror = false } = {}) { + const T = COMBO_TIMING; + if (!fin(t) || t < 0 || t >= T.end) return null; + let scale; + if (t < T.pop) scale = 0.3 + (1.32 - 0.3) * easeOutCubic(t / T.pop); + else if (t < T.settle) { + const u = (t - T.pop) / (T.settle - T.pop); + scale = 1 + 0.32 * (1 - u) ** 2 * Math.cos(3 * Math.PI * u); + } else if (t < T.out) scale = 1; + else scale = 1 + 0.12 * ((t - T.out) / (T.end - T.out)); + const opacity = t < T.fadeIn ? t / T.fadeIn : t >= T.out ? 1 - (t - T.out) / (T.end - T.out) : 1; + const d = t >= T.pop && t < T.shake ? 1 - (t - T.pop) / (T.shake - T.pop) : 0; + const x = 14 * d * Math.sin(2 * Math.PI * 24 * t); + const y = 9 * d * Math.sin(2 * Math.PI * 31 * t + 1); + const tilt = mirror ? 7 : -7; + const rotate = tilt + 4 * d * Math.sin(2 * Math.PI * 19 * t); + return { scale: r3(scale), x: r3(x), y: r3(y), rotate: r3(rotate), opacity: r3(Math.max(0, Math.min(1, opacity))) }; +} + +/** The badge's CSS transform for a frame (`k`: px per 1080-frame px). */ +export const comboTransform = (f, k = 1) => `translate(${r3(f.x * k)}px, ${r3(f.y * k)}px) rotate(${f.rotate}deg) scale(${f.scale})`; + +// --------------------------------------------------------------------------- +// Its box and its look +// --------------------------------------------------------------------------- + +/** The badge's size at rest, px of the item's box: label over count, sized from their characters. */ +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 = 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); + return { width: even(w), height: even(h), number: Math.round(N), label: Math.round(L), k }; +} + +/** + * WHERE IT SITS, px of the item's box: centred on the attachment's corner + * (`position`), pulled in by a third of its size so it overlaps the picture, + * kept inside the box. `region` is what the build draws its frames in: the + * badge at its biggest, tilted and shaken, around the same centre. + * + * @param {{ x: number, y: number, width: number, height: number }} media the attachment's box (stepBoxes) + * @param {{ width: number, height: number }} box the item's box + */ +export function comboPlace(count, knobs, media, box) { + const s = comboSize(count, knobs, box.height); + const pos = COMBO_POSITIONS.includes(knobs?.position) ? knobs.position : COMBO_DEFAULTS.position; + const left = pos.endsWith("left"); + const top = pos.startsWith("top"); + let cx = pos === "center" ? media.x + media.width / 2 : left ? media.x + s.width * 0.18 : media.x + media.width - s.width * 0.18; + let cy = pos === "center" ? media.y + media.height / 2 : top ? media.y + s.height * 0.12 : media.y + media.height - s.height * 0.12; + // The region: the badge at 1.32×, tilted to 11°, shaken 14 px -- its bounding box, even-sized -- kept in the box. + const a = (11 * Math.PI) / 180; + const big = 1.32; + const rw = big * (s.width * Math.cos(a) + s.height * Math.sin(a)) + 2 * 14 * s.k + 4; + const rh = big * (s.width * Math.sin(a) + s.height * Math.cos(a)) + 2 * 9 * s.k + 4; + const even = (v) => Math.max(2, Math.ceil(v / 2) * 2); + const region = { width: Math.min(even(rw), Math.floor(box.width / 2) * 2), height: Math.min(even(rh), Math.floor(box.height / 2) * 2) }; + cx = Math.min(box.width - region.width / 2, Math.max(region.width / 2, cx)); + cy = Math.min(box.height - region.height / 2, Math.max(region.height / 2, cy)); + region.x = Math.round(cx - region.width / 2); + region.y = Math.round(cy - region.height / 2); + return { center: { x: r3(cx), y: r3(cy) }, size: s, region, mirror: left }; +} + +const esc = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); +const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => `\\${c === "\n" ? "a " : c}`); + +function shade(hex, to, t) { + const h = HEX_RE.test(hex) ? hex.slice(1) : COMBO_DEFAULTS.color.slice(1); + const g = HEX_RE.test(to) ? to.slice(1) : "000000"; + const c = [0, 2, 4].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) + (parseInt(g.slice(i, i + 2), 16) - parseInt(h.slice(i, i + 2), 16)) * t)); + return `#${c.map((v) => v.toString(16).padStart(2, "0")).join("")}`; +} + +/** + * THE BADGE's MARKUP, the same in the build's frames and in Play: a `<style>` + * (its own class names, `umc-`) and the badge, `size` px, its label over its + * count -- a heavy face skewed, the count filled top to bottom from `color` + * toward a hot red, a thick dark outline and a red under-shadow. `font`: a url + * for the face (the cut's bold); none, sans-serif. Its transform is set per + * frame on `[data-combo-badge]`. + */ +export function comboBadgeHtml(count, knobs, size, { font = "" } = {}) { + const { label, count: n } = comboText(count, knobs); + const color = HEX_RE.test(knobs?.color) ? knobs.color : COMBO_DEFAULTS.color; + const hot = shade(color, "#ff3b1f", 0.7); + const ink = "#1b0b02"; + const o = Math.max(1, Math.round(size.number * 0.045)); + const ol = Math.max(1, Math.round(size.label * 0.09)); + const outline = (w, c) => `drop-shadow(${w}px 0 0 ${c}) drop-shadow(-${w}px 0 0 ${c}) drop-shadow(0 ${w}px 0 ${c}) drop-shadow(0 -${w}px 0 ${c})`; + return `<style> +${font ? `@font-face { font-family: 'UmcFace'; src: url('${cssStr(font)}'); }` : ""} +.umc-badge { position: absolute; left: 0; top: 0; width: ${size.width}px; height: ${size.height}px; display: flex; flex-direction: column; align-items: center; justify-content: center; transform-origin: 50% 50%; font-family: ${font ? "'UmcFace', " : ""}'Arial Black', 'Helvetica Neue', sans-serif; font-weight: 900; line-height: 1; white-space: nowrap; pointer-events: none; } +.umc-skew { display: flex; flex-direction: column; align-items: center; transform: skewX(-9deg); } +.umc-label { font-size: ${size.label}px; letter-spacing: 0.14em; color: #ffffff; filter: ${outline(ol, ink)} drop-shadow(0 ${ol * 2}px 0 ${hot}); margin-bottom: ${Math.round(size.label * 0.08)}px; } +.umc-count { font-size: ${size.number}px; letter-spacing: 0.01em; background: linear-gradient(180deg, #fffbe6 0%, ${color} 38%, ${hot} 100%); -webkit-background-clip: text; background-clip: text; color: transparent; -webkit-text-fill-color: transparent; filter: ${outline(o, ink)} drop-shadow(0 ${o * 2}px 0 ${hot}) drop-shadow(0 ${o * 3}px ${o * 2}px rgba(0,0,0,0.45)); } +</style><div class="umc-badge" data-combo-badge="${count}"><div class="umc-skew">${label ? `<span class="umc-label">${esc(label)}</span>` : ""}<span class="umc-count">${esc(n)}</span></div></div>`; +} + +// --------------------------------------------------------------------------- +// The validators +// --------------------------------------------------------------------------- + +function knobErrors(o, where, keys) { + const errors = []; + for (const k of Object.keys(o)) if (!keys.includes(k)) errors.push(`${where}.${k} is not a combo knob (${keys.join(", ")})`); + if (o.on !== undefined && typeof o.on !== "boolean") errors.push(`${where}.on must be true or false`); + if (o.label !== undefined && !(typeof o.label === "string" && o.label.length <= COMBO_LABEL_MAX && !/[\n<>]/.test(o.label))) errors.push(`${where}.label must be a short line (at most ${COMBO_LABEL_MAX} characters; "" for the count alone)`); + if (o.position !== undefined && !COMBO_POSITIONS.includes(o.position)) errors.push(`${where}.position must be one of ${COMBO_POSITIONS.join(", ")}`); + if (o.color !== undefined && !(typeof o.color === "string" && HEX_RE.test(o.color))) errors.push(`${where}.color must be a #rrggbb colour`); + if (o.scale !== undefined && !(fin(o.scale) && o.scale >= COMBO_SCALE.min && o.scale <= COMBO_SCALE.max)) errors.push(`${where}.scale must be ${COMBO_SCALE.min}–${COMBO_SCALE.max}`); + if (o.sfx !== undefined && !COMBO_SFX.includes(o.sfx)) errors.push(`${where}.sfx must be one of ${COMBO_SFX.join(", ")}`); + if (o.minCount !== undefined && !(Number.isInteger(o.minCount) && o.minCount >= COMBO_MIN_COUNT.min && o.minCount <= COMBO_MIN_COUNT.max)) errors.push(`${where}.minCount must be a whole number ${COMBO_MIN_COUNT.min}–${COMBO_MIN_COUNT.max} (the use the badge first shows on)`); + if (o.match !== undefined && !COMBO_MATCH.includes(o.match)) errors.push(`${where}.match must be one of ${COMBO_MATCH.join(", ")}`); + return errors; +} + +/** Every reason `render.posts.combo` cannot be built. */ +export function validatePostComboRender(render) { + const p = render?.posts; + if (p === undefined || p === null) return []; + if (!isObj(p)) return ["render.posts must be an object (its `combo` knobs)"]; + const errors = Object.keys(p).filter((k) => k !== "combo").map((k) => `render.posts.${k} is not a knob (combo)`); + if (p.combo === undefined) return errors; + if (!isObj(p.combo)) return [...errors, "render.posts.combo must be an object of knobs"]; + return [...errors, ...knobErrors(p.combo, "render.posts.combo", Object.keys(COMBO_DEFAULTS))]; +} + +/** Every reason one post item's `combo` cannot be built (false, or its overrides). */ +export function validatePostCombo(e) { + if (e?.combo === undefined || e.combo === false) return []; + const where = `timeline ${e?.id ?? "?"}.combo`; + if (!isObj(e.combo)) return [`${where} must be false (no badge on this item) or an object of knobs`]; + return knobErrors(e.combo, where, [...COMBO_ITEM_KEYS]); +} + +/** The cut's: every post item's combo and render.posts.combo (lint.mjs). */ +export function validatePostCombos(manifest) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + return [...validatePostComboRender(manifest?.render), ...tl.filter((e) => e?.type === "post").flatMap((e) => validatePostCombo(e))]; +} diff --git a/umtool/report-to-video/post-combo.test.mjs b/umtool/report-to-video/post-combo.test.mjs @@ -0,0 +1,251 @@ +// 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</); + assert.match(html, />×3</); + assert.match(html, /UmcFace/); + assert.doesNotMatch(comboBadgeHtml(2, { ...k, label: "" }, p.size), /umc-label"/); + assert.match(comboBadgeHtml(2, { ...k, label: "<b>" }, p.size), /&lt;b&gt;/); +}); + +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(); + } +});