commit 7d48675c71ee4ac975c10b142ebcea485093d39b
parent ca21d22b0dfe3e2d00294cfc3108e0326250eb17
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 16:59:13 -0500
Merge lane/post-slam: a corny movie-trailer SLAM over a word as it is read -- one glyph per hit (不動心 on "Fudōshin", 八极拳 on "Baji Quan"), gold with a black outline, each huge then shrinking onto the page above the word with a flash and a shake, the hits spread evenly over the word's spoken span, each with the teaser's trailer hit (operator, 4 Nov: "pop in with three trailer hits like a corny effect", "three hits evenly spaced over the pronunciation of the word", "do it above the word on the page"); the teaser's trailer hit factored into trailer-hits.mjs, its output unchanged
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
18 files changed, 1669 insertions(+), 120 deletions(-)
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -18,6 +18,7 @@ import { liveCombo } from "umtool-report-to-video/post-combo";
import PostZoomPanel from "./PostZoomPanel";
import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
import { captionTimes, resolveCaption } from "umtool-report-to-video/post-caption";
+import { slamLandings, slamSpan, slamTimes } from "umtool-report-to-video/post-slam";
import { clockPlan } from "umtool-report-to-video/post-clock";
import { sceneEntry } from "umtool-report-to-video/post-media-scene";
@@ -291,6 +292,18 @@ export default function PostBench({
}),
[entry, render],
);
+ // Its slams (post-slam.mjs): each from its first glyph in to gone, a tick at each hit.
+ const slamMarks = useMemo(
+ () =>
+ (slamTimes(entry, render) as Array<{ i: number; t?: number; end?: number | null }>)
+ .filter((x) => typeof x.t === "number")
+ .map((x) => {
+ const fx = (entry.fx as Array<Record<string, unknown>>)[x.i];
+ const sp = slamSpan(fx, slamLandings(fx, { t: x.t as number, end: x.end ?? null }));
+ return { i: x.i, t0: sp.t0 ?? 0, t3: sp.t3 ?? 0, landings: sp.landings ?? [] };
+ }),
+ [entry, render],
+ );
const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null;
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const reading = readingSeconds(entry);
@@ -356,6 +369,13 @@ export default function PostBench({
{captionMarks.map((c) => (
<div key={`c${c.i}`} className="absolute bottom-0 h-1/3 border-x border-sky-400/80 bg-sky-400/30" style={{ left: `${(c.t0 / total) * 100}%`, width: `${((c.t3 - c.t0) / total) * 100}%` }} title={`caption ${c.i + 1}`} data-post-bench-caption-mark={c.i} />
))}
+ {slamMarks.map((m) => (
+ <div key={`s${m.i}`} className="absolute top-0 h-1/3 border-x border-yellow-300/90 bg-yellow-300/30" style={{ left: `${(m.t0 / total) * 100}%`, width: `${((m.t3 - m.t0) / total) * 100}%` }} title={`slam ${m.i + 1}: ${m.landings.length} hit(s)`} data-post-bench-slam-mark={m.i}>
+ {m.landings.map((L, j) => (
+ <span key={j} className="absolute inset-y-0 w-0.5 bg-yellow-200" style={{ left: `${((L - m.t0) / Math.max(0.01, m.t3 - m.t0)) * 100}%` }} data-post-bench-slam-hit={j} />
+ ))}
+ </div>
+ ))}
<div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} />
</div>
<PostZoomPanel
diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx
@@ -8,6 +8,7 @@ import {
WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, WORD_ZOOM_LIMITS, cardTokens, normWord, readingEstimate, resolveWordZoom, targetTextOf, wordZoomTimes, zoomSpan,
} from "umtool-report-to-video/word-zoom";
import { CAPTION_DEFAULTS, CAPTION_LIMITS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption";
+import { resolveSlam, slamLandings, slamTimes } from "umtool-report-to-video/post-slam";
// ---------------------------------------------------------------------------
// A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A
@@ -61,6 +62,8 @@ export default function PostZoomPanel({
const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]);
const ctimes = useMemo(() => captionTimes(entry, render), [entry, render]);
const [capText, setCapText] = useState("");
+ const [slamText, setSlamText] = useState("");
+ const stimes = useMemo(() => slamTimes(entry, render), [entry, render]);
const narrated = isNarrated(entry);
const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null;
@@ -76,24 +79,26 @@ export default function PostZoomPanel({
return j.entry;
};
- const zoomHere = async (kind: "word-zoom" | "caption" = "word-zoom") => {
+ const zoomHere = async (kind: "word-zoom" | "caption" | "slam" = "word-zoom") => {
if (!sel) return;
if (kind === "caption" && !capText.trim()) return setError("a caption needs its text");
+ if (kind === "slam" && !slamText.trim()) return setError("a slam needs its glyphs");
const words = tokens.slice(sel.from, sel.to + 1).map((t) => t.tok);
const match = words.length === 1 ? bare(words[0]) : [bare(words[0]), ...words.slice(1, -1), bare(words[words.length - 1])].join(" ");
// Its occurrence: how many times the same run of words came before it, plus one.
const want = words.map(normWord);
let occurrence = 1;
for (let i = 0; i < sel.from; i += 1) if (want.every((w, k) => normWord(tokens[i + k]?.tok ?? "") === w)) occurrence += 1;
- const add: Record<string, unknown> = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) };
+ const add: Record<string, unknown> = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : kind === "slam" ? { text: slamText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) };
// An un-narrated post has no read to time it by: the reading estimate, to nudge.
// (A caption is timed by the reading estimate itself when it has no at.)
if (!narrated && kind === "word-zoom") add.at = readingEstimate(sel.from);
const e = await send({ add });
if (e) {
- setStatus(`${kind === "caption" ? "caption" : "zoom"} added on "${match}"`);
+ setStatus(`${kind === "caption" ? "caption" : kind === "slam" ? "slam" : "zoom"} added on "${match}"`);
setSel(null);
if (kind === "caption") setCapText("");
+ if (kind === "slam") setSlamText("");
}
};
@@ -212,6 +217,17 @@ export default function PostZoomPanel({
<button type="button" className={btn} disabled={!sel || !capText.trim()} onClick={() => void zoomHere("caption")} data-post-caption-here="">
Caption here
</button>
+ <input
+ value={slamText}
+ onChange={(e) => setSlamText(e.target.value)}
+ placeholder="slam glyphs (不動心)"
+ className="w-28 rounded border border-seam bg-ground px-1 py-0.5"
+ aria-label="slam glyphs"
+ data-post-slam-text=""
+ />
+ <button type="button" className={btn} disabled={!sel || !slamText.trim()} onClick={() => void zoomHere("slam")} data-post-slam-here="">
+ Slam here
+ </button>
{sel && (
<span className="text-text-2" data-post-zoom-sel="">
“{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}”
@@ -219,6 +235,30 @@ export default function PostZoomPanel({
)}
</div>
{list.map((fx0, i) => {
+ // A SLAM (post-slam.mjs): its glyphs, its word, its hits; go to it, remove it (its knobs: umtool posts fx … set).
+ if (fx0?.kind === "slam") {
+ const sl = resolveSlam(fx0);
+ const t = stimes[i] as { t?: number; end?: number | null; source?: string; error?: string };
+ const hits = typeof t?.t === "number" ? slamLandings(fx0, { t: t.t, end: t.end ?? null }) : [];
+ const up = hits.length > 0 && s >= hits[0] - 0.2 && s < hits[hits.length - 1] + sl.hold + 0.35;
+ return (
+ <div key={i} className={cn("flex flex-wrap items-center gap-2 rounded border p-2", up ? "border-yellow-300/80" : "border-seam")} data-post-slam-fx={i}>
+ <b>
+ #{i + 1} slam {sl.text}
+ </b>
+ <span className="text-text-2">
+ {typeof fx0.match === "string" ? `on “${sl.match}” · ` : ""}
+ {t?.error ? `no time: ${t.error}` : `hits at ${hits.map((x) => x.toFixed(2)).join(", ")} s (${t.source === "words" ? "over the spoken word" : t.source === "at" ? "its at" : "the estimate"})`}
+ </span>
+ <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (hits[0] ?? 0) - 0.6))} disabled={!hits.length} data-post-slam-go={i}>
+ go
+ </button>
+ <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-slam-remove={i}>
+ remove
+ </button>
+ </div>
+ );
+ }
// Its clock (post-clock.mjs): a row of its own, its rewind knob.
if (fx0?.kind === "clock") {
return (
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -13,6 +13,10 @@ import {
CAPTION_SLIDE, captionCss, captionInnerHtml, captionOpacityAt, captionPlan, captionSlideAt, measureCaptionWords, mountCaptions, paletteOfDoc, placeCaption, setCaptionState, slideDir,
} from "umtool-report-to-video/post-caption";
import { clockCss, clockFace, clockHtml, clockStateAt, measureClockPlace, mountClock, setClockState } from "umtool-report-to-video/post-clock";
+import {
+ SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, setSlamState, slamCss, slamHits, slamLayout, slamListAt, slamPlan, slamShakeAt, slamSize, slamVars,
+} from "umtool-report-to-video/post-slam";
+import { TRAILER_AUDIO, trailerHitSamples } from "umtool-report-to-video/trailer-hits";
import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
@@ -55,6 +59,8 @@ type Rect = { x: number; y: number; width: number; height: number };
/** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */
/** A caption of the item, placed in its card page: its span, its place, the phrase's box and lines when placed. */
type LiveCaption = { i: number; span: { t0: number; t1: number; t2: number; t3: number }; scope: string; from: number; to: number; placed: NonNullable<ReturnType<typeof placeCaption>>; base: Rect; lines: Rect[] };
+/** A slam of the item, placed in its card page: its plan (span, units, its fx), each unit's centre, the words' box when placed. */
+type LiveSlam = { i: number; span: { t0: number; t2: number; t3: number; landings: number[] }; fx: Record<string, unknown> & { fromScale: number; volume: number }; scope: string | null; from: number; to: number; centers: Array<{ x: number; y: number }>; base: Rect | null; where: string };
type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect };
/** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */
@@ -207,6 +213,59 @@ function mixGraph(el: HTMLMediaElement, lowpassHz: number) {
}
}
+// ---------------------------------------------------------------------------
+// A SLAM's HITS, LIVE (post-slam.mjs, trailer-hits.mjs): each hit's layers made
+// by the build's own formulas (trailerHitSamples), filtered as its graph filters
+// them (the punch band-passed, the rumble low-passed, a short echo), at the
+// trailer's level -- started as Play's clock crosses a landing. No limiter: a
+// close approximation of the render's mix, not its bytes.
+// ---------------------------------------------------------------------------
+
+const hitBuffers = new Map<string, AudioBuffer[]>();
+function playTrailerHit(h: { gain: number; decay: number; f0: number; f1: number }, gain = 1) {
+ if (typeof window === "undefined" || typeof window.AudioContext === "undefined") return;
+ audioCtx ??= new window.AudioContext();
+ const ctx = audioCtx;
+ if (ctx.state === "suspended") void ctx.resume().catch(() => {});
+ const key = JSON.stringify([h, ctx.sampleRate]);
+ let bufs = hitBuffers.get(key);
+ if (!bufs) {
+ const smp = trailerHitSamples(h, ctx.sampleRate);
+ bufs = [smp.boom, smp.punch, smp.rumble].map((data) => {
+ const b = ctx.createBuffer(1, data.length, ctx.sampleRate);
+ b.copyToChannel(new Float32Array(data), 0);
+ return b;
+ });
+ hitBuffers.set(key, bufs);
+ }
+ const out = ctx.createGain();
+ out.gain.value = TRAILER_AUDIO.level * gain;
+ const lp = ctx.createBiquadFilter();
+ lp.type = "lowpass";
+ lp.frequency.value = 5000;
+ const echo = ctx.createDelay(0.5);
+ echo.delayTime.value = 0.09;
+ const echoGain = ctx.createGain();
+ echoGain.gain.value = 0.18;
+ out.connect(lp).connect(ctx.destination);
+ out.connect(echo).connect(echoGain).connect(lp);
+ const chain = [[], [["highpass", 180], ["lowpass", 3200]], [["lowpass", 260], ["lowpass", 260]]] as Array<Array<[BiquadFilterType, number]>>;
+ const now = ctx.currentTime;
+ bufs.forEach((b, j) => {
+ const src = ctx.createBufferSource();
+ src.buffer = b;
+ let node: AudioNode = src;
+ for (const [type, f] of chain[j]) {
+ const bq = ctx.createBiquadFilter();
+ bq.type = type;
+ bq.frequency.value = f;
+ node = node.connect(bq);
+ }
+ node.connect(out);
+ src.start(now);
+ });
+}
+
type Censor = { strength: number; boxes: number[][]; band: number[] | null; label: string | null; style: "blur" | "black" | "pixelate" };
/**
@@ -549,6 +608,7 @@ export default function PostItemPlayer({
}, [joinFrom, box]);
const [zooms, setZooms] = useState<LiveZoom[]>([]);
const [caps, setCaps] = useState<LiveCaption[]>([]);
+ const [slams, setSlams] = useState<LiveSlam[]>([]);
// The clock's box (and its badge's) where it is placed: a caption covers neither.
const clockRect = useRef<Rect | null>(null);
const boxes = useRef<Map<Element, Rect>>(new Map());
@@ -586,7 +646,9 @@ export default function PostItemPlayer({
if (!card || !list.length) {
setZooms([]);
setCaps([]);
+ setSlams([]);
mountCaptions({ css: "", chips: [] }, doc);
+ mountSlams(null, doc);
return true;
}
const rect = (el: Element): Rect => {
@@ -618,14 +680,49 @@ export default function PostItemPlayer({
out.push({ i, span: zoomSpan(fx0, t.t), scope, from: m.from, to: m.to, color: fx.highlight === false ? null : String(fx.highlight), region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } });
});
setZooms(out);
- // Its captions: planned as the build plans them (each waits for a zoom), mounted, placed as the card is at each one's peak.
+ const k = box.height / 1080;
+ const fxEnd = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total;
+ // Its slams (post-slam.mjs): planned, mounted and placed as the build places them -- as the card is at the first hit.
+ let splan: ReturnType<typeof slamPlan> = [];
+ try {
+ splan = slamPlan(entry, undefined, { zooms: out.map((z) => ({ ...z.span, i: z.i })), end: fxEnd, schedule: plan.narration as never });
+ } catch {
+ splan = [];
+ }
+ const placedSlams: LiveSlam[] = [];
+ {
+ const inset0 = Math.round(12 * k);
+ const bounds0 = { x: inset0, y: inset0, width: box.width - 2 * inset0, height: box.height - 2 * inset0 };
+ type Geo = { error?: string; card: Rect; word: Rect; lines: Rect[]; avoid: Rect[]; obstacles: Rect[] };
+ const all: Array<{ i: number; k: number; text: string; size: number; face: string; vars: Record<string, string> }> = [];
+ const geos: Array<Geo | null> = [];
+ for (const p of splan) {
+ if (follow) applyFollowState(followStateAt(follow, route, p.span.landings[0]), doc);
+ const g = p.scope ? (measureCaptionWords({ scope: p.scope, from: p.from, to: p.to, avoid: p.avoid }, doc) as Geo) : null;
+ geos.push(g && !g.error ? g : null);
+ const line = g && !g.error ? g.lines.reduce((a, l) => (l.height > a.height ? l : a), g.lines[0]) : null;
+ const size = slamSize(p.fx, line, k);
+ p.units.forEach((text: string, kk: number) => all.push({ i: p.i, k: kk, text, size, face: SLAM_FACE_STACK[p.fx.face as keyof typeof SLAM_FACE_STACK] ?? SLAM_FACE_STACK.jp, vars: slamVars(p.fx, size) }));
+ }
+ const boxes = mountSlams(all.length ? { css: slamCss(), units: all, dust: [...SLAM_DUST] } : null, doc);
+ splan.forEach((p, pi) => {
+ const g = geos[pi];
+ const cardEl = doc.querySelector("[data-post-card]");
+ const cardBox = g ? g.card : cardEl ? rect(cardEl) : null;
+ if (!cardBox || (p.scope && !g)) return;
+ const units = boxes.filter((b) => b.i === p.i).sort((a, b) => a.k - b.k);
+ const lay = slamLayout({ word: g ? g.word : null, card: cardBox, bounds: bounds0, units, place: p.fx.place, gap: Math.round(6 * k), protect: g ? [...g.lines, ...g.avoid] : [], obstacles: g ? g.obstacles : [] });
+ placedSlams.push({ i: p.i, span: p.span, fx: p.fx, scope: p.scope, from: p.from, to: p.to, centers: lay.centers, base: g ? g.word : null, where: lay.where });
+ });
+ }
+ setSlams(placedSlams);
+ // Its captions: planned as the build plans them (each waits for a zoom, and for a slam), mounted, placed as the card is at each one's peak.
let cplan: ReturnType<typeof captionPlan> = [];
try {
- cplan = captionPlan(entry, undefined, { zooms: out.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration as never });
+ cplan = captionPlan(entry, undefined, { zooms: [...out.map((z) => ({ ...z.span, i: z.i })), ...splan.map((p) => ({ t0: p.span.t0, t3: p.span.t3, i: p.i }))], end: fxEnd, schedule: plan.narration as never });
} catch {
cplan = [];
}
- const k = box.height / 1080;
const sizes = mountCaptions({ css: captionCss({ height: box.height, palette: paletteOfDoc(doc) }), chips: cplan.map((c) => ({ i: c.i, html: captionInnerHtml(c.text) })), k }, doc);
const inset = Math.round(12 * k);
// Free space only (as the build places it): the whole box, never over a word, the card's furniture, an attachment or the clock.
@@ -756,6 +853,38 @@ export default function PostItemPlayer({
});
setCaptionState({ list, stroke: Math.max(2, Math.round(2.4 * k)) }, doc);
}, [capsUp, s, follow, followNow, box.height]);
+ // The slams up now (post-slam.mjs): each unit's state on the item's clock, riding its words when the card pans; the
+ // frame's punch at each hit (the page's body moved, as the build moves the frame).
+ const slamsUp = slams.filter((p) => s >= p.span.t0 && s < p.span.t3);
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (!doc) return;
+ const k = box.height / 1080;
+ const list = slamsUp.flatMap((p) => {
+ let dx = 0;
+ let dy = 0;
+ if (follow && p.scope && p.base) {
+ const g = measureCaptionWords({ scope: p.scope, from: p.from, to: p.to, avoid: [] }, doc) as { error?: string; word: Rect };
+ if (!g.error) [dx, dy] = [g.word.x - p.base.x, g.word.y - p.base.y];
+ }
+ return slamListAt(p as never, s, dx, dy);
+ });
+ const sh = slamShakeAt(slamsUp.flatMap((p) => p.span.landings), s);
+ const amp = SLAM_MOTION.shake.amp * k;
+ setSlamState({ list, shake: list.length ? { x: sh.x * amp, y: sh.y * amp } : null }, doc);
+ }, [slamsUp, s, follow, followNow, box.height]);
+ // Its hits, as Play's clock crosses each landing while playing (a seek over one is silent).
+ const lastS = useRef(s);
+ useEffect(() => {
+ const prev = lastS.current;
+ lastS.current = s;
+ if (!playing || s < prev || s - prev > 0.5) return;
+ for (const p of slams) {
+ for (const h of slamHits(p.fx, p.span)) {
+ if (h.kind === "hit" && h.at > prev && h.at <= s) playTrailerHit(h, Number(p.fx.volume ?? 1));
+ }
+ }
+ }, [s, playing, slams]);
const clockSt = useMemo(() => (clock ? clockStateAt(clock, s) : null), [clock, s]);
useEffect(() => {
const doc = readFrame.current?.contentDocument;
@@ -783,6 +912,10 @@ export default function PostItemPlayer({
data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined}
data-post-zoom-fx={live ? String(live.i) : undefined}
data-post-captions={caps.length ? String(caps.length) : undefined}
+ data-post-slams={slams.length ? String(slams.length) : undefined}
+ data-post-slam-fx={slamsUp.length ? slamsUp.map((p) => String(p.i)).join(" ") : undefined}
+ data-post-slam-where={slams.length ? slams.map((p) => p.where).join(" ") : undefined}
+ data-post-slam-landed={slamsUp.length ? String(slamsUp.reduce((a, p) => a + p.span.landings.filter((L) => L <= s).length, 0)) : undefined}
data-post-clock={clockSt ? `${clockSt.time} ${clockSt.date}` : undefined}
data-post-clock-mode={clockSt ? clockSt.mode : undefined}
data-post-clock-gap={clockSt && clockSt.gapOpacity > 0 ? clockSt.gap : undefined}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -90,6 +90,7 @@ Inbox cannot disagree about what is wrong with one.
| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
+| `posts fx <project> <item> 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]` · `set <n> [those flags]` | a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**) |
| `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) |
| `posts fit <project> [--all \| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]` | narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is |
| `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -790,6 +790,23 @@ build's words (`clockErrors`, `validateClockRender`, `report-to-video/post-clock
| one item's clock -- on (or `on: false`: not on this item though the cut's is) | post bench, the clock's row (**remove**) | `umtool posts fx <p> <item> add clock [--off]` · `remove <n>` | `fx: {add: {kind: "clock"}}` |
| `rewind` `auto` (an earlier post rewinds) \| `on` (rewinds anyway) \| `off` (cuts straight to its time) | the clock's **rewind** | `umtool posts fx <p> <item> set <n> --rewind on\|off\|auto` | `fx: {set: <i>, patch: {rewind}}` |
+## A slam (a trailer-style title slam over a word as it is read)
+
+`fx: [{kind: "slam", text, match, …}]` on a post item ([report-video.md](report-video.md#a-slam): the shape, the
+time, the place, the one exemption, the sound, the render). One writer, `updatePostFx`, refused in the build's words
+(`slamErrors`, `report-to-video/post-slam.mjs`, through `validatePostFx`; a row that would cover the words being read,
+`slamCoverErrors`). Play and the bench draw the build's own glyphs, live, and Play sounds the hits.
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a slam -- `text` (≤ 12 characters; one glyph, one hit), `match` (a word or a phrase: "Baji Quan"), `occurrence`, `target`; `whole` (the text as one unit, one hit) | post bench: click a word (shift-click: a phrase), type the glyphs, **Slam here** | `umtool posts fx <p> <item> add slam --text "不動心" --match "Fudōshin" [--whole]` | `POST /api/report/post-item {project, op: "fx", id, fx: {add: {kind: "slam", text, match}}, token}` |
+| WHEN -- the hits spread evenly over the matched words' spoken span (the first on its start, the last on its end); `gap` 0.12–2 s spaces them instead; `at` (item seconds) moves the first; no span: 0.45 s apart | the slam's row (its hits; **go**) | `set <n> --gap 0.4` · `set <n> --at 4.1` (`default` clears one) | `fx: {set: <i>, patch: {gap, at}}` |
+| THE LOOK -- `hold` 0.3–4 s after the last hit (1.6), `fromScale` 1.5–8 (3.5), `color` (#f5c542) and `outline` (#000000), `outlineWidth` 0–30 px (at a 120 px glyph; default 11% of the glyph), `size` 40–320 px at 1080 (by the words' line), `face` `jp` \| `sc` \| `tc` \| `kr` (Noto Sans CJK Black; 八极拳 reads `sc`) | — | `set <n> --hold 2 --from-scale 4 --color #ffd700 --outline #000000 --outline-width 14 --size 130 --face sc` | `fx: {set: <i>, patch: {…}}` |
+| WHERE -- `place` `over-match` (above the words' line; below it when above is out of the frame or over a word read at a hit) \| `center` (the card's middle) | — | `set <n> --place center` | `fx: {set: <i>, patch: {place}}` |
+| THE SOUND -- `sfx` `trailer-hit` \| `off`, `volume` 0–3 × the hit's level (1), `swell` (the teaser's swell under the hold) | — | `set <n> --sfx off` · `--volume 0.7` · `--swell` / `--no-swell` | `fx: {set: <i>, patch: {sfx, volume, swell}}` |
+| remove one | the slam's **remove** | `umtool posts fx <p> <item> remove <n>` | `fx: {remove: <i>}` |
+| list them, each with its hits and where they came from | the block's rows; the plan strip marks each (yellow, a tick per hit) | `umtool posts fx <p> <item> [ls] [--json]` | — |
+
## The pace (a burst played back to back)
| Knob | In umtool | From a terminal | Route |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -702,6 +702,82 @@ chip with its notch; the underline apart) and laid over the card (`postSegmentAr
bench mount the same markup in the card frame (`mountCaptions`, `setCaptionState`) on the
same curve. The post record (`<id>.post.json`) keeps each caption's time, span, place and box.
+### A slam
+
+A post item may carry a SLAM: a corny movie-trailer title slam over the card, a joke as
+a word is read (`report-to-video/post-slam.mjs`; operator, 4 Nov: "the japanese characters
+of 'fudoshin' (不動心) pop in with three trailer hits like a corny effect, … gold with a
+black outline, starting large and shrinking before hitting the page like standard trailer
+hits"; "three hits evenly spaced over the pronunciation of the word, one for each
+character"; "do it above the word on the page"; "do the same with baji quan (八极拳)").
+
+```jsonc
+"fx": [{
+ "kind": "slam",
+ "text": "不動心", // ≤ 12 characters: one unit (and one hit) per glyph; "whole": true -- the text as one
+ "match": "Fudōshin", // the word or phrase it lands over ("Baji Quan": both words), as a word zoom's
+ "target": "post", "occurrence": 1,
+ "at": 4.2, // the first hit; absent: the words' spoken start in the take's word timings
+ "gap": 0.45, // seconds between hits; absent: spread over the words' spoken span
+ "hold": 1.6, // held after the last hit (0.3–4), then a 0.35 s fade
+ "fromScale": 3.5, // how big a glyph comes in (1.5–8 × its size at rest)
+ "color": "#f5c542", "outline": "#000000", "outlineWidth": 13, // gold, a thick black outline (px at a 120 px glyph)
+ "place": "over-match", // "over-match" (default): above the words' line | "center": the card's middle
+ "size": 120, // px at 1080; absent: 2.5 × the words' line, 64–170
+ "face": "jp", // Noto Sans CJK JP | SC | TC | KR, Black (八极拳: "sc")
+ "sfx": "trailer-hit", // | "off"
+ "volume": 1, "swell": false // × the hit's level; the teaser's low swell under the hold
+}]
+```
+
+**When**: each glyph LANDS on a hit. With word timings the hits spread evenly over the
+matched words' SPOKEN span -- the first on the first word's start, the last on the last
+word's end ("Baji"'s start to "Quan"'s end), the rest evenly between; `gap` spaces them
+instead; `at` moves the first hit (keeping the span's length when the words give one). With
+no spoken span (an `at` alone, an un-narrated post: the reading estimate's start) they are
+0.45 s apart, never closer than 0.12 s. A glyph comes in 0.2 s before its landing -- the
+TEASER's slam (`TEASER_MOTION`: power3.in down past rest to 0.968, a power2.out settle over
+0.5 s, its blur focusing), from `fromScale` × its size and smeared, with ghost copies
+trailing the shrink -- and hits with a flash behind it, a shock ring, dust thrown up, and
+the frame's PUNCH (9 px at 1080, dying over 0.3 s). After the last hit it holds `hold`,
+then fades over 0.35 s; the hold is shortened to end by the item's last second (a stack
+card's media phase). A slam up with a word zoom is refused, two slams of a post up at once
+too, and a CAPTION up with it WAITS for it to be gone (the slam first, then the chip).
+
+**Where**: the units side by side, centred on the matched words and just ABOVE their line;
+below it when there is no room above in the frame, or when the row would cover a word being
+read as a glyph lands; `center`: the card's middle. Kept in the frame. It rides the card's
+pan (read-follow): every frame is placed by where the words are drawn then.
+
+**The one exemption** (deliberate, the gag): the landed row may cover the line ABOVE the
+word -- for the slam's own window only (its hits, its hold, its fade). It is drawn OVER the
+card, never in it (no `data-w`, no `data-post-block`), so the read-follow geometry and
+`readInViewErrors` are measured without it; what it may NOT cover is checked instead
+(`slamCoverErrors`): the matched words themselves, and the words whose read starts within
+0.25 s of a hit. When neither above nor below is clear the build refuses, in its own words.
+The record (`<id>.post.json` `slams`) keeps its hits, its span, its place and how many other
+things drawn it lay over (`covers`).
+
+**The sound**: one TRAILER HIT per glyph at its landing -- the teaser's own generator
+(`report-to-video/trailer-hits.mjs`, factored out of the teaser card the ferret-rescue
+finale plays: a pitch-dropping sine boom with its octave, a band-passed noise punch, a low
+rumble, a short echo, under a −6 dBFS limiter), its title tier -- synthesised in ffmpeg, no
+samples; with `swell` the teaser's low swell under the hold. Mixed into the segment's audio
+after the item's own sound and the read (no duck), under a ceiling just below full scale.
+
+**The render**: on the card page as drawn at the first hit, the words measured, the units
+mounted at their size in the slam's face and placed, then the layer shot alone on a clear
+page at every frame of its span (each distinct state once) and laid over everything in the
+segment; the punch is the frame padded in the card's ground and cropped back on `t`. Play
+and the bench mount the same markup in the card frame (`mountSlams`, `setSlamState`) and
+shake the page's body; Play sounds each hit as its clock crosses a landing (WebAudio, the
+generator's own formulas through the graph's filters -- close to the render's mix, without
+its limiter). The segment key carries the slam's fields (the entry) and `slam` (its drawing
+version, its motion, its hit's tier and level): an item without one keeps its key.
+
+From a terminal: `umtool posts fx <p> <item> add slam --text "不動心" --match "Fudōshin"`
+([knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)).
+
### The clock
A post item may show its CLOCK (`report-to-video/post-clock.mjs`; operator, 4 Nov: "show a
diff --git a/umtool/e2e/post-slam.spec.ts b/umtool/e2e/post-slam.spec.ts
@@ -0,0 +1,119 @@
+import { test, expect, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// A POST ITEM's SLAM (report-to-video/post-slam.mjs; knobs.md, "A slam"): a
+// trailer-style title slam -- each glyph huge, shrinking onto the card just
+// above the matched words and hitting, one trailer hit per glyph. Fixture:
+// e2e/fixtures/post-narration-fixture.mjs -- p-11 "The video speaks for
+// itself." narrated by a 2 s take (no word timings: the reading estimate),
+// p-13 words only.
+//
+// POST_SLAM_SHOTS=<dir> screenshots there
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const PROJECT = "reports/post-narration-fixture";
+const SHOTS = process.env.POST_SLAM_SHOTS ?? null;
+
+type Entry = { id: string; fx?: Array<Record<string, unknown>> };
+const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record<string, unknown> };
+const timeline = () => manifest().timeline;
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ rmSync(path.join(DIR, "notes.json"), { force: true });
+});
+
+type Box = { x: number; y: number; width: number; height: number };
+const overlap = (a: Box, b: Box) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
+/** In the card frame: each slam unit's glyph box, and the card words'. */
+const slamBoxes = (page: Page) =>
+ page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body) => {
+ const r = (el: Element) => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ const doc = body.ownerDocument;
+ return {
+ units: Array.from(doc.querySelectorAll(".pslam")).map((el) => ({ id: el.getAttribute("data-post-fx-slam"), opacity: Number((el as HTMLElement).style.opacity), text: el.querySelector(".pslam-front")?.textContent ?? "", ...r(el.querySelector(".pslam-front")!) })),
+ words: Array.from(doc.querySelectorAll("[data-w]")).map((w) => ({ id: w.getAttribute("data-w"), ...r(w) })),
+ inCard: Array.from(doc.querySelectorAll(".pslam")).some((el) => el.closest("[data-post-card]") !== null || !!el.querySelector("[data-w], [data-post-block]")),
+ };
+ });
+
+/** Play the item until every glyph has landed, then pause. */
+async function playUntilLanded(page: Page, id: string, n: number) {
+ const player = page.locator(`[data-post-play="${id}"]`);
+ await expect(player).toHaveAttribute("data-post-slams", "1", { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ await expect(player).toHaveAttribute("data-post-slam-landed", String(n), { timeout: 15_000 });
+ await page.locator("[data-play-toggle]").click();
+ return player;
+}
+
+test("A SLAM (operator, 4 Nov: 不動心 on \"Fudōshin\"): click a word -> type the glyphs -> Slam here -> saved; the bench marks its hits; Play lands three gold glyphs in a row just ABOVE the word, over no word of it, drawn over the card", async ({ page }) => {
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-11"));
+ const panel = page.locator('[data-post-zoom-panel="p-11"]');
+ await panel.locator('[data-post-zoom-word="2"]').click();
+ await expect(panel.locator("[data-post-slam-here]")).toBeDisabled();
+ await panel.locator("[data-post-slam-text]").fill("不動心");
+ await panel.locator("[data-post-slam-here]").click();
+ await expect(panel.locator('[data-post-slam-fx="0"]')).toBeVisible();
+ expect(timeline().find((e) => e.id === "p-11")!.fx).toEqual([{ kind: "slam", match: "speaks", text: "不動心" }]);
+ // No word timings: three hits from the reading estimate's start, SLAM_GAP apart.
+ await expect(panel.locator('[data-post-slam-fx="0"]')).toContainText("the estimate");
+ await expect(page.locator('[data-post-bench-slam-mark="0"]')).toBeVisible();
+ await expect(page.locator('[data-post-bench-slam-mark="0"] [data-post-bench-slam-hit]')).toHaveCount(3);
+ await expect(page.locator('[data-post-play="p-11"]')).toHaveAttribute("data-post-slams", "1", { timeout: 15_000 });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-slam-bench.png") });
+
+ // Play the cut: the three glyphs land, left to right, above the word.
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" }));
+ const player = await playUntilLanded(page, "p-11", 3);
+ await expect(player).toHaveAttribute("data-post-slam-where", "above");
+ const { units, words, inCard } = await slamBoxes(page);
+ expect(units.map((u) => u.text)).toEqual(["不", "動", "心"]);
+ expect(units.every((u) => u.opacity > 0)).toBe(true);
+ expect(units[0].x).toBeLessThan(units[1].x);
+ expect(units[1].x).toBeLessThan(units[2].x);
+ // Never over the word it lands on; sitting above its line; never in the card's words.
+ const word = words.find((w) => w.id === "post:2")!;
+ for (const u of units) {
+ expect(overlap(u, word)).toBe(0);
+ expect(u.y + u.height).toBeLessThanOrEqual(word.y + 2);
+ }
+ const mid = (units[0].x + units[2].x + units[2].width) / 2;
+ expect(Math.abs(mid - (word.x + word.width / 2))).toBeLessThan(word.width);
+ expect(inCard).toBe(false);
+ // The CJK is drawn by a face this machine has, at its Black weight.
+ expect(await page.frameLocator('[data-post-card-frame="read"]').locator(".pslam").first().evaluate((el) => el.ownerDocument.fonts.check("900 100px 'Noto Sans CJK JP'", "不動心"))).toBe(true);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-slam-play.png") });
+});
+
+test("A PHRASE (operator, 4 Nov: 八极拳 on \"Baji Quan\"): a two-word match, the SC face, three glyphs over the phrase; an at and no word span: the hits SLAM_GAP apart from it", async ({ page }) => {
+ const m = manifest();
+ Object.assign(m.timeline.find((e) => e.id === "p-13")!, { fx: [{ kind: "slam", text: "八极拳", match: "waiting for", face: "sc", at: 0.5 }] });
+ writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n");
+ await page.setViewportSize({ width: 1500, height: 1000 });
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-13" }));
+ await playUntilLanded(page, "p-13", 3);
+ const { units, words } = await slamBoxes(page);
+ expect(units.map((u) => u.text)).toEqual(["八", "极", "拳"]);
+ const phrase = words.filter((w) => w.id === "post:2" || w.id === "post:3");
+ expect(phrase).toHaveLength(2);
+ for (const u of units) for (const w of phrase) expect(overlap(u, w)).toBe(0);
+ expect(await page.frameLocator('[data-post-card-frame="read"]').locator(".pslam").first().evaluate((el) => el.ownerDocument.fonts.check("900 100px 'Noto Sans CJK SC'", "八极拳"))).toBe(true);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-slam-phrase.png") });
+});
diff --git a/umtool/lib/report/postFx.test.mjs b/umtool/lib/report/postFx.test.mjs
@@ -111,3 +111,31 @@ test("posts fx add caption: the chip's text kept (CJK too), timed by the reading
r = await cli(["fx", "cap", "p-1", "ls", "--json"]);
assert.deepEqual(JSON.parse(r.out).times, [{ i: 0, t: 1.5, source: "at" }]);
});
+
+test("posts fx add slam: its glyphs and word kept, its hits listed (the estimate's start, 0.45 s apart), its knobs set -- a zoom's refused on it, its own on a zoom", async () => {
+ const p = await project("slam", [item("1")]);
+ let r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "不動心", "--match", "barbecue"]);
+ assert.equal(r.code, 0, r.err);
+ // "barbecue" is word 7: 1 + 7/3.
+ assert.match(r.out, /#1 slam "不動心" on "barbecue" \(post, 1st\) hits at 3\.33, 3\.78, 4\.23 s \(the reading estimate\), gone by 6\.18 s · per glyph, 3\.5× in, held 1\.6 s, over-match, #f5c542\/#000000, face jp, sfx trailer-hit/);
+ r = await cli(["fx", "slam", "p-1", "set", "1", "--gap", "0.3", "--face", "sc", "--from-scale", "4", "--whole", "--swell", "--volume", "0.8"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).timeline[0].fx, [{ kind: "slam", text: "不動心", match: "barbecue", gap: 0.3, face: "sc", fromScale: 4, whole: true, swell: true, volume: 0.8 }]);
+ r = await cli(["fx", "slam", "p-1", "set", "1", "--per-glyph", "--no-swell", "--gap", "default"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).timeline[0].fx[0], { kind: "slam", text: "不動心", match: "barbecue", face: "sc", fromScale: 4, volume: 0.8 });
+ r = await cli(["fx", "slam", "p-1", "ls", "--json"]);
+ assert.deepEqual(JSON.parse(r.out).times[0].landings, [3.33, 3.78, 4.23]);
+ r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "心", "--match", "barbecue", "--scale", "2"]);
+ assert.equal(r.code, 2);
+ assert.match(r.err, /--scale is not a slam's knob/);
+ r = await cli(["fx", "slam", "p-1", "add", "word-zoom", "--match", "myself", "--at", "1", "--from-scale", "2"]);
+ assert.equal(r.code, 2);
+ assert.match(r.err, /--from-scale is a slam's knob/);
+ r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "心", "--match", "nowhere"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /match "nowhere" is not in the post's words/);
+ r = await cli(["fx", "slam", "p-1", "add", "slam", "--text", "心"]);
+ assert.equal(r.code, 2);
+ assert.match(r.err, /add slam needs --match/);
+});
diff --git a/umtool/lib/report/postFxCli.mjs b/umtool/lib/report/postFxCli.mjs
@@ -10,6 +10,10 @@
// [--scale s] [--hold s] [--lead s] [--ease out|inOut|snap] [--highlight #rrggbb|off]
// umtool posts fx <p> <item> add caption --match "…" --text "…" [--target …] [--occurrence n] [--at s]
// [--lead s] [--hold s] [--place below|above|side] (post-caption.mjs)
+// umtool posts fx <p> <item> 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] (post-slam.mjs)
// 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>]
@@ -23,6 +27,7 @@ import {
} 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";
@@ -35,6 +40,9 @@ export const FX_USAGE = [
" umtool posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post|quoted|parent:<i>] [--occurrence n]",
" [--at s] [--lead s] [--hold s] [--place below|above|side] [--json]",
" umtool posts fx <project> <item> add clock [--rewind auto|on|off] [--off]",
+ " umtool posts fx <project> <item> 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] [--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",
@@ -53,14 +61,27 @@ export const FX_USAGE = [
" 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 <p> 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.",
].join("\n");
export class FxError extends Error {}
-const NUM_KEYS = { "--at": "at", "--scale": "scale", "--hold": "hold", "--lead": "lead", "--occurrence": "occurrence" };
+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"];
-/** The flags as an effect patch (null: back to the default). */
-export function fxPatchOf(str) {
+/** 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;
@@ -84,6 +105,14 @@ export function fxPatchOf(str) {
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;
+ }
+ 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;
@@ -99,10 +128,24 @@ export function fxLines(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)${clk ? ", its clock" : ""}${isNarrated(e) || !nz ? "" : " (not narrated: a zoom needs at)"}`,
+ `${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 (${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` : ""}`;
+ }
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)"}`;
@@ -122,7 +165,7 @@ export function fxLines(e, render) {
}
/** `umtool posts fx …` (postsCli.mjs routes it here). */
-export async function fxCommand(project, words, { json = false, out = (s) => console.log(s), str, off = false }) {
+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 ?? {};
@@ -133,7 +176,12 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
const say = (entry, extra = {}) => {
if (json) {
const ct = captionTimes(entry, render);
- 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] : t)), ...extra }, null, 2));
+ 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"));
};
@@ -147,8 +195,18 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
return 0;
}
if (verb === "add") {
- if (arg !== "word-zoom" && arg !== "caption" && arg !== "clock") throw new FxError("add names the effect: add word-zoom --match \"…\" | add caption --match \"…\" --text \"…\" | add clock");
- const patch = Object.fromEntries(Object.entries(fxPatchOf(str)).filter(([, v]) => v !== null));
+ 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 \"<the glyphs that slam in>\"");
+ if ((typeof patch.match !== "string" || !patch.match.trim()) && patch.at === undefined) throw new FxError("add slam needs --match \"<the word it lands on>\" (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)`);
@@ -183,8 +241,8 @@ export async function fxCommand(project, words, { json = false, out = (s) => con
}
if (verb === "set") {
const i = index();
- const patch = fxPatchOf(str);
- 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");
+ 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");
const { result } = await write({ set: i, patch });
say(result.entry);
return 0;
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -129,7 +129,8 @@ export const POSTS_USAGE = [
" 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] … | add caption --match \"…\" --text \"…\" | set <n> … | remove <n>",
" a WORD ZOOM (the card pushed in on a word) or a CAPTION (a chip explaining a phrase) as it is read,",
- " or its CLOCK (add clock [--rewind auto|on|off] [--off]) (umtool posts fx --help)",
+ " or its CLOCK (add clock [--rewind auto|on|off] [--off]), or a SLAM (add slam --text \"不動心\" --match \"…\":",
+ " a trailer-style title slam, a trailer hit per glyph) (umtool posts fx --help)",
" umtool posts clock <project> [on|off|default] [--zone <IANA zone>] the cut's CLOCK default: each post's time on its card, run between items",
" 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/,",
@@ -154,7 +155,7 @@ export const POSTS_USAGE = [
" umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment",
].join("\n");
-const VALUED = new Set(["--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", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone"]);
+const VALUED = new Set(["--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", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -455,7 +456,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
err(FX_USAGE);
return 2;
}
- return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str, off: flags.has("--off") });
+ return await fxCommand(await projectOf(projectArg, root), words.slice(2), { json, out, str, off: flags.has("--off"), has: (f) => flags.has(f) });
}
if (verb === "clock") {
const { CLOCK_USAGE, clockCommand } = await import("./postFxCli.mjs");
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -216,6 +216,7 @@ import {
// The snap itself (a montage's window snaps with it too), re-exported for the tests.
import { snap } from "./snap.mjs";
import { buildPostSegment } from "./post-render.mjs";
+import { TRAILER_AUDIO, trailerHitsGraph } from "./trailer-hits.mjs";
import { planContext, planContextOf } from "./post-conversation.mjs";
/** The item before post item `id` with its own context (post-join.mjs: what the item opens on), or null. */
@@ -2702,94 +2703,18 @@ async function buildNarratedCardSegment(card, render, outDir, nodes, framing, re
export const teaserRecordPath = (seg) => seg.replace(/\.mp4$/, ".teaser.json");
/** The teaser sound's level and ceiling: `limit` is −6 dBFS; `level` is set against the ferret cut's loudness (README). */
-export const TEASER_AUDIO = Object.freeze({ level: 1.4, limit: 0.5 });
-
-/** A number for an aevalsrc expression: 6 decimals, no trailing zeros. */
-const ev6 = (v) => {
- const s = (Math.round(Number(v) * 1e6) / 1e6).toFixed(6).replace(/\.?0+$/, "");
- return s === "-0" ? "0" : s;
-};
+export const TEASER_AUDIO = TRAILER_AUDIO;
/**
* The teaser's sound, as one filtergraph fragment from no inputs to `[ta]`:
- * `hits` (`teaserHits`) synthesised in ffmpeg, no samples.
- *
- * A hit is three layers, each summed over every hit in one `aevalsrc` and
- * gated to its own span, so each starts on the sample its time names:
- * - the boom: a sine whose pitch drops from f0 to f1 (most of the way in
- * ~0.4 s), with its octave for body, on an exponential decay (`decay` is
- * the time constant; it is inaudible by ~7×) after a 3 ms attack;
- * - the punch: a burst of noise (50 ms time constant), band-passed (180 Hz–3.2 kHz);
- * - the tail: a low noise decay (low-passed at 260 Hz) under it.
- * A swell is the boom's sine rising f0 → f1 under an envelope that peaks
- * three quarters of the way through `dur` and settles, with a breath of the
- * low noise. A riser (a dip's, under the black) is a sub whose pitch climbs
- * f0 → f1 over `dur` and a noise swell -- its own layer, band-passed
- * 400 Hz–6.5 kHz, present only when there is a riser -- both rising (the sub
- * squared, the noise cubed) to their peak at the first hit and released over
- * `decay`. The noise is a hash of the sample number, not `random()`, so it
- * is the same whatever else is in the graph. The sum takes a short low-passed
- * echo, then `level`, then a limiter at −6 dBFS (`limit`, no auto-level,
- * latency compensated) so hits that overlap still sum cleanly; trimmed and
- * padded to exactly `seconds`. No hits: digital silence.
+ * `hits` (`teaserHits`) synthesised in ffmpeg, no samples -- the trailer hits'
+ * generator (trailer-hits.mjs trailerHitsGraph, which a post item's slam plays
+ * too), its labels the teaser's own (`t`). The layers, the echo, the level and
+ * the limiter are described there; the graph is byte for byte what it was
+ * before the generator was factored out.
*/
export function teaserAudioGraph(hits, { seconds, render, level = TEASER_AUDIO.level, limit = TEASER_AUDIO.limit }) {
- const rate = render.audioRate;
- const layout = render.audioChannels === 1 ? "mono" : "stereo";
- const len = ev6(seconds);
- const tail = `atrim=end=${len},apad=whole_dur=${len},asetpts=PTS-STARTPTS[ta]`;
- if (!hits.length) return `anullsrc=channel_layout=${layout}:sample_rate=${rate},${tail}`;
- const noise = "(2*(sin(n*12.9898+78.233)*43758.5453-floor(sin(n*12.9898+78.233)*43758.5453))-1)";
- const boom = [];
- const punch = [];
- const rumble = [];
- const whoosh = [];
- for (const h of hits) {
- const a = ev6(h.at);
- const u = `(t-${a})`;
- const g = ev6(h.gain);
- if (h.kind === "riser") {
- const D = ev6(h.dur);
- const v = `min(${u},${D})`;
- const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * h.dur))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`;
- const rel = `clip((${ev6(h.dur + h.decay)}-${u})/${ev6(h.decay)},0,1)`;
- const span = ev6(h.dur + h.decay);
- boom.push(`if(between(t,${a},${a}+${span}),${g}*0.5*pow(${v}/${D},2)*${rel}*sin(2*PI*${phase}),0)`);
- whoosh.push(`if(between(t,${a},${a}+${span}),${g}*0.6*pow(${v}/${D},3)*${rel}*${noise},0)`);
- continue;
- }
- if (h.kind === "swell") {
- const D = h.dur;
- const peak = ev6(D * 0.75);
- const v = `min(${u},${ev6(D)})`;
- const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * D))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`;
- const env = `pow(sin(PI/2*min(1,${u}/${peak})),2)*exp(-max(0,${u}-${peak})/${ev6(h.decay)})`;
- const span = ev6(D * 0.75 + h.decay * 7);
- boom.push(`if(between(t,${a},${a}+${span}),${g}*0.42*${env}*sin(2*PI*${phase}),0)`);
- rumble.push(`if(between(t,${a},${a}+${span}),${g}*0.5*${env}*${noise},0)`);
- continue;
- }
- const k = 0.13; // the pitch drop's time constant
- const phase = `(${ev6(h.f1)}*${u}+${ev6((h.f0 - h.f1) * k)}*(1-exp(-${u}/${k})))`;
- const span = ev6(h.decay * 7);
- boom.push(
- `if(between(t,${a},${a}+${span}),${g}*0.3*min(1,${u}/0.003)*exp(-${u}/${ev6(h.decay)})*` +
- `(sin(2*PI*${phase})+0.6*exp(-${u}/${ev6(h.decay * 0.6)})*sin(4*PI*${phase})),0)`,
- );
- punch.push(`if(between(t,${a},${a}+0.25),${g}*0.5*exp(-${u}/0.05)*${noise},0)`);
- rumble.push(`if(between(t,${a},${a}+${ev6(Math.min(2.6, h.decay * 6))}),${g}*0.32*min(1,${u}/0.02)*exp(-${u}/${ev6(h.decay * 1.3)})*${noise},0)`);
- }
- const src = (terms) => `aevalsrc=exprs='${terms.length ? terms.join("+") : "0"}':s=${rate}:c=${layout}:d=${len}`;
- // The riser's layer only when there is one: a teaser without a dip writes the graph it always did.
- const w = whoosh.length ? [`${src(whoosh)},highpass=f=400,lowpass=f=6500[tw]`] : [];
- return [
- `${src(boom)}[tb]`,
- `${src(punch)},highpass=f=180,lowpass=f=3200[tp]`,
- `${src(rumble)},lowpass=f=260,lowpass=f=260[tr]`,
- ...w,
- `[tb][tp][tr]${w.length ? "[tw]" : ""}amix=inputs=${3 + w.length}:normalize=0,aecho=1:1:90|190:0.18|0.09,lowpass=f=5000,` +
- `volume=${ev6(level)},alimiter=limit=${ev6(limit)}:level=0:latency=1:attack=2:release=80,${tail}`,
- ].join(";");
+ return trailerHitsGraph(hits, { seconds, rate: render.audioRate, layout: render.audioChannels === 1 ? "mono" : "stereo", level, limit, prefix: "t" });
}
/** The teaser segment's encode: its frames, its sound, the shared parameters. */
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -27,6 +27,7 @@ import {
claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck,
} from "./factcheck.mjs";
import { resolveCounter } from "./counter.mjs";
+import { TRAILER_HIT_TIERS, TRAILER_SWELL } from "./trailer-hits.mjs";
import { DECK_PAD_X, COUNTER_CELL } from "./modules/design.mjs";
import {
DECK_DEFAULTS, MARKER_ALIGNS, MARKER_DEFAULT_COLOR, MARKER_LAYOUTS, MARKER_LIMITS, MARKER_PALETTE_KEYS, markerShapeErrors,
@@ -3160,12 +3161,8 @@ export function teaserHits(entry, D = 0.5, fps = 30) {
const { gain, f0, f1 } = DIP_RISER;
out.push({ kind: "riser", at, role: "dip", gain, decay: 0.04, f0, f1, dur: Math.round((end - at) * 10000) / 10000 });
}
- const HIT = {
- title: { gain: 1, decay: 0.42, f0: 92, f1: 40 },
- overline: { gain: 0.72, decay: 0.34, f0: 96, f1: 44 },
- kicker: { gain: 0.8, decay: 0.36, f0: 94, f1: 42 },
- sub: { gain: 0.42, decay: 0.16, f0: 120, f1: 64 },
- };
+ // The tiers are the trailer hits' (trailer-hits.mjs, which a post item's slam plays too).
+ const HIT = TRAILER_HIT_TIERS;
lines.forEach((l, i) => {
out.push({ kind: "hit", at: times.lines[i].impact, role: l.role, ...HIT[l.role] });
if (l.sub && !l.together && times.lines[i].subAt != null) {
@@ -3173,7 +3170,7 @@ export function teaserHits(entry, D = 0.5, fps = 30) {
}
});
if (tail && times.tailAt != null) {
- out.push({ kind: "swell", at: times.tailAt, role: "tail", gain: 0.34, decay: 0.7, f0: 46, f1: 62, dur: times.tailDur });
+ out.push({ kind: "swell", at: times.tailAt, role: "tail", ...TRAILER_SWELL, dur: times.tailDur });
}
return out;
}
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -80,6 +80,8 @@
"./word-zoom": "./word-zoom.mjs",
"./post-caption": "./post-caption.mjs",
"./post-clock": "./post-clock.mjs",
+ "./post-slam": "./post-slam.mjs",
+ "./trailer-hits": "./trailer-hits.mjs",
"./read-follow": "./read-follow.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -27,6 +27,8 @@ import { blurFilters, blurOn, censorEntry, labelFilter } from "./post-censor.mjs
import { sceneEntry } from "./post-media-scene.mjs";
import { CAPTION_OUT, CAPTION_SLIDE, captionCss, captionInnerHtml, captionPlan, measureCaptionWords, mountCaptions, placeCaption, setCaptionState, slideDir } from "./post-caption.mjs";
import { clockCss, clockFace, clockFrameTimes, clockHtml, clockPlan, clockStateAt, measureClockPlace, mountClock, setClockState } from "./post-clock.mjs";
+import { SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, setSlamState, slamCss, slamCoverErrors, slamHits, slamLayout, slamListAt, slamPlan, slamShakeExpr, slamSize, slamVars } from "./post-slam.mjs";
+import { TRAILER_AUDIO, TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs";
import { panelReadErrors } from "./post-thread.mjs";
import { applyJoinState, endMediaOf } from "./post-join.mjs";
import { applyVisitState } from "./post-link-visit.mjs";
@@ -87,7 +89,7 @@ export function scrollExpr(keys) {
*
* @returns {string[]}
*/
-export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null }) {
+export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath, narration = null, zooms = [], follow = null, panelFiles = [], join = null, map = null, captionFx = [], clock = null, slams = [], slamHitList = [] }) {
const fps = render.fps ?? 30;
const T = plan.total;
const inputs = [];
@@ -309,10 +311,30 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
cur = next;
}
}
+ // SLAMS (post-slam.mjs): their frames shot alone over the whole box, laid over everything while each is up; then
+ // the frame's punch at each hit -- the box padded in the card's ground and cropped back, moved on t.
+ for (const [si, sl] of slams.entries()) {
+ const li = add(["-f", "concat", "-safe", "0", "-i", sl.list]);
+ parts.push(`[${li}:v]fps=${fps},format=rgba,setsar=1,setpts=PTS-STARTPTS+${num(sl.t0)}/TB[slm${si}]`);
+ const next = `b${++n}`;
+ parts.push(`[${cur}][slm${si}]overlay=x=0:y=0:eof_action=pass:enable='between(t,${num(sl.t0)},${num(sl.t3)})'[${next}]`);
+ cur = next;
+ }
+ const landings = slams.flatMap((sl) => sl.landings ?? []);
+ if (landings.length) {
+ const amp = SLAM_MOTION.shake.amp * (box.height / 1080);
+ const P = Math.ceil(amp * 2.2) + 2;
+ const bg = String(render.palette?.bg ?? "#12100c").replace("#", "0x");
+ const next = `b${++n}`;
+ parts.push(`[${cur}]pad=iw+${2 * P}:ih+${2 * P}:${P}:${P}:color=${bg},crop=${box.width}:${box.height}:'${P}+${slamShakeExpr(landings, "x", amp)}':'${P}+${slamShakeExpr(landings, "y", amp)}'[${next}]`);
+ cur = next;
+ }
parts.push(`[${cur}]format=yuv420p${place.length ? `,${place.join(",")}` : ",setsar=1"}[v]`);
const sil = add(["-f", "lavfi", "-t", num(T), "-i", `anullsrc=channel_layout=stereo:sample_rate=${render.audioRate ?? 48000}`]);
// Narrated (post-narration.mjs): the item's own sound is the bed the narrator reads over -- muffled, then clean.
- const media = narration && plan.narration ? "pm" : "a";
+ // THE SLAM's HITS (post-slam.mjs, trailer-hits.mjs): mixed in after the item's own sound and the read -- no duck.
+ const outA = slamHitList.length ? "apre" : "a";
+ const media = narration && plan.narration ? "pm" : outA;
if (audio.length) {
parts.push(...audio.map((a) => a.chain));
parts.push(`[${sil}:a]${audio.map((a) => `[${a.label}]`).join("")}amix=inputs=${audio.length + 1}:normalize=0:duration=first[${media}]`);
@@ -322,7 +344,12 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render
// A take that says a slur the cut masks (post-slurs.mjs takeBleeps): silenced or beeped over it, on the take's own clock.
const bl = narration.bleeps?.spans?.length ? bleepFilters(`${vi}:a`, "pnbl", narration.bleeps, { audioRate: render.audioRate ?? 48000, seconds: narration.bleeps.seconds ?? 600 }) : [];
parts.push(...bl);
- parts.push(...postNarrationFilters({ media: "pm", voice: bl.length ? "pnbl" : `${vi}:a`, out: "a", sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 }));
+ parts.push(...postNarrationFilters({ media: "pm", voice: bl.length ? "pnbl" : `${vi}:a`, out: outA, sch: plan.narration, gainDb: narration.gainDb ?? 0, audioRate: render.audioRate ?? 48000 }));
+ }
+ if (slamHitList.length) {
+ parts.push(trailerHitsGraph(slamHitList, { seconds: T, rate: render.audioRate ?? 48000, layout: "stereo", prefix: "sl" }));
+ // A ceiling just under full scale: a hit on a loud word never clips (the read is untouched below it).
+ parts.push(`[apre][sla]amix=inputs=2:normalize=0:duration=first,alimiter=limit=0.95:level=0:latency=1:attack=2:release=60[a]`);
}
return [
"-nostdin", "-v", "error", "-y",
@@ -367,7 +394,7 @@ async function loadChromium() {
* stack layout. The page is a file beside them, so its faces and the parent
* shot load from disk (an about:blank page may not read file: urls).
*/
-export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null, captions = [], clock = null, obstacles = [] }) {
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout, avatars = {}, zooms = [], redaction = null, follow = null, total = 0, joinFrom = null, captions = [], clock = null, obstacles = [], slams = [] }) {
await mkdir(dir, { recursive: true });
const fonts = {
regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
@@ -466,6 +493,7 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la
if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total });
// A caption covers none of the attachments (`obstacles`: their boxes) nor the clock.
if (captions.length) out.captions = await shootCaptions(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, captions, redaction, follow, obstacles: [...obstacles, ...(out.clock ? [out.clock.box] : [])] });
+ if (slams.length) out.slams = await shootSlams(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, slams, redaction, follow });
} finally {
await browser.close();
}
@@ -768,6 +796,128 @@ export async function shootCaptions(browser, entry, { box, render, dir, fonts, p
}
/**
+ * Each SLAM's FRAMES (post-slam.mjs): on the card page as it is drawn at its
+ * first hit (read-follow's state then), its words measured -- the matched
+ * words' lines and the words read at a hit, which it may not cover, and the
+ * rest of what is drawn, which it may (the gag, for its window) -- the units
+ * mounted at their size, the row placed (slamLayout: above the line, else
+ * below it; refused when neither is clear), then the layer shot alone on a
+ * clear page at every frame of its span (each distinct state once; a pan
+ * moves the row with the words, measured frame by frame) and a concat list
+ * holding each for its frames. `slams`: slamPlan's. Returns `[{ ...slam,
+ * list, t0, t3, layout, size, shots }]`.
+ */
+export async function shootSlams(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, slams, redaction = null, follow = null }) {
+ const fps = render.fps ?? 30;
+ const k = box.height / 1080;
+ const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" });
+ const page = await ctx.newPage();
+ const av = Object.fromEntries(Object.entries(avatars).map(([h, f]) => [h, pathToFileURL(f).href]));
+ const out = [];
+ try {
+ const file = path.join(dir, "slam.html");
+ await writeFile(file, postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase: "read", parentShotUrl, avatars: av, redaction, follow: !!follow, thread: follow?.thread ?? null }), "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ await page.evaluate(() => document.fonts.ready.then(() => true));
+ const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null;
+ const stateAt = async (s) => {
+ if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s));
+ };
+ const inset = Math.round(12 * k);
+ const bounds = { x: inset, y: inset, width: box.width - 2 * inset, height: box.height - 2 * inset };
+ const cardRect = () => page.evaluate(() => {
+ const b = document.querySelector("[data-post-card]")?.getBoundingClientRect();
+ return b ? { x: b.left, y: b.top, width: b.width, height: b.height } : null;
+ });
+ for (const p of slams) {
+ await stateAt(p.span.landings[0]);
+ // Judged at each hit (a pan's words too): what it may not cover, and what it lies over.
+ const looks = [];
+ if (p.scope) {
+ for (const L of follow ? p.span.landings : [p.span.landings[0]]) {
+ await stateAt(L);
+ const g = await page.evaluate(measureCaptionWords, { scope: p.scope, from: p.from, to: p.to, avoid: p.avoid });
+ if (g.error) throw new Error(`${entry.id}: slam ${p.i + 1}: its words are ${g.error}`);
+ looks.push(g);
+ }
+ await stateAt(p.span.landings[0]);
+ }
+ const geo = looks[0] ?? null;
+ const card = geo ? geo.card : await cardRect();
+ if (!card) throw new Error(`${entry.id}: slam ${p.i + 1}: the card is not drawn`);
+ // Its size by the words' line (one line's height, not a phrase's wrapped box).
+ const line = geo ? geo.lines.reduce((a, l) => (l.height > a.height ? l : a), geo.lines[0]) : null;
+ const size = slamSize(p.fx, line, k);
+ const units = p.units.map((text, kk) => ({ i: p.i, k: kk, text, size, face: SLAM_FACE_STACK[p.fx.face] ?? SLAM_FACE_STACK.jp, vars: slamVars(p.fx, size) }));
+ const arg = { css: slamCss(), units, dust: [...SLAM_DUST] };
+ await page.evaluate(mountSlams, arg);
+ await page.evaluate(() => document.fonts.ready.then(() => true));
+ // Measured again once its face is in.
+ const boxes = await page.evaluate(mountSlams, arg);
+ const layout = slamLayout({
+ word: geo ? geo.word : null, card, bounds, units: boxes, place: p.fx.place, gap: Math.round(6 * k),
+ protect: looks.flatMap((l) => [...l.lines, ...l.avoid]), obstacles: looks.flatMap((l) => l.obstacles),
+ });
+ const errs = slamCoverErrors(entry.id, p.i, layout);
+ if (errs.length) throw new Error(errs.join("; "));
+ const q = { ...p, centers: layout.centers };
+ // Shot alone: the card hidden, the page clear.
+ await page.evaluate(() => {
+ const st = document.createElement("style");
+ st.setAttribute("data-pslam-solo", "");
+ st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-fx-slams]) { visibility: hidden !important; }";
+ document.head.appendChild(st);
+ });
+ const sdir = path.join(dir, `slam-${p.i}`);
+ await rm(sdir, { recursive: true, force: true });
+ await mkdir(sdir, { recursive: true });
+ const f0 = Math.max(0, Math.floor(p.span.t0 * fps));
+ const f1 = Math.max(f0 + 1, Math.ceil(p.span.t3 * fps));
+ const shots = new Map();
+ const runs = [];
+ const base = geo ? geo.word : null;
+ for (let f = f0; f < f1; f += 1) {
+ const s = f / fps;
+ let dx = 0;
+ let dy = 0;
+ if (follow && p.scope && base) {
+ await stateAt(s);
+ const g = await page.evaluate(measureCaptionWords, { scope: p.scope, from: p.from, to: p.to, avoid: [] });
+ if (!g.error) {
+ dx = Math.round(g.word.x - base.x);
+ dy = Math.round(g.word.y - base.y);
+ }
+ }
+ const list = slamListAt(q, s, dx, dy);
+ const key = JSON.stringify(list);
+ if (!shots.has(key)) {
+ const png = path.join(sdir, `s-${String(shots.size).padStart(4, "0")}.png`);
+ await page.evaluate(setSlamState, { list, shake: null });
+ await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height }, omitBackground: true });
+ shots.set(key, png);
+ }
+ if (runs.length && runs[runs.length - 1].key === key) runs[runs.length - 1].n += 1;
+ else runs.push({ key, n: 1 });
+ }
+ await page.evaluate(setSlamState, { list: [], shake: null });
+ await page.evaluate(() => document.querySelectorAll("style[data-pslam-solo]").forEach((el) => el.remove()));
+ await stateAt(0);
+ const qq = (f) => `'${f.replace(/'/g, "'\\''")}'`;
+ const lines = ["ffconcat version 1.0"];
+ for (const r of runs) lines.push(`file ${qq(shots.get(r.key))}`, `duration ${(r.n / fps).toFixed(6)}`);
+ lines.push(`file ${qq(shots.get(runs[runs.length - 1].key))}`);
+ const list = path.join(sdir, "frames.ffconcat");
+ await writeFile(list, lines.join("\n") + "\n", "utf8");
+ out.push({ ...q, list, t0: f0 / fps, t3: f1 / fps, landings: p.span.landings, layout, size, shots: shots.size });
+ }
+ } finally {
+ await ctx.close();
+ }
+ return out;
+}
+
+/**
* THE CLOCK's FRAMES (post-clock.mjs): on the card page as drawn, the chip
* mounted at its widest and placed (measureClockPlace: the bottom-right corner
* by the counts row, else the top-right -- over no word), then shot alone on a
@@ -873,6 +1023,7 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin
* hold, place; its clock fx's on/rewind -- its `narration.pace`, its id: a
* repeated item is its own segment); what it does NOT carry is added here:
* captionV / clockV the chip's and the clock's drawing (bumped when their look changes)
+ * slam a slam's drawing version, its motion and its trailer hit (post-slam.mjs)
* clock clockPlan -- this post's time, the time it runs from (the
* item before's, when that one is a clock item), the mode
* (forward / rewind / none, a forced rewind) and the zone
@@ -881,10 +1032,18 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin
*/
export const POST_CAPTION_DRAW_V = 2;
export const POST_CLOCK_DRAW_V = 1;
+/**
+ * A SLAM's drawing and sound (post-slam.mjs): bumped when its look changes. Its
+ * fields are in the entry (`fx`); the key adds this, the motion it is drawn on
+ * and the trailer hit's tier and level it sounds (trailer-hits.mjs) -- so a
+ * change to the shared generator rebuilds the items that play it.
+ */
+export const POST_SLAM_DRAW_V = 1;
export function postFxKeyFields(entry, render, prev = null) {
const out = {};
const fx = Array.isArray(entry?.fx) ? entry.fx : [];
if (fx.some((f) => f?.kind === "caption")) out.captionV = POST_CAPTION_DRAW_V;
+ if (fx.some((f) => f?.kind === "slam")) out.slam = { v: POST_SLAM_DRAW_V, motion: SLAM_MOTION, hit: TRAILER_HIT_TIERS.title, audio: TRAILER_AUDIO };
const clk = clockPlan(entry, render, prev);
if (clk) Object.assign(out, { clockV: POST_CLOCK_DRAW_V, clock: clk });
const k = postNarrationKnobs(entry, render);
@@ -1015,10 +1174,14 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
const zoomPlan = postZoomPlan(entry, render, plan.total, plan.narration);
// Its captions (post-caption.mjs): each waits for a zoom it would be up with, and is gone by the media phase (a stack card).
- const capPlan = captionPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total, schedule: plan.narration ?? undefined });
+ // Its slams (post-slam.mjs): never up with a zoom; gone by the media phase (a stack card), as a caption is.
+ const fxEnd = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total;
+ const slPlan = slamPlan(entry, render, { zooms: zoomPlan.map((z) => ({ ...z.span, i: z.i })), end: fxEnd, schedule: plan.narration ?? undefined });
+ // A caption up with a slam WAITS for it to be gone (the slam first, then the chip), as it waits for a zoom.
+ const capPlan = captionPlan(entry, render, { zooms: [...zoomPlan.map((z) => ({ ...z.span, i: z.i })), ...slPlan.map((p) => ({ t0: p.span.t0, t3: p.span.t3, i: p.i }))], end: fxEnd, schedule: plan.narration ?? undefined });
// Its clock (post-clock.mjs): the post's own time, run from the clock item before it.
const clk = clockPlan(entry, render, prev);
- const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [] });
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout, avatars, zooms: zoomPlan, redaction, follow: plan.follow ?? null, total: plan.total, joinFrom: from, captions: capPlan, clock: clk, obstacles: layout.slot ? plan.steps.flatMap((st) => stepBoxes(st, layout.slot)) : [], slams: slPlan });
// NO HIDDEN TEXT IS EVER NARRATED (operator, 4 Nov): a part whose words are not in view, whole and lit, while it
// is said -- or a context post drawn over its context size -- refuses the build (READ_IN_VIEW=warn: a note).
// A part read off a linked post's picture is on screen only while the panel shows it (post-thread.mjs panelReadErrors).
@@ -1052,7 +1215,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
const lufs = Number.isFinite(take.lufs) ? take.lufs : await measureLufsOf(takeFile, { exec, ffmpeg });
narration = { file: takeFile, gainDb: narrationLevelDb(lufs, plan.narration.lufs), lufs, ...(bleeps ? { bleeps } : {}) };
}
- const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null });
+ const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp, narration, zooms, follow: cards.follow ?? null, panelFiles, map: cards.map ?? null, join: from && cards.joinFrom ? { seconds: plan.follow.join.seconds, fadeIn: from.fadeIn, from: from.media } : null, captionFx: cards.captions ?? [], clock: cards.clock ? { ...cards.clock, until: layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : plan.total } : null, slams: cards.slams ?? [], slamHitList: (cards.slams ?? []).flatMap((sl) => slamHits(sl.fx, sl.span).map((h) => ({ ...h, gain: h.gain * sl.fx.volume }))) });
try {
await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
} catch (err) {
@@ -1063,7 +1226,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
// The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides).
if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true });
// Through a rename: a record `--from` linked in (another take's) is replaced, never written through.
- await writeFile(`${record}.tmp`, 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 })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8");
+ await writeFile(`${record}.tmp`, 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 })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}) }, null, 2) + "\n", "utf8");
await rename(`${record}.tmp`, record);
emit("note", {
message: narration
@@ -1072,7 +1235,8 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
});
if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` });
if (cards.clock) emit("note", { message: `${entry.id}: clock ${clockFace(clk.to, clk.zone).time} ${clockFace(clk.to, clk.zone).date} (${clk.mode === "none" ? "shown" : clk.mode === "rewind" ? "rewound" : "run forward"}${clk.mode === "none" ? "" : ` from the item before, ${clk.gap / 60000 | 0} min`}), ${cards.clock.place}${cards.clock.covers ? ` -- WARNING: over ${cards.clock.covers} word(s)` : ""}` });
- for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after word zoom ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` });
+ for (const c of cards.captions ?? []) emit("note", { message: `${entry.id}: caption ${c.i + 1} "${c.text}" at ${c.t.toFixed(2)} s (${c.source === "at" ? "set by hand" : c.source === "words" ? "from the take's words" : "the reading estimate"}${c.span.waited !== null ? `, after ${entry.fx?.[c.span.waited]?.kind === "slam" ? "slam" : "word zoom"} ${c.span.waited + 1}` : ""}), ${c.span.t0}–${c.span.t3} s, ${c.placed.rel} the phrase ${c.placed.place === "card" ? "on the card" : "off the card"}${c.placed.leader ? ", a leader to it" : ""}${c.cutByPan ? ` (gone at ${c.cutByPan} s, before the card pans its phrase)` : ""}${c.placed.covers ? ` -- WARNING: no free space in the frame, it covers ${c.placed.covers} thing(s) drawn (shorten its text)` : ""}` });
+ for (const sl of cards.slams ?? []) emit("note", { message: `${entry.id}: slam ${sl.i + 1} "${sl.fx.text}" -- ${sl.landings.length} hit(s) at ${sl.landings.map((x) => x.toFixed(2)).join(", ")} s (${sl.source === "words" ? "spread over the words' spoken span" : sl.source === "at" ? "from its at" : "the reading estimate"}), up ${sl.span.t0}–${sl.span.t3} s, ${sl.layout.where} the words${sl.layout.covers ? `, over ${sl.layout.covers} other thing(s) drawn for its window (the gag)` : ""}${sl.fx.sfx === "off" ? ", silent" : ""}` });
for (const z of zooms) emit("note", { message: `${entry.id}: word zoom ${z.i + 1} at ${z.t.toFixed(2)} s (${z.source === "at" ? "set by hand" : "from the take's words"}), ${z.span.scale}× over ${z.span.t0}–${z.span.t3} s` });
return seg;
}
diff --git a/umtool/report-to-video/post-slam.mjs b/umtool/report-to-video/post-slam.mjs
@@ -0,0 +1,615 @@
+// A POST ITEM's SLAM (umtool/docs/report-video.md, "A slam"; operator, 4 Nov:
+// "as a joke effect I'd like to see the japanese characters of 'fudoshin'
+// (不動心) pop in with three trailer hits like a corny effect, make the
+// characters gold with a black outline, starting large and shrinking before
+// hitting the page like standard trailer hits"; "three hits evenly spaced over
+// the pronunciation of the word, one for each character"; "do it above the
+// word on the page"; "do the same with baji quan (八极拳)").
+//
+// entry.fx = [{ kind: "slam",
+// text: "不動心", // the glyphs that slam in (≤ SLAM_TEXT_MAX)
+// match?: "Fudōshin", // the word or phrase it lands on (as the card shows it)
+// target?: "post" | "quoted" | "parent:<i>", // whose words (default the post's own)
+// occurrence?: n, // its n-th time in that text (default 1)
+// at?: <item seconds>, // the first hit; absent: the word's start in the take's words
+// gap?: s, // seconds between hits; absent: spread over the word's span
+// whole?: true, // the text as ONE unit and one hit (default: one per glyph)
+// hold?: s, fromScale?: x, // held after the last hit; how big a glyph starts
+// color?: "#rrggbb", outline?: "#rrggbb", outlineWidth?: px,
+// place?: "over-match" | "center", // above the matched words (default), or the card's middle
+// size?: px, // the glyphs' size at rest, px at 1080 (absent: by the word's line)
+// face?: "jp" | "sc" | "tc" | "kr", // the CJK face (Noto Sans CJK <face> Black)
+// sfx?: "trailer-hit" | "off", volume?: x, swell?: true }]
+//
+// WHEN: each glyph LANDS on a hit. Absent `at` and `gap`, the hits are spread
+// evenly over the matched words' SPOKEN span in the picked take's word timings
+// -- the first on its first word's start, the last on its last word's end
+// (a phrase: "Baji"'s start to "Quan"'s end) -- else the reading estimate's
+// start, `SLAM_GAP` apart. `at` moves the first hit; `gap` overrides the
+// spacing. A glyph is in from `hit` before its landing, huge (`fromScale`×) and
+// blurred, and SHRINKS onto its spot -- the teaser's slam (deck.mjs
+// TEASER_MOTION: power3.in down past rest to `under`, a power2.out settle up to
+// it, the blur focusing over hit + 0.12 s) -- with a flash, a dust ring and a
+// screen shake as it hits. After the last hit it holds `hold`, then fades.
+//
+// WHERE: a row of glyphs centred on the matched words and sitting just ABOVE
+// their line (below it when there is no room above in the frame; `center`: the
+// card's middle), each glyph huge and centred on its own landing spot. It
+// follows the card's pan (read-follow): every frame is placed by where the
+// words are drawn then.
+//
+// THE ONE EXEMPTION (deliberate, the gag): the landed row may cover the line
+// ABOVE the word -- for the slam's own window only (t0 → t3: its hits, its
+// hold, its fade; at most SLAM_LIMITS.hold + the hits' spread). It is drawn
+// OVER the card, never in it (no data-w, no data-post-block), so the read-follow
+// geometry and readInViewErrors are measured without it; what it may NOT cover
+// is checked here instead (slamCoverErrors): the matched words themselves, and
+// the words read at each hit. A row that would is placed below the line; when
+// neither place is clear the build refuses, in its own words.
+//
+// THE SOUND: one trailer hit per glyph at its landing (trailer-hits.mjs, the
+// teaser's generator, title tier), the tail's swell after the last with
+// `swell`, mixed into the segment's audio without ducking the read.
+//
+// Pure but for the DOM functions (mountSlams, setSlamState), which are
+// SELF-CONTAINED: the build passes them to a page (page.evaluate), Play calls
+// them on its card frame's document.
+
+import { alignWords, cardWordsOf, findMatch, readingEstimate, targetScope, targetTextOf } from "./word-zoom.mjs";
+import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs";
+import { cardWordTimes } from "./post-caption.mjs";
+import { mixHex } from "./post-item.mjs";
+import { TRAILER_HIT_TIERS, TRAILER_SWELL } from "./trailer-hits.mjs";
+
+export const SLAM_PLACES = Object.freeze(["over-match", "center"]);
+export const SLAM_FACES = Object.freeze(["jp", "sc", "tc", "kr"]);
+export const SLAM_SFX = Object.freeze(["trailer-hit", "off"]);
+export const SLAM_DEFAULTS = Object.freeze({
+ target: "post", occurrence: 1, whole: false, hold: 1.6, fromScale: 3.5, color: "#f5c542", outline: "#000000",
+ place: "over-match", face: "jp", sfx: "trailer-hit", volume: 1, swell: false,
+});
+export const SLAM_LIMITS = Object.freeze({
+ at: [0, 600], gap: [0.12, 2], hold: [0.3, 4], fromScale: [1.5, 8], outlineWidth: [0, 30], size: [40, 320], volume: [0, 3], occurrence: [1, 99],
+});
+export const SLAM_TEXT_MAX = 12;
+/** The spacing between hits when there is no spoken span to spread them over (an `at`, the estimate). */
+export const SLAM_GAP = 0.45;
+/** The tightest even spread: hits closer than this are SLAM_GAP_MIN apart. */
+export const SLAM_GAP_MIN = 0.12;
+/**
+ * THE MOTION -- the teaser's slam (deck.mjs TEASER_MOTION: `hit`, `under`,
+ * `settle`, `blur`; a test holds them equal), from `fromScale` instead of its
+ * 1.42: `fadeIn` its opacity's rise as it comes in, `out` the row's fade after
+ * the hold, `flash` / `ring` / `dust` the impact's light, shock ring and dust
+ * (seconds from the landing), `shake` the frame's punch (px at 1080, its time
+ * constant, its span, its rate).
+ */
+export const SLAM_MOTION = Object.freeze({
+ hit: 0.2, under: 0.968, settle: 0.5, blur: 18, fadeIn: 0.06, out: 0.35, flash: 0.32, ring: 0.45, dust: 0.55,
+ shake: Object.freeze({ amp: 9, tau: 0.075, span: 0.3, hz: 23 }),
+});
+/** The faces: Noto Sans CJK at its Black weight, the region's forms first. */
+export const SLAM_FACE_STACK = Object.freeze({
+ jp: "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', sans-serif",
+ sc: "'Noto Sans CJK SC', 'Noto Sans CJK JP', 'Source Han Sans CN', sans-serif",
+ tc: "'Noto Sans CJK TC', 'Noto Sans CJK JP', 'Source Han Sans TW', sans-serif",
+ kr: "'Noto Sans CJK KR', 'Noto Sans CJK JP', 'Source Han Sans KR', sans-serif",
+});
+
+const KEYS = new Set(["kind", "text", "target", "match", "occurrence", "at", "gap", "whole", "hold", "fromScale", "color", "outline", "outlineWidth", "place", "size", "face", "sfx", "volume", "swell"]);
+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 HEX_RE = /^#[0-9a-fA-F]{6}$/;
+const MATCH_MAX = 120;
+
+/**
+ * One slam with every default filled in.
+ * @param {Record<string, any> | null | undefined} fx
+ * @returns {{ kind?: string, text: string, target: string, match: string, occurrence: number, at?: number, gap?: number, whole: boolean, hold: number, fromScale: number, color: string, outline: string, outlineWidth?: number, place: string, size?: number, face: string, sfx: string, volume: number, swell: boolean }}
+ */
+export const resolveSlam = (fx) => ({ ...SLAM_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) });
+
+/** The slam's units: each glyph (whitespace dropped), or the whole text as one. */
+export function slamUnits(fx) {
+ const t = String(fx?.text ?? "").trim();
+ if (!t) return [];
+ if (fx?.whole === true) return [t];
+ return Array.from(t).filter((c) => c.trim());
+}
+
+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})`);
+
+/** Every reason slam `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */
+export function slamErrors(e, fx, fw) {
+ const errors = [];
+ for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a slam key (${[...KEYS].join(", ")})`);
+ if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be the glyphs that slam in ("不動心")`);
+ else if (Array.from(fx.text.trim()).length > SLAM_TEXT_MAX) errors.push(`${fw}.text is longer than ${SLAM_TEXT_MAX} characters (a slam is a few glyphs, not a sentence)`);
+ const place = fx.place ?? SLAM_DEFAULTS.place;
+ if (fx.place !== undefined && !SLAM_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${SLAM_PLACES.join(", ")}`);
+ const target = fx.target ?? "post";
+ 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>"`);
+ const text = typeof target === "string" ? targetTextOf(e, target) : null;
+ if (fx.match === undefined) {
+ if (!fin(fx.at)) errors.push(`${fw}: a slam needs its word (match) or its second (at)`);
+ else if (place === "over-match") errors.push(`${fw}: a slam with no match has no word to land over (place "center", or set match)`);
+ } else if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase the slam lands on, as the card shows it`);
+ else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`);
+ 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"})`);
+ else {
+ 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}`);
+ }
+ if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, SLAM_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`);
+ for (const k of ["at", "gap", "hold"]) if (fx[k] !== undefined && !numIn(fx[k], SLAM_LIMITS[k])) errors.push(`${fw}.${k} must be ${SLAM_LIMITS[k][0]}–${SLAM_LIMITS[k][1]} seconds`);
+ if (fx.fromScale !== undefined && !numIn(fx.fromScale, SLAM_LIMITS.fromScale)) errors.push(`${fw}.fromScale must be ${SLAM_LIMITS.fromScale[0]}–${SLAM_LIMITS.fromScale[1]} (times its size at rest)`);
+ for (const k of ["outlineWidth", "size"]) if (fx[k] !== undefined && !numIn(fx[k], SLAM_LIMITS[k])) errors.push(`${fw}.${k} must be ${SLAM_LIMITS[k][0]}–${SLAM_LIMITS[k][1]} px (at 1080)`);
+ if (fx.volume !== undefined && !numIn(fx.volume, SLAM_LIMITS.volume)) errors.push(`${fw}.volume must be ${SLAM_LIMITS.volume[0]}–${SLAM_LIMITS.volume[1]} (times the trailer hit's level)`);
+ for (const k of ["color", "outline"]) if (fx[k] !== undefined && !(typeof fx[k] === "string" && HEX_RE.test(fx[k]))) errors.push(`${fw}.${k} must be a colour (#rrggbb)`);
+ if (fx.face !== undefined && !SLAM_FACES.includes(fx.face)) errors.push(`${fw}.face must be one of ${SLAM_FACES.join(", ")}`);
+ if (fx.sfx !== undefined && !SLAM_SFX.includes(fx.sfx)) errors.push(`${fw}.sfx must be one of ${SLAM_SFX.join(", ")}`);
+ for (const k of ["whole", "swell"]) if (fx[k] !== undefined && typeof fx[k] !== "boolean") errors.push(`${fw}.${k} must be true or false`);
+ return errors;
+}
+
+// ---------------------------------------------------------------------------
+// WHEN.
+// ---------------------------------------------------------------------------
+
+/**
+ * Each slam's moment, one per fx (another effect's row is `{ i, kind }`):
+ * `{ i, t, end, source: "at"|"words"|"estimate" }` -- `t` its matched words'
+ * spoken start (or `at`), `end` their spoken end (null when unknown: an `at`
+ * with no words, the estimate) -- or `{ i, error }`.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {Record<string, any> | null} [schedule]
+ * @returns {Array<{ i: number, t?: number, end?: number | null, source?: string, error?: string, kind?: string | null }>}
+ */
+export function slamTimes(entry, render = undefined, schedule = undefined) {
+ const list = Array.isArray(entry?.fx) ? entry.fx : [];
+ return list.map((fx0, i) => {
+ if (!isObj(fx0) || fx0.kind !== "slam") return { i, kind: fx0?.kind ?? null };
+ const fx = resolveSlam(fx0);
+ const w = `${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}")`;
+ if (typeof fx0.match !== "string") return fin(fx0.at) ? { i, t: r3(fx0.at), end: null, source: "at" } : { i, error: `${w} has no time (set at, or match)` };
+ const text = targetTextOf(entry, fx.target);
+ const m = findMatch(text, fx.match, fx.occurrence);
+ if (m.error) return { i, error: `${w}: "${fx.match}" is not on the card` };
+ // The spoken span, from the take's word timings.
+ let span = null;
+ if (isNarrated(entry)) {
+ const take = pickedTake(entry);
+ const timed = Array.isArray(take?.words) && take.words.length ? take.words : null;
+ if (timed) {
+ const sch = schedule ?? narrationSchedule(entry, render);
+ const rate = sch.rate || 1;
+ const map = alignWords(cardWordsOf(text), timed.map((x) => x.w));
+ const ks = [];
+ for (let k = m.from; k <= m.to; k += 1) if (map[k] >= 0) ks.push(map[k]);
+ if (ks.length) {
+ const a = timed[ks[0]];
+ const b = timed[ks[ks.length - 1]];
+ if (fin(a.start) && fin(b.end)) span = { t: r3(sch.at + a.start / rate), end: r3(sch.at + b.end / rate) };
+ }
+ }
+ }
+ if (fin(fx0.at)) return { i, t: r3(fx0.at), end: span ? r3(fx0.at + (span.end - span.t)) : null, source: "at" };
+ if (span) return { i, t: span.t, end: span.end, source: "words" };
+ const wt = cardWordTimes(entry, render, fx.target, schedule);
+ const t = wt?.times?.[m.from];
+ return { i, t: fin(t) ? r3(t) : readingEstimate(m.from), end: null, source: "estimate" };
+ });
+}
+
+/**
+ * Each unit's LANDING (where its hit sounds), item seconds: `gap` apart when the
+ * slam sets one; else spread evenly from `t` to `end` (the first on the word's
+ * start, the last on its end) when the span is known and there are two or more;
+ * else SLAM_GAP apart. Never closer than SLAM_GAP_MIN.
+ * @param {Record<string, any>} fx0
+ * @param {{ t: number, end?: number | null }} time
+ * @returns {number[]}
+ */
+export function slamLandings(fx0, { t, end = null }) {
+ const n = slamUnits(resolveSlam(fx0)).length;
+ if (!n) return [];
+ let gap = SLAM_GAP;
+ if (fin(fx0?.gap)) gap = fx0.gap;
+ else if (fin(end) && n > 1 && end > t) gap = (end - t) / (n - 1);
+ gap = Math.max(SLAM_GAP_MIN, gap);
+ return Array.from({ length: n }, (_, k) => r3(t + k * gap));
+}
+
+/**
+ * One slam's span on the item's clock: in from t0 (its first glyph's start,
+ * `hit` before its landing) through each landing, held to t2 (`hold` after the
+ * last), out by t3 -- the hold shortened to end by `end` (the item's last
+ * second, or a stack card's media phase). `{ t0, t2, t3, landings }` or `{ error }`.
+ * @param {Record<string, any>} fx0
+ * @param {number[]} landings
+ * @param {{ end?: number }} [o]
+ */
+export function slamSpan(fx0, landings, { end = Infinity } = {}) {
+ const fx = resolveSlam(fx0);
+ if (!landings.length) return { error: "has no glyphs" };
+ const last = landings[landings.length - 1];
+ const t0 = Math.max(0, landings[0] - SLAM_MOTION.hit);
+ if (last >= end - 0.05) return { error: `lands at ${r3(last)} s, at or after the item's ${r3(end)} s` };
+ let t2 = last + fx.hold;
+ if (t2 + SLAM_MOTION.out > end) t2 = Math.max(last + 0.15, end - SLAM_MOTION.out);
+ return { t0: r3(t0), t2: r3(t2), t3: r3(Math.min(end, t2 + SLAM_MOTION.out)), landings };
+}
+
+const easeIn3 = (x) => Math.min(1, Math.max(0, x)) ** 3;
+const easeOut2 = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 2;
+
+/**
+ * One unit's look at item second `s` (landing `L`): `{ scale, blur, opacity,
+ * flash, ring, dust, ghost }` -- scale × its rest size, blur px at 1080, the
+ * flash's and ghosts' strength 0–1, the ring's and dust's progress 0–1 (-1:
+ * none) -- or null before it comes in. `fade` is the row's (1 → 0 over its out).
+ * @param {number} L @param {number} s @param {{ fromScale?: number, fade?: number }} [o]
+ */
+export function slamUnitAt(L, s, { fromScale = SLAM_DEFAULTS.fromScale, fade = 1 } = {}) {
+ const M = SLAM_MOTION;
+ const u = s - (L - M.hit);
+ if (u < 0) return null;
+ let scale = 1;
+ if (u < M.hit) scale = fromScale + (M.under - fromScale) * easeIn3(u / M.hit);
+ else if (u < M.hit + M.settle) scale = M.under + (1 - M.under) * easeOut2((u - M.hit) / M.settle);
+ const blur = M.blur * (1 - easeOut2(u / (M.hit + 0.12)));
+ const opacity = Math.min(1, u / M.fadeIn) * fade;
+ const v = s - L;
+ const flash = v >= -0.03 && v < M.flash ? (v < 0 ? 1 + v / 0.03 : 1 - v / M.flash) * fade : 0;
+ const ring = v >= 0 && v < M.ring ? v / M.ring : -1;
+ const dust = v >= 0 && v < M.dust ? v / M.dust : -1;
+ const ghost = u < M.hit ? (1 - u / M.hit) * fade : 0;
+ return { scale: r3(scale), blur: Math.round(blur * 10) / 10, opacity: r3(opacity), flash: r3(Math.max(0, flash)), ring: r3(ring), dust: r3(dust), ghost: r3(ghost) };
+}
+
+/** The row's fade at `s` (1 until its hold ends, 0 by t3). */
+export const slamFadeAt = (span, s) => (s < span.t2 ? 1 : s >= span.t3 ? 0 : 1 - (s - span.t2) / Math.max(1e-6, span.t3 - span.t2));
+
+/**
+ * The slam's state at item second `s`: `{ units: [{ k, …slamUnitAt }] }` for
+ * the units in, or null when it is not up.
+ * @param {{ span: { t0: number, t2: number, t3: number, landings: number[] }, fromScale: number }} p
+ * @param {number} s
+ */
+export function slamStateAt(p, s) {
+ if (!p?.span || s < p.span.t0 || s >= p.span.t3) return null;
+ const fade = slamFadeAt(p.span, s);
+ const units = [];
+ p.span.landings.forEach((L, k) => {
+ const st = slamUnitAt(L, s, { fromScale: p.fromScale, fade });
+ if (st) units.push({ k, ...st });
+ });
+ return { units };
+}
+
+/** The frame's punch at `s` (unit amplitudes: × SLAM_MOTION.shake.amp × k px): `{ x, y }`. */
+export function slamShakeAt(landings, s) {
+ const { tau, span, hz } = SLAM_MOTION.shake;
+ let x = 0;
+ let y = 0;
+ for (const L of landings) {
+ const v = s - L;
+ if (v < 0 || v > span) continue;
+ const e = Math.exp(-v / tau);
+ x += e * Math.sin(2 * Math.PI * hz * v);
+ y += e * 0.75 * Math.cos(2 * Math.PI * hz * 1.37 * v);
+ }
+ return { x: r3(x), y: r3(y) };
+}
+
+/** slamShakeAt's `axis` as an ffmpeg expression of t, × `amp` px ("0" with no landings). */
+export function slamShakeExpr(landings, axis, amp) {
+ const { tau, span, hz } = SLAM_MOTION.shake;
+ const n = (v) => String(r3(v));
+ const terms = landings.map((L) => {
+ const u = `(t-${n(L)})`;
+ const wave = axis === "x" ? `sin(${n(2 * Math.PI * hz)}*${u})` : `0.75*cos(${n(2 * Math.PI * hz * 1.37)}*${u})`;
+ return `if(between(t,${n(L)},${n(L + span)}),exp(-${u}/${n(tau)})*${wave},0)`;
+ });
+ return terms.length ? `${n(amp)}*(${terms.join("+")})` : "0";
+}
+
+/** Two slams of one post up at once: their indices, or null. */
+export function overlappingSlams(spans) {
+ const s = spans.filter((x) => x && fin(x.t0)).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;
+}
+
+// ---------------------------------------------------------------------------
+// THE SOUND.
+// ---------------------------------------------------------------------------
+
+/**
+ * The slam's hits as trailer-hits.mjs reads them: one title-tier hit per
+ * landing, the tail's swell after the last with `swell` (over the hold). Empty
+ * with `sfx: "off"`.
+ * @param {Record<string, any>} fx0
+ * @param {{ t0: number, t2: number, landings: number[] }} span
+ */
+export function slamHits(fx0, span) {
+ const fx = resolveSlam(fx0);
+ if (fx.sfx === "off") return [];
+ const out = span.landings.map((at) => ({ kind: "hit", at, role: "title", ...TRAILER_HIT_TIERS.title }));
+ if (fx.swell === true) {
+ const last = span.landings[span.landings.length - 1];
+ out.push({ kind: "swell", at: r3(last + 0.15), role: "tail", ...TRAILER_SWELL, dur: r3(Math.max(0.6, span.t2 - last)) });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// THE PLAN.
+// ---------------------------------------------------------------------------
+
+/**
+ * Post item `entry`'s slams, resolved: `[{ i, units, scope, from, to, fx,
+ * t, end, source, span, avoid }]` -- `avoid` the target's word indices read
+ * near a hit (their start within SLAM_AVOID_WINDOW of one: the row covers
+ * none of them), the matched words apart (always protected). `zooms`: the
+ * item's word zooms' spans (a slam up with one is refused); `end`: the last
+ * second a slam may be up. Throws in the build's words.
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} [render]
+ * @param {{ zooms?: Array<Record<string, any>>, end?: number, schedule?: Record<string, any> }} [o]
+ */
+export function slamPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) {
+ const list = Array.isArray(entry?.fx) ? entry.fx : [];
+ if (!list.some((f) => f?.kind === "slam")) return [];
+ const times = slamTimes(entry, render, schedule);
+ const bad = times.filter((t) => t.error);
+ if (bad.length) throw new Error(bad.map((t) => t.error).join("; "));
+ /** @type {any[]} */
+ const out = [];
+ for (const [i, fx0] of list.entries()) {
+ if (fx0?.kind !== "slam") continue;
+ const fx = resolveSlam(fx0);
+ const tm = times[i];
+ const landings = slamLandings(fx0, { t: Number(tm.t), end: tm.end ?? null });
+ const span = slamSpan(fx0, landings, { end });
+ if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}") ${span.error} (move its at)`);
+ const z = zooms.find((zz) => fin(zz.t0) && fin(zz.t3) && zz.t0 < span.t3 && span.t0 < zz.t3);
+ if (z) throw new Error(`${entry?.id ?? "?"}: slam ${i + 1} ("${fx.text}") is up while word zoom ${(z.i ?? 0) + 1} is (one at a time: move one's at)`);
+ let scope = null, from = -1, to = -1, avoid = [];
+ if (typeof fx0.match === "string") {
+ const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence);
+ scope = targetScope(fx.target);
+ from = m.from;
+ to = m.to;
+ const read = cardWordTimes(entry, render, fx.target, schedule)?.times ?? [];
+ avoid = read.map((s, k) => (fin(s) && (k < m.from || k > m.to) && landings.some((L) => Math.abs(s - L) <= SLAM_AVOID_WINDOW) ? k : -1)).filter((k) => k >= 0);
+ }
+ out.push({ i, units: slamUnits(fx), scope, from, to, fx, t: Number(tm.t), end: tm.end ?? null, source: String(tm.source), span: { ...span, i }, avoid });
+ }
+ const clash = overlappingSlams(out.map((p) => p.span));
+ if (clash) throw new Error(`${entry?.id ?? "?"}: slams ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at)`);
+ return out;
+}
+
+/** A word whose read starts this near a hit is being read as it lands: the row never covers it. */
+export const SLAM_AVOID_WINDOW = 0.25;
+
+// ---------------------------------------------------------------------------
+// WHERE.
+// ---------------------------------------------------------------------------
+
+/** @typedef {{ x: number, y: number, width: number, height: number }} Rect */
+/** @param {Rect} a @param {Rect} b */
+const hits = (a, b) => Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x) > 0.5 && Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y) > 0.5;
+
+/** The glyphs' size at rest, px: the slam's `size` (at 1080, × k), else by the matched words' line (2.5×), in 64–170 px at 1080. */
+export function slamSize(fx, word, k = 1) {
+ if (fin(fx?.size)) return Math.round(fx.size * k);
+ const h = word ? word.height : 50 * k;
+ return Math.round(Math.min(170 * k, Math.max(64 * k, h * 2.5)));
+}
+
+/**
+ * THE ROW's PLACE: the units (`units`: each one's box at rest, `{ width,
+ * height }`, side by side) centred on the matched words (`word`) and sitting
+ * `gap` above their line -- or, when that leaves the frame (`bounds`) or covers
+ * a `protect`ed box (the matched words, the words read at a hit), `gap` below
+ * it; `center`: the card's middle. Kept in the frame (moved in). `{ x, y, width,
+ * height, centers: [{ x, y }], where: "above"|"below"|"center"|"clamped",
+ * covers: n (the boxes of `obstacles` it lies over: the gag), blocked: bool
+ * (it covers a protected box) }`.
+ * @param {{ word?: Rect | null, card: Rect, bounds: Rect, units: Array<{ width: number, height: number }>, place?: string, gap?: number, protect?: Rect[], obstacles?: Rect[] }} o
+ */
+export function slamLayout({ word = null, card, bounds, units, place = "over-match", gap = 8, protect = [], obstacles = [] }) {
+ const W = units.reduce((a, u) => a + u.width, 0);
+ const H = Math.max(...units.map((u) => u.height));
+ const clampX = (x) => Math.min(bounds.x + bounds.width - W, Math.max(bounds.x, x));
+ const clampY = (y) => Math.min(bounds.y + bounds.height - H, Math.max(bounds.y, y));
+ const tries = [];
+ if (place === "center" || !word) tries.push({ x: clampX(card.x + card.width / 2 - W / 2), y: clampY(card.y + card.height / 2 - H / 2), where: "center" });
+ else {
+ const x = clampX(word.x + word.width / 2 - W / 2);
+ const above = word.y - gap - H;
+ const below = word.y + word.height + gap;
+ if (above >= bounds.y) tries.push({ x, y: above, where: "above" });
+ if (below + H <= bounds.y + bounds.height) tries.push({ x, y: below, where: "below" });
+ tries.push({ x, y: clampY(above), where: "clamped" });
+ }
+ const judged = tries.map((t) => {
+ const r = { x: t.x, y: t.y, width: W, height: H };
+ return { ...t, blocked: protect.some((p) => hits(r, p)), covers: obstacles.filter((o) => hits(r, o)).length };
+ });
+ const pick = judged.find((t) => !t.blocked) ?? judged[0];
+ let cx = pick.x;
+ const centers = units.map((u) => {
+ const c = { x: Math.round(cx + u.width / 2), y: Math.round(pick.y + H / 2) };
+ cx += u.width;
+ return c;
+ });
+ return { x: Math.round(pick.x), y: Math.round(pick.y), width: Math.round(W), height: Math.round(H), centers, where: pick.where, covers: pick.covers, blocked: pick.blocked };
+}
+
+/**
+ * Why a placed row cannot be built, as sentences: it covers the matched words,
+ * or a word read as a glyph lands (the one exemption -- the line above, for
+ * the slam's window -- is the gag; these are not).
+ */
+export function slamCoverErrors(id, i, layout) {
+ return layout.blocked ? [`${id}: slam ${i + 1} would cover the words being read as it lands (its matched words, or a word read at a hit) -- above and below its line alike: set place "center", a smaller size, or move it`] : [];
+}
+
+// ---------------------------------------------------------------------------
+// THE LOOK.
+// ---------------------------------------------------------------------------
+
+/** The CSS of the slams' layer (each unit's colours and face are its own inline variables). */
+export function slamCss() {
+ return `
+[data-post-fx-slams] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 70; overflow: visible; }
+.pslam { position: absolute; left: 0; top: 0; line-height: 1; white-space: nowrap; transform-origin: 50% 50%; opacity: 0; font-weight: 900; font-synthesis: none; will-change: transform, opacity, filter; }
+.pslam-g { position: relative; display: block; }
+.pslam-back, .pslam-front, .pslam-ghost { display: block; }
+.pslam-back { color: var(--pslam-stroke); -webkit-text-stroke: var(--pslam-sw) var(--pslam-stroke); paint-order: stroke fill;
+ filter: drop-shadow(0 0.05em 0.035em rgba(0,0,0,0.6)) drop-shadow(0 0.015em 0.01em rgba(0,0,0,0.5)); }
+.pslam-front { position: absolute; left: 0; top: 0; color: transparent; background: linear-gradient(180deg, var(--pslam-hi) 0%, var(--pslam-gold) 44%, var(--pslam-lo) 56%, var(--pslam-gold) 100%);
+ -webkit-background-clip: text; background-clip: text; -webkit-text-stroke: max(1px, calc(var(--pslam-sw) * 0.12)) var(--pslam-lo); }
+.pslam-ghost { position: absolute; left: 0; top: 0; color: var(--pslam-gold); opacity: 0; transform-origin: 50% 50%; -webkit-text-stroke: var(--pslam-sw) var(--pslam-stroke); paint-order: stroke fill; }
+.pslam-flash { position: absolute; left: 50%; top: 50%; width: 2.4em; height: 2.4em; margin: -1.2em 0 0 -1.2em; border-radius: 50%; opacity: 0;
+ background: radial-gradient(circle, rgba(255,252,232,0.95) 0%, var(--pslam-flash) 30%, rgba(0,0,0,0) 68%); }
+.pslam-ring { position: absolute; left: 50%; top: 50%; width: 1.5em; height: 1.5em; margin: -0.75em 0 0 -0.75em; border-radius: 50%; opacity: 0;
+ border: 0.05em solid var(--pslam-hi); box-shadow: 0 0 0.12em var(--pslam-gold); }
+.pslam-dust { position: absolute; left: 50%; top: 62%; width: 0; height: 0; }
+.pslam-dust i { position: absolute; left: 0; top: 0; width: 0.07em; height: 0.07em; margin: -0.035em; border-radius: 50%; background: var(--pslam-hi); opacity: 0; }
+`;
+}
+
+/** A unit's colour variables: its gold's highlight, body and shadow, its outline and width (px at its size). */
+export function slamVars(fx, size) {
+ const f = resolveSlam(fx);
+ const sw = fin(fx?.outlineWidth) ? fx.outlineWidth * (size / 120) : Math.max(4, size * 0.11);
+ return {
+ "--pslam-gold": f.color, "--pslam-hi": mixHex(f.color, "#ffffff", 0.62), "--pslam-lo": mixHex(f.color, "#5a3a00", 0.55),
+ "--pslam-stroke": f.outline, "--pslam-sw": `${Math.round(sw * 10) / 10}px`, "--pslam-flash": `${f.color}aa`,
+ };
+}
+
+/** The dust's directions (degrees): a fan up and out from the foot of the glyph. */
+export const SLAM_DUST = Object.freeze([-170, -150, -128, -105, -80, -55, -32, -10, 200, 225]);
+
+/**
+ * Mount the slams' units over the card page: `{ css, units: [{ i, k, text,
+ * size, face, vars }] }`. Returns each one's box at rest `[{ i, k, width,
+ * height }]` (its glyph's em box: line height 1).
+ * @param {{ css?: string, units?: Array<{ i: number, k: number, text: string, size: number, face: string, vars: Record<string, string> }>, dust?: number[] } | null} arg
+ * @param {Document} [doc]
+ * @returns {Array<{ i: number, k: number, width: number, height: number }>}
+ */
+export function mountSlams(arg, doc = document) {
+ doc.querySelectorAll("[data-post-fx-slams], style[data-post-fx-slams-css]").forEach((el) => el.remove());
+ const units = (arg && arg.units) || [];
+ if (!units.length) return [];
+ const style = doc.createElement("style");
+ style.setAttribute("data-post-fx-slams-css", "");
+ style.textContent = arg.css || "";
+ doc.head.appendChild(style);
+ const layer = doc.createElement("div");
+ layer.setAttribute("data-post-fx-slams", "");
+ doc.body.appendChild(layer);
+ const dust = (arg && arg.dust) || [];
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] || c);
+ return units.map((u) => {
+ const el = doc.createElement("div");
+ el.className = "pslam";
+ el.setAttribute("data-post-fx-slam", `${u.i}:${u.k}`);
+ el.style.fontSize = `${u.size}px`;
+ el.style.fontFamily = u.face;
+ for (const [k, v] of Object.entries(u.vars || {})) el.style.setProperty(k, v);
+ const t = esc(u.text);
+ el.innerHTML =
+ `<span class="pslam-flash"></span><span class="pslam-ring"></span>` +
+ `<span class="pslam-dust">${dust.map((a) => `<i data-a="${a}"></i>`).join("")}</span>` +
+ `<span class="pslam-g"><span class="pslam-ghost">${t}</span><span class="pslam-ghost">${t}</span><span class="pslam-ghost">${t}</span>` +
+ `<span class="pslam-back">${t}</span><span class="pslam-front">${t}</span></span>`;
+ layer.appendChild(el);
+ const b = el.getBoundingClientRect();
+ el.dataset.rw = String(b.width);
+ el.dataset.rh = String(b.height);
+ return { i: u.i, k: u.k, width: Math.ceil(b.width), height: Math.ceil(b.height) };
+ });
+}
+
+/**
+ * Set the slams: `{ list: [{ i, k, x, y, scale, blur, opacity, flash, ring,
+ * dust, ghost }], shake: { x, y } | null }` -- x, y the unit's centre (px);
+ * a unit not listed is hidden. `shake` (Play) moves the page's body by that
+ * many px (the build shakes the frame in ffmpeg instead).
+ * @param {{ list?: Array<Record<string, any>>, shake?: { x: number, y: number } | null } | null} arg
+ * @param {Document} [doc]
+ */
+export function setSlamState(arg, doc = document) {
+ const list = (arg && arg.list) || [];
+ const shake = arg && arg.shake;
+ if (doc.body) doc.body.style.translate = shake && (shake.x || shake.y) ? `${Math.round(shake.x * 10) / 10}px ${Math.round(shake.y * 10) / 10}px` : "";
+ const layer = doc.querySelector("[data-post-fx-slams]");
+ if (!layer) return;
+ for (const el of Array.from(layer.querySelectorAll(".pslam"))) {
+ const id = el.getAttribute("data-post-fx-slam") || "";
+ const st = list.find((x) => `${x.i}:${x.k}` === id);
+ if (!st) {
+ el.style.opacity = "0";
+ continue;
+ }
+ const w = Number(el.dataset.rw || 0);
+ const h = Number(el.dataset.rh || 0);
+ const size = parseFloat(el.style.fontSize) || 100;
+ el.style.opacity = String(st.opacity);
+ el.style.transform = `translate(${Math.round((st.x - w / 2) * 10) / 10}px, ${Math.round((st.y - h / 2) * 10) / 10}px) scale(${st.scale})`;
+ const g = el.querySelector(".pslam-g");
+ // The teaser's blur (px on its title) scaled to this glyph and halved: a motion smear, never a blob.
+ if (g) g.style.filter = st.blur > 0.2 ? `blur(${Math.round(st.blur * (size / 120) * 0.45 * 10) / 10}px)` : "";
+ // The ghosts: bigger copies trailing the shrink (where it came from), gone as it lands.
+ Array.from(el.querySelectorAll(".pslam-ghost")).forEach((gh, j) => {
+ gh.style.opacity = String(Math.round(st.ghost * (0.3 / (j + 1)) * 1000) / 1000);
+ gh.style.transform = `scale(${Math.round((1 + 0.16 * (j + 1) * st.ghost) * 1000) / 1000})`;
+ });
+ // The impact: a flash behind it (it is drawn under the glyph), a ring, the dust thrown up and out.
+ const fl = el.querySelector(".pslam-flash");
+ if (fl) {
+ fl.style.opacity = String(st.flash);
+ fl.style.transform = `scale(${Math.round((0.7 + 0.5 * (1 - st.flash)) * 1000) / 1000})`;
+ }
+ const ring = el.querySelector(".pslam-ring");
+ if (ring) {
+ ring.style.opacity = st.ring < 0 ? "0" : String(Math.round((1 - st.ring) * 0.9 * st.opacity * 1000) / 1000);
+ ring.style.transform = `scale(${st.ring < 0 ? 0.4 : Math.round((0.45 + 1.5 * (1 - (1 - st.ring) ** 2)) * 1000) / 1000})`;
+ }
+ for (const d of Array.from(el.querySelectorAll(".pslam-dust i"))) {
+ if (st.dust < 0) {
+ d.style.opacity = "0";
+ continue;
+ }
+ const a = (Number(d.getAttribute("data-a")) * Math.PI) / 180;
+ const p = 1 - (1 - st.dust) ** 2;
+ const r = size * (0.25 + 0.75 * p);
+ const fall = size * 0.35 * st.dust * st.dust;
+ d.style.opacity = String(Math.round((1 - st.dust) * st.opacity * 1000) / 1000);
+ d.style.transform = `translate(${Math.round(Math.cos(a) * r * 10) / 10}px, ${Math.round((Math.sin(a) * r * 0.55 + fall) * 10) / 10}px) scale(${Math.round((1.4 - st.dust) * 100) / 100})`;
+ }
+ }
+}
+
+/**
+ * The units of a plan at item second `s` as setSlamState takes them: `p` a
+ * slam (slamPlan's, with `centers` from its layout), `dx`/`dy` how far its
+ * words have moved since it was placed (a pan).
+ */
+export function slamListAt(p, s, dx = 0, dy = 0) {
+ const st = slamStateAt({ span: p.span, fromScale: p.fx.fromScale }, s);
+ if (!st) return [];
+ return st.units.map((u) => ({ i: p.i, ...u, x: p.centers[u.k].x + dx, y: p.centers[u.k].y + dy }));
+}
diff --git a/umtool/report-to-video/post-slam.test.mjs b/umtool/report-to-video/post-slam.test.mjs
@@ -0,0 +1,198 @@
+// A post item's SLAM (post-slam.mjs): its validation, its timing (three hits
+// spread over the word's spoken span, a phrase's too; --gap; --at), its motion
+// (the teaser's slam, from its own scale), its place (above the line, below
+// when it would cover the words read), its sound (the teaser's trailer hit, one
+// per glyph) and the segment key (an item without a slam keeps its key).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ SLAM_GAP, SLAM_MOTION, slamHits, slamLandings, slamLayout, slamPlan, slamShakeAt, slamShakeExpr, slamSpan, slamStateAt, slamTimes, slamUnitAt, slamUnits,
+} from "./post-slam.mjs";
+import { TEASER_MOTION } from "./deck.mjs";
+import { TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs";
+import { captionPlan } from "./post-caption.mjs";
+import { validatePostFx, wordZoomTimes } from "./word-zoom.mjs";
+
+const TEXT = "I'm ignoring my broken bones so my training can continue. I have achieved Fudōshin. Its amazing.";
+const BAJI = "For those wondering, the martial art I'm pursuing is called Baji Quan, need to start.";
+const base = (o = {}) => ({ type: "post", id: "p1", post: "s/1", platform: "x", author: "S", handle: "s", date: "2026-10-20T19:46:00.000Z", text: TEXT, ...o });
+const slam = (o = {}) => ({ kind: "slam", text: "不動心", match: "Fudōshin", ...o });
+const take = (o = {}) => ({ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 10, script: TEXT, ...o });
+// The take's words: "achieved" 3.84–4.24, "Fudōshin." 4.24–5.36 (the proof post's own).
+const WORDS = [["I'm", 0.2, 0.4], ["ignoring", 0.4, 0.8], ["my", 0.8, 0.9], ["broken", 0.9, 1.2], ["bones", 1.2, 1.5], ["so", 1.5, 1.6], ["my", 1.6, 1.7], ["training", 1.7, 2.1], ["can", 2.1, 2.3], ["continue.", 2.3, 2.9], ["I", 3.3, 3.4], ["have", 3.4, 3.84], ["achieved", 3.84, 4.24], ["Fudōshin.", 4.24, 5.36], ["Its", 5.7, 5.9], ["amazing.", 5.9, 6.4]].map(([w, start, end]) => ({ w, start, end }));
+const narrated = (o = {}) => base({ narration: { script: TEXT, takes: [take({ words: WORDS })], lead: 0.5, rate: 1 }, ...o });
+
+test("validation: a slam's keys, text, match, knobs -- in the build's words; a slam is not a word zoom", () => {
+ assert.deepEqual(validatePostFx(base({ fx: [slam()] })), []);
+ const errs = validatePostFx(base({ fx: [slam({ match: "Fudoshinn", text: "", place: "left", hold: 9, scale: 2, color: "gold", face: "zh", sfx: "boom", fromScale: 20 })] }));
+ for (const re of [/fx\[0\]\.scale is not a slam key/, /match "Fudoshinn" is not in the post's words/, /\.text must be the glyphs/, /\.place must be one of over-match, center/, /\.hold must be 0.3–4 seconds/, /\.color must be a colour/, /\.face must be one of jp, sc, tc, kr/, /\.sfx must be one of trailer-hit, off/, /\.fromScale must be 1.5–8/]) {
+ assert.ok(errs.some((e) => re.test(e)), `${re}\n${errs.join("\n")}`);
+ }
+ assert.ok(validatePostFx(base({ fx: [slam({ text: "不".repeat(13) })] })).some((e) => /longer than 12 characters/.test(e)));
+ // No match: an `at` and the card's middle.
+ assert.ok(validatePostFx(base({ fx: [slam({ match: undefined })] })).some((e) => /needs its word \(match\) or its second \(at\)/.test(e)));
+ assert.ok(validatePostFx(base({ fx: [slam({ match: undefined, at: 2 })] })).some((e) => /no word to land over/.test(e)));
+ assert.deepEqual(validatePostFx(base({ fx: [slam({ match: undefined, at: 2, place: "center" })] })), []);
+ assert.deepEqual(wordZoomTimes(base({ fx: [slam()] })), [{ i: 0, kind: "slam" }]);
+});
+
+test("units: one per glyph (whitespace dropped), or the whole text as one", () => {
+ assert.deepEqual(slamUnits(slam()), ["不", "動", "心"]);
+ assert.deepEqual(slamUnits(slam({ text: "八极拳" })), ["八", "极", "拳"]);
+ assert.deepEqual(slamUnits(slam({ text: " 不 動心 " })), ["不", "動", "心"]);
+ assert.deepEqual(slamUnits(slam({ whole: true })), ["不動心"]);
+});
+
+test("WHEN: three hits spread evenly over the word's spoken span -- the first on its start, the last on its end, the second midway", () => {
+ const e = narrated({ fx: [slam()] });
+ const [t] = slamTimes(e);
+ // On the item's clock: the read's lead (0.5) + the take's second.
+ assert.deepEqual(t, { i: 0, t: 4.74, end: 5.86, source: "words" });
+ assert.deepEqual(slamLandings(e.fx[0], t), [4.74, 5.3, 5.86]);
+ // The read's rate (its schedule's): a take second is 1/rate of the item's.
+ assert.deepEqual(slamTimes(e, undefined, { at: 0.5, rate: 2 })[0], { i: 0, t: 2.62, end: 3.18, source: "words" });
+});
+
+test("WHEN: a two-word phrase spreads over both -- the first hit on Baji's start, the last on Quan's end", () => {
+ const words = [["For", 0.1, 0.3], ["those", 0.3, 0.6], ["wondering,", 0.6, 1.1], ["the", 1.2, 1.3], ["martial", 1.3, 1.7], ["art", 1.7, 1.9], ["I'm", 1.9, 2.1], ["pursuing", 2.1, 2.5], ["is", 2.5, 2.6], ["called", 2.6, 2.88], ["Baji", 2.88, 3.36], ["Quan,", 3.44, 3.84], ["need", 4.0, 4.2]].map(([w, start, end]) => ({ w, start, end }));
+ const e = base({ text: BAJI, narration: { script: BAJI, takes: [take({ script: BAJI, words })], lead: 0, rate: 1 }, fx: [slam({ text: "八极拳", match: "Baji Quan", face: "sc" })] });
+ assert.deepEqual(validatePostFx(e), []);
+ const [t] = slamTimes(e);
+ assert.deepEqual(t, { i: 0, t: 2.88, end: 3.84, source: "words" });
+ assert.deepEqual(slamLandings(e.fx[0], t), [2.88, 3.36, 3.84]);
+});
+
+test("WHEN: --gap overrides the spread; --at moves the first hit (the span kept when the words have one); none: SLAM_GAP apart", () => {
+ const e = narrated({ fx: [slam({ gap: 0.3 })] });
+ assert.deepEqual(slamLandings(e.fx[0], slamTimes(e)[0]), [4.74, 5.04, 5.34]);
+ const at = narrated({ fx: [slam({ at: 2 })] });
+ assert.deepEqual(slamTimes(at)[0], { i: 0, t: 2, end: 3.12, source: "at" });
+ const plain = base({ fx: [slam({ match: undefined, at: 1, place: "center" })] });
+ assert.deepEqual(slamTimes(plain)[0], { i: 0, t: 1, end: null, source: "at" });
+ assert.deepEqual(slamLandings(plain.fx[0], slamTimes(plain)[0]), [1, 1 + SLAM_GAP, 1 + 2 * SLAM_GAP]);
+ // Un-narrated with a match: the reading estimate's start ("Fudōshin." is word 13: 1 + 13/3).
+ assert.deepEqual(slamTimes(base({ fx: [slam()] }))[0], { i: 0, t: 5.33, end: null, source: "estimate" });
+ // One glyph (whole): one hit, on the start.
+ assert.deepEqual(slamLandings(slam({ whole: true }), { t: 4, end: 5 }), [4]);
+});
+
+test("SPAN: in from `hit` before the first landing, held after the last, faded; shortened to the item's end, refused past it", () => {
+ const sp = slamSpan(slam(), [4, 4.5, 5]);
+ assert.deepEqual(sp, { t0: 3.8, t2: 6.6, t3: 6.95, landings: [4, 4.5, 5] });
+ assert.equal(slamSpan(slam(), [4, 4.5, 5], { end: 6 }).t3, 6);
+ assert.match(slamSpan(slam(), [4, 4.5, 5], { end: 5 }).error, /lands at 5 s, at or after the item's 5 s/);
+});
+
+test("MOTION: the teaser's slam (deck.mjs TEASER_MOTION's hit, under, settle, blur), from its own scale -- huge, shrinking onto its spot, landing, settling", () => {
+ for (const k of ["hit", "under", "settle", "blur"]) assert.equal(SLAM_MOTION[k], TEASER_MOTION[k], k);
+ assert.equal(slamUnitAt(4, 3.79), null);
+ const start = slamUnitAt(4, 3.8);
+ assert.equal(start.scale, 3.5);
+ assert.equal(start.blur, 18);
+ assert.equal(start.opacity, 0);
+ assert.ok(start.ghost > 0.99);
+ const mid = slamUnitAt(4, 3.9);
+ assert.ok(mid.scale < 3.5 && mid.scale > 2, String(mid.scale));
+ // Lands under its rest size, the flash and the ring and the dust fire.
+ const land = slamUnitAt(4, 4);
+ assert.equal(land.scale, SLAM_MOTION.under);
+ assert.equal(land.flash, 1);
+ assert.equal(land.ring, 0);
+ assert.equal(land.ghost, 0);
+ assert.equal(slamUnitAt(4, 5).scale, 1);
+ assert.equal(slamUnitAt(4, 5).blur, 0);
+ assert.equal(slamUnitAt(4, 5).ring, -1);
+ // The row: glyphs land left to right; before the second's start only the first is in.
+ const st = slamStateAt({ span: slamSpan(slam(), [4, 4.5, 5]), fromScale: 3.5 }, 4.2);
+ assert.deepEqual(st.units.map((u) => u.k), [0]);
+ assert.equal(slamStateAt({ span: slamSpan(slam(), [4, 4.5, 5]), fromScale: 3.5 }, 7), null);
+});
+
+test("SHAKE: a punch at each landing that dies in its span; the ffmpeg term is the same curve", () => {
+ assert.deepEqual(slamShakeAt([4], 3.9), { x: 0, y: 0 });
+ assert.equal(slamShakeAt([4], 4).y, 0.75);
+ assert.deepEqual(slamShakeAt([4], 4.4), { x: 0, y: 0 });
+ const ex = slamShakeExpr([4, 4.5], "x", 9);
+ assert.match(ex, /^9\*\(if\(between\(t,4,4\.3\),exp\(-\(t-4\)\/0\.075\)\*sin\(/);
+ assert.equal(slamShakeExpr([], "x", 9), "0");
+});
+
+test("SOUND: one title-tier trailer hit per landing (the teaser's generator), the swell after the last with swell; none with sfx off", () => {
+ const sp = slamSpan(slam(), [4, 4.5, 5]);
+ const hits = slamHits(slam(), sp);
+ assert.deepEqual(hits.map((h) => [h.kind, h.at, h.gain, h.f0]), [["hit", 4, 1, 92], ["hit", 4.5, 1, 92], ["hit", 5, 1, 92]]);
+ assert.deepEqual({ ...hits[0], kind: undefined, at: undefined, role: undefined }, { ...TRAILER_HIT_TIERS.title, kind: undefined, at: undefined, role: undefined });
+ assert.equal(slamHits(slam({ swell: true }), sp).at(-1).kind, "swell");
+ assert.deepEqual(slamHits(slam({ sfx: "off" }), sp), []);
+ const g = trailerHitsGraph(hits, { seconds: 8, rate: 48000, prefix: "sl" });
+ assert.match(g, /\[sla\]$/);
+ assert.match(g, /\[slb\]\[slp\]\[slr\]amix/);
+ assert.ok(!/\[ta\]/.test(g));
+});
+
+test("PLAN: a slam up with a word zoom is refused; a caption up with it waits for it to be gone (the slam first, then the chip)", () => {
+ const e = narrated({ fx: [{ kind: "caption", match: "Fudōshin", text: "不動心 · fudōshin" }, slam()] });
+ const [p] = slamPlan(e);
+ assert.deepEqual(p.span.landings, [4.74, 5.3, 5.86]);
+ assert.deepEqual(p.units, ["不", "動", "心"]);
+ // "Its" (word 14) starts 5.7 + 0.5 = 6.2 s, within 0.25 s... of no hit (5.86 is 0.34 s before): not protected; nothing else is near.
+ assert.deepEqual(p.avoid, []);
+ const caps = captionPlan(e, undefined, { zooms: [{ t0: p.span.t0, t3: p.span.t3, i: p.i }] });
+ assert.equal(caps[0].span.t0, p.span.t3);
+ assert.equal(caps[0].span.waited, 1);
+ assert.throws(() => slamPlan(e, undefined, { zooms: [{ t0: 5, t3: 6, i: 0 }] }), /is up while word zoom 1 is/);
+ assert.throws(() => slamPlan(narrated({ fx: [slam(), slam({ text: "心" })] })), /slams 1 and 2 are up at once/);
+});
+
+test("WHERE: a row centred on the word just above its line; below when above would leave the frame or cover a word read at a hit; centre on the card", () => {
+ const word = { x: 400, y: 300, width: 200, height: 40 };
+ const card = { x: 100, y: 100, width: 900, height: 800 };
+ const bounds = { x: 12, y: 12, width: 1896, height: 1056 };
+ const units = [{ width: 120, height: 120 }, { width: 120, height: 120 }, { width: 120, height: 120 }];
+ const up = slamLayout({ word, card, bounds, units, gap: 6, protect: [word], obstacles: [{ x: 300, y: 250, width: 400, height: 40 }] });
+ assert.equal(up.where, "above");
+ assert.deepEqual([up.x, up.y, up.width, up.height], [320, 174, 360, 120]);
+ assert.deepEqual(up.centers, [{ x: 380, y: 234 }, { x: 500, y: 234 }, { x: 620, y: 234 }]);
+ // It lies over the line above: the gag, counted.
+ assert.equal(up.covers, 1);
+ assert.equal(up.blocked, false);
+ // Near the frame's top: below its line.
+ assert.equal(slamLayout({ word: { ...word, y: 60 }, card, bounds, units, gap: 6, protect: [{ ...word, y: 60 }] }).where, "below");
+ // A word read at a hit above it: below.
+ const read = { x: 420, y: 250, width: 80, height: 40 };
+ assert.equal(slamLayout({ word, card, bounds, units, gap: 6, protect: [word, read] }).where, "below");
+ // Kept in the frame sideways.
+ assert.equal(slamLayout({ word: { ...word, x: 0, width: 50 }, card, bounds, units, gap: 6 }).x, 12);
+ const mid = slamLayout({ card, bounds, units, place: "center" });
+ assert.deepEqual([mid.where, mid.x, mid.y], ["center", 370, 440]);
+});
+
+test("THE SEGMENT KEY (post-render.mjs postFxKeyFields): nothing for an item without a slam; a slam adds its drawing version, its motion and its hit", async () => {
+ const { postFxKeyFields, POST_SLAM_DRAW_V } = await import("./post-render.mjs");
+ assert.deepEqual(postFxKeyFields(base(), {}), {});
+ assert.deepEqual(postFxKeyFields(base({ fx: [{ kind: "caption", match: "x", text: "y" }] }), {}), { captionV: 2 });
+ const k = postFxKeyFields(base({ fx: [slam()] }), {});
+ assert.deepEqual(Object.keys(k), ["slam"]);
+ assert.equal(k.slam.v, POST_SLAM_DRAW_V);
+ assert.deepEqual(k.slam.hit, TRAILER_HIT_TIERS.title);
+ assert.deepEqual(k.slam.motion, SLAM_MOTION);
+});
+
+test("THE ENCODE (postSegmentArgs): the slam's frames laid over everything while up, the frame's punch, the hits mixed into the audio", async () => {
+ const { postSegmentArgs } = await import("./post-render.mjs");
+ const args = (o) => postSegmentArgs({
+ entry: base(), box: { width: 1600, height: 900 }, plan: { total: 8, steps: [] }, layout: { mode: "card", slot: null }, cards: { read: "/c/read.png" }, files: [],
+ render: { fps: 30, audioRate: 48000, palette: { bg: "#101010" } }, outPath: "/o.mp4", ...o,
+ });
+ const plainArgs = args({});
+ const fc0 = plainArgs[plainArgs.indexOf("-filter_complex") + 1];
+ assert.ok(!/slm|sla|crop=/.test(fc0));
+ assert.match(fc0, /anull\[a\]$/);
+ const a = args({ slams: [{ list: "/c/slam-1/frames.ffconcat", t0: 3.8, t3: 6.95, landings: [4, 4.5, 5] }], slamHitList: slamHits(slam(), slamSpan(slam(), [4, 4.5, 5])) });
+ const fc = a[a.indexOf("-filter_complex") + 1];
+ assert.match(fc, /\[slm0\]overlay=x=0:y=0:eof_action=pass:enable='between\(t,3\.8,6\.95\)'/);
+ assert.match(fc, /pad=iw\+\d+:ih\+\d+:\d+:\d+:color=0x101010,crop=1600:900:'\d+\+7\.5\*\(if\(between\(t,4,/);
+ assert.match(fc, /anull\[apre\]/);
+ assert.match(fc, /\[apre\]\[sla\]amix=inputs=2:normalize=0:duration=first,alimiter=limit=0\.95/);
+ assert.ok(a.includes("/c/slam-1/frames.ffconcat"));
+});
diff --git a/umtool/report-to-video/trailer-hits.mjs b/umtool/report-to-video/trailer-hits.mjs
@@ -0,0 +1,152 @@
+// TRAILER HITS: the movie-trailer boom the teaser card plays under each pop
+// (deck.mjs teaserHits, build-video.mjs teaserAudioGraph -- the ferret-rescue
+// finale's), factored out so a post item's SLAM (post-slam.mjs) plays the same
+// generator: one hit per glyph, the title tier, and optionally the tail's swell.
+//
+// Synthesised in ffmpeg, no samples: nothing is downloaded or bundled. The
+// teaser's graph is byte for byte what it was before this module (its tests,
+// and so the ferret cut's render key, are unchanged); the slam's names its own
+// labels (`prefix`) so the graph can sit inside a post segment's.
+//
+// Plain ESM, no imports: build-video, deck, post-render and the browser (Play's
+// live sound, trailerHitSamples) all read it.
+
+/**
+ * The hits' tiers (gains relative: the main title is 1): a title's hit is the
+ * biggest, an overline's and a kicker's a little smaller, a second tier's
+ * lighter and shorter. `decay` is the boom's time constant, `f0 → f1` its pitch drop.
+ */
+export const TRAILER_HIT_TIERS = Object.freeze({
+ title: Object.freeze({ gain: 1, decay: 0.42, f0: 92, f1: 40 }),
+ overline: Object.freeze({ gain: 0.72, decay: 0.34, f0: 96, f1: 44 }),
+ kicker: Object.freeze({ gain: 0.8, decay: 0.36, f0: 94, f1: 42 }),
+ sub: Object.freeze({ gain: 0.42, decay: 0.16, f0: 120, f1: 64 }),
+});
+
+/** The tail's swell (a low rise under a slow entrance): its gain, decay and pitch, the duration the caller's. */
+export const TRAILER_SWELL = Object.freeze({ gain: 0.34, decay: 0.7, f0: 46, f1: 62 });
+
+/** The sound's level and ceiling: `limit` is −6 dBFS; `level` is set against the ferret cut's loudness (README). */
+export const TRAILER_AUDIO = Object.freeze({ level: 1.4, limit: 0.5 });
+
+/** A number for an aevalsrc expression: 6 decimals, no trailing zeros. */
+export const ev6 = (v) => {
+ const s = (Math.round(Number(v) * 1e6) / 1e6).toFixed(6).replace(/\.?0+$/, "");
+ return s === "-0" ? "0" : s;
+};
+
+/** The hash noise every layer uses (the same whatever else is in the graph), as an expression of the sample `n`. */
+const NOISE = "(2*(sin(n*12.9898+78.233)*43758.5453-floor(sin(n*12.9898+78.233)*43758.5453))-1)";
+
+/**
+ * The hits' sound, as one filtergraph fragment from no inputs to `[<prefix>a]`
+ * (`prefix` "t": the teaser's `[ta]`, and its inner labels `[tb] [tp] [tr] [tw]`).
+ *
+ * A hit is three layers, each summed over every hit in one `aevalsrc` and
+ * gated to its own span, so each starts on the sample its time names:
+ * - the boom: a sine whose pitch drops from f0 to f1 (most of the way in
+ * ~0.4 s), with its octave for body, on an exponential decay (`decay` is
+ * the time constant; it is inaudible by ~7×) after a 3 ms attack;
+ * - the punch: a burst of noise (50 ms time constant), band-passed (180 Hz–3.2 kHz);
+ * - the tail: a low noise decay (low-passed at 260 Hz) under it.
+ * A swell is the boom's sine rising f0 → f1 under an envelope that peaks
+ * three quarters of the way through `dur` and settles, with a breath of the
+ * low noise. A riser (a dip's, under the black) is a sub whose pitch climbs
+ * f0 → f1 over `dur` and a noise swell -- its own layer, band-passed
+ * 400 Hz–6.5 kHz, present only when there is a riser -- both rising (the sub
+ * squared, the noise cubed) to their peak at the first hit and released over
+ * `decay`. The sum takes a short low-passed echo, then `level`, then a limiter
+ * at `limit` (no auto-level, latency compensated) so hits that overlap still
+ * sum cleanly; trimmed and padded to exactly `seconds`. No hits: digital silence.
+ *
+ * @param {Array<{ kind: string, at: number, gain: number, decay: number, f0: number, f1: number, dur?: number }>} hits
+ * @param {{ seconds: number, rate: number, layout?: string, level?: number, limit?: number, prefix?: string }} o
+ */
+export function trailerHitsGraph(hits, { seconds, rate, layout = "stereo", level = TRAILER_AUDIO.level, limit = TRAILER_AUDIO.limit, prefix = "t" }) {
+ const p = prefix;
+ const len = ev6(seconds);
+ const tail = `atrim=end=${len},apad=whole_dur=${len},asetpts=PTS-STARTPTS[${p}a]`;
+ if (!hits.length) return `anullsrc=channel_layout=${layout}:sample_rate=${rate},${tail}`;
+ const noise = NOISE;
+ const boom = [];
+ const punch = [];
+ const rumble = [];
+ const whoosh = [];
+ for (const h of hits) {
+ const a = ev6(h.at);
+ const u = `(t-${a})`;
+ const g = ev6(h.gain);
+ if (h.kind === "riser") {
+ const D = ev6(h.dur);
+ const v = `min(${u},${D})`;
+ const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * h.dur))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`;
+ const rel = `clip((${ev6(h.dur + h.decay)}-${u})/${ev6(h.decay)},0,1)`;
+ const span = ev6(h.dur + h.decay);
+ boom.push(`if(between(t,${a},${a}+${span}),${g}*0.5*pow(${v}/${D},2)*${rel}*sin(2*PI*${phase}),0)`);
+ whoosh.push(`if(between(t,${a},${a}+${span}),${g}*0.6*pow(${v}/${D},3)*${rel}*${noise},0)`);
+ continue;
+ }
+ if (h.kind === "swell") {
+ const D = h.dur;
+ const peak = ev6(D * 0.75);
+ const v = `min(${u},${ev6(D)})`;
+ const phase = `(${ev6(h.f0)}*${v}+${ev6((h.f1 - h.f0) / (2 * D))}*${v}*${v}+${ev6(h.f1)}*(${u}-${v}))`;
+ const env = `pow(sin(PI/2*min(1,${u}/${peak})),2)*exp(-max(0,${u}-${peak})/${ev6(h.decay)})`;
+ const span = ev6(D * 0.75 + h.decay * 7);
+ boom.push(`if(between(t,${a},${a}+${span}),${g}*0.42*${env}*sin(2*PI*${phase}),0)`);
+ rumble.push(`if(between(t,${a},${a}+${span}),${g}*0.5*${env}*${noise},0)`);
+ continue;
+ }
+ const k = HIT_PITCH_TAU;
+ const phase = `(${ev6(h.f1)}*${u}+${ev6((h.f0 - h.f1) * k)}*(1-exp(-${u}/${k})))`;
+ const span = ev6(h.decay * 7);
+ boom.push(
+ `if(between(t,${a},${a}+${span}),${g}*0.3*min(1,${u}/0.003)*exp(-${u}/${ev6(h.decay)})*` +
+ `(sin(2*PI*${phase})+0.6*exp(-${u}/${ev6(h.decay * 0.6)})*sin(4*PI*${phase})),0)`,
+ );
+ punch.push(`if(between(t,${a},${a}+0.25),${g}*0.5*exp(-${u}/0.05)*${noise},0)`);
+ rumble.push(`if(between(t,${a},${a}+${ev6(Math.min(2.6, h.decay * 6))}),${g}*0.32*min(1,${u}/0.02)*exp(-${u}/${ev6(h.decay * 1.3)})*${noise},0)`);
+ }
+ const src = (terms) => `aevalsrc=exprs='${terms.length ? terms.join("+") : "0"}':s=${rate}:c=${layout}:d=${len}`;
+ // The riser's layer only when there is one: a teaser without a dip writes the graph it always did.
+ const w = whoosh.length ? [`${src(whoosh)},highpass=f=400,lowpass=f=6500[${p}w]`] : [];
+ return [
+ `${src(boom)}[${p}b]`,
+ `${src(punch)},highpass=f=180,lowpass=f=3200[${p}p]`,
+ `${src(rumble)},lowpass=f=260,lowpass=f=260[${p}r]`,
+ ...w,
+ `[${p}b][${p}p][${p}r]${w.length ? `[${p}w]` : ""}amix=inputs=${3 + w.length}:normalize=0,aecho=1:1:90|190:0.18|0.09,lowpass=f=5000,` +
+ `volume=${ev6(level)},alimiter=limit=${ev6(limit)}:level=0:latency=1:attack=2:release=80,${tail}`,
+ ].join(";");
+}
+
+/** The hit's pitch drop's time constant, seconds. */
+export const HIT_PITCH_TAU = 0.13;
+
+/**
+ * ONE HIT's raw layers as samples (Play's live sound: the same formulas as
+ * trailerHitsGraph's `aevalsrc`, which a browser then filters as the graph does
+ * -- the punch band-passed 180 Hz–3.2 kHz, the rumble low-passed at 260 Hz).
+ * `{ boom, punch, rumble }`, Float32Arrays of `seconds` at `rate`, from the hit's
+ * own start (sample 0 is its `at`).
+ * @param {{ gain: number, decay: number, f0: number, f1: number }} h
+ * @param {number} rate
+ */
+export function trailerHitSamples(h, rate = 48000) {
+ const seconds = Math.min(3, h.decay * 7);
+ const n = Math.max(1, Math.round(seconds * rate));
+ const boom = new Float32Array(n);
+ const punch = new Float32Array(n);
+ const rumble = new Float32Array(n);
+ const k = HIT_PITCH_TAU;
+ const fr = (x) => x - Math.floor(x);
+ for (let i = 0; i < n; i += 1) {
+ const u = i / rate;
+ const phase = h.f1 * u + (h.f0 - h.f1) * k * (1 - Math.exp(-u / k));
+ boom[i] = h.gain * 0.3 * Math.min(1, u / 0.003) * Math.exp(-u / h.decay) * (Math.sin(2 * Math.PI * phase) + 0.6 * Math.exp(-u / (h.decay * 0.6)) * Math.sin(4 * Math.PI * phase));
+ const nz = 2 * fr(Math.sin(i * 12.9898 + 78.233) * 43758.5453) - 1;
+ punch[i] = u <= 0.25 ? h.gain * 0.5 * Math.exp(-u / 0.05) * nz : 0;
+ rumble[i] = u <= Math.min(2.6, h.decay * 6) ? h.gain * 0.32 * Math.min(1, u / 0.02) * Math.exp(-u / (h.decay * 1.3)) * nz : 0;
+ }
+ return { boom, punch, rumble, seconds };
+}
diff --git a/umtool/report-to-video/word-zoom.mjs b/umtool/report-to-video/word-zoom.mjs
@@ -33,10 +33,12 @@ import { cardText, contextText, parentsOf } from "./post-item.mjs";
import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs";
import { captionErrors } from "./post-caption.mjs";
import { clockErrors } from "./post-clock.mjs";
+import { slamErrors } from "./post-slam.mjs";
// A post's effects: a word zoom, a CAPTION (post-caption.mjs: a chip explaining a phrase as it is read), and its
-// CLOCK (post-clock.mjs: the post's time on the card, running from the item before's).
-export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock"]);
+// CLOCK (post-clock.mjs: the post's time on the card, running from the item before's), and a SLAM (post-slam.mjs:
+// a trailer-style title slam of a few glyphs over the word as it is read, one trailer hit per glyph).
+export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock", "slam"]);
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" });
@@ -142,6 +144,7 @@ export function validatePostFx(e) {
if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`);
if (fx.kind === "caption") return errors.push(...captionErrors(e, fx, fw));
if (fx.kind === "clock") return errors.push(...clockErrors(e, fx, fw));
+ if (fx.kind === "slam") return errors.push(...slamErrors(e, fx, fw));
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;