// `umtool posts fx` and `umtool posts narrate
- --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
- [ls]
// umtool posts fx
- add word-zoom --match "…" [--target post|quoted|parent:] [--occurrence n] [--at s]
// [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off]
// umtool posts fx
- add caption --match "…" --text "…" [--target …] [--occurrence n] [--at s]
// [--lead s] [--hold s] [--place below|above|side] (post-caption.mjs)
// umtool posts fx
- add slam --text "不動心" [--match "…" | --at s] [--whole | --per-glyph] [--gap s]
// [--hold s] [--from-scale x] [--color #] [--outline #] [--outline-width px]
// [--place over-match|center] [--size px] [--face jp|sc|tc|kr] [--sfx trailer-hit|off]
// [--volume x] [--swell | --no-swell] [--bar "…" [--bar-style dark|gold|plain]] (post-slam.mjs)
// umtool posts fx
- set [the same flags; a flag's value `default` clears it]
// umtool posts fx
- remove
// umtool posts narrate
- --words [--worker ]
//
// 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 { CAPTION_DEFAULTS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption";
import { CLOCK_REWINDS, CLOCK_ZONE, clockFace, clockOn, clockZoneOf } from "umtool-report-to-video/post-clock";
import { SLAM_DEFAULTS, SLAM_FACES, SLAM_GAP, SLAM_PLACES, SLAM_SFX, resolveSlam, slamLandings, slamSpan, slamTimes } from "umtool-report-to-video/post-slam";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updatePostClock, updatePostFx, updatePostNarration } from "./manifest.mjs";
import { findPostItem } from "./postNarrationCli.mjs";
export const FX_USAGE = [
"usage: umtool posts fx
- [ls] [--json] (any form, + --in-take or --take : on a take's patch)",
" umtool posts fx
- add word-zoom --match \"…\" [--target post|quoted|parent:] [--occurrence n]",
" [--at s] [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off] [--json]",
" umtool posts fx
- add caption --match \"…\" --text \"…\" [--target post|quoted|parent:] [--occurrence n]",
" [--at s] [--lead s] [--hold s] [--place below|above|side] [--json]",
" umtool posts fx
- add clock [--rewind auto|on|off] [--off]",
" umtool posts fx
- add slam --text \"不動心\" [--match \"…\" | --at s] [--whole | --per-glyph] [--gap s] [--hold s]",
" [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match|center]",
" [--size px] [--face jp|sc|tc|kr] [--sfx trailer-hit|off] [--volume x] [--swell | --no-swell]",
" [--bar \"\" [--bar-style dark|gold|plain]] [--json]",
" umtool posts fx
- set [those flags; `default` clears one] | remove ",
" 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
- --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}). : the effect's number as ls shows it.`,
" A CAPTION: a chip explaining a phrase (--text, any script: CJK is drawn), up as the phrase is read and held a beat,",
" by the phrase (--place; it never covers a word read while it is up) with a notch and an underline. WHEN: --at, else",
" the word's start in the take's word timings, else the reading estimate (a narrated read spread over its script).",
` --lead 0–3 s in before the word (${CAPTION_DEFAULTS.lead}), --hold 0.5–10 s from it (${CAPTION_DEFAULTS.hold}), --place ${CAPTION_PLACES.join("|")} (${CAPTION_DEFAULTS.place}).`,
" A caption up while a word zoom is waits for the zoom to be out.",
" A CLOCK: the post's own time on its card (\"4:10 AM ET · Wed 4 Nov\", the cut's zone), run from the clock item",
" before it in its first 0.8 s -- forward with the gap flashing (\"+38 min\"), or REWOUND when this post is earlier",
" (⟲ rewind). --rewind off cuts straight to it, on rewinds anyway; --off: no clock on this item though the cut's is",
" on (umtool posts clock
on).",
" A SLAM: a corny movie-trailer title slam -- each glyph of --text (--whole: the text as one) comes in huge",
` (--from-scale, ${SLAM_DEFAULTS.fromScale}×) and blurred, shrinks onto the card and HITS (a flash, dust, the frame's punch, a trailer`,
" hit's boom), gold with a black outline, in a row just above --match's line (--place center: the card's middle).",
" WHEN: the hits spread evenly over the matched words' spoken span in the take's word timings (the first on its",
` first word's start, the last on its last word's end); --gap s spaces them instead; --at moves the first hit (no span:`,
` ${SLAM_GAP} s apart). Held --hold s after the last (${SLAM_DEFAULTS.hold}), then gone; a caption up with it waits for it.`,
` --size px at 1080 (default: by the word's line), --face ${SLAM_FACES.join("|")} (the CJK forms, ${SLAM_DEFAULTS.face}), --sfx ${SLAM_SFX.join("|")},`,
" --volume × the hit's level (1), --swell the teaser's low swell under the hold.",
" --bar \"fudōshin — \\\"immovable mind\\\"\": the glyphs land ON a translation bar (rising in at the first hit, held,",
" faded with them; the part before \" — \" bold), the row and the bar placed as one; --bar-style dark (the card's",
" ground, a gold rule) | gold | plain; --bar off clears it.",
].join("\n");
export class FxError extends Error {}
const NUM_KEYS = {
"--at": "at", "--scale": "scale", "--hold": "hold", "--lead": "lead", "--occurrence": "occurrence",
"--gap": "gap", "--from-scale": "fromScale", "--outline-width": "outlineWidth", "--size": "size", "--volume": "volume",
};
/** A slam's own knobs (the CLI refuses them on another kind, and another kind's on a slam). */
const SLAM_ONLY = ["gap", "fromScale", "outlineWidth", "size", "volume", "color", "outline", "face", "sfx", "whole", "swell", "bar", "barStyle"];
/** The flags as an effect patch (null: back to the default). `has`: a bare flag's presence (--whole, --swell). */
export function fxPatchOf(str, has = () => false) {
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 rw = str("--rewind");
if (rw !== null) out.rewind = rw === "default" || rw === "auto" ? null : rw;
const tx = str("--text");
if (tx !== null) out.text = tx;
const pl = str("--place");
if (pl !== null) out.place = pl === "default" ? null : pl;
const e = str("--ease");
if (e !== null) out.ease = e === "default" ? null : e;
for (const [flag, key] of [["--color", "color"], ["--outline", "outline"], ["--face", "face"], ["--sfx", "sfx"]]) {
const v = str(flag);
if (v !== null) out[key] = v === "default" ? null : v;
}
const bar = str("--bar");
if (bar !== null) out.bar = ["default", "off", "none"].includes(bar) ? null : bar;
const bs = str("--bar-style");
if (bs !== null) out.barStyle = bs === "default" ? null : bs;
if (has("--whole")) out.whole = true;
if (has("--per-glyph")) out.whole = null;
if (has("--swell")) out.swell = true;
if (has("--no-swell")) out.swell = null;
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 effects (word zooms, captions) as lines. */
export function fxLines(e, render) {
const list = Array.isArray(e.fx) ? e.fx : [];
if (!list.length) return [`${e.id}: no effects (add one: umtool posts fx
${e.id} add word-zoom --match "…" | add caption --match "…" --text "…")`];
const times = wordZoomTimes(e, render);
const ctimes = captionTimes(e, render);
const nz = list.filter((f) => f?.kind === "word-zoom").length;
const nc = list.filter((f) => f?.kind === "caption").length;
const ns = list.filter((f) => f?.kind === "slam").length;
const clk = list.some((f) => f?.kind === "clock");
const stimes = ns ? slamTimes(e, render) : [];
return [
`${e.id}: ${nz} word zoom(s), ${nc} caption(s)${ns ? `, ${ns} slam(s)` : ""}${clk ? ", its clock" : ""}${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`,
...list.map((fx0, i) => {
if (fx0?.kind === "slam") {
const sl = resolveSlam(fx0);
const t = stimes[i];
let when;
if (t.error) when = `NO TIME -- ${t.error}`;
else {
const L = slamLandings(fx0, { t: t.t, end: t.end ?? null });
const sp = slamSpan(fx0, L);
when = `hits at ${L.map((x) => x.toFixed(2)).join(", ")} s (${Number.isFinite(fx0.gap) ? `${fx0.gap} s apart from ${t.source === "words" ? "the word's start" : t.source === "at" ? "its at" : "the reading estimate"}` : t.source === "words" ? "spread over the words' spoken span" : t.source === "at" ? "from its at" : "the reading estimate"}), gone by ${sp.t3 ?? "?"} s`;
}
return ` #${i + 1} slam "${sl.text}"${typeof fx0.match === "string" ? ` on "${sl.match}" (${sl.target}, ${nth(sl.occurrence)})` : ""} ${when} · ${sl.whole ? "whole" : "per glyph"}, ${sl.fromScale}× in, held ${sl.hold} s, ${sl.place}, ${sl.color}/${sl.outline}, face ${sl.face}, sfx ${sl.sfx}${sl.volume !== 1 ? ` ×${sl.volume}` : ""}${sl.swell ? ", swell" : ""}${sl.size ? `, ${sl.size} px` : ""}${typeof fx0.bar === "string" ? ` · on a ${sl.barStyle} bar "${fx0.bar}"` : ""}`;
}
if (fx0?.kind === "clock") {
const on = fx0.on !== false;
return ` #${i + 1} clock ${on ? `on -- ${clockFace(Date.parse(e.date), clockZoneOf(render)).time} ${clockFace(Date.parse(e.date), clockZoneOf(render)).date}, rewind ${fx0.rewind ?? "auto"}` : "off (the cut's clock not shown here)"}`;
}
if (fx0?.kind === "caption") {
const c = resolveCaption(fx0);
const t = ctimes[i];
const when = t.error ? `NO TIME -- ${t.error}` : `at ${t.t.toFixed(2)} s (${t.source === "at" ? "set by hand" : t.source === "words" ? "from the take's words" : "the reading estimate"})`;
return ` #${i + 1} caption "${c.match}" (${c.target}, ${nth(c.occurrence)}) ${when} · "${c.text}" · in ${c.lead} s before, held ${c.hold} s, ${c.place}`;
}
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, off = false, has = () => false }) {
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) {
const ct = captionTimes(entry, render);
const st = slamTimes(entry, render).map((t, i) => {
if (entry.fx?.[i]?.kind !== "slam" || t.error) return t;
const landings = slamLandings(entry.fx[i], { t: t.t, end: t.end ?? null });
return { ...t, landings, span: slamSpan(entry.fx[i], landings) };
});
out(JSON.stringify({ ok: true, id: entry.id, fx: entry.fx ?? [], times: wordZoomTimes(entry, render).map((t, i) => (entry.fx?.[i]?.kind === "caption" ? ct[i] : entry.fx?.[i]?.kind === "slam" ? st[i] : t)), ...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 effect'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" && arg !== "caption" && arg !== "clock" && arg !== "slam") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\" | add clock | add slam --text \"…\" --match \"…\"");
const patch = Object.fromEntries(Object.entries(fxPatchOf(str, has)).filter(([, v]) => v !== null));
if (arg === "slam") {
for (const k of ["scale", "ease", "highlight", "lead", "rewind"]) if (k in patch) throw new FxError(`--${k} is not a slam's knob`);
if (typeof patch.text !== "string" || !patch.text.trim()) throw new FxError("add slam needs --text \"\"");
if ((typeof patch.match !== "string" || !patch.match.trim()) && patch.at === undefined) throw new FxError("add slam needs --match \"\" (or --at s with --place center)");
if (patch.place !== undefined && !SLAM_PLACES.includes(patch.place)) throw new FxError(`--place is ${SLAM_PLACES.join(" or ")} for a slam`);
const { result } = await write({ add: { kind: "slam", ...patch } });
say(result.entry, { index: result.index });
return 0;
}
for (const k of SLAM_ONLY) if (k in patch) throw new FxError(`--${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} is a slam's knob (add slam …)`);
if (arg === "clock") {
const extra = Object.keys(patch).filter((k) => k !== "rewind");
if (extra.length) throw new FxError(`--${extra[0]} is not a clock's knob (--rewind ${CLOCK_REWINDS.join("|")}, --off)`);
if ((e.fx ?? []).some((f) => f?.kind === "clock")) throw new FxError(`${e.id} has its clock already (set --rewind …, or remove )`);
const { result } = await write({ add: { kind: "clock", ...patch, ...(off ? { on: false } : {}) } });
say(result.entry, { index: result.index });
return 0;
}
if ("rewind" in patch) throw new FxError("--rewind is a clock's knob (add clock …)");
if (arg === "caption") {
if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add caption needs --match \"\"");
if (typeof patch.text !== "string" || !patch.text.trim()) throw new FxError("add caption needs --text \"\"");
for (const k of ["scale", "ease", "highlight"]) if (k in patch) throw new FxError(`--${k} is a word zoom's knob, not a caption's`);
const { result } = await write({ add: { kind: "caption", ...patch } });
say(result.entry, { index: result.index });
return 0;
}
if ("text" in patch || "place" in patch) throw new FxError("--text and --place are a caption's knobs (add caption …)");
if (typeof patch.match !== "string" || !patch.match.trim()) throw new FxError("add word-zoom needs --match \"\"");
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 --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, has);
if (!Object.keys(patch).length) throw new FxError("set changes something: --match, --at, --hold, --lead, --occurrence, --target; a zoom's --scale, --ease, --highlight; a caption's --text, --place; a slam's --text, --gap, --from-scale, --color, --outline, --outline-width, --place, --size, --face, --sfx, --volume, --whole/--per-glyph, --swell/--no-swell, --bar, --bar-style");
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`);
}
export const CLOCK_USAGE = [
"usage: umtool posts clock [on|off|default] [--zone ] [--json]",
" THE CUT's CLOCK (render.posts.clock): each post item's own time on its card (\"4:10 AM ET · Wed 4 Nov\"), run",
" forward between two clock items (the gap flashing), rewound when the next is earlier. on/off is the cut's",
` default (an item's own: umtool posts fx - add clock [--off]); --zone the clock's zone (${CLOCK_ZONE}).`,
" With no word: which items show it.",
].join("\n");
/** `umtool posts clock …` (postsCli.mjs routes it here). */
export async function clockCommand(project, words, { json = false, out = (s) => console.log(s), str }) {
const [verb] = words;
const zone = str("--zone");
if (verb !== undefined && !["on", "off", "default", "ls"].includes(verb)) throw new FxError(`${verb}: on, off or default`);
if ((verb && verb !== "ls") || zone !== null) {
const patch = {};
if (verb === "on" || verb === "off") patch.on = verb === "on";
if (verb === "default") patch.on = null;
if (zone !== null) patch.zone = zone === "default" ? null : zone;
await withEditNotes(project, async () => updatePostClock(project.dir, patch, { token: await manifestToken(project.dir) }));
}
const manifest = await readManifest(project.dir);
const render = manifest?.render ?? {};
const items = (manifest?.timeline ?? []).filter((x) => x?.type === "post");
const shown = items.filter((x) => clockOn(x, render));
if (json) out(JSON.stringify({ ok: true, clock: render.posts?.clock ?? null, zone: clockZoneOf(render), items: shown.map((x) => x.id) }, null, 2));
else out([`clock: the cut's ${render.posts?.clock?.on ? "on" : "off"}, zone ${clockZoneOf(render)}; ${shown.length} of ${items.length} post item(s) show it`, ...shown.slice(0, 40).map((x) => ` ${x.id} ${clockFace(Date.parse(x.date), clockZoneOf(render)).time} ${clockFace(Date.parse(x.date), clockZoneOf(render)).date}`)].join("\n"));
return 0;
}
/**
* 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
${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 };
}