commit 261f017798da793268934f7b70875253037d4873
parent 36b1b1c040a8010f7911c102b5bc15c5f8f77639
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 13:57:15 -0500
umtool: a WORD ZOOM on a post item -- the card pushed in on a word as it is read, a highlight under it, then back out (operator: "zoom in on the "barbecue" typo when it's being read out and make that effect a standard thing")
`fx: [{kind: "word-zoom", match, target?, occurrence?, at?, lead?, hold?, scale?, ease?, highlight?}]`
on a post item (word-zoom.mjs), validated with the post: unknown keys refused, the
match must be in the target's words ("… is not in the post's words"). Its time is
`at`, else the matched word's start in the picked take's word timings (lead +
start / rate). `umtool posts narrate <p> <item> --words` asks the editor's
transcribe op (words: true) on the take (or each of its parts, at their starts)
and aligns what was heard to the script, fuzzy and in order (a typo read as the
word it means still pairs). The card wraps each word in a data-w span; the build
measures the word's box at 2-4x, and zoompan pushes the card's region in toward
it on the eased curve, frame by frame, the highlight fading in under it --
over the card only, before the attachments. `umtool posts fx <p> <item> ls |
add word-zoom … | set <n> … | remove <n>` through updatePostFx.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 1132 insertions(+), 30 deletions(-)
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -2519,7 +2519,7 @@ export function postNarrationIn(m, id, patch) {
const e = m.timeline[i];
if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
for (const k of Object.keys(patch)) {
- if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake"].join(", ")})`);
+ if (!POST_NARRATION_KNOBS.includes(k) && !["addTake", "dropTake", "keepPick", "takeWords"].includes(k)) throw new Error(`${k} is not a narration knob (${[...POST_NARRATION_KNOBS, "addTake", "dropTake", "takeWords"].join(", ")})`);
}
const before = isObj(e.narration) ? JSON.parse(JSON.stringify(e.narration)) : null;
const n = isObj(e.narration) ? e.narration : { takes: [] };
@@ -2534,6 +2534,14 @@ export function postNarrationIn(m, id, patch) {
n.takes.push(patch.addTake);
if (patch.keepPick !== true) n.pick = n.takes.length - 1;
}
+ // A take's word timings (posts narrate --words; word-zoom.mjs): `{ take: <index>, words: [{w, start, end}] | null }`.
+ if (patch.takeWords !== undefined && patch.takeWords !== null) {
+ const tw = patch.takeWords;
+ const t = isObj(tw) && Number.isInteger(tw.take) ? n.takes[tw.take] : null;
+ if (!t) throw new Error(`${id} has no take ${isObj(tw) ? tw.take : "?"} to time`);
+ if (tw.words === null) delete t.words;
+ else t.words = tw.words;
+ }
if (patch.dropTake !== undefined && patch.dropTake !== null) {
const d = Number(patch.dropTake);
if (!Number.isInteger(d) || !n.takes[d]) throw new Error(`${id} has no take ${patch.dropTake}`);
@@ -2555,6 +2563,66 @@ export function postNarrationIn(m, id, patch) {
}
/**
+ * A POST ITEM's EFFECTS (`fx`, word-zoom.mjs), in memory: `op` is `{ add: fx }`
+ * (appended), `{ set: <i>, patch }` (keys set; null clears one), `{ remove: <i> }`,
+ * or `{ list: [...] }` (all of them; [] none). Refused in the build's words.
+ *
+ * @param {Record<string, any>} m
+ * @param {string} id
+ * @param {Record<string, any>} op
+ */
+export function postFxIn(m, id, op) {
+ 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 (!isObj(op)) throw new Error("an effects change is { add } | { set, patch } | { remove } | { list }");
+ const list = Array.isArray(e.fx) ? e.fx.map((x) => ({ ...x })) : [];
+ const at = (k) => {
+ const n = Number(k);
+ if (!Number.isInteger(n) || !list[n]) throw new Error(list.length ? `${id} has no effect ${k} (0–${list.length - 1})` : `${id} has no effects`);
+ return n;
+ };
+ const tidy = (fx) => {
+ const out = {};
+ for (const [k, v] of Object.entries(fx)) if (v !== null && v !== undefined) out[k] = typeof v === "number" && k !== "occurrence" ? round2(v) : v;
+ return out;
+ };
+ let index = null;
+ if (op.add !== undefined) {
+ if (!isObj(op.add)) throw new Error("add is an effect ({ kind: \"word-zoom\", match, … })");
+ list.push(tidy({ kind: "word-zoom", ...op.add }));
+ index = list.length - 1;
+ } else if (op.set !== undefined) {
+ index = at(op.set);
+ if (!isObj(op.patch)) throw new Error("set takes a patch of the effect's keys");
+ list[index] = tidy({ ...list[index], ...op.patch });
+ } else if (op.remove !== undefined) {
+ list.splice(at(op.remove), 1);
+ } else if (op.list !== undefined) {
+ if (!Array.isArray(op.list)) throw new Error("list is the whole list of effects");
+ list.splice(0, list.length, ...op.list.map((x) => (isObj(x) ? tidy(x) : x)));
+ } else throw new Error("an effects change is { add } | { set, patch } | { remove } | { list }");
+ if (list.length) e.fx = list;
+ else delete e.fx;
+ const errors = validatePostItem(e);
+ if (errors.length) throw new StructureRefused(errors);
+ return { id, at: i, entry: e, fx: e.fx ?? [], index };
+}
+
+/**
+ * CHANGE A POST ITEM's EFFECTS (`umtool posts fx`, the post bench's Zoom here):
+ * one structural write (one undo point). See postFxIn.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {Record<string, any>} op
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostFx(dir, id, op, { token = null } = {}) {
+ return structural(dir, "post-fx", token, (m) => postFxIn(m, id, op));
+}
+
+/**
* SET A POST ITEM's NARRATION (`umtool posts narrate`, the post bench): one
* structural write (one undo point) -- the script, a take added or dropped,
* the pick, the approval, off, and the mix's knobs for this post.
diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs
@@ -0,0 +1,90 @@
+// A post item's word zooms through the writer and the CLI (postFxCli.mjs,
+// manifest.mjs updatePostFx), and a take's word timings (`posts narrate --words`:
+// the editor's transcription, stood in for here, aligned to the script).
+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 { takeWords, takeWordSources } from "./postFxCli.mjs";
+import { updatePostFx } from "./manifest.mjs";
+import { wordZoomTimes } from "umtool-report-to-video/word-zoom";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-fx-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+const TEXT = "stop me and save me from myself, barbecue if no one does, I'm going after him.";
+const item = (id, o = {}) => ({
+ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-11-03T10:00:00.000Z", text: TEXT, ...o,
+});
+async function project(name, timeline) {
+ const dir = path.join(REPORTS, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const cli = async (args) => {
+ const lines = [];
+ const errs = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) });
+ return { code, out: lines.join("\n"), err: errs.join("\n") };
+};
+
+test("posts fx: add (an un-narrated post gets the reading estimate), set, ls, remove -- refused in the build's words", async () => {
+ const p = await project("fx", [item("1")]);
+ let r = await cli(["fx", "fx", "p-1", "add", "word-zoom", "--match", "barbecue", "--scale", "2.5", "--hold", "1.5", "--ease", "snap", "--highlight", "off"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /not narrated: at 3.33 s, the reading estimate/);
+ assert.match(r.out, /#1 word-zoom "barbecue" \(post, 1st\) at 3.33 s \(set by hand\) · 2.5× in 0.5 s, held 1.5 s, snap, highlight off/);
+ let fx = (await manifest(p)).timeline[0].fx;
+ assert.deepEqual(fx, [{ kind: "word-zoom", match: "barbecue", scale: 2.5, hold: 1.5, ease: "snap", highlight: false, at: 3.33 }]);
+ r = await cli(["fx", "fx", "p-1", "set", "1", "--at", "2.9", "--highlight", "default"]);
+ assert.equal(r.code, 0, r.err);
+ fx = (await manifest(p)).timeline[0].fx;
+ assert.equal(fx[0].at, 2.9);
+ assert.equal(fx[0].highlight, undefined);
+ // Not in the words: refused, nothing written.
+ r = await cli(["fx", "fx", "p-1", "add", "word-zoom", "--match", "because", "--at", "1"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /fx\[1\]\.match "because" is not in the post's words/);
+ assert.equal((await manifest(p)).timeline[0].fx.length, 1);
+ r = await cli(["fx", "fx", "p-1", "ls", "--json"]);
+ assert.equal(JSON.parse(r.out).times[0].t, 2.9);
+ r = await cli(["fx", "fx", "p-1", "remove", "1"]);
+ assert.equal(r.code, 0, r.err);
+ assert.equal((await manifest(p)).timeline[0].fx, undefined);
+ assert.match(r.out, /no word zooms/);
+ await assert.rejects(updatePostFx(p.dir, "p-1", { remove: 0 }), /has no effects/);
+});
+
+test("posts narrate --words: the take transcribed by the editor (its parts, at their starts), aligned to the script, kept on the take", async () => {
+ const take = { file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: TEXT };
+ const p = await project("words", [item("1", { narration: { script: TEXT, takes: [take], lead: 0.5, rate: 1.25 }, fx: [{ kind: "word-zoom", match: "barbecue" }] })]);
+ // Before: no time.
+ assert.match(wordZoomTimes((await manifest(p)).timeline[0])[0].error, /no word timings yet/);
+ const asked = [];
+ // The editor stood in for: it "hears" the script with the typo read as the word it means.
+ const ask = async (route, body) => {
+ asked.push({ route, body });
+ const heard = TEXT.replace("barbecue", "barbeque").split(" ").map((w, i) => ({ w, start: i * 0.4, end: i * 0.4 + 0.3, conf: 0.9 }));
+ await mkdir(path.dirname(body.out), { recursive: true });
+ await writeFile(body.out, JSON.stringify({ path: body.path, cues: [], text: "", words: heard }));
+ return { jobId: "job-1", result: null };
+ };
+ const project1 = { id: "words", dir: p.dir };
+ const r = await takeWords(project1, (await manifest(p)).timeline[0], { ask, worker: "parakeet-cpu" });
+ assert.deepEqual(asked.map((a) => [a.route, a.body.words, a.body.workerId, path.relative(p.dir, a.body.out)]), [["/api/ops/transcribe", true, "parakeet-cpu", "narration/posts/1/take-1.orpheus-zac.words.json"]]);
+ assert.equal(r.heard, r.of);
+ const e = (await manifest(p)).timeline[0];
+ assert.deepEqual(e.narration.takes[0].words[7], { w: "barbecue", start: 2.8, end: 3.1 });
+ // Its time: lead 0.5 + 2.8 ÷ 1.25.
+ assert.equal(wordZoomTimes(e)[0].t, 2.74);
+ // A take read part by part: each part transcribed on its own file, at its start.
+ const parted = { ...take, parts: [{ n: 1, file: "narration/posts/1/take-1.parts/p01.wav", start: 0, seconds: 2 }, { n: 2, file: "narration/posts/1/take-1.parts/p02.wav", start: 2.6, seconds: 3 }] };
+ assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: take.file, offset: 0 }]); // the parts' files are not there: the take's
+ await mkdir(path.join(p.dir, "narration/posts/1/take-1.parts"), { recursive: true });
+ for (const f of ["p01", "p02"]) await writeFile(path.join(p.dir, `narration/posts/1/take-1.parts/${f}.wav`), "");
+ assert.deepEqual(await takeWordSources(p.dir, parted), [{ file: parted.parts[0].file, offset: 0 }, { file: parted.parts[1].file, offset: 2.6 }]);
+});
diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs
@@ -0,0 +1,195 @@
+// `umtool posts fx` and `umtool posts narrate <p> <item> --words`
+// (report-to-video/word-zoom.mjs; umtool/docs/report-video.md, "A word zoom"):
+// a post item's WORD ZOOMS -- the card pushed in on a word as it is read -- through
+// the writer (updatePostFx), and the word timings of its take, asked of the
+// EDITOR's transcription (never ASR here) and aligned to the script it read
+// (updatePostNarration's takeWords).
+//
+// umtool posts fx <p> <item> [ls]
+// umtool posts fx <p> <item> 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]
+// umtool posts fx <p> <item> set <n> [the same flags; a flag's value `default` clears it]
+// umtool posts fx <p> <item> remove <n>
+// umtool posts narrate <p> <item> --words [--worker <id>]
+//
+// Plain ESM: the CLI runs under bare node.
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration";
+import {
+ WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, findMatch, readingEstimate, resolveWordZoom, scriptWordTimes, targetTextOf, wordZoomTimes,
+} from "umtool-report-to-video/word-zoom";
+import { readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updatePostFx, updatePostNarration } from "./manifest.mjs";
+import { findPostItem } from "./postNarrationCli.mjs";
+
+export const FX_USAGE = [
+ "usage: umtool posts fx <project> <item> [ls] [--json]",
+ " umtool posts fx <project> <item> 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] [--json]",
+ " umtool posts fx <project> <item> set <n> [those flags; `default` clears one] | remove <n>",
+ " A WORD ZOOM: the card pushed in on a word (or a phrase) as it is read, a highlight under it, then back out.",
+ " --match is the word as the card shows it (case and edge punctuation aside); --occurrence its n-th time in the",
+ " text (default 1); --target whose words: the post's own (default), the post it quotes, the posts it answers.",
+ " WHEN: --at (item seconds) when set; else the word's start in the picked take's word timings (lead + start ÷ the",
+ " read's rate) -- `umtool posts narrate <p> <item> --words` gets them from the editor's transcription. An",
+ " un-narrated post needs --at (add fills the reading estimate: 1 s + 3 words a second).",
+ ` --scale 1.2–4 (default ${WORD_ZOOM_DEFAULTS.scale}), --lead 0–3 s in before the word (${WORD_ZOOM_DEFAULTS.lead}), --hold 0–10 s on it (${WORD_ZOOM_DEFAULTS.hold}),`,
+ ` --ease ${WORD_ZOOM_EASES.join("|")} (${WORD_ZOOM_DEFAULTS.ease}), --highlight a colour or off (${WORD_ZOOM_DEFAULTS.highlight}). <n>: the zoom's number as ls shows it.`,
+].join("\n");
+
+export class FxError extends Error {}
+
+const NUM_KEYS = { "--at": "at", "--scale": "scale", "--hold": "hold", "--lead": "lead", "--occurrence": "occurrence" };
+
+/** The flags as an effect patch (null: back to the default). */
+export function fxPatchOf(str) {
+ const out = {};
+ const m = str("--match");
+ if (m !== null) out.match = m;
+ const t = str("--target");
+ if (t !== null) out.target = t === "default" ? null : t;
+ for (const [flag, key] of Object.entries(NUM_KEYS)) {
+ const v = str(flag);
+ if (v === null) continue;
+ if (v === "default" || v === "off" && key === "at") out[key] = null;
+ else {
+ const x = Number(v);
+ if (!Number.isFinite(x)) throw new FxError(`${flag} takes a number`);
+ out[key] = x;
+ }
+ }
+ const e = str("--ease");
+ if (e !== null) out.ease = e === "default" ? null : e;
+ const h = str("--highlight");
+ if (h !== null) out.highlight = h === "default" ? null : ["off", "none", "false", "no"].includes(h.toLowerCase()) ? false : h;
+ return out;
+}
+
+const nth = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`;
+
+/** One item's zooms as lines. */
+export function fxLines(e, render) {
+ const list = Array.isArray(e.fx) ? e.fx : [];
+ if (!list.length) return [`${e.id}: no word zooms (add one: umtool posts fx <p> ${e.id} add word-zoom --match "…")`];
+ const times = wordZoomTimes(e, render);
+ return [
+ `${e.id}: ${list.length} word zoom(s)${isNarrated(e) ? "" : " (not narrated: each needs at)"}`,
+ ...list.map((fx0, i) => {
+ const fx = resolveWordZoom(fx0);
+ const t = times[i];
+ const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s ${t.source === "at" ? "(set by hand)" : `(from the take's words: "${t.word.w}" at ${t.word.start} s)`}`;
+ return ` #${i + 1} word-zoom "${fx.match}" (${fx.target}, ${nth(fx.occurrence)}) ${when} · ${fx.scale}× in ${fx.lead} s, held ${fx.hold} s, ${fx.ease}, highlight ${fx.highlight === false ? "off" : fx.highlight}`;
+ }),
+ ];
+}
+
+/** `umtool posts fx …` (postsCli.mjs routes it here). */
+export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str }) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new FxError(`${project.id} has no manifest`);
+ const render = manifest.render ?? {};
+ const [ref, verb = "ls", arg] = words;
+ const e = findPostItem(manifest, ref);
+ if (!e) throw new FxError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
+ const write = async (op) => withEditNotes(project, async () => updatePostFx(project.dir, e.id, op, { token: await manifestToken(project.dir) }));
+ const say = (entry, extra = {}) => {
+ if (json) out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render), ...extra }, null, 2));
+ else out(fxLines(entry, render).join("\n"));
+ };
+ const index = () => {
+ const n = Number(arg);
+ if (!Number.isInteger(n) || n < 1) throw new FxError(`${verb} takes the zoom's number as ls shows it (1 = the first)`);
+ return n - 1;
+ };
+ if (verb === "ls") {
+ say(e);
+ return 0;
+ }
+ if (verb === "add") {
+ if (arg !== "word-zoom") throw new FxError("add names the effect: add word-zoom --match \"…\"");
+ const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null));
+ if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add word-zoom needs --match \"<the word, as the card shows it>\"");
+ let note = null;
+ if (patch.at === undefined && !isNarrated(e)) {
+ const m = findMatch(targetTextOf(e, patch.target ?? "post") ?? "", patch.match, patch.occurrence ?? 1);
+ if (!m.error) {
+ patch.at = readingEstimate(m.from);
+ note = `not narrated: at ${patch.at} s, the reading estimate (nudge it: set <n> --at s)`;
+ }
+ }
+ const { result } = await write({ add: { kind: "word-zoom", ...patch } });
+ if (note && !json) out(note);
+ say(result.entry, { index: result.index });
+ return 0;
+ }
+ if (verb === "set") {
+ const i = index();
+ const patch = fxPatchOf(str);
+ if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --scale, --hold, --lead, --ease, --highlight, --occurrence, --target");
+ const { result } = await write({ set: i, patch });
+ say(result.entry);
+ return 0;
+ }
+ if (verb === "remove") {
+ const { result } = await write({ remove: index() });
+ say(result.entry);
+ return 0;
+ }
+ throw new FxError(`${verb}: ls, add, set or remove`);
+}
+
+/**
+ * Where a take is transcribed from: its PARTS (a long post read part by part),
+ * each on its own file and offset by its start in the take, when every part's
+ * file is there; else the take's own file. `[{ file, offset }]`, project-relative.
+ */
+export async function takeWordSources(projectDir, take) {
+ const parts = Array.isArray(take?.parts) ? take.parts : [];
+ if (parts.length && parts.every((p) => typeof p?.file === "string" && Number.isFinite(p.start))) {
+ const here = await Promise.all(parts.map((p) => stat(path.join(projectDir, ...p.file.split("/"))).then((s) => s.isFile(), () => false)));
+ if (here.every(Boolean)) return parts.map((p) => ({ file: p.file, offset: p.start }));
+ }
+ return [{ file: take.file, offset: 0 }];
+}
+
+/** The words file the editor writes beside a sound file. */
+export const wordsFileOf = (rel) => String(rel).replace(/\.[^./]+$/, "") + ".words.json";
+
+/** The recognized words of a transcribe result (`{ words: [{w, start, end}] }`), moved by `offset`. */
+export function recognizedOf(doc, offset = 0) {
+ const list = Array.isArray(doc?.words) ? doc.words : [];
+ return list
+ .filter((x) => x && typeof x.w === "string" && Number.isFinite(x.start) && Number.isFinite(x.end))
+ .map((x) => ({ w: x.w, start: Math.round((x.start + offset) * 1000) / 1000, end: Math.round((x.end + offset) * 1000) / 1000 }));
+}
+
+/**
+ * THE TAKE's WORD TIMINGS: the picked take (or its parts) transcribed by the
+ * editor's transcribe op (`words: true`, a job; parakeet keeps word times), the
+ * words heard aligned to the script it read (scriptWordTimes), stored on the
+ * take (`takes[i].words`) by one write. `ask` (tests) stands in for askEditorOp.
+ */
+export async function takeWords(project, e, { worker = null, emit = () => {}, ask = null } = {}) {
+ const t = pickedTake(e);
+ if (!t) throw new FxError(`${e.id} has no take to time (umtool posts narrate <p> ${e.id} --take, or record one on the bench)`);
+ const script = typeof t.script === "string" && t.script.trim() ? t.script : String(e.narration?.script ?? "");
+ if (!script.trim()) throw new FxError(`${e.id}'s take has no script to align its words to`);
+ const askOp = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorOp;
+ const heard = [];
+ const sources = await takeWordSources(project.dir, t);
+ for (const src of sources) {
+ const abs = path.join(project.dir, ...src.file.split("/"));
+ const outFile = path.join(project.dir, ...wordsFileOf(src.file).split("/"));
+ emit("note", { message: `${e.id}: transcribing ${src.file} on the editor…` });
+ await askOp("/api/ops/transcribe", { path: abs, words: true, out: outFile, ...(worker ? { workerId: worker } : {}) }, { emit });
+ const doc = JSON.parse(await readFile(outFile, "utf8"));
+ heard.push(...recognizedOf(doc, src.offset));
+ }
+ if (!heard.length) throw new FxError(`the editor's transcription of ${t.file} came back with no word timings (a parakeet worker keeps them; name one with --worker)`);
+ const r = scriptWordTimes(script, heard);
+ const { result } = await withEditNotes(project, async () =>
+ updatePostNarration(project.dir, e.id, { takeWords: { take: t.index, words: r.words } }, { token: await manifestToken(project.dir) }));
+ return { take: t, heard: r.heard, of: r.of, recognized: heard.length, sources: sources.length, result };
+}
diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs
@@ -15,6 +15,7 @@
// umtool posts narrate <p> --all --draft-scripts [--force] scripts from the posts' words (verbatim)
// umtool posts narrate <p> --all --take [--limit N] every missing take, one at a time (resumable)
// umtool posts narrate <p> --cut k=v … the cut's mix (render.postNarration)
+// umtool posts narrate <p> <item> --words [--worker <id>] its take's word timings (the editor's transcription, aligned; postFxCli.mjs)
//
// Plain ESM: the CLI runs under bare node.
import { execFile } from "node:child_process";
@@ -55,6 +56,9 @@ export const NARRATE_USAGE = [
" once `umtool posts fit` has scanned it (else from its in point). clip=full plays the attachments whole.",
" rate=0.8–1.5 (default 1): the READ sped up (its pitch kept), the attachment untouched; the post's length, its",
" muffle and its parts follow the faster read (a 10 s take at rate=1.25 reads in 8 s).",
+ " --words [--worker <id>]: the picked take's WORD TIMINGS -- the editor's transcribe op (a job; parakeet keeps word times)",
+ " on the take (or each of its parts), the words heard aligned to its script, kept on the take: a word zoom's time",
+ " (umtool posts fx) is its word's start there.",
].join("\n");
export class NarrateError extends Error {}
@@ -390,6 +394,16 @@ export async function narrateCommand(project, words, flags, { json = false, dryR
throw err;
}
}
+ if (flags.has("--words")) {
+ const { takeWords, fxLines } = await import("./postFxCli.mjs");
+ const r = await takeWords(project, e, { worker: str("--worker"), emit: (_ev, f) => !json && f?.message && out(f.message) });
+ if (json) out(JSON.stringify({ ok: true, id: e.id, take: r.take.file, heard: r.heard, of: r.of, recognized: r.recognized, words: r.result.entry.narration.takes[r.take.index].words, token: r.result.token }, null, 2));
+ else {
+ out(`${e.id}: take ${r.take.file} timed: ${r.heard} of its script's ${r.of} words heard (${r.recognized} recognized${r.sources > 1 ? `, over ${r.sources} parts` : ""}); the rest placed between them`);
+ if (Array.isArray(r.result.entry.fx) && r.result.entry.fx.length) out(fxLines(r.result.entry, render).join("\n"));
+ }
+ return 0;
+ }
if (flags.has("--take")) {
const speedRaw = str("--speed");
const r = await makeTake(project, e, {
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -68,6 +68,8 @@ export const POSTS_USAGE = [
" umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix",
" (umtool posts narrate --help)",
" umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
+ " umtool posts fx <project> <item> [ls] | add word-zoom --match \"…\" [--at s] [--scale s] … | set <n> … | remove <n>",
+ " a WORD ZOOM: the card pushed in on a word as it is read (umtool posts fx --help)",
" umtool posts avatar <project> [<handle> <image-file> | <handle> off] [--json]",
" an author's PICTURE on every card that draws them (postAvatars): the file copied into posts-media/_avatars/,",
" never replaced by the archive's; `off` clears it; no handle lists them. A blurred author never shows one.",
@@ -80,7 +82,7 @@ export const POSTS_USAGE = [
" none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.",
].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"]);
+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"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -361,6 +363,14 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
}
return await narrateCommand(await projectOf(projectArg, root), words.slice(2), flags, { json, dryRun, out, str });
}
+ if (verb === "fx") {
+ const { FX_USAGE, fxCommand } = await import("./postFxCli.mjs");
+ if (!projectArg || !ref || flags.has("--help")) {
+ err(FX_USAGE);
+ return 2;
+ }
+ return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str });
+ }
if (verb === "fit") {
const { FIT_USAGE, fitCommand } = await import("./postNarrationCli.mjs");
if (!projectArg || flags.has("--help") || (!flags.has("--all") && words.length < 3)) {
@@ -447,7 +457,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
return 1;
}
err(`umtool posts: ${e instanceof Error ? e.message : String(e)}`);
- return e instanceof CliError || e?.constructor?.name === "NarrateError" ? 2 : 1;
+ return e instanceof CliError || e?.constructor?.name === "NarrateError" || e?.constructor?.name === "FxError" ? 2 : 1;
}
}
diff --git a/umtool/report-to-video/fx.mjs b/umtool/report-to-video/fx.mjs
@@ -298,6 +298,8 @@ export function validateFxEntries(manifest, { schedule = undefined } = {}) {
const render = manifest?.render ?? {};
for (const e of timeline) {
if (e?.fx === undefined) continue;
+ // A post item's `fx` is its own list of effects (a word zoom), post-item.mjs's to judge (word-zoom.mjs).
+ if (e.type === "post") continue;
const w = `timeline entry ${e.id ?? "?"}: fx`;
if (!isObj(e.fx)) { errors.push(`${w} must be an object`); continue; }
if (e.type !== "clip" && e.type !== "image") errors.push(`${w} is for a clip or an image`);
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -64,6 +64,7 @@
"./post-item": "./post-item.mjs",
"./post-narration": "./post-narration.mjs",
"./post-render": "./post-render.mjs",
+ "./word-zoom": "./word-zoom.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.mjs",
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -10,7 +10,10 @@
// replyingTo?: "<handle>", parentShot?: "<file>",
// media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?,
// start?, end?, mute?, crop?: [x, y, w, h], push?, words? }],
-// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen? }
+// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen?,
+// fx?: [{ kind: "word-zoom", match, target?, occurrence?, at?, lead?, hold?, scale?, ease?, highlight? }] }
+//
+// (`fx`: the card pushed in on a word as it is read -- word-zoom.mjs.)
//
// where a <ref> (a post it quotes, the posts it answers, nearest first) is
// `{ id?, author?, handle?, badge?, date?, text?, url?, paraphrase? }` --
@@ -28,6 +31,7 @@
import {
isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration,
} from "./post-narration.mjs";
+import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, validatePostFx } from "./word-zoom.mjs";
/** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */
export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]);
@@ -458,6 +462,8 @@ export function validatePostItem(e) {
}
// Its narration (post-narration.mjs): the script, the takes, the mix's knobs.
errors.push(...validatePostNarration(e));
+ // Its effects (word-zoom.mjs): a word zoomed on as it is read.
+ errors.push(...validatePostFx(e));
return errors;
}
@@ -676,13 +682,27 @@ export const hueOf = (s) => {
return h;
};
-/** The words with @mentions of the blurred authors blurred (their handle never in the page). */
-export function wordsHtml(text, blurred) {
+/**
+ * The words with @mentions of the blurred authors blurred (their handle never
+ * in the page). With `scope`, each word (cardTokens' runs of non-space) is a
+ * span `data-w="<scope>:<i>"` -- the build measures a word zoom's word by it,
+ * 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) {
const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase()));
- return esc(text)
- .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>`)
- .replace(/\n/g, "<br>");
+ 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>");
+ 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>`;
+ })
+ .join("");
}
/**
@@ -728,12 +748,17 @@ export function nameHtml(who, { redact, cls = "" }) {
* post it answers is not archived. `avatars`: `{ <handle>: url }`, the
* authors' pictures (the project's `postAvatars`, post-avatars.mjs); an
* author with none is drawn as the initial, a redacted one never shows one.
+ * 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).
*
* @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> }} o
+ * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean, avatars?: Record<string, string>,
+ * highlight?: { scope: string, from: number, to: number, color: string } | null }} o
*/
-export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {} }) {
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false, avatars = {}, highlight = null }) {
+ const hlOf = (scope) => (highlight && highlight.scope === scope ? highlight : null);
const pic = (who) => avatarUrlOf(avatars, who?.handle);
const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette };
const L = postLayout(entry, { width, height });
@@ -762,7 +787,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)}</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}`))}</div></div></div>`,
);
}
if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`);
@@ -771,14 +796,14 @@ 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)}</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"))}</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)}</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">${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>`
: "";
@@ -827,7 +852,8 @@ 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; }
+.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; }${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; }` : ""}
</style></head>
<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${body}
<script>
diff --git a/umtool/report-to-video/post-item.test.mjs b/umtool/report-to-video/post-item.test.mjs
@@ -103,10 +103,12 @@ test("the privacy rule: another author is blurred unless the subject, gold/grey
const e = base({ text: "@KacamnGamesYT you are wrong", parents: [{ handle: "KacamnGamesYT", author: "Kacamn", text: "a question" }] });
assert.deepEqual(cardAuthors(e).map((a) => [a.where, a.redact]), [["parents[0]", true]]);
const html = postCardHtml(e, { width: 1440, height: 810 });
+ // The words as read (each word is its own span on the card: word-zoom.mjs).
+ const text = html.replace(/<[^>]+>/g, "");
// The parent's name and handle are never in the page, and the mention of them is blurred.
assert.ok(!html.includes("KacamnGamesYT"));
assert.ok(!html.includes("Kacamn"));
- assert.ok(html.includes("a question"));
+ assert.ok(text.includes("a question"));
assert.ok(html.includes('data-redacted=""'));
// A self-thread (his own parent) is drawn plainly.
const self = postCardHtml(base({ parents: [{ handle: "ObviousRises", author: "MR. OBVIOUS", text: "first" }] }), { width: 1440, height: 810 });
@@ -165,19 +167,21 @@ test("a context post's PARAPHRASE: validated, drawn in place of its words with a
assert.ok(readingSeconds(base({ quoted: short })) < readingSeconds(base({ quoted })));
// The card: the paraphrase and the label, never the original words.
const html = postCardHtml(base({ quoted: short, parents: [{ ...parent, paraphrase: "A parent asked a question." }] }), { width: 1920, height: 1080 });
- assert.ok(html.includes("He reviewed three videos."));
- assert.ok(html.includes("A parent asked a question."));
- assert.ok(!html.includes("spent all morning"), "the quoted post's original words are not on the card");
- assert.ok(!html.includes("the original parent words"), "the parent's original words are not on the card");
+ // The words as read (each word is its own span on the card: word-zoom.mjs).
+ const text = html.replace(/<[^>]+>/g, "");
+ assert.ok(text.includes("He reviewed three videos."));
+ assert.ok(text.includes("A parent asked a question."));
+ assert.ok(!text.includes("spent all morning"), "the quoted post's original words are not on the card");
+ assert.ok(!text.includes("the original parent words"), "the parent's original words are not on the card");
assert.equal(html.match(/data-post-paraphrased=""[^>]*>paraphrased</g)?.length, 2);
assert.equal(html.match(/data-post-paraphrase=""/g)?.length, 2);
// Unparaphrased: the original, and no label.
const plain = postCardHtml(base({ quoted }), { width: 1920, height: 1080 });
- assert.ok(plain.includes("spent all morning"));
+ assert.ok(plain.replace(/<[^>]+>/g, "").includes("spent all morning"));
assert.ok(!plain.includes("data-post-paraphrased"));
// The author stays under the blur rule: a private quoted author is blurred over a paraphrase too.
const priv = postCardHtml(base({ quoted: { ...short, badge: "blue", handle: "private_person" } }), { width: 1920, height: 1080 });
assert.ok(priv.includes('data-post-quoted="" data-redacted=""'));
assert.ok(!priv.includes("private_person"));
- assert.ok(priv.includes("He reviewed three videos."));
+ assert.ok(priv.replace(/<[^>]+>/g, "").includes("He reviewed three videos."));
});
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -10,7 +10,8 @@
// excerpt?: true, // drafted as an excerpt of a longer post
// engine?, voice?, speed?, // the next take's (default: render.postNarration's)
// takes: [{ file: "narration/posts/<postId>/take-<n>.<engine>-<voice>.wav",
-// engine, voice, seconds, script, at, note?, speed?, lufs?, jobId? }],
+// engine, voice, seconds, script, at, note?, speed?, lufs?, jobId?,
+// words?: [{ w, start, end }] }], // its script's words, timed (posts narrate --words; word-zoom.mjs)
// pick?: <index into takes>, // absent: the first
// approved?: true, // the picked take on this script, approved
// off?: true, // kept, but the item plays un-narrated
@@ -162,7 +163,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz",
// `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"]);
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"]);
+const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words"]);
const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]);
const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId"]);
const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/;
@@ -524,6 +525,13 @@ export function validatePostNarration(e) {
);
if (!ok) errors.push(`${tw}.source must be {kind: "tts", engine, voice}, {kind: "recorded", voice} or {kind: "take", from: <one of its takes' id>}`);
}
+ if (t.words !== undefined) {
+ // Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes).
+ const ws = t.words;
+ const bad = !Array.isArray(ws) || ws.length > 20000 ? -2 : ws.findIndex((x) => !isObj(x) || typeof x.w !== "string" || !fin(x.start) || !fin(x.end) || x.start < 0 || x.end < x.start || Object.keys(x).some((kk) => kk !== "w" && kk !== "start" && kk !== "end"));
+ if (bad === -2) errors.push(`${tw}.words must be a list of { w, start, end } (its words, timed; at most 20000)`);
+ else if (bad >= 0) errors.push(`${tw}.words[${bad}] must be { w, start, end } (take seconds, end ≥ start)`);
+ }
if (t.steps !== undefined) {
if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`);
else t.steps.forEach((st, k) => {
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -20,6 +20,7 @@ import path from "node:path";
import { pathToFileURL } from "node:url";
import { POST_PICTURE_XFADE, POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs";
import { isNarrated, narrationLevelDb, pickedTake, postNarrationFilters } from "./post-narration.mjs";
+import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs";
const r3 = (v) => Math.round(v * 1000) / 1000;
const num = (v) => String(r3(v));
@@ -62,7 +63,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 }) {
+export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [] }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -85,6 +86,30 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
parts.push(`[${mi}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[mc]`);
lay("mc", 0, 0, plan.steps[0].at, T);
}
+ // WORD ZOOMS (word-zoom.mjs): the card's region, shot at k× (crisp when pushed in), zoomed toward the word on
+ // the curve -- frame by frame, zoompan on the item's second -- its highlight fading in under the word; laid over
+ // the card's region only while it is up, before the attachments (which it never covers).
+ zooms.forEach((zm, zi) => {
+ const { span, region, target, k } = zm;
+ const D = Math.max(1 / fps, span.t3 - span.t0);
+ const pi = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", zm.plain]);
+ parts.push(`[${pi}:v]scale=${region.width * k}:${region.height * k},setsar=1,format=rgba[wzp${zi}]`);
+ let src = `wzp${zi}`;
+ if (zm.hl) {
+ const hi = add(["-loop", "1", "-framerate", String(fps), "-t", num(D), "-i", zm.hl]);
+ parts.push(
+ `[${hi}:v]scale=${region.width * k}:${region.height * k},setsar=1,format=rgba,fade=t=in:st=0:d=${num(Math.max(0.04, span.t1 - span.t0))}:alpha=1,` +
+ `fade=t=out:st=${num(span.t2 - span.t0)}:d=${num(Math.max(0.04, span.t3 - span.t2))}:alpha=1[wzh${zi}]`,
+ `[wzp${zi}][wzh${zi}]overlay=0:0:format=auto[wzc${zi}]`,
+ );
+ src = `wzc${zi}`;
+ }
+ const ex = zoompanExprs(span, target, k, `(${num(span.t0)}+on/${fps})`);
+ parts.push(`[${src}]zoompan=z='${ex.z}':x='${ex.x}':y='${ex.y}':d=1:s=${region.width}x${region.height}:fps=${fps},setsar=1,setpts=PTS-STARTPTS+${num(span.t0)}/TB[wz${zi}]`);
+ const next = `b${++n}`;
+ parts.push(`[${cur}][wz${zi}]overlay=x=${region.x}:y=${region.y}:eof_action=pass:enable='between(t,${num(span.t0)},${num(span.t3)})'[${next}]`);
+ cur = next;
+ });
const audio = [];
const picture = (st) => !!st && (st.kind === "image" || st.kind === "grid" || st.kind === "gif");
plan.steps.forEach((step, si) => {
@@ -186,7 +211,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 = {} }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [] }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -214,12 +239,109 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
out[phase] = png;
}
await ctx.close();
+ if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms });
} finally {
await browser.close();
}
return out;
}
+/** 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)))));
+
+/**
+ * Each WORD ZOOM's shots and geometry: the card's page at k× (zoomShotScale),
+ * its card's box inset by its corner (the REGION a zoom fills), the matched
+ * words' box (their spans' union, `data-w="<scope>:<i>"`) -- refused when a
+ * word is cut off the card (a clamped context post, a post shrunk to fit) --
+ * 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 }) {
+ 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 }), "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ };
+ const out = [];
+ try {
+ await load("zoom", null);
+ const radius = Math.round(18 * (box.height / 1080)) + 1;
+ for (const z of zooms) {
+ const geo = await page.evaluate(({ scope, from, to, radius: r }) => {
+ const rect = (el) => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ const card = document.querySelector("[data-post-card]");
+ if (!card) return { error: "the card is not drawn" };
+ const c = rect(card);
+ const spans = [];
+ for (let i = from; i <= to; i += 1) {
+ const el = document.querySelector(`[data-w="${scope}:${i}"]`);
+ if (!el) return { error: `word ${i} is not on the card` };
+ spans.push(el);
+ }
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const el of spans) {
+ const b = rect(el);
+ const clip = el.closest(".words, .ptext, .qtext");
+ const cb = clip ? clip.getBoundingClientRect() : card.getBoundingClientRect();
+ if (b.y + b.height > cb.bottom + 1 || b.y < cb.top - 1 || b.width === 0) return { error: "cut off the card (the text is longer than the card shows)" };
+ x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y); x1 = Math.max(x1, b.x + b.width); y1 = Math.max(y1, b.y + b.height);
+ }
+ const even = (v) => Math.max(2, Math.floor(v / 2) * 2);
+ const region = { x: Math.ceil(c.x + r), y: Math.ceil(c.y + r), width: even(c.width - 2 * r), height: even(c.height - 2 * r) };
+ return { region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } };
+ }, { scope: z.scope, from: z.from, to: z.to, radius });
+ if (geo.error) throw new Error(`${entry.id}: word zoom ${z.i + 1}: the word is ${geo.error}`);
+ out.push({ ...z, k, region: geo.region, word: geo.word });
+ }
+ 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 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 });
+ z.hl = path.join(dir, `zoom-hl-${z.i}.png`);
+ await page.screenshot({ path: z.hl, clip: clip(z.region) });
+ }
+ } finally {
+ await ctx.close();
+ }
+ return out;
+}
+
+/**
+ * A post item's word zooms, resolved for the build: `[{ i, scope, from, to,
+ * scale, highlight, span }]`, each on its time (wordZoomTimes) -- refused in
+ * the build's words when one has no time, or two are up at once.
+ */
+export function postZoomPlan(entry, render, total = Infinity) {
+ const fx = Array.isArray(entry?.fx) ? entry.fx : [];
+ if (!fx.length) return [];
+ const times = wordZoomTimes(entry, render);
+ const bad = times.filter((t) => t.error);
+ if (bad.length) throw new Error(bad.map((t) => t.error).join("; "));
+ const zooms = fx.map((f0, i) => {
+ const f = resolveWordZoom(f0);
+ const m = findMatch(targetTextOf(entry, f.target), f.match, f.occurrence);
+ return { i, scope: targetScope(f.target), from: m.from, to: m.to, scale: f.scale, highlight: f.highlight === false ? null : f.highlight, t: times[i].t, source: times[i].source, span: zoomSpan(f0, times[i].t) };
+ });
+ const late = zooms.find((z) => z.span.t0 >= total - 0.05);
+ if (late) throw new Error(`${entry.id}: word zoom ${late.i + 1} ("${resolveWordZoom(fx[late.i]).match}") starts at ${late.span.t0} s, after the post's ${total} s (move its at)`);
+ const clash = overlappingZooms(zooms.map((z) => z.span));
+ if (clash) throw new Error(`${entry.id}: word zooms ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`);
+ return zooms;
+}
+
/**
* Build post item `entry`'s segment. `ctx`: `{ render, outDir, manifestDir,
* box, place, encode, exec, ffmpeg, emit, avatars }` -- the box it fills (the
@@ -254,7 +376,9 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
return seg;
}
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
- const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars });
+ const zoomPlan = postZoomPlan(entry, render, plan.total);
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan });
+ 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 = [];
for (const [si, step] of plan.steps.entries()) {
@@ -274,7 +398,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 };
}
- const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration });
+ const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -282,12 +406,13 @@ 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, ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs } } : {}) }, null, 2) + "\n", "utf8");
+ 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 } } : {}) }, 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)` : ""})`,
});
+ 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/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs
@@ -0,0 +1,411 @@
+// A POST ITEM's WORD ZOOM (umtool/docs/report-video.md, "A word zoom"; operator,
+// 3 Nov: "zoom in on the "barbecue" typo when it's being read out and make that
+// effect a standard thing we can use and tune in the UI"): the card pushed in on
+// one word (or a phrase) of its text as it is read, a highlight under it, then
+// back out.
+//
+// entry.fx = [{ kind: "word-zoom",
+// target?: "post" | "parent:<i>" | "quoted", // whose words (default: the post's own)
+// match: "<the word or phrase, as the card shows it>",
+// occurrence?: n, // its n-th time in that text (default 1)
+// at?: <item seconds>, // when; absent: from the take's word timings
+// lead?: s, hold?: s, scale?: 1.2–4, // in over lead before it, held, x scale
+// ease?: "out" | "inOut" | "snap",
+// highlight?: "#rrggbb" | false }] // the marker under it (default WORD_ZOOM_DEFAULTS)
+//
+// WHEN: `at` when it is set (the operator's nudge wins), else the matched
+// word's start in the picked take (`takes[i].words`, the editor's transcription
+// aligned to the script: `umtool posts narrate <p> <item> --words`) on the
+// item's clock -- the read's lead + start ÷ the read's rate. An un-narrated
+// post has no read to time it by: its zoom needs `at`.
+//
+// THE CURVE (one function, the render's ffmpeg expressions and Play's CSS read
+// it): progress p 0 → 1 over [t - lead, t] on the ease, 1 for `hold`, back to 0
+// over WORD_ZOOM_OUT on the same ease. The zoom is z = 1 + (scale - 1)·p; the
+// window is the card's region at 1/z of its size, moving toward the word so the
+// word's box is centred (clamped inside the region) when z = scale.
+//
+// PURE and dependency-free but for the post's text rules: the validator, the
+// card's word tokens (the card HTML wraps each in a span the build measures),
+// the match, the alignment of recognized words to a script, the time, the curve.
+
+import { cardText, contextText, parentsOf } from "./post-item.mjs";
+import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs";
+
+export const POST_FX_KINDS = Object.freeze(["word-zoom"]);
+export const POST_FX_MAX = 8;
+export const WORD_ZOOM_EASES = Object.freeze(["out", "inOut", "snap"]);
+export const WORD_ZOOM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.5, hold: 1.2, scale: 2, ease: "inOut", highlight: "#ffd84d" });
+export const WORD_ZOOM_LIMITS = Object.freeze({ lead: [0, 3], hold: [0, 10], scale: [1.2, 4], at: [0, 600], occurrence: [1, 99] });
+/** The way back out, seconds, on the zoom's ease. */
+export const WORD_ZOOM_OUT = 0.4;
+/** The highlight's fill: the colour at this opacity, under the words (the card's text stays on top, readable). */
+export const WORD_ZOOM_HIGHLIGHT_ALPHA = 0.42;
+/** The longest match, in characters. */
+export const WORD_ZOOM_MATCH_MAX = 120;
+
+const KEYS = new Set(["kind", "target", "match", "occurrence", "at", "lead", "hold", "scale", "ease", "highlight"]);
+const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const str = (v) => (typeof v === "string" ? v : "");
+
+// ---------------------------------------------------------------------------
+// The card's words.
+// ---------------------------------------------------------------------------
+
+/** The text's tokens as the card draws them: `[{ tok, i }]` for each run of non-space (i from 0), `{ space }` between. */
+export function cardTokens(text) {
+ const out = [];
+ let i = 0;
+ for (const part of str(text).split(/(\s+)/)) {
+ if (!part) continue;
+ if (/^\s+$/.test(part)) out.push({ space: part });
+ else out.push({ tok: part, i: i++ });
+ }
+ return out;
+}
+
+/** The card's words of `text` (cardTokens' words, in order). */
+export const cardWordsOf = (text) => cardTokens(text).filter((t) => t.tok !== undefined).map((t) => t.tok);
+
+/** A word reduced for matching: lower case, its leading and trailing punctuation gone ("Barbecue," -> "barbecue"). */
+export const normWord = (w) => str(w).toLowerCase().normalize("NFKC").replace(/[‘’]/g, "'").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
+
+/** The text a target names on the card (the post's own words; a context post's: its paraphrase when it has one), or null. */
+export function targetTextOf(entry, target = "post") {
+ if (target === "post") return cardText(entry);
+ if (target === "quoted") return isObj(entry?.quoted) ? contextText(entry.quoted) : null;
+ const m = /^parent:(\d+)$/.exec(String(target));
+ if (m) {
+ const p = parentsOf(entry)[Number(m[1])];
+ return p ? contextText(p) : null;
+ }
+ return null;
+}
+
+/** The scope a target's word spans carry on the card (`data-w="<scope>:<i>"`). */
+export const targetScope = (target = "post") => String(target ?? "post");
+
+/**
+ * Where `match` is in `text`: its `occurrence`-th run of words (1-based), as
+ * `{ from, to, count }` card-word indices (inclusive), or `{ error, count }`
+ * (from and to -1).
+ * @param {string|null|undefined} text
+ * @param {string} match
+ * @param {number} [occurrence]
+ * @returns {{ from: number, to: number, count: number, error?: string }}
+ */
+export function findMatch(text, match, occurrence = 1) {
+ const want = str(match).split(/\s+/).map(normWord).filter(Boolean);
+ if (!want.length) return { error: "match names no word", count: 0, from: -1, to: -1 };
+ const words = cardWordsOf(text).map(normWord);
+ const hits = [];
+ for (let i = 0; i + want.length <= words.length; i += 1) {
+ if (want.every((w, k) => words[i + k] === w)) hits.push(i);
+ }
+ const n = Number.isInteger(occurrence) ? occurrence : 1;
+ if (!hits.length) return { error: "not in", count: 0, from: -1, to: -1 };
+ if (n > hits.length) return { error: "occurrence", count: hits.length, from: -1, to: -1 };
+ return { from: hits[n - 1], to: hits[n - 1] + want.length - 1, count: hits.length };
+}
+
+const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`);
+
+// ---------------------------------------------------------------------------
+// The validator.
+// ---------------------------------------------------------------------------
+
+/**
+ * One zoom with every default filled in.
+ * @param {Record<string, any> | null | undefined} fx
+ * @returns {{ kind?: string, target: string, match: string, occurrence: number, at?: number, lead: number, hold: number, scale: number, ease: string, highlight: string | false }}
+ */
+export const resolveWordZoom = (fx) => ({ ...WORD_ZOOM_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) });
+
+/** Every reason post item `e`'s `fx` cannot be built, as sentences (empty: it can). Time is the build's to judge (wordZoomTimes). */
+export function validatePostFx(e) {
+ if (e?.fx === undefined) return [];
+ const w = `timeline ${e?.id ?? "?"}.fx`;
+ if (!Array.isArray(e.fx)) return [`${w} must be a list of the post's effects ([{ kind: "word-zoom", match, … }])`];
+ const errors = [];
+ if (e.fx.length > POST_FX_MAX) errors.push(`${w}: at most ${POST_FX_MAX} effects`);
+ e.fx.forEach((fx, i) => {
+ const fw = `${w}[${i}]`;
+ if (!isObj(fx)) return errors.push(`${fw} must be an object`);
+ if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`);
+ for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a word-zoom key (${[...KEYS].join(", ")})`);
+ const target = fx.target ?? "post";
+ const text = typeof target === "string" ? targetTextOf(e, target) : null;
+ if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:<i>"`);
+ else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`);
+ if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase to zoom on, as the card shows it`);
+ else if (fx.match.length > WORD_ZOOM_MATCH_MAX) errors.push(`${fw}.match is longer than ${WORD_ZOOM_MATCH_MAX} characters`);
+ if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, WORD_ZOOM_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`);
+ if (typeof fx.match === "string" && fx.match.trim() && text !== null) {
+ const m = findMatch(text, fx.match, fx.occurrence ?? 1);
+ if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`);
+ else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`);
+ else if (m.error) errors.push(`${fw}.match: ${m.error}`);
+ }
+ for (const k of ["at", "lead", "hold", "scale"]) {
+ if (fx[k] !== undefined && !numIn(fx[k], WORD_ZOOM_LIMITS[k])) errors.push(`${fw}.${k} must be ${WORD_ZOOM_LIMITS[k][0]}–${WORD_ZOOM_LIMITS[k][1]}${k === "scale" ? " (times the card)" : " seconds"}`);
+ }
+ if (fx.ease !== undefined && !WORD_ZOOM_EASES.includes(fx.ease)) errors.push(`${fw}.ease must be one of ${WORD_ZOOM_EASES.join(", ")}`);
+ if (fx.highlight !== undefined && fx.highlight !== false && !(typeof fx.highlight === "string" && HEX_RE.test(fx.highlight))) errors.push(`${fw}.highlight must be a colour (#rrggbb) or false (none)`);
+ });
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// Word timings: the editor's recognized words aligned to the script.
+// ---------------------------------------------------------------------------
+
+const NUMBERS = { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 20: "twenty", 100: "hundred" };
+const spoken = (w) => {
+ const n = normWord(w).replace(/'/g, "");
+ return /^\d+$/.test(n) && NUMBERS[Number(n)] ? NUMBERS[Number(n)] : n;
+};
+
+function lev(a, b) {
+ if (a === b) return 0;
+ if (!a.length) return b.length;
+ if (!b.length) return a.length;
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
+ for (let i = 1; i <= a.length; i += 1) {
+ const cur = [i];
+ for (let j = 1; j <= b.length; j += 1) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
+ prev = cur;
+ }
+ return prev[b.length];
+}
+
+/** How alike two words are, 0–1: 1 the same, else 1 - edit distance ÷ the longer (a typo read as the word it means scores high). */
+export function wordSimilarity(a, b) {
+ const x = spoken(a);
+ const y = spoken(b);
+ if (!x || !y) return 0;
+ if (x === y) return 1;
+ return Math.max(0, 1 - lev(x, y) / Math.max(x.length, y.length));
+}
+
+/** Below this, two words are not the same word. */
+export const ALIGN_MIN = 0.5;
+
+/**
+ * THE ALIGNMENT, in order: each word of `a` paired with at most one of `b`,
+ * never crossing, maximising the summed similarity (pairs under ALIGN_MIN are
+ * not pairs). Returns `map[i]` = b's index for a's word i, or -1.
+ *
+ * @param {string[]} a
+ * @param {string[]} b
+ */
+export function alignWords(a, b) {
+ const n = a.length;
+ const m = b.length;
+ const map = new Array(n).fill(-1);
+ if (!n || !m) return map;
+ const W = m + 1;
+ const D = new Float32Array((n + 1) * W);
+ const sim = (i, j) => wordSimilarity(a[i], b[j]);
+ for (let i = 1; i <= n; i += 1) {
+ for (let j = 1; j <= m; j += 1) {
+ const s = sim(i - 1, j - 1);
+ const diag = s >= ALIGN_MIN ? D[(i - 1) * W + j - 1] + s : -1;
+ D[i * W + j] = Math.max(D[(i - 1) * W + j], D[i * W + j - 1], diag);
+ }
+ }
+ let i = n;
+ let j = m;
+ while (i > 0 && j > 0) {
+ const here = D[i * W + j];
+ if (here === D[(i - 1) * W + j]) i -= 1;
+ else if (here === D[i * W + j - 1]) j -= 1;
+ else {
+ map[i - 1] = j - 1;
+ i -= 1;
+ j -= 1;
+ }
+ }
+ return map;
+}
+
+/** A script's spoken words: its runs of non-space, Orpheus's tags (<sigh>) dropped. */
+export const scriptWordsOf = (script) => str(script).replace(/<[^<>]*>/g, " ").split(/\s+/).filter((w) => normWord(w));
+
+/**
+ * A TAKE's WORD TIMINGS from what the editor heard: `recognized` `[{ w, start,
+ * end }]` (take seconds, in order) aligned to the script's words; each script
+ * word gets the times of the word it was heard as, and a word not heard (or
+ * heard as something else) is spread evenly between its heard neighbours.
+ * Returns `[{ w, start, end }]`, one per script word, and how many were heard.
+ *
+ * @param {string} script
+ * @param {Array<{ w: string, start: number, end: number }>} recognized
+ */
+export function scriptWordTimes(script, recognized) {
+ const words = scriptWordsOf(script);
+ const heard = (Array.isArray(recognized) ? recognized : []).filter((r) => r && typeof r.w === "string" && fin(r.start) && fin(r.end) && normWord(r.w));
+ const map = alignWords(words, heard.map((r) => r.w));
+ const out = words.map((w, i) => (map[i] >= 0 ? { w, start: r3(heard[map[i]].start), end: r3(Math.max(heard[map[i]].start, heard[map[i]].end)) } : { w, start: null, end: null }));
+ const total = heard.length ? heard[heard.length - 1].end : 0;
+ for (let i = 0; i < out.length; ) {
+ if (out[i].start !== null) {
+ i += 1;
+ continue;
+ }
+ let k = i;
+ while (k < out.length && out[k].start === null) k += 1;
+ const from = i > 0 ? out[i - 1].end : heard[0]?.start ?? 0;
+ const to = k < out.length ? out[k].start : Math.max(from, total);
+ const step = (to - from) / (k - i);
+ for (let x = i; x < k; x += 1) out[x] = { w: out[x].w, start: r3(from + step * (x - i)), end: r3(from + step * (x - i + 1)) };
+ i = k;
+ }
+ return { words: out, heard: map.filter((x) => x >= 0).length, of: words.length };
+}
+
+// ---------------------------------------------------------------------------
+// WHEN: each zoom's second on the item's clock.
+// ---------------------------------------------------------------------------
+
+/**
+ * Each zoom's moment, `[{ i, t, source: "at"|"words", word? } | { i, error }]`:
+ * `at` when set; else the matched word in the picked take's words -- the card's
+ * words aligned to the script it read -- at lead + start ÷ rate.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {Record<string, any> | null} [schedule]
+ * @returns {Array<{ i: number, t?: number, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>}
+ */
+export function wordZoomTimes(entry, render = undefined, schedule = undefined) {
+ const list = Array.isArray(entry?.fx) ? entry.fx : [];
+ const narrated = isNarrated(entry);
+ const take = narrated ? pickedTake(entry) : null;
+ // `schedule`: the item's narration schedule when the caller has it (Play: the plan's), else worked out here.
+ const sch = narrated ? schedule ?? narrationSchedule(entry, render) : null;
+ return list.map((fx0, i) => {
+ if (!isObj(fx0) || fx0.kind !== "word-zoom") return { i, error: "not a word zoom" };
+ const fx = resolveWordZoom(fx0);
+ if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" };
+ const w = `${entry?.id ?? "?"}: word zoom ${i + 1} ("${fx.match}")`;
+ if (!narrated) return { i, error: `${w} has no time: the post is not narrated, so set its second (at, item seconds)` };
+ const words = Array.isArray(take?.words) ? take.words : null;
+ if (!words?.length) return { i, error: `${w} has no time: its take has no word timings yet (umtool posts narrate <p> ${entry.id} --words, or the bench's Get word timings) -- or set at` };
+ const text = targetTextOf(entry, fx.target);
+ const m = findMatch(text, fx.match, fx.occurrence);
+ if (m.error) return { i, error: `${w} is not on the card` };
+ const map = alignWords(cardWordsOf(text), words.map((x) => x.w));
+ let hit = -1;
+ for (let k = m.from; k <= m.to && hit < 0; k += 1) hit = map[k];
+ if (hit < 0) return { i, error: `${w} is not in the read (the script does not say it, or the take's words do not reach it) -- set at` };
+ return { i, t: r3(sch.at + words[hit].start / (sch.rate || 1)), source: "words", word: { ...words[hit], index: hit } };
+ });
+}
+
+/** The reading estimate for an un-narrated post's word (the CLI's and the bench's first `at`): 1 s to find it, then 3 words a second. */
+export const readingEstimate = (wordIndex) => Math.round((1 + Math.max(0, wordIndex) / 3) * 100) / 100;
+
+// ---------------------------------------------------------------------------
+// THE CURVE.
+// ---------------------------------------------------------------------------
+
+/** The ease, 0–1 → 0–1. */
+export function easeOf(name, x) {
+ const v = Math.min(1, Math.max(0, x));
+ if (name === "out") return 1 - (1 - v) ** 3;
+ if (name === "snap") return v >= 1 ? 1 : 1 - 2 ** (-10 * v);
+ return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2;
+}
+
+/** One zoom's span on the item's clock: in from t0 to t1 (= t), held to t2, out by t3. */
+export function zoomSpan(fx0, t) {
+ const fx = resolveWordZoom(fx0);
+ const t1 = r3(t);
+ const t0 = r3(Math.max(0, t1 - fx.lead));
+ const t2 = r3(t1 + fx.hold);
+ return { t0, t1, t2, t3: r3(t2 + WORD_ZOOM_OUT), scale: fx.scale, ease: fx.ease };
+}
+
+/** The zoom's progress at item second `s` (0 none, 1 all the way in). */
+export function zoomProgressAt(span, s) {
+ if (!span || s < span.t0 || s >= span.t3) return 0;
+ if (s < span.t1) return span.t1 > span.t0 ? easeOf(span.ease, (s - span.t0) / (span.t1 - span.t0)) : 1;
+ if (s < span.t2) return 1;
+ return 1 - easeOf(span.ease, (s - span.t2) / (span.t3 - span.t2));
+}
+
+/** The highlight's opacity at item second `s`, 0–1: linear in over the lead, out over the way back (the render's alpha fades). */
+export function highlightAt(span, s) {
+ if (!span || s < span.t0 || s >= span.t3) return 0;
+ if (s < span.t1) return span.t1 > span.t0 ? (s - span.t0) / (span.t1 - span.t0) : 1;
+ if (s < span.t2) return 1;
+ return 1 - (s - span.t2) / (span.t3 - span.t2);
+}
+
+/** The zoom factor at progress p. */
+export const zoomAt = (span, p) => 1 + (span.scale - 1) * p;
+
+/**
+ * THE WINDOW at zoom z: the part of `region` (the card's box, px) shown
+ * filling it -- 1/z of its size, moving from the whole region (z = 1) to the
+ * one centred on `word` (its box, px; clamped inside the region) at z = scale.
+ * @returns {{ x: number, y: number, width: number, height: number }}
+ */
+export function zoomWindow(region, word, scale, z) {
+ const fw = region.width / scale;
+ const fh = region.height / scale;
+ const cx = word.x + word.width / 2;
+ const cy = word.y + word.height / 2;
+ const fx = Math.min(region.x + region.width - fw, Math.max(region.x, cx - fw / 2));
+ const fy = Math.min(region.y + region.height - fh, Math.max(region.y, cy - fh / 2));
+ // q runs 0 → 1 as z runs 1 → scale, so the window is exactly region / z.
+ const q = scale > 1 ? (1 - 1 / z) / (1 - 1 / scale) : 0;
+ return { x: region.x + (fx - region.x) * q, y: region.y + (fy - region.y) * q, width: region.width / z, height: region.height / z };
+}
+
+/** The final window's offset in the region (zoomWindow at z = scale, relative to the region's corner). */
+export function zoomTarget(region, word, scale) {
+ const f = zoomWindow(region, word, scale, scale);
+ return { x: f.x - region.x, y: f.y - region.y };
+}
+
+const f4 = (v) => {
+ const s = (Math.round(Number(v) * 1e4) / 1e4).toFixed(4).replace(/\.?0+$/, "");
+ return s === "-0" ? "0" : s;
+};
+
+/** The ease as an ffmpeg expression of `X` (an expression clipped 0–1 by the caller). */
+export function easeExpr(name, X) {
+ if (name === "out") return `(1-pow(1-${X},3))`;
+ if (name === "snap") return `if(gte(${X},1),1,1-pow(2,-10*${X}))`;
+ return `if(lt(${X},0.5),4*pow(${X},3),1-pow(-2*${X}+2,3)/2)`;
+}
+
+/** zoomProgressAt as an ffmpeg expression of `S` (the item second). */
+export function progressExpr(span, S) {
+ const { t0, t1, t2, t3 } = span;
+ const inX = t1 > t0 ? `clip((${S}-${f4(t0)})/${f4(t1 - t0)},0,1)` : "1";
+ const outX = `clip((${S}-${f4(t2)})/${f4(t3 - t2)},0,1)`;
+ return `if(lt(${S},${f4(t0)}),0,if(lt(${S},${f4(t1)}),${t1 > t0 ? easeExpr(span.ease, inX) : "1"},if(lt(${S},${f4(t2)}),1,if(lt(${S},${f4(t3)}),1-${easeExpr(span.ease, outX)},0))))`;
+}
+
+/**
+ * The zoompan expressions for one zoom over its region scaled by `k` (the
+ * hi-res card's device scale): `z` from the item second `S`, and `x`, `y` --
+ * the window's corner in the region's px × k -- from zoompan's own `zoom`.
+ */
+export function zoompanExprs(span, target, k, S) {
+ const p = progressExpr(span, S);
+ const q = span.scale > 1 ? `(1-1/zoom)/${f4(1 - 1 / span.scale)}` : "0";
+ return { z: `1+${f4(span.scale - 1)}*${p}`, x: `${f4(target.x * k)}*${q}`, y: `${f4(target.y * k)}*${q}` };
+}
+
+/** Two zooms of one post that are up at once (they would fight): their indices, or null. */
+export function overlappingZooms(spans) {
+ const s = spans.map((x, i) => ({ ...x, i })).filter((x) => x.t3 !== undefined).sort((a, b) => a.t0 - b.t0);
+ for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i];
+ return null;
+}
diff --git a/umtool/report-to-video/word-zoom.test.mjs b/umtool/report-to-video/word-zoom.test.mjs
@@ -0,0 +1,148 @@
+// word-zoom.mjs: a post item's word zoom -- the validator, the match, the
+// alignment of the words heard to the script, the time on the item's clock and
+// the curve (the render's expressions and Play's CSS read the same one).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { postCardHtml, validatePostItem } from "./post-item.mjs";
+import { postSegmentArgs, postZoomPlan } from "./post-render.mjs";
+import { postItemPlan, postLayout } from "./post-item.mjs";
+import {
+ WORD_ZOOM_OUT, alignWords, cardWordsOf, easeOf, findMatch, overlappingZooms, progressExpr, scriptWordTimes, wordSimilarity, wordZoomTimes,
+ zoomAt, zoomProgressAt, zoomSpan, zoomWindow, zoompanExprs,
+} from "./word-zoom.mjs";
+
+const TEXT = "If no one does stop me and save me from myself, barbecue if no one does, I'm going after him.";
+const base = (o = {}) => ({
+ type: "post", id: "p1", post: "obvious-x/2117488972809330822", platform: "x", author: "MR. OBVIOUS", handle: "ObviousRises",
+ date: "2026-11-03T04:00:00.000Z", text: TEXT, ...o,
+});
+const zoom = (o = {}) => ({ kind: "word-zoom", match: "barbecue", ...o });
+const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 6, script: TEXT, ...o });
+
+test("the validator: unknown keys refused, the match must be in the target's words, the knobs in their bounds", () => {
+ assert.deepEqual(validatePostItem(base({ fx: [zoom()] })), []);
+ assert.deepEqual(validatePostItem(base({ fx: [zoom({ match: "Barbecue,", occurrence: 1, at: 2, lead: 0.3, hold: 1, scale: 3, ease: "snap", highlight: false })] })), []);
+ // "if no one does" is said twice: its second time is there, a third is not.
+ assert.deepEqual(validatePostItem(base({ fx: [zoom({ match: "if no one does", occurrence: 2 })] })), []);
+ const errs = (fx) => validatePostItem(base({ fx: [fx] })).join("\n");
+ assert.match(errs(zoom({ match: "if no one does", occurrence: 3 })), /is in the post's words 2 times: occurrence 3 is not there/);
+ assert.match(errs(zoom({ match: "because" })), /fx\[0\]\.match "because" is not in the post's words/);
+ assert.match(errs(zoom({ zoomy: 1 })), /fx\[0\]\.zoomy is not a word-zoom key/);
+ assert.match(errs(zoom({ scale: 9 })), /scale must be 1.2–4/);
+ assert.match(errs(zoom({ ease: "bounce" })), /ease must be one of out, inOut, snap/);
+ assert.match(errs(zoom({ highlight: "yellow" })), /highlight must be a colour/);
+ assert.match(errs(zoom({ target: "quoted" })), /target quoted: the card draws no such post \(it quotes none\)/);
+ assert.match(errs({ kind: "sparkle" }), /kind must be one of word-zoom/);
+ assert.match(validatePostItem(base({ fx: { kind: "word-zoom" } })).join(), /fx must be a list/);
+ // A context post's words: its paraphrase when it has one (what the card shows).
+ const q = { quoted: { handle: "someone", text: "the original words", paraphrase: "a short retelling" } };
+ assert.deepEqual(validatePostItem(base({ ...q, fx: [zoom({ target: "quoted", match: "retelling" })] })), []);
+ assert.match(validatePostItem(base({ ...q, fx: [zoom({ target: "quoted", match: "original" })] })).join(), /not in the quoted post's words/);
+});
+
+test("the match: the card's words, case and edge punctuation aside, the n-th run", () => {
+ assert.deepEqual(findMatch(TEXT, "BARBECUE"), { from: 11, to: 11, count: 1 });
+ assert.equal(cardWordsOf(TEXT)[11], "barbecue");
+ assert.deepEqual(findMatch(TEXT, "no one does", 2), { from: 13, to: 15, count: 2 });
+ assert.equal(findMatch(TEXT, "zzz").error, "not in");
+});
+
+test("the card: each word a span the build measures; the highlight marks the zoom's words", () => {
+ const html = postCardHtml(base(), { width: 1280, height: 720 });
+ assert.match(html, /<span data-w="post:11">barbecue<\/span>/);
+ const lit = postCardHtml(base(), { width: 1280, height: 720, highlight: { scope: "post", from: 11, to: 11, color: "#ffd84d" } });
+ assert.match(lit, /<span data-w="post:11" data-w-hl="">barbecue<\/span>/);
+ assert.match(lit, /\[data-w-hl\] \{ background: rgba\(255, 216, 77, 0.42\)/);
+});
+
+test("the alignment: in order, fuzzy -- a typo read as the word it means, a word misheard, a word not heard", () => {
+ assert.ok(wordSimilarity("barbecue", "barbeque") > 0.8);
+ assert.ok(wordSimilarity("barbecue,", "Barbecue") === 1);
+ assert.ok(wordSimilarity("2", "two") === 1);
+ assert.ok(wordSimilarity("because", "barbecue") < 0.5);
+ // The script has the typo; the voice said it, the transcription heard "barbeque"; "myself" was not heard.
+ const script = "save me from myself, barbecue if no one does";
+ const heard = [
+ ["save", 0.1, 0.4], ["me", 0.4, 0.5], ["from", 0.5, 0.7], ["barbeque", 1.6, 2.1], ["if", 2.2, 2.3], ["know", 2.3, 2.5], ["one", 2.5, 2.7], ["does", 2.7, 3.0],
+ ].map(([w, start, end]) => ({ w, start, end }));
+ const r = scriptWordTimes(script, heard);
+ assert.equal(r.of, 9);
+ assert.equal(r.heard, 8); // "no" was heard as "know": fuzzy (2 letters of 4 apart is half: a pair)
+ assert.deepEqual(r.words[4], { w: "barbecue", start: 1.6, end: 2.1 });
+ // "myself," not heard: placed between "from" (ends 0.7) and "barbecue" (starts 1.6).
+ assert.deepEqual(r.words[3], { w: "myself,", start: 0.7, end: 1.6 });
+ // Tags are not words; order holds (a word heard later never pairs with an earlier one).
+ assert.equal(scriptWordTimes("<sigh> fine then", [{ w: "fine", start: 0, end: 0.3 }, { w: "then", start: 0.3, end: 0.6 }]).of, 2);
+ assert.deepEqual(alignWords(["a", "b", "c"], ["c", "a", "b"]), [1, 2, -1]);
+});
+
+test("the time: at when set; else the word's start in the take ÷ the read's rate, after its lead", () => {
+ const words = scriptWordTimes(TEXT, cardWordsOf(TEXT).map((w, i) => ({ w, start: i * 0.3, end: i * 0.3 + 0.25 }))).words;
+ const narrated = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4 }, fx: [zoom()] });
+ // "barbecue" is word 11: 3.3 s into the take, read from 0.4 s.
+ assert.deepEqual(wordZoomTimes(narrated)[0].t, 3.7);
+ assert.equal(wordZoomTimes(narrated)[0].source, "words");
+ // At rate 1.25 the take's 3.3 s are 2.64 s of the item.
+ const fast = base({ narration: { script: TEXT, takes: [take({ words })], lead: 0.4, rate: 1.25 }, fx: [zoom()] });
+ assert.equal(wordZoomTimes(fast)[0].t, 3.04);
+ // The cut's rate too.
+ assert.equal(wordZoomTimes(narrated, { postNarration: { rate: 1.5 } })[0].t, 2.6);
+ // at wins.
+ assert.deepEqual(wordZoomTimes(base({ ...narrated, fx: [zoom({ at: 1.25 })] }))[0], { i: 0, t: 1.25, source: "at" });
+ // No words yet, or not narrated: no time, said how to give it one.
+ assert.match(wordZoomTimes(base({ narration: { script: TEXT, takes: [take()] }, fx: [zoom()] }))[0].error, /no word timings yet \(umtool posts narrate <p> p1 --words/);
+ assert.match(wordZoomTimes(base({ fx: [zoom()] }))[0].error, /not narrated, so set its second \(at/);
+ assert.throws(() => postZoomPlan(base({ fx: [zoom()] })), /not narrated/);
+ assert.throws(() => postZoomPlan(base({ fx: [zoom({ at: 1, hold: 3 }), zoom({ match: "him", at: 2 })] })), /word zooms 1 and 2 are up at once/);
+ assert.throws(() => postZoomPlan(base({ fx: [zoom({ at: 9 })] }), undefined, 5), /starts at 8.5 s, after the post's 5 s/);
+});
+
+test("the curve: in over lead on the ease, held, out over WORD_ZOOM_OUT; the window is region ÷ z, landing on the word", () => {
+ const span = zoomSpan(zoom({ lead: 0.5, hold: 1, scale: 2.5 }), 3);
+ assert.deepEqual(span, { t0: 2.5, t1: 3, t2: 4, t3: 4 + WORD_ZOOM_OUT, scale: 2.5, ease: "inOut" });
+ assert.equal(zoomProgressAt(span, 2.4), 0);
+ assert.equal(zoomProgressAt(span, 2.75), 0.5); // inOut is half way at half time
+ assert.equal(zoomProgressAt(span, 3.5), 1);
+ assert.ok(zoomProgressAt(span, 4.2) > 0 && zoomProgressAt(span, 4.2) < 1);
+ assert.equal(zoomProgressAt(span, 4.4), 0);
+ assert.equal(easeOf("out", 0.5), 0.875);
+ assert.ok(easeOf("snap", 0.3) > 0.85);
+ const region = { x: 40, y: 40, width: 800, height: 600 };
+ const word = { x: 700, y: 500, width: 100, height: 40 };
+ assert.deepEqual(zoomWindow(region, word, 2.5, 1), region);
+ const full = zoomWindow(region, word, 2.5, 2.5);
+ assert.equal(full.width, 320);
+ assert.equal(full.height, 240);
+ // Centred on the word, clamped inside the region (the word is near its corner).
+ assert.equal(full.x, 40 + 800 - 320);
+ assert.equal(full.y, 40 + 600 - 240);
+ const mid = zoomWindow(region, word, 2.5, zoomAt(span, 0.5));
+ assert.ok(Math.abs(mid.width - 800 / 1.75) < 1e-9);
+ // The ffmpeg expression is the same curve: evaluated at a few seconds.
+ const S = (s) => progressExpr(span, String(s));
+ const evalExpr = (ex) => Function("lt", "gte", "clip", "pow", "if_", `return ${ex.replace(/\bif\(/g, "if_(")};`)(
+ (a, b) => (a < b ? 1 : 0), (a, b) => (a >= b ? 1 : 0), (v, lo, hi) => Math.min(hi, Math.max(lo, v)), Math.pow, (c, a, b) => (c ? a : b),
+ );
+ for (const s of [2, 2.6, 2.75, 2.9, 3.5, 4.1, 4.3, 5]) assert.ok(Math.abs(evalExpr(S(s)) - zoomProgressAt(span, s)) < 1e-3, `at ${s}`);
+ const ex = zoompanExprs(span, { x: 480, y: 360 }, 3, "S");
+ assert.match(ex.x, /^1440\*\(1-1\/zoom\)\/0\.6$/);
+ assert.deepEqual(overlappingZooms([zoomSpan({}, 1), zoomSpan({}, 1.5)]), [0, 1]);
+ assert.equal(overlappingZooms([zoomSpan({}, 1), zoomSpan({}, 5)]), null);
+});
+
+test("the render: the zoom's region shot zoomed on the curve, laid over the card before the attachments, only while up", () => {
+ const e = base({ fx: [zoom({ at: 1.5 })], media: [{ src: "m/i.jpg", kind: "image", width: 1000, height: 1000 }] });
+ const box = { width: 1440, height: 810 };
+ const span = zoomSpan(e.fx[0], 1.5);
+ const zooms = [{ i: 0, k: 2, span, region: { x: 30, y: 30, width: 500, height: 740 }, target: { x: 100, y: 200 }, plain: "/c/zoom-0.png", hl: "/c/zoom-hl-0.png", t: 1.5 }];
+ const argv = postSegmentArgs({ entry: e, box, plan: postItemPlan(e), layout: postLayout(e, box), cards: { read: "/c/read.png" }, files: ["/m/i.jpg"], render: { fps: 30 }, outPath: "/o.mp4", zooms });
+ const graph = argv[argv.indexOf("-filter_complex") + 1];
+ assert.ok(argv.includes("/c/zoom-0.png") && argv.includes("/c/zoom-hl-0.png"));
+ assert.match(graph, /\[1:v\]scale=1000:1480,setsar=1,format=rgba\[wzp0\]/);
+ assert.match(graph, /fade=t=in:st=0:d=0.5:alpha=1,fade=t=out:st=1.7:d=0.4:alpha=1\[wzh0\]/);
+ assert.match(graph, /zoompan=z='1\+1\*if\(lt\(\(1\+on\/30\),1\)/);
+ assert.match(graph, /d=1:s=500x740:fps=30,setsar=1,setpts=PTS-STARTPTS\+1\/TB\[wz0\]/);
+ assert.match(graph, /\[b0\]\[wz0\]overlay=x=30:y=30:eof_action=pass:enable='between\(t,1,3.1\)'\[b1\]/);
+ // The attachment is laid after it: on top.
+ assert.ok(graph.indexOf("[wz0]overlay") < graph.indexOf("[m0_0]"));
+});