commit 66536345341d87b74b1c10e3ef79e41cc686f624
parent cd9b5dfeeeeb45f8c09ecd99f0e83303cca35d3f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 21:23:31 -0500
Merge main (read-follow, combo-counter) into lane/slur-censor: every feature kept -- post-render keys a segment on the read-follow plan AND the slur filter's beeps and config, records the follow shots and the slur spans side by side, and prunes the follow frames after the encode; the beep is laid on the take's own voice before the narrator's chain (the bed, the muffle and the combo badge untouched); the placeholder pill sits in its word's data-w slot inside read-follow's data-post-block, as a redaction bar does (both tested)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
39 files changed, 3558 insertions(+), 40 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/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts
@@ -7,6 +7,7 @@ import { withEditNotes } from "@/lib/report/guard";
import { StaleToken, StructureRefused, manifestToken, updatePostFx, updatePostItem, updatePostNarration } from "@/lib/report/manifest.mjs";
import { pickedTake } from "umtool-report-to-video/post-narration";
import { scriptWordTimes } from "umtool-report-to-video/word-zoom";
+import { followKnobs } from "umtool-report-to-video/read-follow";
import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxCli.mjs";
import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
@@ -175,6 +176,8 @@ export async function GET(request: Request) {
fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` },
phase: q.get("phase") === "media" ? "media" : "read",
parentShotUrl: parentShot,
+ // Its read-follow (read-follow.mjs): the blocks and the flow Play lights and pans, as the build's page has them.
+ follow: q.get("phase") !== "media" && followKnobs(found.item, (found.manifest.render ?? render) as Record<string, unknown>).on,
redaction,
});
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } });
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
@@ -8,8 +8,12 @@ import { cn } from "@/lib/utils";
import { postBenchHref } from "@/lib/hrefs";
import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item";
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";
@@ -52,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;
@@ -65,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);
@@ -132,6 +138,8 @@ export default function PostBench({
hold: typeof e.hold === "number" ? e.hold : null,
mediaLayout: e.mediaLayout ?? null,
redact: typeof e.redact === "boolean" ? e.redact : null,
+ // Its read-follow (read-follow.mjs): false is off; its knobs, each null when it is the cut's.
+ follow: e.follow === false ? false : e.follow && typeof e.follow === "object" ? { on: null, dim: null, ease: null, ...(e.follow as Record<string, unknown>) } : null,
media: Object.fromEntries(
(e.media ?? []).map((m, i) => [
i,
@@ -250,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))}>
@@ -298,6 +307,7 @@ export default function PostBench({
setToken(t);
}}
/>
+ <PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} />
<PostNarrationPanel
project={project}
entry={entry}
@@ -368,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/PostFollowPanel.tsx b/umtool/components/projects/PostFollowPanel.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { useMemo } from "react";
+import { FOLLOW_DEFAULTS, FOLLOW_LIMITS, cardScopes, followBlockAt, followKnobs } from "umtool-report-to-video/read-follow";
+import { cardWordsOf } from "umtool-report-to-video/word-zoom";
+import type { PostPlan } from "./review/PostItemPlayer";
+
+// ---------------------------------------------------------------------------
+// A POST's READ-FOLLOW ON THE BENCH (report-to-video/read-follow.mjs; knobs.md,
+// "Read-follow"): the BLOCK MAP -- each block of the card's words, which text
+// it is in, the part of the read that reads it and when (click: the playhead
+// there), the one being read marked -- and this post's knobs: follow on, off or
+// the cut's, the other blocks' dim, the ease. The knobs are the bench's draft
+// (its Save writes them, as hold and redact).
+// ---------------------------------------------------------------------------
+
+type Entry = Record<string, unknown> & { id: string };
+type Follow = false | { on?: boolean; dim?: number; ease?: number } | undefined;
+
+const SCOPE_NAME = (s: string) => (s === "post" ? "post" : s === "quoted" ? "quoted" : s.replace("parent:", "parent "));
+
+export default function PostFollowPanel({
+ entry, plan, render, s, setS, setEntry,
+}: {
+ entry: Entry;
+ plan: PostPlan;
+ render: Record<string, unknown>;
+ s: number;
+ setS: (s: number) => void;
+ setEntry: (f: (e: Entry) => Entry) => void;
+}) {
+ const follow = plan.follow ?? null;
+ const own = entry.follow as Follow;
+ const k = followKnobs(entry, render) as { on: boolean; dim: number; ease: number };
+ const cutOn = (followKnobs({}, render) as { on: boolean }).on;
+ const mode = own === false ? "off" : own && typeof own === "object" && own.on === true ? "on" : "auto";
+ const texts = useMemo(() => new Map(cardScopes(entry).map((sc: { scope: string; text: string }) => [sc.scope, cardWordsOf(sc.text)])), [entry]);
+ const cur = follow ? followBlockAt(follow, s) : null;
+ const setOwn = (next: Follow) =>
+ setEntry((e) => {
+ const out = { ...e };
+ if (next === undefined || (typeof next === "object" && !Object.keys(next).length)) delete out.follow;
+ else out.follow = next;
+ return out;
+ });
+ const knob = (key: "dim" | "ease", v: string) => {
+ const base = own && typeof own === "object" ? { ...own } : {};
+ if (v === "") delete base[key];
+ else base[key] = Number(v);
+ setOwn(base);
+ };
+ const read = follow ? follow.blocks.filter((b) => b.start !== null).length : 0;
+ return (
+ <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-follow-panel="">
+ <div className="mb-2 flex flex-wrap items-center gap-2">
+ <h2 className="micro m-0">read-follow</h2>
+ <select
+ value={mode}
+ onChange={(e) => setOwn(e.target.value === "off" ? false : e.target.value === "on" ? { ...(own && typeof own === "object" ? own : {}), on: true } : own && typeof own === "object" ? (({ on: _on, ...rest }) => rest)(own) : undefined)}
+ data-post-follow-mode=""
+ aria-label="read-follow on this post"
+ >
+ <option value="auto">the cut's ({cutOn ? "on" : "off"})</option>
+ <option value="on">on</option>
+ <option value="off">off</option>
+ </select>
+ <label className="flex items-center gap-1">
+ dim
+ <input
+ type="number"
+ min={FOLLOW_LIMITS.dim[0]}
+ max={FOLLOW_LIMITS.dim[1]}
+ step={0.05}
+ className="w-16"
+ value={own && typeof own === "object" && typeof own.dim === "number" ? own.dim : ""}
+ placeholder={String(k.dim ?? FOLLOW_DEFAULTS.dim)}
+ onChange={(e) => knob("dim", e.target.value)}
+ data-post-follow-dim=""
+ />
+ </label>
+ <label className="flex items-center gap-1">
+ ease
+ <input
+ type="number"
+ min={FOLLOW_LIMITS.ease[0]}
+ max={FOLLOW_LIMITS.ease[1]}
+ step={0.05}
+ className="w-16"
+ value={own && typeof own === "object" && typeof own.ease === "number" ? own.ease : ""}
+ placeholder={String(k.ease ?? FOLLOW_DEFAULTS.ease)}
+ onChange={(e) => knob("ease", e.target.value)}
+ data-post-follow-ease=""
+ />
+ s
+ </label>
+ </div>
+ {!follow ? (
+ <p className="m-0 text-text-2">off: the card shows its words as they are, shrunk to fit.</p>
+ ) : (
+ <>
+ <p className="m-0 mb-1 text-text-2" data-post-follow-summary="">
+ {follow.blocks.length} block{follow.blocks.length === 1 ? "" : "s"}, {read} read
+ {follow.source === "take" ? " (the take's parts)" : follow.source === "script" ? " (the script's parts, timed by words)" : " (the reading rule)"}; the read ends at {follow.readEnd.toFixed(1)} s
+ </p>
+ <ol className="m-0 max-h-56 list-none space-y-0.5 overflow-auto p-0" data-post-follow-map="">
+ {follow.blocks.map((b) => {
+ const words = texts.get(b.scope) ?? [];
+ const head = words.slice(b.from, Math.min(b.to + 1, b.from + 8)).join(" ");
+ return (
+ <li key={b.k} data-post-follow-row={b.k} data-current={cur === b.k ? "1" : undefined} className={cur === b.k ? "rounded bg-white/10" : ""}>
+ <button
+ type="button"
+ disabled={b.start === null}
+ className="flex w-full gap-2 px-1 text-left disabled:opacity-60"
+ onClick={() => b.start !== null && setS(b.start)}
+ title={b.start === null ? "no part reads it: dimmed while the read runs" : `part ${b.part! + 1}`}
+ >
+ <span className="w-12 shrink-0 font-mono tabular-nums">{b.start === null ? "—" : `${b.start.toFixed(1)}s`}</span>
+ <span className="w-14 shrink-0 text-text-2">{SCOPE_NAME(b.scope)}</span>
+ <span className="min-w-0 truncate">
+ {head}
+ {b.to + 1 - b.from > 8 ? "…" : ""}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ol>
+ </>
+ )}
+ </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 = {
@@ -853,6 +856,20 @@ export default function PlayCut({
uncensored={uncensored}
/>
) : 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}
@@ -1003,6 +1020,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}
@@ -1020,7 +1038,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/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item";
import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration";
+import { applyFollowState, followPath, followStateAt, measureFollow } from "umtool-report-to-video/read-follow";
import { blurCqw, blurOf } from "umtool-report-to-video/post-censor";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
@@ -24,6 +25,11 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar
// card's contents scaled toward the word's box (measured in the card page: its
// `data-w` spans) inside the card, which clips them, its highlight fading in
// under the word -- the card page's own elements transformed, nothing redrawn.
+//
+// READ-FOLLOW (read-follow.mjs) plays live on the plan's `follow`: the card
+// page carries the read's blocks and its flow; the pan's path is worked out
+// from the page's geometry once it is drawn, and each tick sets the state at
+// the item's second (followStateAt -- the build's frames are the same states).
// ---------------------------------------------------------------------------
type Rect = { x: number; y: number; width: number; height: number };
@@ -70,11 +76,21 @@ function applyZoom(doc: Document, z: LiveZoom | null, zf: number, hl: number, bo
/** A narrated item's mix on its clock (post-narration.mjs narrationSchedule). */
export type NarrationSchedule = { at: number; seconds: number; takeSeconds?: number; rate?: number; voiceEnd: number; rampEnd: number; wet: number; lowpassHz: number; duck: boolean; attach?: string; lufs?: number };
+/** The plan's read-follow (read-follow.mjs followSchedule). */
+export type FollowPlan = {
+ dim: number;
+ ease: number;
+ readEnd: number;
+ source: string;
+ blocks: Array<{ k: number; scope: string; from: number; to: number; part: number | null; start: number | null; end: number | null }>;
+};
+
export type PostPlan = {
reading: number;
total: number;
held: number;
narration?: NarrationSchedule;
+ follow?: FollowPlan;
steps: Array<{
kind: string;
at: number;
@@ -345,10 +361,19 @@ export default function PostItemPlayer({
const [zooms, setZooms] = useState<LiveZoom[]>([]);
const boxes = useRef<Map<Element, Rect>>(new Map());
const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]);
+ // ---- read-follow, live: the page's geometry measured once it is drawn, the path from it ----
+ const follow = plan.follow ?? null;
+ const [followGeo, setFollowGeo] = useState<ReturnType<typeof measureFollow>>(null);
+ const followRoute = useMemo(() => (follow && followGeo ? followPath(follow, followGeo) : null), [follow, followGeo]);
const measure = useCallback(() => {
const doc = readFrame.current?.contentDocument;
if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return false;
const card = doc.querySelector("[data-post-card]") as HTMLElement | null;
+ // Laid out untransformed (no zoom), the follow geometry first; a zoom's word is measured as the card is at its peak.
+ if (card) for (const k of Array.from(card.children) as HTMLElement[]) k.style.transform = "";
+ const geo = follow && doc.querySelector("[data-post-flow]") ? measureFollow(doc) : null;
+ setFollowGeo(geo);
+ const route = follow && geo ? followPath(follow, geo) : null;
const list = Array.isArray(entry.fx) ? (entry.fx as Array<Record<string, unknown>>) : [];
if (!card || !list.length) {
setZooms([]);
@@ -372,6 +397,7 @@ export default function PostItemPlayer({
const m = findMatch(targetTextOf(entry, fx.target) ?? "", fx.match, fx.occurrence);
if (m.error) return;
const scope = targetScope(fx.target);
+ if (follow) applyFollowState(followStateAt(follow, route, zoomSpan(fx0, t.t).t1), doc);
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (let w = m.from; w <= m.to; w += 1) {
const el = doc.querySelector(`[data-w="${scope}:${w}"]`);
@@ -383,7 +409,7 @@ export default function PostItemPlayer({
});
setZooms(out);
return true;
- }, [entry, zoomTimes, box.height]);
+ }, [entry, zoomTimes, box.height, follow]);
const onFrameLoad = useCallback(() => {
let tries = 0;
const tick = () => {
@@ -403,6 +429,11 @@ export default function PostItemPlayer({
const doc = readFrame.current?.contentDocument;
if (doc) applyZoom(doc, live, zf, hl, boxes.current);
}, [live, zf, hl]);
+ const followNow = useMemo(() => (follow ? followStateAt(follow, followRoute, s) : null), [follow, followRoute, s]);
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (doc && follow && doc.querySelector("[data-post-follow]")) applyFollowState(followNow, doc);
+ }, [follow, followNow, followGeo]);
const src = shown && inStep ? mediaTimeAt(shown, s) : null;
const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null;
return (
@@ -420,6 +451,9 @@ export default function PostItemPlayer({
data-post-zooms={zooms.length ? String(zooms.length) : undefined}
data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined}
data-post-zoom-fx={live ? String(live.i) : undefined}
+ data-post-follow-block={followNow?.current !== null && followNow?.current !== undefined ? String(followNow.current) : undefined}
+ data-post-follow-offset={followNow && followRoute?.segments.length ? String(Math.round(followNow.offset)) : undefined}
+ data-post-follow-pans={followRoute ? String(followRoute.segments.length) : undefined}
className="pointer-events-none absolute inset-0 overflow-hidden"
>
{mix && voiceTake && (
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -83,14 +83,17 @@ Inbox cannot disagree about what is wrong with one.
| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` |
-| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) |
-| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration`. Refused in the build's words (**exit 1**) |
+| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) |
+| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`). Refused in the build's words (**exit 1**) |
| `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) |
| `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is |
| `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 slurs <project> [ls] \| on \| off \| level strong\|all \| visual blackout\|placeholder \| voice skip\|beep\|placeholder \| add <word> \| except <word> \| remove <word> [--json]` | **THE SLUR FILTER** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): `render.posts.slurs` (`updatePostSlurs`, one undo point each), on by default -- the slurs of the shipped list (`report-to-video/slurs.json`; `level strong`: only the strong ones) and the project's own (`add`; `except` never masks one) masked in everything the cut publishes: a dark pill with its mask (`visual placeholder`, the default, "f*****") or a bar (`blackout`) on the card; said and beeped by the take's word timings (`voice beep`, the default), left out of a synthesized read (`skip`), or its stand-in said (`placeholder`). `ls` counts what the cut masks per slur and per post -- masks only, never the word -- and names each narrated post whose take says one with no word timings (a censored build refuses it; `posts narrate <p> <item> --words`). `off` is the uncensored cut (the redaction stays). A word already on a list, or on neither for `remove`, is refused (**exit 1**); an unknown verb or value (**exit 2**) |
| `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
@@ -777,6 +777,47 @@ its bounds. Its bench is the post bench's **word zoom** block; Play the cut zoom
| list them, each with its time and where it came from | the block's rows; the plan strip and the read lane mark each from its lead-in to back out | `umtool posts fx <p> <item> [ls] [--json]` | — |
| `narration.takes[i].words` — the take's WORD TIMINGS, `[{w, start, end}]` per script word (take seconds): the editor's `transcribe` op (`words: true`; parakeet keeps word times) on the take -- or each of its parts' files, at their starts -- the words heard aligned to its script, fuzzy and in order (a typo read as the word it means still pairs; a word not heard is placed between its neighbours); what a word zoom is timed by, and what the slur filter silences or beeps a said slur by | post bench, **Get word timings** (a job on the editor; the block says when the take is timed) | `umtool posts narrate <p> <item> --words [--worker <id>]` | `POST {op: "take-words", id, worker?}` → `{jobs}` · `GET ?project&id&takeWords=<job>,…` keeps them when done |
+## Read-follow (the block being read lit, the card panned to it)
+
+A post item's card follows its read ([report-video.md](report-video.md#read-follow): the blocks, the schedule, the
+pan, the render). On by default; the cut's knobs ride on `render.postNarration` (`updatePostNarrationRender`), one
+post's on the item (`updatePostItem`), each refused in the build's words (`followKnobErrors`,
+`report-to-video/read-follow.mjs`). Its bench is the post bench's **read-follow** block; Play the cut lights and pans
+the card live on the same states the build shoots.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| `render.postNarration.follow.on` — the cut's read-follow on (default) or off | — | `umtool posts narrate <p> --cut follow=off` (`follow=on`, `follow=default`) | — |
+| `render.postNarration.follow.dim` — the other blocks' opacity, 0.2–1 (default 0.65) · `.ease` — the light moving from one block to the next, 0–2 s (default 0.25) | — | `umtool posts narrate <p> --cut follow.dim=0.6 follow.ease=0.3` (`default` clears one) | — |
+| `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
@@ -709,6 +709,114 @@ only while it is up and before the attachments: the attachments are never covere
about the same window; the post bench's **word zoom** block makes and tunes them
([knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)).
+### Read-follow
+
+A post item's card FOLLOWS ITS READ (`report-to-video/read-follow.mjs`; operator, 3 Nov:
+"'I'm someone who has never watched Ember' goes on beyond the text but the text doesn't
+scroll? That needs to be an effect, something like highlight the current paragraph and
+panning down as needed" — and "a subtle effect of highlighting the block currently being
+read by making it brighter"): the card's words are laid out in BLOCKS that match the read's
+parts, the block being read is drawn at full strength and the others dimmed a little, and
+a card whose words are taller than their box pans so the block being read stays in view.
+It is on by default, for narrated and un-narrated posts alike:
+
+```jsonc
+"render": { "postNarration": { "follow": { "on": true, "dim": 0.65, "ease": 0.25 } } }, // the cut's
+"follow": false // one post's: off; or { on?, dim?, ease? } over the cut's
+```
+
+**The blocks** (from the entry alone): the read's parts — the picked take's `parts` (its
+paragraphs, or a long paragraph's ≤60-word sentence runs; a take that reads the post it
+answers first numbers that piece's paragraphs 0…, the post's 100…), else the script's
+parts (scriptParts), else, un-narrated, the card's own paragraphs and sentence runs. Each
+part is matched BY ITS WORDS to the run of the card's words it reads, in whichever of the
+card's texts it is (a parent's, the post's, the quoted post's): the script is the post as a
+voice says it ("this slash that", a shout lower-cased), so the match is a fitting alignment
+of normalized words, in order — never by index. Words no part reads join the block before
+them up to a paragraph break; a paragraph no part reads (a bare link, a quoted post that is
+not read aloud) is a block that is never lit.
+
+**When**: a block starts at its part's start in the take on the item's clock — lead +
+start ÷ the read's `rate` (partStartOnItem); a take without parts shares the read's seconds
+by words; un-narrated, the reading rule's seconds (each context post's context read, the
+post's reading time shared by words; a `hold` longer than the reading spreads it, less a
+second). The block being read rises to full over `ease` (centred on its start) while the
+one before falls back to `dim`; before the first block's start the first is lit, and after
+the read's end every block rises back to full. A post with one block read is never dimmed.
+
+**The pan**: following, the post's words never shrink below 28 px of a 1080 frame to fit
+(they used to shrink to 18 and cut the rest); when they are still taller than their box,
+they sit in a window that pans. A block about to be read that is not in view pans
+(0.7 s, eased, starting 0.4 s before its read) to sit a margin (a tenth of the window)
+below the window's top; a block taller than the window pans on through it as it is read.
+A short card never moves. A fading edge at the window's foot (and top) says there is more.
+
+**The render**: the card page wraps each block (`data-post-block="<k>"`) and puts the
+post's words in a flow (`data-post-flow`); the build measures the page (the window, the
+flow, each block's top and bottom), works out the pan's path, and for every frame the
+state at its second (followStateAt — pure, seek-safe); each DISTINCT state is applied to
+the page and the card's region shot once, and a concat list holds each shot for its frames,
+laid over the card before the attachments and the word zooms (which are shot as the card is
+at their peak). **Play** sets the same states on its card page each tick; the post bench's
+**read-follow** block shows the block map — each block, its text, the part that reads it and
+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/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -325,6 +325,63 @@ test("A WORD ZOOM: Get word timings (the editor's transcription), click a word -
await page.locator("[data-play-toggle]").click();
});
+test("READ-FOLLOW (operator, 3 Nov: \"highlight the current paragraph and panning down as needed\"): a long post read part by part -- the second block brightens at its part's start, the others dim, and the card pans so a late block is in view; the bench shows the block map", async ({ page }) => {
+ // p-13 made long: ten paragraphs, a take read paragraph by paragraph (a part every 2 s of the take).
+ const para = (i: number) => `Paragraph ${i + 1} begins here and it goes on for a while, ${"saying the same kind of thing again and again, ".repeat(3)}until it ends with mark ${i + 1}.`;
+ const paras = Array.from({ length: 10 }, (_, i) => para(i));
+ const m = JSON.parse(readFileSync(MANIFEST, "utf8"));
+ const e = m.timeline.find((x: { id: string }) => x.id === "p-13");
+ e.text = paras.join("\n\n");
+ e.narration = {
+ script: e.text,
+ takes: [{ file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 20, script: e.text, parts: paras.map((text, i) => ({ n: i + 1, para: i, text, start: i * 2, seconds: 1.8 })) }],
+ pick: 0,
+ };
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-13"));
+ const panel = page.locator("[data-post-follow-panel]");
+ await expect(panel.locator("[data-post-follow-summary]")).toHaveText(/10 blocks, 10 read \(the take's parts\)/);
+ await expect(panel.locator("[data-post-follow-row]")).toHaveCount(10);
+ const player = page.locator('[data-post-play="p-13"]');
+ const frame = page.frameLocator('[data-post-card-frame="read"]');
+ await expect(frame.locator("body")).toHaveAttribute("data-post-follow", "10", { timeout: 15_000 });
+ const op = (k: number) => frame.locator(`[data-post-block="${k}"]`).evaluate((el) => (el as HTMLElement).style.opacity);
+ const scrub = page.locator("[data-post-bench-scrub]");
+ // Before the second part: the first block lit, the second dimmed.
+ await scrub.fill("1");
+ await expect(player).toHaveAttribute("data-post-follow-block", "0");
+ await expect.poll(() => op(0)).toBe("");
+ await expect.poll(() => op(1)).toBe("0.65");
+ // The second part starts at lead 0.4 + 2 s: past its ease (0.125 s) it is lit and the first is dimmed.
+ await scrub.fill("2.6");
+ await expect(player).toHaveAttribute("data-post-follow-block", "1");
+ await expect.poll(() => op(1)).toBe("");
+ await expect.poll(() => op(0)).toBe("0.65");
+ await expect(panel.locator('[data-post-follow-row="1"]')).toHaveAttribute("data-current", "1");
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-follow-second-block.png") });
+ // The words are taller than the card: a late block is panned into view.
+ await expect(player).toHaveAttribute("data-post-follow-pans", /^[1-9]/);
+ await scrub.fill("17.2");
+ await expect(player).toHaveAttribute("data-post-follow-block", "8");
+ await expect.poll(async () => Number(await player.getAttribute("data-post-follow-offset"))).toBeGreaterThan(0);
+ const view = await frame.locator("[data-post-words]").evaluate((w) => {
+ const r = w.getBoundingClientRect();
+ const b = (w.querySelector('[data-post-block="8"]') as HTMLElement).getBoundingClientRect();
+ return { top: r.top, bottom: r.bottom, bTop: b.top, bBottom: b.bottom, flow: (w.querySelector("[data-post-flow]") as HTMLElement).style.transform };
+ });
+ expect(view.flow).toMatch(/translateY\(-\d/);
+ expect(view.bTop).toBeGreaterThanOrEqual(view.top - 1);
+ expect(view.bBottom).toBeLessThanOrEqual(view.bottom + 1);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-follow-panned.png") });
+ // A row of the map puts the playhead at its block's start.
+ await panel.locator('[data-post-follow-row="3"] button').click();
+ await expect(page.locator("[data-post-bench-clock]")).toHaveText(/^6\.4 \//);
+ // Off on this post: the card shows its words as they are (no blocks lit, no pan).
+ await panel.locator("[data-post-follow-mode]").selectOption("off");
+ await expect(panel).toContainText("off: the card shows its words as they are");
+});
+
test("THE RECORDING SESSION: part by part, a reload resumes, redo one, the last part makes the recorded take and picks it", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1200 });
await page.goto(urls.projectHref(PROJECT, { tab: "cut" }));
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";
@@ -2351,7 +2352,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i
}
/** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */
-export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact"]);
+export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact", "follow"]);
/** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */
export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]);
/** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */
@@ -2359,7 +2360,7 @@ export const POST_CONTEXT_KNOBS = Object.freeze(["paraphrase"]);
/**
* SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch`
- * is `{ hold?, mediaLayout?, redact?, media?: { <i>: { start?, end?, mute?,
+ * is `{ hold?, mediaLayout?, redact?, follow?: false | { on?, dim?, ease? }, media?: { <i>: { start?, end?, mute?,
* crop?, push?, words?, blur? } }, quoted?: { paraphrase? }, parents?: { <i>:
* { paraphrase? } } }`; a null clears a knob (the default again), and so
* does an empty paraphrase (the context's own words again; its `text` is
@@ -2384,7 +2385,19 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
if (v === null || v === undefined) delete o[k];
else o[k] = typeof v === "number" ? round2(v) : v;
};
- for (const k of POST_ITEM_KNOBS) if (k in patch) set(e, k, patch[k]);
+ for (const k of POST_ITEM_KNOBS) {
+ if (!(k in patch)) continue;
+ // Its read-follow (read-follow.mjs): false is off; an object's knobs merge into the one it has (null: the default).
+ if (k === "follow" && isObj(patch.follow)) {
+ const f = isObj(e.follow) ? e.follow : {};
+ for (const [fk, fv] of Object.entries(patch.follow)) {
+ if (fv === null || fv === undefined) delete f[fk];
+ else f[fk] = typeof fv === "number" ? round2(fv) : fv;
+ }
+ if (Object.keys(f).length) e.follow = f;
+ else delete e.follow;
+ } else set(e, k, patch[k]);
+ }
if (isObj(patch.media)) {
const media = Array.isArray(e.media) ? e.media : [];
for (const [key, mp] of Object.entries(patch.media)) {
@@ -2441,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) --------------
/**
@@ -2737,7 +2846,7 @@ export async function setPostItemsContext(dir, patches, { token = null } = {}) {
}
/** The cut's mix knobs a write may set (`render.postNarration`). */
-export const POST_NARRATION_RENDER_KNOBS = Object.freeze(Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach"));
+export const POST_NARRATION_RENDER_KNOBS = Object.freeze([...Object.keys(POST_NARRATION_DEFAULTS).filter((k) => k !== "attach"), "follow"]);
/**
* SET THE CUT's NARRATION MIX (`render.postNarration`; `umtool posts narrate
@@ -2756,7 +2865,16 @@ export async function updatePostNarrationRender(dir, patch, { token = null } = {
const r = isObj(m.render.postNarration) ? m.render.postNarration : {};
for (const [k, v] of Object.entries(patch)) {
if (v === null || v === undefined) delete r[k];
- else r[k] = typeof v === "number" ? round2(v) : v;
+ else if (k === "follow" && isObj(v)) {
+ // The read-follow's knobs merge ({ on, dim, ease }; a null one back to its default).
+ const f = isObj(r.follow) ? r.follow : {};
+ for (const [fk, fv] of Object.entries(v)) {
+ if (fv === null || fv === undefined) delete f[fk];
+ else f[fk] = typeof fv === "number" ? round2(fv) : fv;
+ }
+ if (Object.keys(f).length) r.follow = f;
+ else delete r.follow;
+ } else r[k] = typeof v === "number" ? round2(v) : v;
}
if (Object.keys(r).length) m.render.postNarration = r;
else delete m.render.postNarration;
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/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -43,7 +43,7 @@ export const NARRATE_USAGE = [
" [--pick <n>] [--approve|--unapprove] [--off|--on] [lead=… tail=… ramp=… linger=… clip=read|full",
" wet=… lowpass=… duck=on|off short=hold|loop attach=under|after lufs=… rate=…] [--json]",
" umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]",
- " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… engine=… voice=…",
+ " umtool posts narrate <project> --cut lead=… tail=… ramp=… linger=… clip=read|full wet=… lowpass=… duck=on|off short=hold|loop lufs=… rate=… engine=… voice=… follow=on|off follow.dim=… follow.ease=…",
" A NARRATED POST ITEM: its script read by a stock synthetic voice, its attachment playing under the read (muffled,",
" then clean). Takes are files of the project (narration/posts/<postId>/take-<n>.<engine>-<voice>.wav) the EDITOR",
" writes (`pnpm ops tts`, a job on its tts queue; ARCHILYZER_EDITOR_URL + WORKER_TOKEN) -- umtool never synthesizes.",
@@ -227,13 +227,16 @@ export function mixPatchOf(pairs, { cut = false } = {}) {
else if (k === "short") out.short = clear ? null : v;
else if (k === "attach" && !cut) out.attach = clear ? null : v;
else if ((k === "engine" || k === "voice") && cut) out[k] = clear ? null : raw;
+ // The cut's read-follow (read-follow.mjs): follow=on|off, follow.dim=<0.2-1>, follow.ease=<s>.
+ else if (k === "follow" && cut) out.follow = { ...(out.follow ?? {}), on: clear ? null : ON.has(v) ? true : OFF.has(v) ? false : (() => { throw new NarrateError("follow= takes on or off"); })() };
+ else if ((k === "follow.dim" || k === "follow.ease") && cut) out.follow = { ...(out.follow ?? {}), [k.slice(7)]: clear ? null : num() };
else if (k === "fit" && !cut) {
// fit=read[:linger]: the item ends `linger` after the words (posts fit picks the clip's best part for it).
const m = /^read(?::([\d.]+))?$/.exec(v);
if (!m) throw new NarrateError("fit= takes read or read:<linger seconds>");
out.linger = m[1] !== undefined ? Number(m[1]) : null;
out.clip = null;
- } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, engine, voice" : "linger, clip, attach, lufs, rate, fit"})`);
+ } else throw new NarrateError(`${pair}: not a narration knob (lead, tail, ramp, end, wet, lowpass, duck, short, ${cut ? "linger, clip, lufs, rate, engine, voice, follow, follow.dim, follow.ease" : "linger, clip, attach, lufs, rate, fit"})`);
}
if (!Object.keys(out).length) throw new NarrateError("nothing to set");
return out;
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -65,7 +65,7 @@ export const POSTS_USAGE = [
" POST ITEMS: each archived post as an entry of the cut, its card and its attachments (report-video.md, \"Post items\"):",
" the channels merged in time order, de-duplicated by post id; a post already in the cut is skipped, so a re-run",
" adds only what is new -- in ONE write (one undo point), at the end unless --after.",
- " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto]",
+ " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [follow=on|off|auto] [follow.dim=<0.2-1>] [follow.ease=<s>]",
" [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]",
" [media.<i>.push=on|off] [media.<i>.trim=off] [quoted.paraphrase=\"…\"|off]",
" [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]",
@@ -101,6 +101,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"]);
@@ -418,6 +421,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;
@@ -597,6 +602,12 @@ export function postItemPatchOf(pairs) {
if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw);
else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v;
else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k);
+ // Its read-follow (read-follow.mjs): follow=on|off|auto, follow.dim=<0.2-1>, follow.ease=<s> (auto/default: the cut's).
+ else if (k === "follow") out.follow = v === "auto" || v === "default" || v === "" ? null : onOff(v, k) ? { on: true } : false;
+ else if (k === "follow.dim" || k === "follow.ease") {
+ if (out.follow === false) throw new CliError("follow=off goes alone");
+ out.follow = { ...(out.follow ?? {}), [k.slice(7)]: v === "default" || v === "" ? null : Number(raw) };
+ }
else if (k === "quoted.paraphrase") out.quoted = { paraphrase: paraphraseOf(raw) };
else if (/^parents?\.\d+\.paraphrase$/.test(k)) (out.parents ??= {})[k.split(".")[1]] = { paraphrase: paraphraseOf(raw) };
else if (/^media\.\d+\.blur(\.(strength|label|boxes))?$/.test(k)) {
@@ -610,7 +621,7 @@ export function postItemPatchOf(pairs) {
if (typeof blur.strength === "number" && !Number.isFinite(blur.strength)) throw new CliError(`${k}= takes a number (1-10)`);
} else {
const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k);
- if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes]=, quoted.paraphrase=, parent.<i>.paraphrase=)`);
+ if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, follow=, follow.dim|ease=, media.<i>.start|end|mute|crop|push|trim=, media.<i>.blur[.strength|.label|.boxes]=, quoted.paraphrase=, parent.<i>.paraphrase=)`);
const media = (out.media ??= {});
const one = (media[m[1]] ??= {});
if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw);
@@ -624,6 +635,7 @@ export function postItemPatchOf(pairs) {
}
if (!Object.keys(out).length) throw new CliError("nothing to set");
for (const [k, v] of Object.entries(out)) if (typeof v === "number" && !Number.isFinite(v)) throw new CliError(`${k}= takes a number`);
+ for (const [fk, fv] of Object.entries(out.follow && typeof out.follow === "object" ? out.follow : {})) if (typeof fv === "number" && !Number.isFinite(fv)) throw new CliError(`follow.${fk}= takes a number`);
return out;
}
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
@@ -219,6 +219,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";
@@ -6309,6 +6311,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.
@@ -6427,6 +6434,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",
@@ -69,6 +72,7 @@
"./post-slurs": "./post-slurs.mjs",
"./post-render": "./post-render.mjs",
"./word-zoom": "./word-zoom.mjs",
+ "./read-follow": "./read-follow.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
+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), /<b>/);
+});
+
+test("the knobs are refused in the build's words", () => {
+ assert.deepEqual(validatePostComboRender({}), []);
+ assert.deepEqual(validatePostComboRender({ posts: { combo: { ...COMBO_DEFAULTS, sfx: "hit", match: "audio" } } }), []);
+ const bad = validatePostComboRender({ posts: { combo: { on: "yes", position: "middle", color: "red", scale: 9, sfx: "boom", minCount: 1, match: "pixels", size: 2 }, other: 1 } });
+ for (const want of ["render.posts.other", ".on must", ".position must", ".color must", ".scale must", ".sfx must", ".minCount must", ".match must", ".size is not"]) {
+ assert.ok(bad.some((e) => e.includes(want)), `${want} in ${bad.join(" | ")}`);
+ }
+ assert.deepEqual(validatePostCombo({ id: "p", combo: false }), []);
+ assert.deepEqual(validatePostCombo({ id: "p", combo: { on: false, label: "HIT" } }), []);
+ assert.match(validatePostCombo({ id: "p", combo: { minCount: 3 } })[0], /minCount is not a combo knob/);
+ assert.match(validatePostCombo({ id: "p", combo: true })[0], /must be false/);
+ assert.match(validatePostCombo({ id: "p", combo: { label: "x".repeat(17) } })[0], /at most 16/);
+ assert.equal(validatePostCombos({ render: { posts: { combo: { on: 1 } } }, timeline: [{ type: "post", id: "p", combo: 2 }, { type: "clip", id: "c", combo: 2 }] }).length, 2);
+});
+
+// ---------------------------------------------------------------------------
+// The prints, off disk
+// ---------------------------------------------------------------------------
+
+const ff = (args) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]);
+ if (r.status !== 0) throw new Error(String(r.stderr));
+};
+
+function project() {
+ const root = mkdtempSync(path.join(os.tmpdir(), "umtool-combo-"));
+ const dir = path.join(root, "proj");
+ const channels = path.join(root, "channels");
+ return { root, dir, channels, done: () => rmSync(root, { recursive: true, force: true }) };
+}
+
+test("the prints: the media id and sha256 from the capture (the project's copy, else the corpus's), else the file hashed; cached", async () => {
+ const p = project();
+ try {
+ const put = (rel, body) => {
+ mkdirSync(path.dirname(path.join(p.dir, rel)), { recursive: true });
+ writeFileSync(path.join(p.dir, rel), body);
+ };
+ // 1 and 3: the same bytes, different X ids (a GIF re-uploaded); 2: other bytes; 4: like 1, no capture anywhere.
+ put("posts-media/ch/1/1_1.mp4", "SAME-BYTES");
+ put("posts-media/ch/2/2_1.mp4", "OTHER");
+ put("posts-media/ch-replies/3/3_1.mp4", "SAME-BYTES");
+ put("posts-media/ch/4/4_1.mp4", "SAME-BYTES");
+ const sha = execFileSync("sha256sum", [path.join(p.dir, "posts-media/ch/1/1_1.mp4")], { encoding: "utf8" }).split(" ")[0];
+ // 1's record copied into the project (posts add does); 3's only in the corpus, under the replies channel.
+ writeFileSync(path.join(p.dir, "posts-media/ch/1/capture.json"), JSON.stringify({ media: [{ name: "1_1.mp4", bytes: 10, sha256: sha, url: "https://video.twimg.com/tweet_video/AAA.mp4" }] }));
+ mkdirSync(path.join(p.channels, "ch-replies", "posts-media", "3"), { recursive: true });
+ writeFileSync(path.join(p.channels, "ch-replies", "posts-media", "3", "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", bytes: 10, sha256: sha, url: "https://video.twimg.com/tweet_video/BBB.mp4" }] }));
+ // 2's record lies about its bytes (a file replaced since): it is hashed, not trusted.
+ writeFileSync(path.join(p.dir, "posts-media/ch/2/capture.json"), JSON.stringify({ media: [{ name: "2_1.mp4", bytes: 999, sha256: sha, url: "https://video.twimg.com/amplify_video/22/x.mp4" }] }));
+ const manifest = {
+ render: {},
+ timeline: [
+ item("p1", "posts-media/ch/1/1_1.mp4", { post: "ch/1" }),
+ item("p2", "posts-media/ch/2/2_1.mp4", { post: "ch/2" }),
+ item("p3", "posts-media/ch-replies/3/3_1.mp4", { post: "ch/3" }),
+ item("p4", "posts-media/ch/4/4_1.mp4", { post: "ch/4" }),
+ item("p5", "posts-media/ch/5/gone.mp4", { post: "ch/5" }),
+ ],
+ };
+ const cacheDir = path.join(p.root, "cache");
+ const prints = await attachmentPrints(manifest, p.dir, { channelsDir: p.channels, cacheDir });
+ assert.deepEqual(prints["p1:0"], { mediaId: "tweet_video/AAA", sha256: sha, via: "capture" });
+ assert.deepEqual(prints["p3:0"], { mediaId: "tweet_video/BBB", sha256: sha, via: "capture" });
+ assert.equal(prints["p2:0"].via, "hashed");
+ assert.notEqual(prints["p2:0"].sha256, sha);
+ assert.equal(prints["p2:0"].mediaId, "amplify_video/22");
+ assert.deepEqual(prints["p4:0"], { mediaId: null, sha256: sha, via: "hashed" });
+ assert.equal(prints["p5:0"], undefined, "a file not on disk has no print");
+ const r = await projectCombos(p.dir, manifest, { channelsDir: p.channels, cacheDir });
+ assert.deepEqual(r.groups.map((g) => g.members.map((m) => `${m.id}#${m.n}`)), [["p1#1", "p3#2", "p4#3"]]);
+ assert.equal(r.combos.p4.count, 3);
+ assert.equal(r.combos.p2, undefined);
+ // id-only: the GIF's new ids do not match.
+ assert.deepEqual((await projectCombos(p.dir, manifest, { channelsDir: p.channels, cacheDir, match: "id" })).groups, []);
+ // Cached: a second look reads the cache (a hash that would fail is never run).
+ const again = await attachmentPrints(manifest, p.dir, { channelsDir: p.channels, cacheDir: path.join(p.root, "cache") });
+ assert.equal(again["p4:0"].sha256, sha);
+ } finally {
+ p.done();
+ }
+});
+
+test("the sound's print: the same clip re-encoded matches, another sound does not; the coarse hash when there is no fpcalc", async () => {
+ const p = project();
+ try {
+ mkdirSync(p.dir, { recursive: true });
+ const a = path.join(p.dir, "a.mp4");
+ const b = path.join(p.dir, "b.mp4");
+ const c = path.join(p.dir, "c.mp4");
+ const src = "aevalsrc=0.6*sin(2*PI*(220+180*sin(2*PI*0.7*t))*t)*(0.5+0.5*sin(2*PI*1.3*t)):s=44100:d=6";
+ ff(["-f", "lavfi", "-i", "color=c=black:s=64x64:d=6", "-f", "lavfi", "-i", src, "-shortest", "-c:v", "libx264", "-c:a", "aac", "-b:a", "128k", a]);
+ ff(["-i", a, "-c:v", "libx264", "-crf", "35", "-c:a", "aac", "-b:a", "64k", b]);
+ ff(["-f", "lavfi", "-i", "color=c=black:s=64x64:d=6", "-f", "lavfi", "-i", "anoisesrc=d=6:c=pink:a=0.4", "-shortest", "-c:v", "libx264", "-c:a", "aac", c]);
+ const vid = (id, src2) => ({ type: "post", id, text: "", date: "2026-11-01T00:00:00Z", media: [{ src: src2, kind: "video", seconds: 6, audio: true }] });
+ const manifest = { render: { posts: { combo: { match: "audio" } } }, timeline: [vid("a", "a.mp4"), vid("b", "b.mp4"), vid("c", "c.mp4")] };
+ const r = await projectCombos(p.dir, manifest, { cacheDir: null });
+ assert.deepEqual(r.groups.map((g) => g.members.map((m) => `${m.id}:${m.tier ?? "-"}`)), [["a:-", "b:audio"]]);
+ assert.notEqual(r.prints["a:0"].sha256, r.prints["b:0"].sha256);
+ // No fpcalc: ffmpeg's energy hash still tells the two sounds apart.
+ const noFp = await projectCombos(p.dir, manifest, { cacheDir: null, audioPrint: (f) => import("./post-combo-prints.mjs").then((m) => m.audioPrintOf(f, { fpcalc: "/nonexistent/fpcalc" })) });
+ assert.equal(noFp.prints["a:0"].audio.kind, "energy");
+ assert.deepEqual(noFp.groups.map((g) => g.members.map((m) => m.id)), [["a", "b"]]);
+ assert.equal(energyPrint(Buffer.alloc(16000 * 2)), null, "silence has no print");
+ } finally {
+ p.done();
+ }
+});
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -35,6 +35,7 @@ import {
import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactionOn, validatePostsRender } from "./post-redact.mjs";
import { blurErrors } from "./post-censor.mjs";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs";
+import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs";
/** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */
export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]);
@@ -233,7 +234,9 @@ function planOf(entry, render, hold) {
const narrated = isNarrated(entry);
const k = postNarrationKnobs(entry, render);
const sch = narrated ? narrationSchedule(entry, render) : null;
- const extra = sch ? { narration: sch } : {};
+ // Its read-follow (read-follow.mjs): each block's start on the item's clock -- null when it is off.
+ const follow = followSchedule(entry, render, { hold, narration: sch });
+ const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) };
if (sch && k.attach === "after") {
const voiceOnly = round3(sch.at + sch.seconds + k.tail);
const all = mediaSteps(entry);
@@ -467,6 +470,8 @@ export function validatePostItem(e) {
errors.push(...validatePostNarration(e));
// Its effects (word-zoom.mjs): a word zoomed on as it is read.
errors.push(...validatePostFx(e));
+ // Its read-follow's knobs (read-follow.mjs): false, or { on, dim, ease }.
+ errors.push(...validatePostFollow(e));
return errors;
}
@@ -730,18 +735,22 @@ export const hueOf = (s) => {
* and Play zooms toward it; `hl` (`{ from, to }`) marks those words'
* spans `data-w-hl` (the zoom's highlight is drawn under them).
*/
-export function wordsHtml(text, blurred, scope = null, hl = null) {
+export function wordsHtml(text, blurred, scope = null, hl = null, blocks = null) {
const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase()));
const word = (t) =>
esc(t)
.replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`))
.replace(/https?:\/\/\S+/g, (u) => `<span class="link">${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`);
if (!scope) return word(str(text)).replace(/\n/g, "<br>");
+ // `blocks` (read-follow.mjs scopeBlocks): runs of words wrapped `data-post-block="<k>"`, the read's blocks.
+ const opens = new Map((blocks ?? []).map((b) => [b.from, b.k]));
+ const closes = new Set((blocks ?? []).map((b) => b.to));
return cardTokens(text)
.map((t) => {
if (t.space !== undefined) return t.space.replace(/[^\n]+/g, " ").replace(/\n/g, "<br>");
const lit = hl && t.i >= hl.from && t.i <= hl.to;
- return `<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}>${word(t.tok)}</span>`;
+ const open = opens.has(t.i) ? `<span class="fblock" data-post-block="${opens.get(t.i)}">` : "";
+ return `${open}<span data-w="${esc(scope)}:${t.i}"${lit ? " data-w-hl=\"\"" : ""}>${word(t.tok)}</span>${closes.has(t.i) ? "</span>" : ""}`;
})
.join("");
}
@@ -792,15 +801,22 @@ export function nameHtml(who, { redact, cls = "" }) {
* Every word of the post's and its context's text is a span `data-w="<scope>:<i>"`
* (wordsHtml); `highlight` -- `{ scope, from, to, color }` -- draws a word
* zoom's marker under those words (word-zoom.mjs; the build's zoom shot).
+ * `follow` (read-follow.mjs): the read's blocks wrapped `data-post-block`, the
+ * post's words in a flow (`data-post-flow`) with fading edges, never shrunk
+ * below FOLLOW_MIN_SIZE -- the build and Play light and pan them.
*
* @param {Record<string, any>} entry
* @param {{ width: number, height: number, palette?: Record<string, string>, fonts?: { regular?: string, bold?: string },
* phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean, avatars?: Record<string, string>,
* highlight?: { scope: string, from: number, to: number, color: string } | null,
- * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null }} o
+ * redaction?: { terms: Array<{term: string, wholeWord?: boolean}>, markup?: Record<string, any> } | null, follow?: boolean }} o
*/
-export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null }) {
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null, redaction = null, follow = false }) {
const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null);
+ // READ-FOLLOW (read-follow.mjs): the read's blocks wrapped on the card, the post's words in a flow that pans --
+ // mapped on the words as written (the plan's are), whose indices the redaction's bars keep.
+ const fmap = follow ? followBlocks(entry) : null;
+ const blk = (scope) => (fmap ? scopeBlocks(fmap, scope) : null);
// AS PUBLISHED (post-redact.mjs): every redacted match drawn as a bar, its letters never in the page. The
// marks keep the text's length and its spaces, so the card's word indices (a word zoom's) are the original's.
entry = redactEntry(entry, redaction);
@@ -808,7 +824,9 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette };
const L = postLayout(entry, { width, height });
const k = height / 1080;
- const size = L.size;
+ // Following, the words never shrink below a readable size to fit: the card pans them instead.
+ const followMin = Math.round(FOLLOW_MIN_SIZE * k);
+ const size = follow ? Math.max(L.size, followMin) : L.size;
const authors = cardAuthors(entry);
const blurred = authors.filter((a) => a.redact && a.handle).map((a) => a.handle);
const red = (where) => authors.find((a) => a.where === where)?.redact ?? false;
@@ -832,7 +850,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
const r = red(`parents[${i}]`);
const subject = !r && subjectsOf(entry).some((h) => String(h).toLowerCase() === String(p.handle ?? "").replace(/^@/, "").toLowerCase());
ctx.push(
- `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span>${paraLabel(p)}</div><div class="ptext"${isParaphrased(p) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(p) || (p.url ? "(not archived)" : ""), blurred, contextText(p) ? `parent:${i}` : null, hlOf(`parent:${i}`))}</div></div></div>`,
+ `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined, img: pic(p) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span>${paraLabel(p)}</div><div class="ptext"${isParaphrased(p) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(p) || (p.url ? "(not archived)" : ""), blurred, contextText(p) ? `parent:${i}` : null, hlOf(`parent:${i}`), blk(`parent:${i}`))}</div></div></div>`,
);
}
if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`);
@@ -841,20 +859,20 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
}
const q = isObj(entry.quoted) ? entry.quoted : null;
const quoted = q
- ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${paraLabel(q)}</div><div class="qtext"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(q), blurred, "quoted", hlOf("quoted"))}</div></div>`
+ ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${paraLabel(q)}</div><div class="qtext"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""}>${wordsHtml(contextText(q), blurred, "quoted", hlOf("quoted"), blk("quoted"))}</div></div>`
: "";
const repost = entry.repostedBy
? `<div class="repost" data-post-repost="">↻ ${esc(str(entry.repostedBy.author) || `@${entry.repostedBy.handle}`)} reposted</div>`
: "";
const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`;
// A card alone (text, or a stack's reading) is as tall as its words, centred in its box; beside the attachments, the box's height.
- const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${wordsHtml(cardText(entry), blurred, "post", hlOf("post"))}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`;
+ const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${follow ? `<div class="wflow" data-post-flow="">${wordsHtml(cardText(entry), blurred, "post", hlOf("post"), blk("post"))}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div>` : wordsHtml(cardText(entry), blurred, "post", hlOf("post"))}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`;
const stripHtml = L.strip
? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: ownRed, size: Math.round(56 * k), accent: ownRed ? undefined : pal.accent, img: pic(own) })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>`
: "";
const slot = L.slot && (L.mode === "side" || strip) ? `<div class="slot" data-post-slot="" style="left:${L.slot.x}px;top:${L.slot.y}px;width:${L.slot.width}px;height:${L.slot.height}px"></div>` : "";
const body = strip ? `${stripHtml}${slot}` : `${card(L.card)}${slot}`;
- const minSize = Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k);
+ const minSize = follow ? followMin : Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k);
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}">
<style>
@@ -897,11 +915,16 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; }
.counts b { color: ${pal.fg}; }
.redact { filter: blur(${Math.round(9 * k)}px); color: ${pal.muted}; }
.avatar.redact { background: ${rgbaOf(pal.muted, 0.6)} !important; }
-.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; }${highlight ? `
+.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; }${follow ? `
+.words { position: relative; }
+.wflow { will-change: transform; }
+.wfade { position: absolute; left: 0; right: 0; height: 1.5em; pointer-events: none; opacity: 0; }
+.wfade[data-post-fade="top"] { top: 0; background: linear-gradient(${cardBg}, ${rgbaOf(cardBg, 0)}); }
+.wfade[data-post-fade="bottom"] { bottom: 0; background: linear-gradient(${rgbaOf(cardBg, 0)}, ${cardBg}); }` : ""}${highlight ? `
[data-w-hl] { background: ${rgbaOf(highlight.color, WORD_ZOOM_HIGHLIGHT_ALPHA)}; box-shadow: inset 0 -0.12em 0 ${highlight.color}; border-radius: 0.16em; padding: 0 0.08em; margin: 0 -0.08em; -webkit-box-decoration-break: clone; box-decoration-break: clone; }` : ""}
${BAR_CSS(pal.fg)}
</style></head>
-<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${barsHtml(body)}
+<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}"${fmap ? ` data-post-follow="${fmap.blocks.length}"` : ""}>${barsHtml(body)}
<script>
// The words at the layout's size, shrunk while they overflow (the browser
// knows how they wrap; the layout only estimated it). Then say so.
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -31,6 +31,8 @@
// from the post's words. The plan of what plays when is post-item.mjs's
// (postItemPlan's narrated branch), which reads these.
+import { followKnobErrors } from "./read-follow.mjs";
+
/** The engines a post's narration may name (the editor's tts op). */
export const POST_NARRATION_ENGINES = Object.freeze(["orpheus", "kokoro", "espeak-ng"]);
/** A take's engine: one of those, or `recorded` -- a person's own voice, recorded on the post bench (never synthesized). */
@@ -161,7 +163,8 @@ export const POST_NARRATION_CLIP = Object.freeze(["read", "full"]);
const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", "duck", "short", "attach", "lufs", "rate"];
// `attach` is one post's (it decides the card's layout, which is drawn from the entry alone).
-const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice"]);
+// `follow`: the cut's read-follow (read-follow.mjs) -- { on, dim, ease } -- kept here with the mix it rides on.
+const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow"]);
const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]);
const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]);
@@ -474,7 +477,7 @@ export function validatePostNarrationRender(render) {
if (!isObj(r)) return ["render.postNarration must be an object of the mix's knobs"];
const errors = [];
for (const k of Object.keys(r)) if (!RENDER_KEYS.has(k)) errors.push(`render.postNarration.${k} is not a knob (${[...RENDER_KEYS].join(", ")})`);
- return [...errors, ...mixErrors(r, "render.postNarration")];
+ return [...errors, ...mixErrors(r, "render.postNarration"), ...followKnobErrors(r.follow, "render.postNarration.follow")];
}
/** Every reason one post item's `narration` cannot be built (empty: it can). */
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -15,11 +15,12 @@
// attachment's size and mtime), and a build whose key matches keeps the
// segment it has.
import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { POST_PICTURE_XFADE, POST_PUSH, fxRedactionErrors, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs";
import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters, rootTakeOf } from "./post-narration.mjs";
+import { applyFollowState, followPath, followStateAt, followStateKey, measureFollow } from "./read-follow.mjs";
import { redactEntry, redactionOn, shownLine, termsFor } from "./post-redact.mjs";
import { bleepFilters, slursOn, takeBleeps } from "./post-slurs.mjs";
import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs";
@@ -66,7 +67,7 @@ export function stepCaptions(step, cues) {
*
* @returns {string[]}
*/
-export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [] }) {
+export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -84,6 +85,15 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
parts.push(`[${cur}][${label}]overlay=x=${x}:y=${y}:enable='between(t,${num(a)},${num(b)})'[${next}]`);
cur = next;
};
+ // READ-FOLLOW (read-follow.mjs): the card's region as the browser drew it frame by frame -- the block being read
+ // lit, the words panned -- one shot per distinct state, held for its frames (a concat list), over the card.
+ if (follow) {
+ const fi = add(["-f", "concat", "-safe", "0", "-i", follow.list]);
+ parts.push(`[${fi}:v]fps=${fps},setsar=1,setpts=PTS-STARTPTS[rf]`);
+ const next = `b${++n}`;
+ parts.push(`[${cur}][rf]overlay=x=${follow.clip.x}:y=${follow.clip.y}:eof_action=repeat[${next}]`);
+ cur = next;
+ }
if (layout.mode === "stack" && cards.media && plan.steps.length) {
const mi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", cards.media]);
parts.push(`[${mi}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[mc]`);
@@ -226,7 +236,7 @@ async function loadChromium() {
* stack layout. The page is a file beside them, so its faces and the parent
* shot load from disk (an about:blank page may not read file: urls).
*/
-export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0 }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -244,6 +254,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
const html = postCardHtml(entry, {
width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl,
avatars: Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href])),
+ follow: !!follow && phase === "read",
redaction,
});
const file = path.join(dir, `${phase}.html`);
@@ -253,15 +264,67 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
const png = path.join(dir, `${phase}.png`);
await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height } });
out[phase] = png;
+ if (phase === "read" && follow) out.follow = await shootFollow(page, { follow, total, fps: render.fps ?? 30, box, dir });
}
await ctx.close();
- if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction });
+ if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow });
} finally {
await browser.close();
}
return out;
}
+/**
+ * READ-FOLLOW's FRAMES (read-follow.mjs): on the drawn card page, the pan's
+ * path from its geometry, then every frame's state (followStateAt at frame
+ * i / fps); each distinct state applied and the card's region shot once, and
+ * a concat list holding each shot for its frames. Null when nothing would
+ * move (fewer than two blocks read and no pan). `{ list, clip, shots, frames,
+ * geo, path }`.
+ */
+export async function shootFollow(page, { follow, total, fps, box, dir }) {
+ const geo = await page.evaluate(measureFollow);
+ const path0 = followPath(follow, geo);
+ const read = follow.blocks.filter((b) => b.start !== null).length;
+ if (read < 2 && !path0.segments.length) return null;
+ const r = await page.evaluate(() => {
+ const b = document.querySelector("[data-post-card]")?.getBoundingClientRect();
+ return b ? { x: b.left, y: b.top, width: b.width, height: b.height } : null;
+ });
+ if (!r) return null;
+ const x = Math.max(0, Math.floor(r.x));
+ const y = Math.max(0, Math.floor(r.y));
+ const clip = { x, y, width: Math.min(box.width - x, Math.ceil(r.x + r.width) - x), height: Math.min(box.height - y, Math.ceil(r.y + r.height) - y) };
+ const fdir = path.join(dir, "follow");
+ await rm(fdir, { recursive: true, force: true });
+ await mkdir(fdir, { recursive: true });
+ const frames = Math.max(1, Math.round(total * fps));
+ const runs = [];
+ for (let i = 0; i < frames; i += 1) {
+ const st = followStateAt(follow, path0, i / fps);
+ const key = followStateKey(st);
+ const last = runs[runs.length - 1];
+ if (last && last.key === key) last.n += 1;
+ else runs.push({ key, st, n: 1 });
+ }
+ const shots = new Map();
+ for (const run of runs) {
+ if (shots.has(run.key)) continue;
+ const file = path.join(fdir, `f-${String(shots.size).padStart(5, "0")}.png`);
+ await page.evaluate(applyFollowState, run.st);
+ await page.screenshot({ path: file, clip });
+ shots.set(run.key, file);
+ }
+ await page.evaluate(applyFollowState, null);
+ const q = (f) => `'${f.replace(/'/g, "'\\''")}'`;
+ const lines = ["ffconcat version 1.0"];
+ for (const run of runs) lines.push(`file ${q(shots.get(run.key))}`, `duration ${(run.n / fps).toFixed(6)}`);
+ lines.push(`file ${q(shots.get(runs[runs.length - 1].key))}`);
+ const list = path.join(fdir, "frames.ffconcat");
+ await writeFile(list, lines.join("\n") + "\n", "utf8");
+ return { list, clip, shots: shots.size, frames, geo, path: path0 };
+}
+
/** The device scale a word zoom's shots are taken at: crisp at its scale (2–4). */
export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.max(1, ...zooms.map((z) => z.scale ?? WORD_ZOOM_DEFAULTS.scale)))));
@@ -273,22 +336,30 @@ export const zoomShotScale = (zooms) => Math.min(4, Math.max(2, Math.ceil(Math.m
* and the region shot plain and with the zoom's highlight under the words.
* `zooms`: `[{ i, scope, from, to, scale, highlight }]`.
*/
-async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction = null }) {
+async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction = null, follow = null }) {
const k = zoomShotScale(zooms);
const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: k, offline: true, serviceWorkers: "block" });
const page = await ctx.newPage();
const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href]));
const load = async (name, highlight) => {
const file = path.join(dir, `${name}.html`);
- await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction }), "utf8");
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, highlight, redaction, follow: !!follow }), "utf8");
await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
};
+ // Following (read-follow.mjs): each zoom is shot as the card is at its peak -- that block lit, the words panned there.
+ let fpath = null;
+ const atZoom = async (z) => {
+ if (!follow) return;
+ fpath ??= followPath(follow, await page.evaluate(measureFollow));
+ await page.evaluate(applyFollowState, followStateAt(follow, fpath, z.span.t1));
+ };
const out = [];
try {
await load("zoom", null);
const radius = Math.round(18 * (box.height / 1080)) + 1;
for (const z of zooms) {
+ await atZoom(z);
const geo = await page.evaluate(({ scope, from, to, radius: r }) => {
const rect = (el) => {
const b = el.getBoundingClientRect();
@@ -321,11 +392,13 @@ async function shootZooms(browser, entry, { box, render, dir, fonts, parentShotU
const clip = (r) => ({ x: r.x, y: r.y, width: r.width, height: r.height });
for (const z of out) {
z.plain = path.join(dir, `zoom-${z.i}.png`);
+ await atZoom(z);
await page.screenshot({ path: z.plain, clip: clip(z.region) });
}
for (const z of out) {
if (!z.highlight) continue;
await load(`zoom-hl-${z.i}`, { scope: z.scope, from: z.from, to: z.to, color: z.highlight });
+ await atZoom(z);
z.hl = path.join(dir, `zoom-hl-${z.i}.png`);
await page.screenshot({ path: z.hl, clip: clip(z.region) });
}
@@ -393,7 +466,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
}));
const key = createHash("sha256")
// A redaction that changes what the card draws changes the key; none leaves it as it was.
- .update(JSON.stringify({ v: 1, entry, ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), ...(bleeps ? { bleeps } : {}), ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}) }))
+ .update(JSON.stringify({ v: 1, entry, ...(redactionOn(redaction) ? { published: redactEntry(entry, redaction), blank: termsFor(entry, redaction) } : {}), box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps, ...(Object.keys(avatars).length ? { avatars } : {}), ...(take ? { narration: plan.narration, postNarration: render.postNarration ?? null } : {}), ...(plan.follow ? { follow: plan.follow } : {}), ...(bleeps ? { bleeps } : {}), ...(slursOn(redaction?.slurs) ? { slurs: redaction.slurs } : {}) }))
.digest("hex");
const record = postRecordPath(seg);
const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null);
@@ -403,7 +476,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
}
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
const zoomPlan = postZoomPlan(entry, render, plan.total);
- const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction });
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total });
const zooms = (cards.zooms ?? []).map((z) => ({ ...z, target: zoomTarget(z.region, { ...z.word }, z.span.scale) }));
// Its video attachments' words, when transcribed: one textfile per cue.
const captions = [];
@@ -427,7 +500,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg });
narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) };
}
- const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms });
+ const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -435,12 +508,15 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
throw new Error(`${entry.id}: ffmpeg failed on the post item\n${detail}`);
}
await rename(tmp, seg);
- await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}) }, null, 2) + "\n", "utf8");
+ // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides).
+ if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true });
+ await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8");
emit("note", {
message: narration
? `${entry.id}: post item ${plan.total.toFixed(1)} s, narrated (${take.file}: ${plan.narration.seconds.toFixed(1)} s from ${plan.narration.at} s, muffled to ${plan.narration.voiceEnd.toFixed(1)} s)`
: `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`,
});
+ if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` });
for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` });
return seg;
}
diff --git a/umtool/report-to-video/post-slurs.test.mjs b/umtool/report-to-video/post-slurs.test.mjs
@@ -202,3 +202,33 @@ test("takeSlurBleeps (post-render.mjs): a take's state is its own or its source'
assert.equal(takeSlurBleeps(entry([tts]), tts, { terms: [], slurs: resolveSlurs({}, LIST, { uncensored: true }) }), null);
assert.equal(takeSlurBleeps(entry([tts]), tts, null), null);
});
+
+test("with read-follow: the pill sits in its word's slot inside the read's block, as a redaction bar does", () => {
+ const e = post(`First para here.\n\nThen you ${F} and more words follow here.`);
+ const html = postCardHtml(e, { width: 1280, height: 720, follow: true, redaction: { terms: [{ term: "more" }], slurs: ON } });
+ assert.match(html, /data-post-follow=/);
+ assert.ok(!html.toLowerCase().includes(F));
+ assert.match(html, /<span class="fblock" data-post-block="1"><span data-w="post:3">Then<\/span> <span data-w="post:4">you<\/span> <span data-w="post:5"><span class="slur" data-post-slur="">f\*{5}<\/span><\/span> <span data-w="post:6">and<\/span> <span data-w="post:7"><span class="rbar" data-post-blanked=""/);
+});
+
+test("with the narration mix: the beep is laid on the take's own voice before the narrator's chain, the bed and the muffle unchanged", async () => {
+ const { postSegmentArgs } = await import("./post-render.mjs");
+ const { postItemPlan, postLayout } = await import("./post-item.mjs");
+ const e = post(`you ${F} there`, { narration: { script: `you ${F} there`, takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 3, script: `you ${F} there` }] } });
+ const plan = postItemPlan(e, {});
+ const box = { width: 1440, height: 810 };
+ const args = (bleeps) => {
+ const argv = postSegmentArgs({
+ entry: e, box, plan, layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: [], render: { fps: 30, audioRate: 48000 }, outPath: "/o/p1.mp4",
+ narration: { file: "/t/take.wav", gainDb: 0, ...(bleeps ? { bleeps } : {}) },
+ });
+ return argv[argv.indexOf("-filter_complex") + 1];
+ };
+ const plain = args(null);
+ const beeped = args({ mode: "beep", spans: [[0.96, 1.56]], seconds: 3 });
+ assert.doesNotMatch(plain, /pnbl/);
+ assert.match(beeped, /\[\d+:a\]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,volume=0:enable='between\(t,0\.96,1\.56\)'\[pnbl_m\]/);
+ assert.match(beeped, /\[pnbl_m\]\[pnbl_t\]amix=inputs=2:normalize=0:duration=first\[pnbl\];\[pnbl\]aresample=48000/);
+ // Everything after the voice's input is the same mix.
+ assert.equal(beeped.slice(beeped.indexOf("[pnbl]aresample")).replace("[pnbl]", ""), plain.slice(plain.search(/\[\d+:a\]aresample/)).replace(/^\[\d+:a\]/, ""));
+});
diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs
@@ -0,0 +1,513 @@
+// A POST ITEM's READ-FOLLOW (umtool/docs/report-video.md, "Read-follow"; operator,
+// 3 Nov: "'I'm someone who has never watched Ember' goes on beyond the text but
+// the text doesn't scroll? That needs to be an effect, something like highlight
+// the current paragraph and panning down as needed" -- and "a subtle effect of
+// highlighting the block currently being read by making it brighter may be
+// good"): the card's words laid out in BLOCKS that match the read's parts, the
+// block being read drawn at full strength and the others dimmed a little, and a
+// card whose words are taller than their box PANNED so the block being read
+// stays in view -- where it used to shrink its words to 18 px and cut the rest.
+//
+// render.postNarration.follow = { on?: true, dim?: 0.65, ease?: 0.25 } the cut's
+// entry.follow = false | { on?, dim?, ease? } one post's (false: off)
+//
+// THE BLOCKS (followBlocks, from the entry alone): the read's parts -- a
+// narrated take's `parts` (its paragraphs, or a long paragraph's <=60-word
+// sentence runs; `para` = piece*100 + paragraph when a take reads the post it
+// answers first), else the script's parts, else (un-narrated) the card's own
+// paragraphs and sentence runs -- each matched BY ITS WORDS to the run of the
+// card's words it reads, in whichever of the card's texts it is (a parent's,
+// the post's, the quoted post's). The script is the post as a voice says it
+// ("this slash that", a shout lower-cased), so the match is by normalized
+// words, in order (a windowed longest common subsequence), never by index.
+// Words no part reads join the block before them up to a paragraph break; a
+// whole paragraph no part reads is a block that is never lit.
+//
+// THE SCHEDULE (followSchedule, the plan's `follow`): each block's start on the
+// item's clock -- a part's start in the take at the read's rate (lead + start ÷
+// rate, post-narration.mjs partStartOnItem); without parts, the read's seconds
+// shared by words; un-narrated, the reading rule's seconds (post-item.mjs
+// readSeconds, contextReadSeconds) -- and the read's end, after which every
+// block is back at full strength.
+//
+// THE PAN (followPath, from the card page's geometry, measureFollow): the post's
+// words in a window of the card (`.words`); when a block to be read is not in
+// view, the words pan (eased, FOLLOW_PAN.seconds, starting FOLLOW_PAN.lead
+// before its read) so it sits a margin below the window's top; a block taller
+// than the window pans on through it as it is read. Short posts never move.
+// A fading edge says there is more text above or below.
+//
+// The build and Play draw the same thing: the card page carries the blocks
+// (`data-post-block`), its flow (`data-post-flow`) and fades; followStateAt(t)
+// is a pure function of the item's second (seek-safe), and applyFollowState
+// sets it on the page -- in the build per frame before a screenshot
+// (post-render.mjs), in Play per tick (PostItemPlayer).
+
+import { cardText, contextReadSeconds, contextText, parentsOf, readSeconds } from "./post-item.mjs";
+import { isNarrated, narrationSchedule, partStartOnItem, pickedTake, scriptParts } from "./post-narration.mjs";
+import { cardTokens, easeOf, normWord, scriptWordsOf } from "./word-zoom.mjs";
+
+export const FOLLOW_DEFAULTS = Object.freeze({ on: true, dim: 0.65, ease: 0.25 });
+export const FOLLOW_LIMITS = Object.freeze({ dim: [0.2, 1], ease: [0, 2] });
+/** The pan: it starts `lead` s before the block's read and takes `seconds`, eased; the block sits `margin` (of the window) below its top. */
+export const FOLLOW_PAN = Object.freeze({ lead: 0.4, seconds: 0.7, margin: 0.1 });
+/** While follow is on, the words never shrink below this (px of a 1080-high frame) to fit: the card pans instead. */
+export const FOLLOW_MIN_SIZE = 28;
+/** A block's words are matched if at least this share of a part's words are found. */
+const MATCH_MIN = 0.35;
+
+const KEYS = new Set(["on", "dim", "ease"]);
+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;
+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
+const str = (v) => (typeof v === "string" ? v : "");
+
+// ---------------------------------------------------------------------------
+// The knobs.
+// ---------------------------------------------------------------------------
+
+/** One follow knob's errors (`where`: its path in the manifest). `false` is off. */
+export function followKnobErrors(v, where) {
+ if (v === undefined || v === null || v === false) return [];
+ if (!isObj(v)) return [`${where} must be false (off) or { on?, dim?, ease? }`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!KEYS.has(k)) errors.push(`${where}.${k} is not a follow knob (on, dim, ease)`);
+ if (v.on !== undefined && typeof v.on !== "boolean") errors.push(`${where}.on must be true or false`);
+ for (const k of ["dim", "ease"]) {
+ if (v[k] !== undefined && !(fin(v[k]) && v[k] >= FOLLOW_LIMITS[k][0] && v[k] <= FOLLOW_LIMITS[k][1])) {
+ errors.push(`${where}.${k} must be ${FOLLOW_LIMITS[k][0]}–${FOLLOW_LIMITS[k][1]}${k === "dim" ? " (the other blocks' opacity)" : " seconds"}`);
+ }
+ }
+ return errors;
+}
+
+/** A post item's `follow` errors (validatePostItem). */
+export const validatePostFollow = (e) => followKnobErrors(e?.follow, `timeline ${e?.id ?? "?"}.follow`);
+
+const pick = (o) => (isObj(o) ? Object.fromEntries(Object.entries(o).filter(([k, v]) => KEYS.has(k) && v !== undefined && v !== null)) : {});
+
+/**
+ * One post's follow knobs: its own, else the cut's (`render.postNarration.follow`), else the defaults.
+ * @param {Record<string, any> | null | undefined} entry
+ * @param {Record<string, any>} [render]
+ * @returns {{ on: boolean, dim: number, ease: number }}
+ */
+export function followKnobs(entry, render = undefined) {
+ const r = isObj(render?.postNarration) ? render.postNarration.follow : undefined;
+ const e = entry?.follow;
+ return {
+ ...FOLLOW_DEFAULTS,
+ ...(r === false ? { on: false } : pick(r)),
+ ...(e === false ? { on: false } : pick(e)),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// THE BLOCKS: the read's parts matched to the card's words.
+// ---------------------------------------------------------------------------
+
+/** The card's texts in the order they are drawn: the posts it answers (oldest first), the post, the quoted post. */
+export function cardScopes(entry) {
+ const out = [];
+ const parents = parentsOf(entry);
+ for (let i = parents.length - 1; i >= 0; i -= 1) {
+ const t = contextText(parents[i]);
+ if (t.trim()) out.push({ scope: `parent:${i}`, text: t, ref: parents[i] });
+ }
+ out.push({ scope: "post", text: cardText(entry), ref: null });
+ if (isObj(entry?.quoted) && contextText(entry.quoted).trim()) out.push({ scope: "quoted", text: contextText(entry.quoted), ref: entry.quoted });
+ return out;
+}
+
+/** A word as matching sees it: normalized, apostrophes gone. */
+const keyOf = (w) => normWord(w).replace(/'/g, "");
+
+/** A card text's match keys: `[{ key, ci }]` (ci its card word), a "this/that" word split at its slashes. */
+function cardKeys(text) {
+ const out = [];
+ for (const t of cardTokens(text)) {
+ if (t.tok === undefined) continue;
+ for (const sub of t.tok.split("/")) {
+ const key = keyOf(sub);
+ if (key) out.push({ key, ci: t.i });
+ }
+ }
+ return out;
+}
+
+/** A part's words as keys ("slash" is the voice's reading of a "/": the card has none). */
+const partKeys = (text) => scriptWordsOf(text).map(keyOf).filter((k) => k && k !== "slash");
+
+/** The paragraph starts of a card text: the card word indices that begin a paragraph (after a blank line). */
+function paragraphStarts(text) {
+ const starts = new Set([0]);
+ let seenWord = false;
+ let next = 0;
+ for (const t of cardTokens(text)) {
+ if (t.tok !== undefined) {
+ seenWord = true;
+ next = t.i + 1;
+ } else if (seenWord && /\n\s*\n/.test(t.space)) starts.add(next);
+ }
+ return starts;
+}
+
+/**
+ * A FITTING ALIGNMENT of `a` (a part's keys) inside `b` (a card text's keys,
+ * from `lo` to `hi`): all of `a`, a compact run of `b` -- a word in common
+ * +2, a word skipped on either side -1, free before and after the run (so
+ * a common word far away never stretches the span). Returns the matched b
+ * indices, in order.
+ */
+function fitMatch(a, b, lo, hi) {
+ const n = a.length;
+ const m = hi - lo;
+ if (!n || m <= 0) return [];
+ const W = m + 1;
+ const S = new Int32Array((n + 1) * W);
+ for (let i = 1; i <= n; i += 1) S[i * W] = -i;
+ for (let i = 1; i <= n; i += 1) {
+ for (let j = 1; j <= m; j += 1) {
+ const diag = S[(i - 1) * W + j - 1] + (a[i - 1] === b[lo + j - 1].key ? 2 : -1);
+ S[i * W + j] = Math.max(diag, S[(i - 1) * W + j] - 1, S[i * W + j - 1] - 1);
+ }
+ }
+ let j = 0;
+ for (let x = 1; x <= m; x += 1) if (S[n * W + x] > S[n * W + j]) j = x;
+ const hits = [];
+ let i = n;
+ while (i > 0 && j > 0) {
+ const here = S[i * W + j];
+ const eq = a[i - 1] === b[lo + j - 1].key;
+ if (here === S[(i - 1) * W + j - 1] + (eq ? 2 : -1)) {
+ if (eq) hits.push(lo + j - 1);
+ i -= 1;
+ j -= 1;
+ } else if (here === S[(i - 1) * W + j] - 1) i -= 1;
+ else j -= 1;
+ }
+ return hits.reverse();
+}
+
+/** The parts a block map is made from: `[{ text, scope? }]` -- the take's, the script's, or (un-narrated) the card's own. */
+export function followParts(entry) {
+ if (isNarrated(entry)) {
+ const t = pickedTake(entry);
+ if (Array.isArray(t?.parts) && t.parts.length) return { source: "take", parts: t.parts.map((p) => ({ text: str(p.text), start: fin(p.start) ? p.start : null })) };
+ const script = str(t?.script).trim() ? t.script : str(entry?.narration?.script);
+ return { source: "script", parts: scriptParts(script).map((p) => ({ text: p.text })) };
+ }
+ const parts = [];
+ for (const sc of cardScopes(entry)) for (const p of scriptParts(sc.text)) parts.push({ text: p.text, scope: sc.scope });
+ return { source: "card", parts };
+}
+
+/**
+ * THE BLOCK MAP, pure, from the entry alone: `{ source, blocks: [{ k, scope,
+ * from, to, part }], parts }` -- each block a run of one card text's words
+ * (card word indices, inclusive), `part` the index of the part that reads it
+ * (null: a paragraph no part reads). Blocks are in the card's order within a
+ * scope; `k` is their id on the page (`data-post-block`).
+ */
+export function followBlocks(entry) {
+ const { source, parts } = followParts(entry);
+ const scopes = cardScopes(entry).map((sc) => ({ ...sc, keys: cardKeys(sc.text), starts: paragraphStarts(sc.text), words: cardTokens(sc.text).filter((t) => t.tok !== undefined).length }));
+ const byScope = new Map(scopes.map((sc) => [sc.scope, { sc, spans: [], cursor: 0 }]));
+ parts.forEach((p, pi) => {
+ const keys = partKeys(p.text);
+ if (!keys.length) return;
+ // Which of the card's texts it reads: its own scope (the card's parts), else the one most of its words are in.
+ let target = p.scope ? byScope.get(p.scope) : null;
+ if (!target) {
+ let best = 0;
+ for (const s of byScope.values()) {
+ const set = new Set(s.sc.keys.map((x) => x.key));
+ const share = keys.filter((k) => set.has(k)).length / keys.length;
+ if (share > best + 1e-9 || (Math.abs(share - best) < 1e-9 && s.sc.scope === "post" && share > 0)) {
+ best = share;
+ target = s;
+ }
+ }
+ if (best < 0.5) target = null;
+ }
+ if (!target) return;
+ const ck = target.sc.keys;
+ // In order: a window from where the last part ended, then (a part read out of order) the whole text.
+ let hits = fitMatch(keys, ck, target.cursor, Math.min(ck.length, target.cursor + 2 * keys.length + 40));
+ if (hits.length < Math.max(1, Math.ceil(MATCH_MIN * keys.length))) hits = fitMatch(keys, ck, 0, ck.length);
+ if (hits.length < Math.max(1, Math.ceil(MATCH_MIN * keys.length))) return;
+ target.cursor = hits[hits.length - 1] + 1;
+ target.spans.push({ part: pi, from: ck[hits[0]].ci, to: ck[hits[hits.length - 1]].ci });
+ });
+ const blocks = [];
+ for (const { sc, spans } of byScope.values()) {
+ if (!sc.words) continue;
+ // Overlaps (a part re-read) are clipped to what the earlier part did not cover.
+ const sorted = [...spans].sort((a, b) => a.from - b.from || a.part - b.part);
+ const clean = [];
+ for (const s of sorted) {
+ const last = clean[clean.length - 1];
+ const from = last ? Math.max(s.from, last.to + 1) : s.from;
+ if (from <= s.to) clean.push({ ...s, from });
+ }
+ const segs = [];
+ const gap = (from, to, prev, nextSpan) => {
+ if (from > to) return;
+ // The gap split at its paragraph starts: its first piece joins the block before (no break between),
+ // its last piece the block after; a piece between breaks is a paragraph no part reads.
+ const cuts = [from];
+ for (let i = from + 1; i <= to; i += 1) if (sc.starts.has(i)) cuts.push(i);
+ const pieces = cuts.map((c, j) => ({ from: c, to: j + 1 < cuts.length ? cuts[j + 1] - 1 : to }));
+ pieces.forEach((pc, j) => {
+ if (j === 0 && prev && !sc.starts.has(pc.from)) prev.to = pc.to;
+ else if (j === pieces.length - 1 && nextSpan && !sc.starts.has(to + 1)) nextSpan.from = pc.from;
+ else segs.push({ scope: sc.scope, from: pc.from, to: pc.to, part: null });
+ });
+ };
+ let pos = 0;
+ let prev = null;
+ for (const s of clean) {
+ const span = { scope: sc.scope, from: s.from, to: s.to, part: s.part };
+ gap(pos, s.from - 1, prev, span);
+ segs.push(span);
+ prev = span;
+ pos = s.to + 1;
+ }
+ gap(pos, sc.words - 1, prev, null);
+ segs.sort((a, b) => a.from - b.from);
+ blocks.push(...segs);
+ }
+ return { source, parts: parts.length, blocks: blocks.map((b, k) => ({ k, ...b })) };
+}
+
+/** A block map's runs for one scope, as wordsHtml wraps them: `[{ from, to, k }]`. */
+export const scopeBlocks = (map, scope) => (map?.blocks ?? []).filter((b) => b.scope === scope).map((b) => ({ from: b.from, to: b.to, k: b.k }));
+
+// ---------------------------------------------------------------------------
+// THE SCHEDULE: each block's start on the item's clock.
+// ---------------------------------------------------------------------------
+
+const wordsIn = (t) => scriptWordsOf(t).length;
+
+/**
+ * THE FOLLOW SCHEDULE, pure (the plan's `follow`): `{ dim, ease, readEnd,
+ * blocks: [{ k, scope, from, to, part, start, end }] }` -- `start` the
+ * block's read on the item's clock (null: never read), `end` the next
+ * block's start (the read's end for the last). Null when follow is off.
+ * `o.total`/`o.hold`: the item's length, its hold (an un-narrated post with a
+ * hold longer than its reading spreads the reading over it, less a second).
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {{ hold?: number | null, narration?: Record<string, any> | null }} [o]
+ */
+export function followSchedule(entry, render = undefined, { hold = null, narration = undefined } = {}) {
+ const k = followKnobs(entry, render);
+ if (!k.on) return null;
+ const map = followBlocks(entry);
+ const { parts } = followParts(entry);
+ const starts = new Array(parts.length).fill(null);
+ let readEnd;
+ if (isNarrated(entry)) {
+ const sch = narration ?? narrationSchedule(entry, render);
+ readEnd = r3(sch.at + sch.seconds);
+ const take = pickedTake(entry);
+ const timed = map.source === "take" && parts.every((p) => fin(p.start));
+ if (timed) take.parts.forEach((p, i) => (starts[i] = partStartOnItem(sch, p)));
+ else {
+ // No parts: the read's seconds shared by words.
+ const total = parts.reduce((n, p) => n + wordsIn(p.text), 0) || 1;
+ let w = 0;
+ parts.forEach((p, i) => {
+ starts[i] = r3(sch.at + (sch.seconds * w) / total);
+ w += wordsIn(p.text);
+ });
+ }
+ } else {
+ // The reading rule: each context post its context seconds, the post its reading seconds, shared by words.
+ const spans = new Map();
+ for (const sc of cardScopes(entry)) spans.set(sc.scope, sc.ref ? contextReadSeconds(sc.ref) : readSeconds(entry));
+ const reading = [...spans.values()].reduce((n, v) => n + v, 0);
+ const f = fin(hold) && hold > reading + 1 ? (hold - 1) / reading : 1;
+ let t = 0;
+ for (const sc of cardScopes(entry)) {
+ const mine = parts.map((p, i) => ({ p, i })).filter((x) => x.p.scope === sc.scope);
+ const words = mine.reduce((n, x) => n + Math.max(1, wordsIn(x.p.text)), 0) || 1;
+ const secs = spans.get(sc.scope) * f;
+ for (const x of mine) {
+ starts[x.i] = r3(t);
+ t += (secs * Math.max(1, wordsIn(x.p.text))) / words;
+ }
+ if (!mine.length) t += secs;
+ }
+ readEnd = r3(t);
+ }
+ const blocks = map.blocks.map((b) => ({ ...b, start: b.part === null ? null : starts[b.part] }));
+ // In the order they are read; each ends where the next starts.
+ const lit = blocks.filter((b) => b.start !== null).sort((a, b) => a.start - b.start || a.k - b.k);
+ lit.forEach((b, i) => (b.end = i + 1 < lit.length ? lit[i + 1].start : Math.max(b.start, readEnd)));
+ for (const b of blocks) if (b.start === null) b.end = null;
+ return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks };
+}
+
+/** The block being read at item second `s` (its k), or null (before the read's first block, or none). */
+export function followBlockAt(follow, s) {
+ let cur = null;
+ for (const b of follow?.blocks ?? []) if (b.start !== null && s >= b.start - 0.05 && (cur === null || b.start >= cur.start)) cur = b;
+ return cur ? cur.k : null;
+}
+
+// ---------------------------------------------------------------------------
+// THE PAN: the window over the post's words, from the page's geometry.
+// ---------------------------------------------------------------------------
+
+/**
+ * THE PAN's PATH, pure: `{ max, segments: [{ t0, t1, from, to }] }` -- the
+ * flow's offset (px, down) eased from `from` to `to` over each segment. `geo`
+ * is measureFollow's: the window's height `H`, the flow's `C`, each post
+ * block's `{ top, bottom }` in the flow. No overflow: no segments.
+ */
+export function followPath(follow, geo) {
+ const H = fin(geo?.H) ? geo.H : 0;
+ const C = fin(geo?.C) ? geo.C : 0;
+ const max = Math.max(0, Math.round((C - H) * 100) / 100);
+ if (!follow || max < 1 || H <= 0) return { max, segments: [] };
+ const m = Math.round(H * FOLLOW_PAN.margin);
+ const segments = [];
+ let off = 0;
+ let free = 0;
+ const moveTo = (target, at) => {
+ const to = Math.round(clamp(target, 0, max) * 100) / 100;
+ if (Math.abs(to - off) < 1) return;
+ const t0 = r3(Math.max(0, at, free));
+ const t1 = r3(t0 + FOLLOW_PAN.seconds);
+ segments.push({ t0, t1, from: off, to });
+ off = to;
+ free = t1;
+ };
+ const read = (follow.blocks ?? []).filter((b) => b.scope === "post" && b.start !== null && geo.blocks?.[b.k]).sort((a, b) => a.start - b.start);
+ for (const b of read) {
+ const { top, bottom } = geo.blocks[b.k];
+ const h = bottom - top;
+ // Not in view (above the window, or running past its foot): it pans to sit a margin below the top.
+ if (top < off - 0.5 || bottom > off + H - m / 2 + 0.5) moveTo(top - m, b.start - FOLLOW_PAN.lead);
+ // Taller than the window: on through it as it is read (the reading line taken as even through its words).
+ const room = H - 2 * m;
+ if (h > room && room > 0) {
+ const over = h - room;
+ const n = Math.ceil(over / (0.6 * room));
+ const span = Math.max(0.1, b.end - b.start);
+ for (let i = 1; i <= n; i += 1) {
+ const target = top - m + (over * i) / n;
+ const line = target - (top - m) + room * 0.6;
+ moveTo(target, Math.min(b.end - FOLLOW_PAN.seconds, b.start + (span * line) / h));
+ }
+ }
+ }
+ return { max, segments };
+}
+
+/** The flow's offset at item second `s` on the path. */
+export function followOffsetAt(path, s) {
+ let off = 0;
+ for (const g of path?.segments ?? []) {
+ if (s >= g.t1) off = g.to;
+ else if (s >= g.t0) return g.from + (g.to - g.from) * easeOf("inOut", (s - g.t0) / Math.max(1e-6, g.t1 - g.t0));
+ else break;
+ }
+ return off;
+}
+
+/** An eased ramp 0 -> 1 over [a, a + d]. */
+const ramp = (s, a, d) => (d <= 0 ? (s >= a ? 1 : 0) : easeOf("inOut", (s - a) / d));
+
+/**
+ * THE STATE at item second `s`, pure and seek-safe: `{ op: { <k>: opacity },
+ * offset, fadeTop, fadeBottom, current }`. The block being read rises to full
+ * over `ease` (centred on its start) while the one before falls back to
+ * `dim`; before the first block's start the first is lit; after the read's
+ * end every block rises back to full. A map of fewer than two read blocks is
+ * never dimmed. `path`: followPath's (null: no pan).
+ */
+export function followStateAt(follow, path, s) {
+ const op = {};
+ if (!follow) return { op, offset: 0, fadeTop: 0, fadeBottom: 0, current: null };
+ const read = follow.blocks.filter((b) => b.start !== null).sort((a, b) => a.start - b.start);
+ const e = follow.ease;
+ const after = ramp(s, follow.readEnd, e);
+ if (read.length >= 2) {
+ const lit = new Map();
+ read.forEach((b, i) => {
+ const up = i === 0 ? 1 : ramp(s, b.start - e / 2, e);
+ const down = i + 1 < read.length ? ramp(s, read[i + 1].start - e / 2, e) : 0;
+ lit.set(b.k, Math.min(up, 1 - down));
+ });
+ for (const b of follow.blocks) {
+ const l = Math.max(lit.get(b.k) ?? 0, after);
+ op[b.k] = Math.round((follow.dim + (1 - follow.dim) * l) * 1000) / 1000;
+ }
+ }
+ const offset = Math.round(followOffsetAt(path, s) * 4) / 4;
+ const max = path?.max ?? 0;
+ const edge = 24;
+ return {
+ op,
+ offset,
+ fadeTop: max >= 1 ? Math.round(clamp(offset / edge, 0, 1) * 100) / 100 : 0,
+ fadeBottom: max >= 1 ? Math.round(clamp((max - offset) / edge, 0, 1) * 100) / 100 : 0,
+ current: read.length ? followBlockAt(follow, s) ?? read[0].k : null,
+ };
+}
+
+/** A state's key: two frames with the same key draw the same card (the build shoots each key once). */
+export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom]);
+
+// ---------------------------------------------------------------------------
+// In the page: self-contained (the build passes them to page.evaluate; Play
+// calls them on its frame's document). They reach for nothing outside.
+// ---------------------------------------------------------------------------
+
+/** The page's geometry for the pan: the window's height, the flow's, each post block's top and bottom in the flow. */
+export function measureFollow(doc = document) {
+ const words = doc.querySelector("[data-post-words]");
+ const flow = doc.querySelector("[data-post-flow]");
+ if (!words || !flow) return null;
+ const had = flow.style.transform;
+ flow.style.transform = "none";
+ const fr = flow.getBoundingClientRect();
+ const blocks = {};
+ for (const el of Array.from(flow.querySelectorAll("[data-post-block]"))) {
+ let top = Infinity;
+ let bottom = -Infinity;
+ for (const r of Array.from(el.getClientRects())) {
+ if (r.width === 0 && r.height === 0) continue;
+ top = Math.min(top, r.top);
+ bottom = Math.max(bottom, r.bottom);
+ }
+ if (top < bottom) blocks[el.getAttribute("data-post-block")] = { top: Math.round((top - fr.top) * 100) / 100, bottom: Math.round((bottom - fr.top) * 100) / 100 };
+ }
+ const out = { H: words.clientHeight, C: Math.round(fr.height * 100) / 100, blocks };
+ flow.style.transform = had;
+ return out;
+}
+
+/** Set a follow state on the page: each block's opacity, the flow's offset, the fading edges. */
+export function applyFollowState(state, doc = document) {
+ const op = (state && state.op) || {};
+ for (const el of Array.from(doc.querySelectorAll("[data-post-block]"))) {
+ const o = op[el.getAttribute("data-post-block")];
+ const v = typeof o === "number" && o < 0.9995 ? String(o) : "";
+ if (el.style.opacity !== v) el.style.opacity = v;
+ }
+ const flow = doc.querySelector("[data-post-flow]");
+ if (flow) {
+ const t = state && state.offset ? `translateY(${-state.offset}px)` : "";
+ if (flow.style.transform !== t) flow.style.transform = t;
+ }
+ for (const [side, v] of [["top", state ? state.fadeTop : 0], ["bottom", state ? state.fadeBottom : 0]]) {
+ const el = doc.querySelector(`[data-post-fade="${side}"]`);
+ if (el) el.style.opacity = String(v || 0);
+ }
+ if (doc.body) doc.body.setAttribute("data-post-follow-block", state && state.current !== null && state.current !== undefined ? String(state.current) : "");
+}
diff --git a/umtool/report-to-video/read-follow.test.mjs b/umtool/report-to-video/read-follow.test.mjs
@@ -0,0 +1,223 @@
+// read-follow.mjs: a post item's read-follow -- the read's parts matched to the
+// card's words (a long paragraph split into parts, a script that reads "this
+// slash that" and lower-cases a shout), the schedule on the item's clock (a
+// take's part starts divided by the read's rate; un-narrated, the reading
+// rule), the pan that keeps the block being read in view, and the card page.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs";
+import { postSegmentArgs } from "./post-render.mjs";
+import { speakableText, validatePostNarrationRender } from "./post-narration.mjs";
+import {
+ FOLLOW_DEFAULTS, FOLLOW_PAN, followBlockAt, followBlocks, followKnobs, followOffsetAt, followPath, followSchedule, followStateAt, followStateKey,
+} from "./read-follow.mjs";
+import { cardWordsOf } from "./word-zoom.mjs";
+
+const LONG_PARA =
+ "Believe it or not, two people can read the same thing and come to a different conclusion. That doesn't make me a leftist, nor does it mean I'm pretending not to get it. " +
+ "At first I didn't have much context but looking into things, Strawb appears to be a malicious actor and Maria appears to be malicious as well. " +
+ "I think the entire thing was blown WAY out of proportion and a lot of people are being really obtuse/vindictive about it. " +
+ "For example Ember did not infiltrate this group chat, it was actually Strawb who was invited later to the chat, and Ember was one of the three original members.";
+const TEXT = `Normally I don't respond to stuff like this.\n\nKirsche you have lost the plot.\n\n${LONG_PARA}\n\nThat is all.`;
+const base = (o = {}) => ({
+ type: "post", id: "p1", post: "obvious-x/2115851166383063324", platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises",
+ date: "2026-10-29T17:00:03.000Z", text: TEXT, ...o,
+});
+/** A take read part by part, as the orchestrator's generator makes one: the script's parts, each timed. */
+function narrated(entry, { rate } = {}) {
+ const script = speakableText(entry.text);
+ const paras = script.split(/\n\n/);
+ const parts = [];
+ let at = 0;
+ paras.forEach((p, para) => {
+ // The long paragraph read in two runs of sentences (as scriptParts splits one over 60 words).
+ const runs = p.split(/ (?=At first|For example)/);
+ for (const text of runs) {
+ const seconds = text.split(/\s+/).length / 3;
+ parts.push({ n: parts.length + 1, para, text, start: Math.round(at * 100) / 100, seconds: Math.round(seconds * 100) / 100 });
+ at += seconds + 0.5;
+ }
+ });
+ return {
+ ...entry,
+ narration: { script, takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: Math.round(at * 100) / 100, script, parts }], ...(rate ? { rate } : {}) },
+ };
+}
+const wordsOf = (entry, b) => cardWordsOf(entry.text).slice(b.from, b.to + 1).join(" ");
+
+test("the knobs: on by default, dim 0.65, ease 0.25; the cut's, then the post's; false is off", () => {
+ assert.deepEqual(followKnobs(base()), FOLLOW_DEFAULTS);
+ assert.deepEqual(followKnobs(base(), { postNarration: { follow: { dim: 0.5 } } }), { on: true, dim: 0.5, ease: 0.25 });
+ assert.equal(followKnobs(base({ follow: false }), { postNarration: { follow: { dim: 0.5 } } }).on, false);
+ assert.equal(followKnobs(base({ follow: { on: true } }), { postNarration: { follow: { on: false } } }).on, true);
+ assert.deepEqual(validatePostItem(base({ follow: { dim: 0.1 } })), ["timeline p1.follow.dim must be 0.2–1 (the other blocks' opacity)"]);
+ assert.deepEqual(validatePostItem(base({ follow: "yes" })), ["timeline p1.follow must be false (off) or { on?, dim?, ease? }"]);
+ assert.deepEqual(validatePostItem(base({ follow: false })), []);
+ assert.deepEqual(validatePostNarrationRender({ postNarration: { follow: { ease: 0.4, dim: 0.7 } } }), []);
+ assert.match(validatePostNarrationRender({ postNarration: { follow: { pan: 1 } } }).join(), /follow.pan is not a follow knob/);
+ assert.equal(postItemPlan(base({ follow: false })).follow, undefined);
+});
+
+test("parts -> blocks: each part's words found on the card in order, a long paragraph split where its parts split", () => {
+ const e = narrated(base());
+ const { blocks, source } = followBlocks(e);
+ assert.equal(source, "take");
+ assert.equal(blocks.length, 6);
+ assert.deepEqual(blocks.map((b) => b.part), [0, 1, 2, 3, 4, 5]);
+ assert.equal(wordsOf(e, blocks[0]), "Normally I don't respond to stuff like this.");
+ assert.equal(wordsOf(e, blocks[1]), "Kirsche you have lost the plot.");
+ // The long paragraph: three blocks, each a run of its sentences, covering it without a gap.
+ assert.match(wordsOf(e, blocks[2]), /^Believe it or not, .* pretending not to get it\.$/);
+ assert.match(wordsOf(e, blocks[3]), /^At first .* malicious as well\. I think .*obtuse\/vindictive about it\.$/);
+ assert.match(wordsOf(e, blocks[4]), /^For example .* original members\.$/);
+ assert.equal(blocks[3].from, blocks[2].to + 1);
+ assert.equal(blocks[4].from, blocks[3].to + 1);
+ assert.equal(wordsOf(e, blocks[5]), "That is all.");
+ assert.equal(blocks[5].to, cardWordsOf(e.text).length - 1);
+});
+
+test("parts -> blocks: a parent read first (para 0) then the post (para 100+), matched by words, not by index; an unread quote is a block never lit", () => {
+ const parent = { handle: "someone", text: "I think she's just super paranoid" };
+ const e = base({ text: "And that's fair.\n\nJUST keep in mind this/that is a lot.", parents: [parent], quoted: { handle: "q", text: "A quoted post nobody reads aloud." } });
+ e.narration = {
+ script: "x",
+ takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 9, parts: [
+ { n: 1, para: 0, text: "I think she's just super paranoid", start: 0, seconds: 2 },
+ { n: 2, para: 100, text: "And that's fair.", start: 2.6, seconds: 1.5 },
+ { n: 3, para: 101, text: "just keep in mind this slash that is a lot!", start: 4.7, seconds: 3 },
+ ] }],
+ };
+ const { blocks } = followBlocks(e);
+ const by = (scope) => blocks.filter((b) => b.scope === scope);
+ assert.deepEqual(by("parent:0").map((b) => [b.from, b.to, b.part]), [[0, 5, 0]]);
+ assert.deepEqual(by("post").map((b) => [b.part, b.from, b.to]), [[1, 0, 2], [2, 3, 10]]);
+ assert.deepEqual(by("quoted").map((b) => b.part), [null]);
+ const sch = followSchedule(e);
+ assert.deepEqual(sch.blocks.filter((b) => b.start !== null).map((b) => b.start), [0.4, 3, 5.1]);
+ assert.equal(sch.blocks.find((b) => b.scope === "quoted").start, null);
+});
+
+test("the schedule: a part starts at lead + its start in the take ÷ the read's rate", () => {
+ const e = narrated(base(), { rate: 1.25 });
+ const plan = postItemPlan(e);
+ const parts = e.narration.takes[0].parts;
+ const f = plan.follow;
+ assert.equal(f.blocks.length, parts.length);
+ parts.forEach((p, i) => assert.equal(f.blocks[i].start, Math.round((0.4 + p.start / 1.25) * 1000) / 1000));
+ assert.equal(f.readEnd, Math.round((0.4 + e.narration.takes[0].seconds / 1.25) * 1000) / 1000);
+ // Each block ends where the next starts, the last at the read's end.
+ assert.equal(f.blocks[0].end, f.blocks[1].start);
+ assert.equal(f.blocks[5].end, f.readEnd);
+ // The cut's rate does the same.
+ const g = postItemPlan(narrated(base()), { postNarration: { rate: 1.25 } }).follow;
+ assert.deepEqual(g.blocks.map((b) => b.start), f.blocks.map((b) => b.start));
+ assert.equal(followBlockAt(f, f.blocks[3].start + 0.01), 3);
+ assert.equal(followBlockAt(f, f.blocks[3].start - 0.2), 2);
+});
+
+test("un-narrated: the card's own paragraphs and sentence runs, paced by the reading rule", () => {
+ const e = base();
+ const f = postItemPlan(e).follow;
+ assert.equal(f.source, "card");
+ assert.ok(f.blocks.length >= 4);
+ assert.equal(f.blocks[0].start, 0);
+ // The post's reading time (clamped 3-15 s) is shared by words; the read ends there.
+ assert.equal(f.readEnd, 15);
+ for (let i = 1; i < f.blocks.length; i += 1) assert.ok(f.blocks[i].start > f.blocks[i - 1].start);
+ // A hold longer than the reading spreads it, less a second.
+ assert.equal(postItemPlan(base({ hold: 61 })).follow.readEnd, 60);
+});
+
+test("the state: the block being read at full, the others dimmed, eased; back to full after the read", () => {
+ const f = postItemPlan(narrated(base())).follow;
+ const at = (s) => followStateAt(f, null, s);
+ const s3 = f.blocks[3].start;
+ const mid = at((s3 + f.blocks[4].start) / 2);
+ assert.equal(mid.current, 3);
+ assert.equal(mid.op[3], 1);
+ assert.equal(mid.op[2], 0.65);
+ assert.equal(mid.op[0], 0.65);
+ // Halfway through the ease, the two meet.
+ const half = at(s3);
+ assert.ok(half.op[3] > 0.65 && half.op[3] < 1 && half.op[2] > 0.65 && half.op[2] < 1);
+ assert.equal(at(s3 + f.ease / 2 + 0.001).op[3], 1);
+ // Before the first block's start the first is lit; after the read everything is back.
+ assert.equal(at(0).op[0], 1);
+ assert.equal(at(0).op[1], 0.65);
+ const after = at(f.readEnd + f.ease + 0.01);
+ assert.ok(Object.values(after.op).every((v) => v === 1));
+ // Seek-safe: the same second gives the same state, whichever came before.
+ assert.equal(followStateKey(at(s3 + 0.1)), followStateKey(at(s3 + 0.1)));
+ // One block read: nothing dims.
+ const one = postItemPlan(base({ text: "Just one short line." })).follow;
+ assert.deepEqual(followStateAt(one, null, 1).op, {});
+});
+
+test("the pan: short cards never move; a tall one keeps the block being read in view, starting before its read", () => {
+ const f = postItemPlan(narrated(base())).follow;
+ // Six blocks stacked 200 px apart in a flow of 1200 px.
+ const blocks = Object.fromEntries(f.blocks.map((b, i) => [b.k, { top: i * 200, bottom: i * 200 + 180 }]));
+ assert.deepEqual(followPath(f, { H: 1300, C: 1200, blocks }).segments, []);
+ const geo = { H: 500, C: 1200, blocks };
+ const path = followPath(f, geo);
+ assert.equal(path.max, 700);
+ assert.ok(path.segments.length >= 2);
+ const m = Math.round(500 * FOLLOW_PAN.margin);
+ for (const b of f.blocks) {
+ // Once its read is under way (past the pan), the block is inside the window.
+ const s = Math.min(b.end - 0.01, b.start + FOLLOW_PAN.seconds);
+ const off = followOffsetAt(path, s);
+ const { top, bottom } = blocks[b.k];
+ assert.ok(top >= off - 0.5 && bottom <= off + 500 + 0.5, `block ${b.k} in view at ${s}: ${top}-${bottom} in ${off}-${off + 500}`);
+ }
+ // A pan starts before the block it brings into view is read.
+ const first = path.segments[0];
+ const target = f.blocks.find((b) => blocks[b.k].bottom > 500 - m / 2);
+ assert.ok(first.t0 < target.start && first.t0 >= target.start - FOLLOW_PAN.lead - 0.001);
+ // Never past the end of the words.
+ assert.ok(path.segments.every((g) => g.to <= 700 && g.to >= 0));
+ // The fading edges: more below at the start, more above at the end.
+ const s0 = followStateAt(f, path, 0);
+ assert.equal(s0.fadeTop, 0);
+ assert.equal(s0.fadeBottom, 1);
+ const end = followStateAt(f, path, f.readEnd + 1);
+ assert.equal(end.offset, 700);
+ assert.equal(end.fadeBottom, 0);
+ assert.equal(end.fadeTop, 1);
+});
+
+test("the pan: a block taller than the window pans on through it while it is read", () => {
+ const f = postItemPlan(narrated(base())).follow;
+ const blocks = Object.fromEntries(f.blocks.map((b, i) => [b.k, i === 2 ? { top: 100, bottom: 1300 } : i < 2 ? { top: i * 50, bottom: i * 50 + 40 } : { top: 1300 + (i - 2) * 50, bottom: 1340 + (i - 2) * 50 }]));
+ const path = followPath(f, { H: 400, C: 1550, blocks });
+ const b = f.blocks[2];
+ const inside = path.segments.filter((g) => g.t0 >= b.start - FOLLOW_PAN.lead - 0.001 && g.t1 <= b.end + 0.001);
+ assert.ok(inside.length >= 3, `${inside.length} pans through the tall block`);
+ assert.ok(followOffsetAt(path, b.end - 0.01) >= 1300 - 400);
+});
+
+test("the card page: the blocks wrapped on the card, the post's words in a flow that pans, never shrunk below the readable size", () => {
+ const e = narrated(base({ text: `${TEXT}\n\n${LONG_PARA}\n\n${LONG_PARA}` }));
+ const html = postCardHtml(e, { width: 1600, height: 900, follow: true });
+ assert.match(html, /data-post-flow=""/);
+ assert.match(html, /data-post-fade="bottom"/);
+ assert.match(html, /<span class="fblock" data-post-block="0"><span data-w="post:0">Normally<\/span>/);
+ assert.match(html, /data-post-follow="\d+"/);
+ // The fit script's floor: FOLLOW_MIN_SIZE (28) at 900/1080, not the old 18.
+ assert.match(html, /var min = 23;/);
+ const off = postCardHtml(e, { width: 1600, height: 900 });
+ assert.doesNotMatch(off, /data-post-block|data-post-flow/);
+ assert.match(off, /var min = 15;/);
+});
+
+test("the encode: the follow frames are a concat list laid over the card's region, before the attachments", () => {
+ const e = base({ text: "Hello there." });
+ const plan = postItemPlan(e);
+ const argv = postSegmentArgs({
+ entry: e, box: { width: 1600, height: 900 }, plan, layout: { mode: "text", card: { x: 0, y: 0, width: 100, height: 100 }, slot: null }, cards: { read: "/c/read.png" },
+ files: [], render: { fps: 30 }, outPath: "/o.mp4", follow: { list: "/c/follow/frames.ffconcat", clip: { x: 210, y: 40, width: 1180, height: 820 } },
+ });
+ const fc = argv[argv.indexOf("-filter_complex") + 1];
+ assert.ok(argv.join(" ").includes("-f concat -safe 0 -i /c/follow/frames.ffconcat"));
+ assert.match(fc, /\[1:v\]fps=30,setsar=1,setpts=PTS-STARTPTS\[rf\];\[b0\]\[rf\]overlay=x=210:y=40:eof_action=repeat\[b1\]/);
+});