Archilyzer · Source

archilyzer

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

commit a0a53216be6ee046613c27309b4ceca62648b40d
parent b4fe08e1ae246ba973d626843f9d436a5ffacb78
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 19:35:43 -0500

Merge main (post-slam, long-reads) into lane/fast-fix-render

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

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 16+++++++++++++---
Mumtool/components/projects/PostBench.tsx | 25++++++++++++++++++++++++-
Mumtool/components/projects/PostZoomPanel.tsx | 46+++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/review/PlayCut.tsx | 3+++
Mumtool/components/projects/review/PostItemPlayer.tsx | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/docs/cli.md | 4++++
Mumtool/docs/knobs.md | 32++++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 147++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/e2e/long-reads.spec.ts | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/post-slam.spec.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 24+++++++++++++++++++++++-
Mumtool/lib/report/playView.mjs | 6+++++-
Mumtool/lib/report/postFx.test.mjs | 28++++++++++++++++++++++++++++
Mumtool/lib/report/postFxCli.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/lib/report/postReread.mjs | 299+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/lib/report/postReread.test.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postYell.mjs | 393+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postYell.test.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/build-video.mjs | 91+++++++------------------------------------------------------------------------
Mumtool/report-to-video/deck.mjs | 11++++-------
Mumtool/report-to-video/package.json | 3+++
Mumtool/report-to-video/post-item.mjs | 3+++
Mumtool/report-to-video/post-narration.mjs | 20++++++++++++++++----
Aumtool/report-to-video/post-progress.mjs | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-progress.test.mjs | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-redact.mjs | 4+++-
Mumtool/report-to-video/post-render.mjs | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/report-to-video/post-slam.mjs | 615+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-slam.test.mjs | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/trailer-hits.mjs | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/word-zoom.mjs | 7+++++--
32 files changed, 3392 insertions(+), 195 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -11,7 +11,7 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; -import { rereadTake } from "@/lib/report/postReread.mjs"; +import { parseTempoSpec, rereadTake } from "@/lib/report/postReread.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; @@ -42,6 +42,7 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // when the editor has no engine for it // POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) // POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece +// POST {project, op: "reread", id, tempo: "4-16=1.35", stretch?} its parts RE-TIMED (no TTS); {…, yell: true, yellGain?, yellStyle?}: its caps raised // (postReread.mjs: no TTS; a new take, picked, one undo point) // POST {project, op: "undo"} the last structural write undone @@ -223,10 +224,19 @@ export async function POST(request: Request) { // The bench's "Read without it" (postReread.mjs): the picked take's kept parts cut and joined again, no TTS. const list = (v: unknown) => (Array.isArray(v) ? v.map(String) : typeof v === "string" && v ? v.split(",") : []); try { - const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true }); + // `tempo`: "4-16=1.35,21-25=1.3" (postReread.mjs parseTempoSpec) -- the parts re-timed; `yell: true` -- the caps raised (postYell.mjs). + if (body.yell === true) { + const { yellTake } = await import("@/lib/report/postYell.mjs"); + const { cutSlurs } = await import("umtool-report-to-video/post-redact-files"); + const yy = await yellTake(r.project, e, { slurs: cutSlurs(m), ...(typeof body.yellGain === "number" ? { gain: body.yellGain } : {}), ...(typeof body.yellStyle === "string" ? { style: body.yellStyle } : {}) }); + return Response.json({ ok: true, take: yy.take, spans: yy.plan.spans, entry: yy.result?.entry ?? null, token: yy.result?.token ?? null }, { headers: noStore }); + } + const pt = pickedTake(e) as { parts?: unknown[] } | null; + const tempo = typeof body.tempo === "string" && body.tempo ? parseTempoSpec({ spec: body.tempo, count: Array.isArray(pt?.parts) ? pt.parts.length : 0 }) : null; + const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true, tempo, ...(body.stretch === "rubberband" ? { stretch: "rubberband" } : {}) }); return Response.json({ ok: true, take: rr.take, entry: rr.result?.entry ?? null, token: rr.result?.token ?? null }, { headers: noStore }); } catch (err) { - if ((err as Error)?.name === "RereadError") return Response.json({ error: (err as Error).message }, { status: 400 }); + if ((err as Error)?.name === "RereadError" || (err as Error)?.name === "YellError") return Response.json({ error: (err as Error).message }, { status: 400 }); throw err; } } diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -18,7 +18,9 @@ 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 { progressPlan } from "umtool-report-to-video/post-progress"; import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // --------------------------------------------------------------------------- @@ -123,6 +125,8 @@ export default function PostBench({ ); const shown = useMemo(() => panelEntry(sceneEntry(entry, scene), render) as Entry, [entry, scene, render]); const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, scene: conversation, mediaScene: conversation ? null : scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene, conversation]); + // Its progress bar (post-progress.mjs): the read's span and its parts' ticks. + const progressP = useMemo(() => progressPlan(shown, render, plan as never), [shown, render, plan]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -291,6 +295,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); @@ -317,7 +333,7 @@ export default function PostBench({ </span> </div> <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}> - <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} clock={clockPlan(shown, render, before)} /> + <PostItemPlayer project={project} entry={shown} plan={plan} box={box} s={s} playing={playing} cardKey={`${token}:${scene?.key ?? "-"}`} scene={scene} clock={clockPlan(shown, render, before)} progress={progressP} /> <ComboBadge project={project} entry={shown} plan={plan} combo={liveCombo(combo, render, entry) as ComboInfo | null} box={box} s={s} playing={playing} /> </div> <div className="flex items-center gap-2 text-[12px]"> @@ -356,6 +372,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/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -122,6 +122,8 @@ export type PlayEntry = { /** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */ post?: Record<string, unknown> & { id: string }; postPlan?: PostPlan; + /** Its progress bar (post-progress.mjs progressPlan), or null. */ + postProgress?: { from: number; to: number; ticks: number[]; until: number; mode: string } | null; /** Its clock (post-clock.mjs clockPlan), or null. */ postClock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; /** Its combo badge (post-combo.mjs): the attachment it repeats, its count, the knobs. */ @@ -860,6 +862,7 @@ export default function PlayCut({ uncensored={uncensored} scene={postNow.entry.postScene ?? null} clock={postNow.entry.postClock ?? null} + progress={postNow.entry.postProgress ?? null} joinFrom={(() => { // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended. const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null; diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -13,6 +13,11 @@ 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 { measureProgressPlace, mountProgress, progressAt, progressCss, progressHeight, progressOpacityAt, setProgressState } from "umtool-report-to-video/post-progress"; +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"; // --------------------------------------------------------------------------- @@ -52,9 +57,14 @@ import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, tar // --------------------------------------------------------------------------- type Rect = { x: number; y: number; width: number; height: number }; +/** A progress bar's plan (post-progress.mjs progressPlan): the read's span on the item's clock, the parts' ticks. */ +export type ProgressPlan = { from: number; to: number; ticks: number[]; until: number; mode: string }; + /** 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 +217,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" }; /** @@ -428,7 +491,7 @@ function JoinEnds({ project, ends, layout, box, op }: { project: string; ends: A } export default function PostItemPlayer({ - project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, + project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, progress = null, }: { project: string; take?: string | null; @@ -452,6 +515,8 @@ export default function PostItemPlayer({ clock?: { to: number; from: number | null; mode: "forward" | "rewind" | "none"; zone: string; gap: number; forced: boolean } | null; /** THE JOIN (post-join.mjs): the item before (its entry and plan) -- this one opens on it as it ended. */ joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null; + /** Its progress bar (post-progress.mjs progressPlan), or none. */ + progress?: ProgressPlan | null; }) { const wrap = useRef<HTMLDivElement | null>(null); const [scale, setScale] = useState(0); @@ -549,6 +614,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 +652,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 +686,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. @@ -673,10 +776,44 @@ export default function PostItemPlayer({ }, [clock, box.height, follow, plan.total]); const placeClockRef = useRef(placeClock); placeClockRef.current = placeClock; + // ---- the progress bar, live (post-progress.mjs): mounted and placed as the build places it, set each tick ---- + const [progAt, setProgAt] = useState<{ x: number; y: number; width: number } | null>(null); + const placeProgress = useCallback(() => { + const doc = readFrame.current?.contentDocument; + if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return; + if (!progress) { + mountProgress(null, doc); + setProgAt(null); + return; + } + const k = box.height / 1080; + const h = mountProgress({ css: progressCss({ height: box.height, palette: paletteOfDoc(doc) }), ticks: progress.ticks }, doc) ?? progressHeight(box.height); + const route = follow && doc.querySelector("[data-post-flow]") ? followPath(follow, measureFollow(doc)) : null; + // Judged over the read (its end, start and middle), as the build judges it: the place over fewest words. + const states = follow && route ? [plan.total, 0, plan.total / 2] : [0]; + const cb = clockRect.current ? { x: clockRect.current.x + 240 * k, y: clockRect.current.y, width: clockRect.current.width - 240 * k, height: clockRect.current.height } : null; + let first: ReturnType<typeof measureProgressPlace> = null; + const sums: number[] = []; + for (const st of states) { + if (follow && route) applyFollowState(followStateAt(follow, route, st), doc); + const l = measureProgressPlace({ height: h, inset: Math.round(22 * k), avoid: cb ? [cb] : [], fixed: first?.tries ?? null }, doc); + if (!first) first = l; + (l?.counts ?? []).forEach((c: number, i: number) => (sums[i] = (sums[i] ?? 0) + c)); + } + if (follow && route) applyFollowState(followStateAt(follow, route, 0), doc); + const best = first ? first.tries.map((t: { x: number; y: number; width: number }, i: number) => ({ ...t, covers: sums[i] ?? 0 })).sort((a: { covers: number }, b: { covers: number }) => a.covers - b.covers)[0] : null; + setProgAt(best ? { x: best.x, y: best.y, width: best.width } : null); + }, [progress, box.height, follow, plan.total]); + const placeProgressRef = useRef(placeProgress); + placeProgressRef.current = placeProgress; + useEffect(() => { + placeProgress(); + }, [placeProgress]); const onFrameLoad = useCallback(() => { let tries = 0; const tick = () => { placeClockRef.current(); + placeProgressRef.current(); if (measure() || tries++ > 50) return; setTimeout(tick, 100); }; @@ -756,6 +893,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; @@ -763,6 +932,15 @@ export default function PostItemPlayer({ const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity; setClockState(clockSt && clockAt && s < until ? { ...clockAt, st: clockSt } : null, doc); }, [clockSt, clockAt, s, layout.mode, plan.steps]); + // The bar's fill: the read's real seconds (a part read faster moves it faster), gone in a stack card's media phase. + const progFrac = progress ? progressAt(progress, s) : null; + useEffect(() => { + const doc = readFrame.current?.contentDocument; + if (!doc || !progress) return; + const until = layout.mode === "stack" && plan.steps.length ? plan.steps[0].at : Infinity; + const op = s < until ? progressOpacityAt(progress, s) : 0; + setProgressState(progAt && progFrac !== null ? { ...progAt, frac: progFrac, opacity: op } : null, doc); + }, [progress, progAt, progFrac, s, layout.mode, plan.steps]); const src = shown && inStep ? mediaTimeAt(shown, s) : null; const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null; return ( @@ -783,6 +961,12 @@ 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-progress={progFrac !== null ? String(Math.round(progFrac * 1000) / 1000) : undefined} + data-post-progress-place={progress && progAt ? `${Math.round(progAt.x)},${Math.round(progAt.y)},${Math.round(progAt.width)}` : 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 @@ -85,11 +85,15 @@ Inbox cannot disagree about what is wrong with one. | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | | `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\|off] [thread.map=auto\|on\|off\|map\|label\|both] [panel=auto\|side\|top\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\|@<file>\|off] [parent.<i>.media=<file>[,…]\|off] [link.add=<json ref>] [link.<i>=<json ref>\|off] [link.<i>.media=<file>\|off] [link.<i>.transcript="…"\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit | | `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) | +| `posts reread <project> <item> --tempo-for "4-16=1.35,21-25=1.3" \| --tempo <x> --parts <runs> [--stretch atempo\|rubberband] [--dry-run] [--json]` | a narrated read's **parts re-timed**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled)): the parts named time-stretched (1–1.6, pitch kept), the rest untouched, joined with the read's pauses (each stretched part padded and trimmed to its length, sample-exact), its words scaled with their part, a derived take (`steps: [{op: "tempo", tempo, params: {stretch}}]`) picked in ONE write. A tempo is absolute: on a re-timed take it re-cuts from the take before. `posts set-item <p> <item> narration.tempo="4-16=1.35"` runs the same. A part outside the take, a tempo outside 1–1.6, nothing changed: **exit 1** | +| `posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run] [--json]` · `posts yell <project> --all \| <item …> [--yell-gain …] [--yell-style …] [--dry-run] [--json]` | a narrated read's **caps yelled**, no TTS ([report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled), `lib/report/postYell.mjs`): his ALL-CAPS words found in the take's word timings and raised (the lift measured, its loudness within 1 LU), acronyms and masked slurs left flat, a derived take (`steps: [{op: "yell", spans, params}]`) picked (one undo point per item). No word timings: **exit 1** naming `posts narrate --words`; `posts yell --dry-run` lists every item's caps, the flat ones and why, and which need word timings | +| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it | | `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | | `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,36 @@ 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}}` | +## The progress bar (a long read's progress along its card's foot) + +`render.posts.progress` (the cut's default) and `progress` on a post item ([report-video.md](report-video.md#the-progress-bar)): +a thin bar along the card's foot that fills with the item's READ -- its real seconds, so a part read faster (a tempo +step) moves it faster and it never jumps -- ticked at each part's start. Refused in the build's words +(`progressErrors`, `validateProgressRender`, `report-to-video/post-progress.mjs`); in the segment key only for an item +that draws it. + +| Knob | In umtool | From a terminal | Route | +|---|---|---|---| +| the cut's bar -- `auto` (a read of 60 s or more, as the item plays it), `on`, `off` (absent: off) | — | `umtool posts progress <p> auto\|on\|off\|default` (`updatePostProgressRender`); bare: which items draw it | — | +| one item's -- `on`, `off`, `auto` (absent: the cut's) | Play and the post bench draw it | `umtool posts set-item <p> <item> progress=on\|off\|auto\|default` | `POST /api/report/post-item {project, op: "set", id, patch: {progress}, token}` | + +## 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 | @@ -854,6 +884,8 @@ gathers them). | `thread` on a post item — `{parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan?}` over the cut's (`parent` one mode, or a list, nearest parent first) | post bench, **thread read**: the post it answers / its parent / the quoted post (the cut's, or a mode), **carry**, **shrink**, **dim**, **over**, **pan**; the guard's refusals listed before Save | `umtool posts set-item <p> <item> thread.parent=excerpt` · `thread.parent.1=hidden` · `thread.quoted=context` · `thread.carry=off` · `thread.shrink=0.5` … · `thread=auto` (the cut's) | `POST /api/report/post-item {project, op: "set", id, patch: {thread}, token}` (an object merges; `null` clears) | | a part's role — the text it reads: `parent:<i>`, `quoted`, `post`, `media:<i>` (stored, else inferred) | post bench, **thread read**: the read piece by piece (click one: the playhead at its start; `·` marks an inferred role) | `umtool posts roles <p> [<item> …]` (list, with the guard's verdict and the warnings: a link said aloud, a text cut short) · `--write` (store the inferred roles) · `<item> --set 3=parent:0,4=post` (`off`: inferred again) | — (`updatePostNarration {partRoles: {take, roles}}`) | | a read RE-JOINED without a piece (no TTS) — the picked take's kept parts cut from its own file and joined with the read's pauses: a derived take (`steps: [{op: "rejoin", drop}]`), picked | post bench, **thread read**: **Read without it** on a context piece the take reads | `umtool posts reread <p> <item> --without parent:0` (`parent:1`, `quoted`) · `--drop-parts 3,4` · `--drop-urls` · `--dry-run`; `umtool posts set-item <p> <item> thread.parent.0=context` re-joins first when the take reads it (the knob alone when it does not; `--no-reread`: refused) | `POST /api/report/post-narration {project, op: "reread", id, without: ["parent:0"], dropParts?, dropUrls?}` | +| a read's PARTS RE-TIMED (no TTS) — the parts named read at a tempo of 1–1.6 (pitch kept: ffmpeg `atempo`, or `rubberband`), the rest untouched, joined with the read's pauses; the words scaled with their part (read-follow, zooms, captions, slams, beeps keep their place); a derived take (`steps: [{op: "tempo", tempo: {"4-16": 1.35}, params: {stretch}}]`, each part's `tempo` stored), picked. A tempo is ABSOLUTE: on a re-timed take it re-cuts from the take before (each part stretched once) | — | `umtool posts reread <p> <item> --tempo-for "4-16=1.35,21-25=1.3"` · `--tempo 1.3 --parts 4-16,21-25` · `--stretch rubberband` · `--dry-run`; `umtool posts set-item <p> <item> narration.tempo="4-16=1.35"` (the same) | `POST /api/report/post-narration {project, op: "reread", id, tempo: "4-16=1.35", stretch?}` | +| a read's CAPS YELLED (no TTS) — the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the take's word timings and raised: +5.5 dB measured over the spans, a presence lift, compressed, gently saturated, limited, 50 ms ramps; acronyms (`YELL_ACRONYMS`, any caps word with no vowel) and masked slurs left flat; timings kept; loudness within 1 LU of its source; a derived take (`steps: [{op: "yell", spans, params: {gain, style}}]`), picked. Needs the take's word timings (`posts narrate --words`) | — | `umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run]` · the cut's: `umtool posts yell <p> --all \| <item …> [--dry-run]` (the dry run lists each item's caps, the ones left flat and why, and the items with no word timings) | `POST /api/report/post-narration {project, op: "reread", id, yell: true, yellGain?, yellStyle?}` | | the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | — | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) | | a post item's `conversation` (the archive row's threadId) and `quoted.via: "link"` (a status link resolved to an archived post) | — | `umtool posts context <p> [--dry-run]` | — (`setPostItemsContext`) | 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 @@ -734,6 +810,74 @@ stack card's, until its media phase); Play and the bench mount the same chip (`mountClock`, `setClockState`) from `clockPlan`, which needs the item before it (`playView` `postClock`; the bench's `before`). +### The progress bar + +A long read may draw a PROGRESS BAR (`report-to-video/post-progress.mjs`; operator, 4 Nov, a +6.5-minute post: "we might want a per-clip progress bar in the engine specifically for clips +like this"): a thin bar along the card's foot -- under its counts row, inside the card, inset +from its rounded corners -- that fills with the item's READ, with a subtle tick where each +part of the read starts. + +```jsonc +"render": { "posts": { "progress": "auto" } }, // the cut's default: auto | on | off (absent: off) +"progress": "on" // one item's (absent: the cut's) +``` + +`auto` draws it for a read of 60 s or more as the item plays it (its `rate` counted). It +fills over the read's REAL seconds -- from the narrator's first word to the last, linear -- +so a part read faster by a tempo step (below) moves it faster and it never jumps at a part's +edge; an item with no read fills over its own length. It fades in over 0.35 s as the read +starts and is gone in a stack card's media phase. Its place is judged over the read (its +start, middle and end: the place over fewest words, the words as seen, clipped to their +window) and short of the clock when that sits on its line; over a word anywhere it moves just +under the card's edge. Drawn OVER the card, never in it (`readInViewErrors` never counts it). +The render shoots its track and its fill once each on a clear page and lays them over the +card, the fill clipped at its leading edge frame by frame (`geq` on the frame's time: +`progressFilters`); Play and the bench mount the same bar (`mountProgress`, +`measureProgressPlace`, `setProgressState`) from `progressPlan` (`playView` `postProgress`). +In the segment key only for an item that draws it (`progress`: its plan and drawing version). +`umtool posts progress <p> auto|on|off|default`; one item's: `posts set-item <p> <item> +progress=on|off|auto|default`. + +### A long read sped up, and its caps yelled + +Two edits of a read that is already there -- no TTS, nothing re-synthesized -- each a DERIVED +take (`source: {kind: "take", from}`), picked in one write (one undo point), chained in either +order (`lib/report/postReread.mjs`, `lib/report/postYell.mjs`): + +- **Per-part tempo** (operator, 4 Nov: "This one is really long, what if we sped it up ... + and then slowing back down here on the juicy persecution complex paragraph"; "dynamic speed + over boring parts of a long message ... nothing too crazy"): `umtool posts reread <p> <item> + --tempo-for "4-16=1.35,21-25=1.3"` (or `--tempo 1.3 --parts 4-16,21-25`; `posts set-item + <p> <item> narration.tempo="…"`). Each part named is time-stretched to that tempo (1–1.6, + its pitch kept: ffmpeg `atempo`, `--stretch rubberband` the alternative), padded and trimmed + to its length so the parts after it land sample-exact; the others are untouched; all are + joined with the read's pauses. Its parts are re-timed (each stretched one's `tempo` + stored) and its word timings scaled with their part, so read-follow, word zooms, captions, + slams and slur beeps keep their place. `steps: [{op: "tempo", tempo: {"4-16": 1.35, + "21-25": 1.3}, params: {stretch}}]`. A tempo is ABSOLUTE (against the part's first read): + on a re-timed take it re-cuts from the take before it, so a part is stretched once, never + twice, and the parts it does not name keep the tempo they had (`1` sets one back). The cut's + `rate` still plays over the whole read: a part at 1.35 in a cut at 1.08 plays at 1.46. +- **The caps yelled** (operator, 4 Nov: "I feel like allcaps needs to be yelled more"): the + scripts are drafted with his ALL-CAPS words lowercased (a stock voice spells a caps word out + letter by letter), so the read said them flat. `umtool posts reread <p> <item> --yell-caps + [--yell-gain 5.5] [--yell-style raise|shout|loud]`, or the cut's `umtool posts yell <p> --all + | <item …>`: the words whose SOURCE word -- his post, or the piece a part reads (the post he + answers, the quote, a linked post: looked for only in the words that read it) -- is ALL CAPS + of two letters or more, found in the take's word timings (aligned like a word zoom's), and + raised over each run of them (spans padded, a run merged): louder by the lift MEASURED over + the spans (+5.5 dB), a presence lift (~3.2 kHz) and some body, compressed, a gentle tanh + saturation, limited under 0 dBFS, crossfaded in and out over 50 ms -- a voice raised, not + turned up. Left flat: acronyms and initialisms (`YELL_ACRONYMS`: FBI, DM, KF, TV, OK …; any + caps word with no vowel reads as letters) and a slur the cut masks (beeped anyway). The take's + loudness stays within 1 LU of its source (over it, the lift is lowered: an all-caps post + keeps the timbre, not the level); its length and its timings are the source's. + `steps: [{op: "yell", spans, params: {gain, style, trim?}}]`. It needs the take's word + timings (`umtool posts narrate <p> <item> --words`) and says so; `posts yell <p> --dry-run` + lists each item's caps, the ones left flat and why, and the items with no word timings. A + yell on a yelled take re-yells the take before it; one further up the chain is refused. + ### The pace `pace: "fast"` on a narrated post's narration (or `render.postNarration.pace`, the cut's) @@ -750,7 +894,8 @@ caption's text and knobs, the clock fx, the narration's `pace`, the item's id (a segment) -- and `postFxKeyFields` (`post-render.mjs`) APPENDS what the entry does not carry: `captionV` and `clockV` (the chip's and the clock's drawing, bumped when their look changes), `clock` (the plan: this post's time, the time it runs from -- the item before's, when that one is a clock item -- the mode, a forced rewind, -the zone) and `pace` (the gap knobs a cut-level pace resolved to). An item with none of these adds nothing, so +the zone), `pace` (the gap knobs a cut-level pace resolved to) and `progress` (the progress bar's plan and its +drawing version, only for an item that draws it). An item with none of these adds nothing, so its key is the one it had before they existed and a take `--from` an earlier one reuses its segment. A take `--from` another hard-links a post item's record (`.post.json`) and its combo pass's files (`.combo.json`, `.plain.mp4`) with its segment (`SEGMENT_FILE_SUFFIXES`), and a post item's files are no longer detached before diff --git a/umtool/e2e/long-reads.spec.ts b/umtool/e2e/long-reads.spec.ts @@ -0,0 +1,184 @@ +import { test, expect, type Page } from "@playwright/test"; +import { spawnSync } from "node:child_process"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// LONG READS (operator, 4 Nov, a 6.5-minute post): a read's parts RE-TIMED with +// no TTS (lib/report/postReread.mjs tempoPlan: the parts named faster, pitch +// kept, the words scaled with them), its caps YELLED (lib/report/postYell.mjs), +// and the PROGRESS BAR along the card's foot (report-to-video/post-progress.mjs) +// that fills over the read's real seconds -- in the bench and in Play. +// Fixture: e2e/fixtures/post-narration-fixture.mjs -- p-11, given here a take +// of three timed parts (6.6 s of tone, its words timed) and progress "on". +// +// LONG_READS_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.LONG_READS_SHOTS ?? null; +const TAKE = "narration/posts/11/take-7.parts-zac.wav"; +const TEXT = "The video speaks for ITSELF.\n\nThen it says it AGAIN, louder.\n\nAnd that is all."; + +type Part = { n: number; para: number; text: string; start: number; seconds: number; tempo?: number }; +type Take = { file: string; seconds: number; parts?: Part[]; words?: Array<{ w: string; start: number; end: number }>; steps?: Array<Record<string, unknown>>; source?: { kind: string; from?: string } }; +type Entry = { id: string; progress?: string; text?: string; narration?: { takes: Take[]; pick?: number; script?: string } }; +const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record<string, unknown> }; +const p11 = () => manifest().timeline.find((e) => e.id === "p-11")!; +const picked = () => { + const n = p11().narration!; + return n.takes[n.pick ?? 0]; +}; + +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 }); + // A take of three parts: 2 s, 2 s, 1.4 s of tone with the read's pauses (0.6 s), every word timed. + const file = path.join(DIR, ...TAKE.split("/")); + const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='0.2*sin(2*PI*220*t)*(0.6+0.4*sin(2*PI*4*t))*(lt(t,2)+between(t,2.6,4.6)+between(t,5.2,6.6))':s=24000:d=6.6", file]); + if (r.status !== 0) throw new Error(String(r.stderr)); + const script = TEXT.replace("ITSELF", "itself").replace("AGAIN", "again"); + const words: Array<{ w: string; start: number; end: number }> = []; + const parts: Part[] = script.split("\n\n").map((text, i) => ({ n: i + 1, para: i, text, start: [0, 2.6, 5.2][i], seconds: [2, 2, 1.4][i] })); + for (const p of parts) { + const ws = p.text.split(/\s+/); + ws.forEach((w, j) => words.push({ w, start: Math.round((p.start + (j * p.seconds) / ws.length) * 1000) / 1000, end: Math.round((p.start + ((j + 0.8) * p.seconds) / ws.length) * 1000) / 1000 })); + } + const m = manifest(); + const e = m.timeline.find((x) => x.id === "p-11")!; + e.text = TEXT; + e.progress = "on"; + e.narration = { ...e.narration!, script, takes: [...e.narration!.takes, { file: TAKE, engine: "orpheus", voice: "zac", seconds: 6.6, script, words, parts } as Take], pick: e.narration!.takes.length }; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); +}); + +/** In the card frame: the bar's box and its fill's clip, the counts row's box, the card words' boxes. */ +const barBoxes = (page: Page) => + page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body) => { + const doc = body.ownerDocument; + const r = (el: Element | null) => { + if (!el) return null; + const b = el.getBoundingClientRect(); + return { x: b.left, y: b.top, width: b.width, height: b.height }; + }; + const bar = doc.querySelector("[data-post-progress]") as HTMLElement | null; + return { + bar: r(bar), + opacity: bar ? Number(bar.style.opacity) : null, + frac: bar ? Number(bar.getAttribute("data-frac")) : null, + ticks: doc.querySelectorAll(".pprog-tick").length, + inCard: !!bar?.closest("[data-post-card]"), + counts: r(doc.querySelector("[data-post-counts]")), + card: r(doc.querySelector("[data-post-card]")), + words: Array.from(doc.querySelectorAll("[data-w]")).map((w) => r(w)!), + }; + }); +const overlap = (a: { x: number; y: number; width: number; height: number }, b: { x: number; y: number; width: number; height: number }) => + 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)); + +test("PER-PART TEMPO, no TTS: the route's reread with tempo \"2=1.5\" makes a derived take -- part 2 shorter by 1.5, its words scaled, the rest untouched -- picked; a re-tune cuts from the first read", async ({ page }) => { + const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.5" } }); + expect(res.ok(), await res.text()).toBeTruthy(); + const t = picked(); + expect(t.file).toMatch(/take-\d+\.tempo-orpheus\.wav$/); + expect(t.steps?.[0]).toMatchObject({ op: "tempo", tempo: { 2: 1.5 }, params: { stretch: "atempo" } }); + expect(t.parts!.map((p) => [p.start, p.seconds, p.tempo ?? 1])).toEqual([[0, 2, 1], [2.6, 1.333, 1.5], [4.533, 1.4, 1]]); + expect(Math.abs(t.seconds - 5.933)).toBeLessThan(0.02); + // The words of part 2 scaled from its start; part 3's moved up by what part 2 lost. + const then = t.words!.find((w) => w.w === "Then")!; + const again = t.words!.find((w) => w.w === "again,")!; + const and = t.words!.find((w) => w.w === "And")!; + expect([then.start, and.start]).toEqual([2.6, 4.533]); + // "again," began 1.333 s into part 2: 0.889 s into it now. + expect(again.start - 2.6).toBeCloseTo(1.333 / 1.5, 2); + // A re-tune: 2=1.2 is cut from the three-part take, not the re-timed one. + const res2 = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.2" } }); + expect(res2.ok(), await res2.text()).toBeTruthy(); + expect(picked().source).toEqual({ kind: "take", from: "take-7.parts-zac" }); + expect(picked().parts!.map((p) => p.tempo ?? 1)).toEqual([1, 1.2, 1]); + // Out of range: refused in the tool's words. + const bad = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.9" } }); + expect(bad.status()).toBe(400); + expect((await bad.json()).error).toMatch(/a tempo is 1–1\.6/); +}); + +test("THE CAPS YELLED: the route's reread with yell makes a derived take of the same length and timings, its spans over ITSELF and AGAIN, picked", async ({ page }) => { + const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", yell: true } }); + expect(res.ok(), await res.text()).toBeTruthy(); + const t = picked(); + expect(t.file).toMatch(/take-\d+\.yell-orpheus\.wav$/); + expect(t.steps?.[0]).toMatchObject({ op: "yell", params: { style: "raise" } }); + const spans = t.steps![0].spans as number[][]; + expect(spans).toHaveLength(2); + const itself = t.words!.find((w) => w.w === "itself.")!; + const again = t.words!.find((w) => w.w === "again,")!; + expect(spans[0][0]).toBeLessThanOrEqual(itself.start); + expect(spans[1][0]).toBeLessThanOrEqual(again.start); + expect(Math.abs(t.seconds - 6.6)).toBeLessThan(0.02); + expect(t.parts!.map((p) => p.start)).toEqual([0, 2.6, 5.2]); +}); + +test("THE PROGRESS BAR on the bench: along the card's foot under its counts row, over no word, ticked at the parts, filling linearly with the read -- and after a tempo, no jump", async ({ page }) => { + await page.setViewportSize({ width: 1500, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-11")); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-progress", "0", { timeout: 15_000 }); + await expect(player).toHaveAttribute("data-post-progress-place", /\d+,\d+,\d+/); + let g = await barBoxes(page); + expect(g.bar).not.toBeNull(); + expect(g.inCard, "drawn over the card, never in it").toBe(false); + expect(g.ticks).toBe(2); + expect(g.bar!.y).toBeGreaterThanOrEqual(g.counts!.y + g.counts!.height); + expect(g.bar!.y + g.bar!.height).toBeLessThanOrEqual(g.card!.y + g.card!.height + 1); + for (const w of g.words) expect(overlap(g.bar!, w)).toBe(0); + // Play it: the fill follows the read. + await page.locator("[data-post-bench-play]").click(); + await expect.poll(async () => Number(await player.getAttribute("data-post-progress")), { timeout: 15_000 }).toBeGreaterThan(0.3); + await page.locator("[data-post-bench-play]").click(); + g = await barBoxes(page); + expect(g.opacity).toBe(1); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "long-reads-bench-progress.png") }); + // Its fill is real time over the read: at a second of the item, (s - lead) / read. + const s = Number(await player.getAttribute("data-post-s")); + const frac = Number(await player.getAttribute("data-post-progress")); + const lead = 0.4; + expect(Math.abs(frac - Math.min(1, Math.max(0, (s - lead) / 6.6)))).toBeLessThan(0.02); +}); + +test("THE PROGRESS BAR in Play, with the read re-timed: it fills over the new read's seconds, monotonic across the faster part", async ({ page }) => { + const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.5" } }); + expect(res.ok(), await res.text()).toBeTruthy(); + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); + const player = page.locator('[data-post-play="p-11"]'); + await expect(player).toHaveAttribute("data-post-progress", "0", { timeout: 15_000 }); + await page.locator("[data-play-toggle]").click(); + const seen: Array<[number, number]> = []; + await expect + .poll(async () => { + const s = Number(await player.getAttribute("data-post-s")); + const f = Number(await player.getAttribute("data-post-progress")); + seen.push([s, f]); + return f; + }, { timeout: 20_000, intervals: [150] }) + .toBeGreaterThan(0.95); + await page.locator("[data-play-toggle]").click(); + // Monotonic, and never a jump: each step of the fill is the step of the clock over the read's 5.933 s. + for (let i = 1; i < seen.length; i += 1) { + const [s0, f0] = seen[i - 1]; + const [s1, f1] = seen[i]; + expect(f1).toBeGreaterThanOrEqual(f0); + if (f0 > 0 && f1 < 1) expect(Math.abs(f1 - f0 - (s1 - s0) / 5.933)).toBeLessThan(0.03); + } + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "long-reads-play-progress.png") }); +}); 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/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2356,7 +2356,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i } /** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ -export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ @@ -3079,6 +3079,28 @@ export async function updatePostClock(dir, patch, { token = null } = {}) { }); } +/** + * THE CUT's PROGRESS BAR default (`render.posts.progress`, post-progress.mjs): "auto" (a read of 60 s or more), + * "on", "off"; null back to the default (off). Validated with the build's check. + * + * @param {string} dir + * @param {"auto" | "on" | "off" | null} mode + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostProgressRender(dir, mode, { token = null } = {}) { + return structural(dir, "post-progress", token, (m) => { + if (!isObj(m.render)) m.render = {}; + const posts = isObj(m.render.posts) ? m.render.posts : {}; + if (mode === null || mode === undefined) delete posts.progress; + else posts.progress = mode; + if (Object.keys(posts).length) m.render.posts = posts; + else delete m.render.posts; + const errors = validatePostsRender(m.render); + if (errors.length) throw new StructureRefused(errors); + return { progress: posts.progress ?? null }; + }); +} + // ---- the slur filter (post-slurs.mjs; `umtool posts slurs`) --------------- /** diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -17,6 +17,7 @@ import { dateKeyLabel } from "./playCut.mjs"; import { panelEntry, postDay, postItemPlan } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { clockPlan } from "umtool-report-to-video/post-clock"; +import { progressPlan } from "umtool-report-to-video/post-progress"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; @@ -52,6 +53,7 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu const day = postDay(e.date); const dateKey = day ? Number(day.replace(/-/g, "")) : null; const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); + const plan = postItemPlan(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null }); return { id: e.id, type: "post", @@ -64,7 +66,9 @@ export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = nu post: panelEntry(sceneEntry(e, mediaScene), render), // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: the // posts its run left on screen (post-conversation.mjs: one conversation played as one scene) -- it wins the card. - postPlan: postItemPlan(panelEntry(sceneEntry(e, mediaScene), render), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene, join: ctx?.join ?? null }), + postPlan: plan, + // Its progress bar (post-progress.mjs): the read's span and its parts' ticks (Play lays a stack card's end). + postProgress: progressPlan(e, render, plan), // Its clock (post-clock.mjs): its post's time, run from the clock item before it. postClock: clockPlan(e, render, ctx?.prev ?? null), ...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}), 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/postReread.mjs b/umtool/lib/report/postReread.mjs @@ -23,7 +23,7 @@ import { execFile } from "node:child_process"; import { mkdir, readdir, rm, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; -import { POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { POST_NARRATION_LIMITS, POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takeSourceOf, takesDirOf } from "umtool-report-to-video/post-narration"; import { partRoles } from "umtool-report-to-video/post-thread"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -37,6 +37,8 @@ const r3 = (v) => Math.round(v * 1000) / 1000; export const REREAD_USAGE = [ " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", + " umtool posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" | --tempo 1.3 --parts 4-16,21-25 [--stretch atempo|rubberband] [--dry-run] [--json]", + " umtool posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", " A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with", " the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without", " drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;", @@ -54,6 +56,69 @@ export class RereadError extends Error { const PIECE_RE = /^(parent:\d|quoted)$/; /** + * THE JOIN of a take's parts, pure: `keep` -- `[{ k, factor }]` in order, `k` + * the part's index in `t.parts`, `factor` the time-stretch it is read at + * (1: untouched) -- cut from `t`'s file and joined with the read's pauses + * (POST_PART_GAP: between paragraphs, inside one). Returns `{ spans, parts, + * words, script, seconds }`: `spans` in the source take's seconds (`at` the + * part's start in the new one, `len` its length there), the parts re-timed + * (roles stored, a stretched part's `tempo` its reading speed against its + * first read), the words moved -- a stretched part's scaled by its factor -- + * and a word in no kept part dropped. + * + * @param {Record<string, any>} t the source take + * @param {Array<{ k: number, factor: number, tempo?: number }>} keep + * @param {Array<{ role?: string | null }>} roles partRoles of the entry + */ +export function joinParts(t, keep, roles = []) { + const parts = t.parts; + const spans = []; + let cur = 0; + keep.forEach(({ k, factor, tempo }, j) => { + const p = parts[k]; + const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1].k].para ? POST_PART_GAP.para : POST_PART_GAP.inside; + const at = r3(cur + gap); + const f = fin(factor) && factor > 0 ? factor : 1; + const len = r3(p.seconds / f); + spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap, ...(Math.abs(f - 1) > 1e-6 ? { factor: Math.round(f * 1e6) / 1e6 } : {}), len, tempo: fin(tempo) ? tempo : fin(p.tempo) ? p.tempo : 1 }); + cur = at + len; + }); + const newParts = spans.map((s, j) => { + const p = parts[s.k]; + const { gapBefore: _g, role: _r, tempo: _t, ...rest } = p; + const role = roles[s.k]?.role ?? p.role ?? null; + const tempo = Math.round(s.tempo * 1000) / 1000; + return { ...rest, n: j + 1, start: s.at, seconds: s.len, ...(role ? { role } : {}), ...(Math.abs(tempo - 1) > 1e-6 ? { tempo } : {}) }; + }); + // Its words moved with their parts (a word is its part's when it starts inside the part's span), scaled with a stretched one. + const words = Array.isArray(t.words) + ? t.words.flatMap((w) => { + const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05); + if (!s) return []; + const f = s.factor ?? 1; + const at = (v) => r3(Math.min(s.at + s.len + 0.05, Math.max(0, s.at + (v - s.from) / f))); + return [{ w: w.w, start: at(w.start), end: Math.max(at(w.start), at(w.end)) }]; + }) + : null; + const script = spans.reduce((acc, s, j) => { + const p = parts[s.k]; + const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " "; + return acc + sep + String(p.text ?? "").trim(); + }, ""); + return { spans, parts: newParts, words, script, seconds: r3(cur) }; +} + +/** The picked take's parts, all timed -- or a RereadError (a take read in one go has none). */ +function timedParts(entry, t, what = "re-join") { + if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to ${what}`); + const parts = Array.isArray(t.parts) ? t.parts : []; + if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) { + throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate <p> ${entry.id} --take)`); + } + return parts; +} + +/** * THE RE-JOIN's PLAN, pure: which parts of `entry`'s picked take are kept and * where each lands in the new take -- `{ take, keep: [k…], drop: [{ k, why }], * spans: [{ k, from, to, at }], parts, words, script, seconds, steps }`. @@ -66,11 +131,7 @@ const PIECE_RE = /^(parent:\d|quoted)$/; */ export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = false } = {}) { const t = pickedTake(entry); - if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to re-join`); - const parts = Array.isArray(t.parts) ? t.parts : []; - if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) { - throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate <p> ${entry.id} --take)`); - } + const parts = timedParts(entry, t); for (const w of without) if (!PIECE_RE.test(w)) throw new RereadError(`--without ${w}: a piece is parent:0, parent:1 or quoted`); for (const n of dropParts) if (!(Number.isInteger(n) && n >= 1 && n <= parts.length)) throw new RereadError(`--drop-parts ${n}: ${entry.id}'s take has parts 1-${parts.length}`); const roles = partRoles(entry); @@ -85,41 +146,122 @@ export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = fal const dropped = new Set(drop.map((d) => d.k)); const keep = parts.map((_, k) => k).filter((k) => !dropped.has(k)); if (!keep.length) throw new RereadError(`${entry.id}: that drops every part of its take -- nothing would be read`); - // The kept parts, joined with the read's pauses (a new paragraph's, a part inside one's). - const spans = []; - let cur = 0; - keep.forEach((k, j) => { - const p = parts[k]; - const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1]].para ? POST_PART_GAP.para : POST_PART_GAP.inside; - const at = r3(cur + gap); - spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap }); - cur = at + p.seconds; - }); - const newParts = spans.map((s, j) => { - const p = parts[s.k]; - const { gapBefore: _g, role: _r, ...rest } = p; - const role = roles[s.k]?.role ?? null; - return { ...rest, n: j + 1, start: s.at, seconds: r3(p.seconds), ...(role ? { role } : {}) }; - }); - // Its words moved with their parts (a word is its part's when it starts inside the part's span). - const words = Array.isArray(t.words) - ? t.words.flatMap((w) => { - const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05); - if (!s) return []; - const d = s.at - s.from; - return [{ w: w.w, start: r3(Math.max(0, w.start + d)), end: r3(Math.max(0, w.end + d)) }]; - }) - : null; - const script = spans.reduce((acc, s, j) => { - const p = parts[s.k]; - const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " "; - return acc + sep + String(p.text ?? "").trim(); - }, ""); - return { take: t, keep, drop, spans, parts: newParts, words, script, seconds: r3(cur), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] }; + const j = joinParts(t, keep.map((k) => ({ k, factor: 1 })), roles); + return { take: t, keep, drop, ...j, spans: j.spans.map(({ k, from, to, at, gap }) => ({ k, from, to, at, gap })), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] }; +} + +// --------------------------------------------------------------------------- +// PER-PART TEMPO (operator, 4 Nov, a 6.5-minute post: "what if we sped it up ... and then slowing back down here on the +// juicy persecution complex paragraph"; "dynamic speed over boring parts of a long message ... nothing too crazy"). +// --------------------------------------------------------------------------- + +/** The stretchers a tempo step may use: ffmpeg's atempo (the default, as the read's `rate` is played) or rubberband. */ +export const TEMPO_STRETCHERS = Object.freeze(["atempo", "rubberband"]); + +/** + * A TEMPO SPEC as the CLI writes it, pure: `"4-16=1.35,21-25=1.3"` (each run of + * parts and its tempo), or `{ tempo: 1.3, parts: "4-16,21-25" }` (one tempo for + * the runs named) -- `{ <part n>: tempo }` (1-based). Refused: a part outside + * 1-`count`, a tempo outside POST_NARRATION_LIMITS.tempo, a part named twice. + * + * @param {{ spec?: string | null, tempo?: number | string | null, parts?: string | null, count: number }} o + * @returns {Record<string, number>} + */ +export function parseTempoSpec({ spec = null, tempo = null, parts = null, count }) { + const [lo, hi] = POST_NARRATION_LIMITS.tempo; + /** @type {Record<string, number>} */ + const out = {}; + const runs = (list, where) => + String(list).split(",").map((x) => x.trim()).filter(Boolean).flatMap((r) => { + const m = /^(\d+)(?:-(\d+))?$/.exec(r); + if (!m) throw new RereadError(`${where} ${r}: a part (4) or a run of them (4-16)`); + const a = Number(m[1]); + const b = m[2] === undefined ? a : Number(m[2]); + if (!(a >= 1 && b >= a && b <= count)) throw new RereadError(`${where} ${r}: the take has parts 1-${count}`); + return Array.from({ length: b - a + 1 }, (_, i) => a + i); + }); + const put = (n, v, where) => { + if (!(fin(v) && v >= lo && v <= hi)) throw new RereadError(`${where}: a tempo is ${lo}–${hi} (1.3 reads 30% faster, its pitch kept)`); + if (out[n] !== undefined && out[n] !== v) throw new RereadError(`${where}: part ${n} is named twice`); + out[n] = v; + }; + if (tempo !== null && tempo !== undefined) { + if (parts === null || parts === undefined) throw new RereadError("--tempo needs --parts (the runs it reads faster: 4-16,21-25)"); + for (const n of runs(parts, "--parts")) put(n, Number(tempo), `--tempo ${tempo}`); + } + if (spec !== null && spec !== undefined) { + for (const item of String(spec).split(/[,;](?=\s*\d+(?:-\d+)?\s*=)/)) { + const m = /^\s*([\d,\s-]+?)\s*=\s*([\d.]+)\s*$/.exec(item); + if (!m) throw new RereadError(`--tempo-for ${item.trim()}: <parts>=<tempo>, e.g. 4-16=1.35,21-25=1.3`); + for (const n of runs(m[1], "--tempo-for")) { + delete out[n]; + put(n, Number(m[2]), `--tempo-for ${item.trim()}`); + } + } + } + if (!Object.keys(out).length) throw new RereadError("name the parts and their tempo: --tempo-for \"4-16=1.35,21-25=1.3\" (or --tempo 1.3 --parts 4-16,21-25)"); + return out; +} + +/** Parts' tempos as runs, pure: `[1, 1.35, 1.35, 1]` → `{ "2-3": 1.35 }` (a part at 1 left out). */ +export function tempoRanges(tempos) { + const out = {}; + let i = 0; + while (i < tempos.length) { + const v = tempos[i] ?? 1; + let j = i; + while (j + 1 < tempos.length && (tempos[j + 1] ?? 1) === v) j += 1; + if (Math.abs(v - 1) > 1e-6) out[i === j ? String(i + 1) : `${i + 1}-${j + 1}`] = v; + i = j + 1; + } + return out; +} + +/** A take's last step, when it is one of `ops`; and the take it was made from, when that is in `takes`. */ +export function lastLocalStep(takes, t, ops) { + const st = Array.isArray(t?.steps) ? t.steps[t.steps.length - 1] : null; + if (!st || !ops.includes(st.op)) return null; + const src = takeSourceOf(t); + const from = src.kind === "take" ? takes.find((x) => takeIdOf(x) === src.from) ?? null : null; + return { step: st, from }; +} + +/** + * THE TEMPO's PLAN, pure: `tempo` `{ <part n>: target }` (parseTempoSpec's) -- + * each part named READ AT that tempo against its first read, the rest as they + * are. A tempo is absolute: on a take made by a tempo step (a re-tune) the plan + * starts from the take that one was made from (each part stretched once, never + * twice), the parts it does not name keeping the tempo they had. Every part is + * kept, joined with the read's pauses; the words scaled with their part. + * Returns rereadPlan's shape plus `base` (the take it cuts), `tempos` (each + * part's, after) and `was` (before). + * + * @param {Record<string, any>} entry + * @param {{ tempo: Record<string, number>, stretch?: string }} o + */ +export function tempoPlan(entry, { tempo, stretch = "atempo" }) { + const t = pickedTake(entry); + const parts = timedParts(entry, t, "re-time"); + if (!TEMPO_STRETCHERS.includes(stretch)) throw new RereadError(`--stretch ${stretch}: ${TEMPO_STRETCHERS.join(" or ")}`); + const takes = entry.narration.takes; + const was = parts.map((p) => (fin(p.tempo) ? p.tempo : 1)); + // A re-tune: the take before the tempo step, when it is there and has the same parts. + const up = lastLocalStep(takes, t, ["tempo"]); + const base = up?.from && Array.isArray(up.from.parts) && up.from.parts.length === parts.length && up.from.parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0) ? { ...up.from, index: takes.indexOf(up.from) } : t; + for (const n of Object.keys(tempo)) if (!(Number(n) >= 1 && Number(n) <= parts.length)) throw new RereadError(`part ${n}: ${entry.id}'s take has parts 1-${parts.length}`); + const tempos = parts.map((_, k) => (tempo[k + 1] !== undefined ? tempo[k + 1] : was[k])); + if (tempos.every((v, k) => Math.abs(v - was[k]) < 1e-6)) throw new RereadError(`${entry.id}'s picked take reads those parts at that tempo already: nothing to change`); + const baseTempo = base.parts.map((p) => (fin(p.tempo) ? p.tempo : 1)); + const roles = partRoles(entry); + const j = joinParts(base, base.parts.map((_, k) => ({ k, factor: tempos[k] / baseTempo[k], tempo: tempos[k] })), roles); + return { + take: base, picked: t, base, keep: parts.map((_, k) => k), drop: [], was, tempos, ...j, stretch, + steps: [{ op: "tempo", tempo: tempoRanges(tempos), params: { stretch }, ranAt: new Date().toISOString() }], + }; } -/** The ffmpeg arguments that cut the plan's spans out of `src` and join them with silence into `out`. */ -export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { +/** The ffmpeg arguments that cut the plan's spans out of `src` (each stretched by its factor, its length exact) and join them with silence into `out`. */ +export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono", stretch = plan.stretch ?? "atempo" } = {}) { const chains = []; const labels = []; plan.spans.forEach((s, j) => { @@ -127,7 +269,13 @@ export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono" } = { chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=duration=${s.gap}[g${j}]`); labels.push(`[g${j}]`); } - chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}[a${j}]`); + // A stretched part: its pitch kept, then padded and trimmed to its length in the plan (sample-exact: the parts after + // it land where their word timings say). + const f = s.factor ?? 1; + const stretched = Math.abs(f - 1) > 1e-6 + ? `,${stretch === "rubberband" ? `rubberband=tempo=${f}:transients=mixed:pitchq=quality` : `atempo=${f}`},apad,atrim=end_sample=${Math.round(s.len * rate)},asetpts=PTS-STARTPTS` + : ""; + chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}${stretched}[a${j}]`); labels.push(`[a${j}]`); }); chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`); @@ -143,33 +291,35 @@ async function audioFormat(file) { } /** - * RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan - * takes them): the file written, measured, the take added and picked in one - * write. `dryRun`: the plan only. Returns `{ plan, take?, result? }`. + * WRITE A DERIVED TAKE of post item `e` from `plan` (rereadPlan's, tempoPlan's, postYell.mjs yellPlan's): `plan.take`'s + * file through `argsOf(src, out, fmt)` (ffmpeg) into take-<n>.<op>-<engine>.wav, measured, added with the plan's + * parts, words, script and steps -- and picked, in ONE write (updatePostNarration: one undo point). Returns `{ take, + * result }`. The source take is never touched. * * @param {{ id: string, dir: string }} project * @param {Record<string, any>} e - * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o] + * @param {Record<string, any>} plan + * @param {{ op: string, argsOf: (src: string, out: string, fmt: { rate: number, layout: string }) => string[], measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }>, verb?: string, after?: (abs: string, m: { seconds: number|null, lufs: number|null }) => Promise<{ seconds: number|null, lufs: number|null }> }} o */ -export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, dryRun = false, measure = undefined } = {}) { - const plan = rereadPlan(e, { without, dropParts, dropUrls }); - if (dryRun) return { plan }; +export async function writeDerivedTake(project, e, plan, { op, argsOf, measure = undefined, verb = "re-join", after = undefined }) { const t = plan.take; const pid = postIdOf(e); const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); await mkdir(dir, { recursive: true }); - const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), "rejoin", t.engine === "derived" ? "take" : t.engine ?? "take"); + const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), op, t.engine === "derived" ? "take" : t.engine ?? "take"); const abs = (r) => path.join(project.dir, ...String(r).split("/")); const src = abs(t.file); - if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s picked take is not on disk: ${t.file}`); + if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s take is not on disk: ${t.file}`); const fmt = await audioFormat(src); try { - await execFileP(FFMPEG(), rejoinArgs(src, abs(rel), plan, fmt), { maxBuffer: 1 << 24 }); + await execFileP(FFMPEG(), argsOf(src, abs(rel), fmt), { maxBuffer: 1 << 24 }); } catch (err) { await rm(abs(rel), { force: true }); - throw new RereadError(`ffmpeg could not re-join ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`); + throw new RereadError(`ffmpeg could not ${verb} ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`); } - const m = await (measure ?? (await import("./postNarrationCli.mjs")).measureTake)(abs(rel)); + const measureOf = measure ?? (await import("./postNarrationCli.mjs")).measureTake; + let m = await measureOf(abs(rel)); + if (after) m = await after(abs(rel), m); const take = { file: rel, engine: "derived", @@ -185,6 +335,24 @@ export async function rereadTake(project, e, { without = [], dropParts = [], dro parts: plan.parts, }; const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + return { take, result }; +} + +/** + * RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan + * takes them), or with its parts RE-TIMED (`tempo`, tempoPlan's): the file + * written, measured, the take added and picked in one write. `dryRun`: the + * plan only. Returns `{ plan, take?, result? }`. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, tempo?: Record<string, number> | null, stretch?: string, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o] + */ +export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, tempo = null, stretch = "atempo", dryRun = false, measure = undefined } = {}) { + if (tempo && (without.length || dropParts.length || dropUrls)) throw new RereadError("a tempo goes alone: re-join without the piece first, then re-time that take (it is picked)"); + const plan = tempo ? tempoPlan(e, { tempo, stretch }) : rereadPlan(e, { without, dropParts, dropUrls }); + if (dryRun) return { plan }; + const { take, result } = await writeDerivedTake(project, e, plan, { op: tempo ? "tempo" : "rejoin", argsOf: (src, out, fmt) => rejoinArgs(src, out, plan, fmt), measure, verb: tempo ? "re-time" : "re-join" }); return { plan, take, result }; } @@ -200,19 +368,34 @@ export function piecesHidden(e, thread) { return out; } -/** `umtool posts reread <p> <item> …`. */ -export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { +/** `umtool posts reread <p> <item> …`: a re-join without a piece, a tempo (`tempoSpec`, tempoPlan's), or a yell (`yell`: postYell.mjs). */ +export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, tempoSpec = null, tempo = null, parts = null, stretch = "atempo", yell = null, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new RereadError(`${project.id} has no manifest`); const e = (manifest.timeline ?? []).find((x) => x?.type === "post" && (x.id === ref || postIdOf(x) === ref || x.id === `p-${ref}`)); if (!e) throw new RereadError(`no post item ${ref} in ${project.id}`); - const r = await rereadTake(project, e, { without, dropParts, dropUrls, dryRun }); - const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", "); + if (yell) { + if (tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--yell-caps goes alone: re-join or re-time first, then yell that take (it is picked) -- or the other way round"); + const { yellCommand } = await import("./postYell.mjs"); + return yellCommand(project, manifest, [e], { ...yell, dryRun, json, out }); + } + const timed = tempoSpec !== null || tempo !== null; + const t0 = pickedTake(e); + const spec = timed ? parseTempoSpec({ spec: tempoSpec, tempo, parts, count: Array.isArray(t0?.parts) ? t0.parts.length : 0 }) : null; + const r = await rereadTake(project, e, { without, dropParts, dropUrls, tempo: spec, stretch, dryRun }); + const secs = (r.take?.seconds ?? r.plan.seconds).toFixed(2); + const was = Number((r.plan.picked ?? r.plan.take).seconds).toFixed(2); if (json) { - out(JSON.stringify({ ok: true, id: e.id, dryRun, drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1), seconds: r.take?.seconds ?? r.plan.seconds, take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); + out(JSON.stringify({ ok: true, id: e.id, dryRun, ...(timed ? { tempo: r.plan.steps[0].tempo, stretch: r.plan.stretch, from: takeIdOf(r.plan.take) } : { drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1) }), seconds: r.take?.seconds ?? r.plan.seconds, was: Number(was), take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); return 0; } - out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${(r.take?.seconds ?? r.plan.seconds).toFixed(2)} s (was ${Number(r.plan.take.seconds).toFixed(2)} s)`); + if (timed) { + const runs = Object.entries(r.plan.steps[0].tempo).map(([k, v]) => `${k} at ${v}x`).join(", ") || "every part at 1x"; + out(`${dryRun ? "would re-time" : "re-timed"} ${e.id}'s take (${r.plan.stretch}, pitch kept): parts ${runs} -- ${secs} s (was ${was} s)${r.plan.take !== r.plan.picked ? `, cut from ${takeIdOf(r.plan.take)} (each part stretched once)` : ""}`); + } else { + const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", "); + out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${secs} s (was ${was} s)`); + } if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`); return 0; } diff --git a/umtool/lib/report/postReread.test.mjs b/umtool/lib/report/postReread.test.mjs @@ -130,3 +130,74 @@ test("set-item thread.parent.0=context on a piece the take reads RE-JOINS first const dry = await cli(["reread", "setitem", "p-1", "--drop-parts", "1", "--dry-run"]); assert.match(dry.err + dry.out, /only part|drops every part/); }); + +// ---- PER-PART TEMPO (operator, 4 Nov: "sped it up ... and then slowing back down here on the juicy persecution +// complex paragraph"): the parts named stretched (pitch kept), the rest untouched, the words scaled with their part. +import { parseTempoSpec, rereadCommand, tempoPlan, tempoRanges } from "./postReread.mjs"; + +test("THE TEMPO SPEC: runs and their tempo, one tempo for --parts, the refusals; runs back from per-part tempos", () => { + assert.deepEqual(parseTempoSpec({ spec: "4-6=1.35,8=1.3", count: 9 }), { 4: 1.35, 5: 1.35, 6: 1.35, 8: 1.3 }); + assert.deepEqual(parseTempoSpec({ tempo: "1.3", parts: "1-2,4", count: 4 }), { 1: 1.3, 2: 1.3, 4: 1.3 }); + // --tempo-for wins over --tempo for a part both name. + assert.deepEqual(parseTempoSpec({ tempo: 1.2, parts: "1-3", spec: "2=1.4", count: 3 }), { 1: 1.2, 2: 1.4, 3: 1.2 }); + assert.throws(() => parseTempoSpec({ spec: "4-16=1.35", count: 10 }), /the take has parts 1-10/); + assert.throws(() => parseTempoSpec({ spec: "1=1.7", count: 3 }), /a tempo is 1–1\.6/); + assert.throws(() => parseTempoSpec({ spec: "1=0.9", count: 3 }), /a tempo is 1–1\.6/); + assert.throws(() => parseTempoSpec({ tempo: 1.3, count: 3 }), /--tempo needs --parts/); + assert.throws(() => parseTempoSpec({ count: 3 }), /name the parts/); + assert.deepEqual(tempoRanges([1, 1.35, 1.35, 1, 1.3]), { "2-3": 1.35, 5: 1.3 }); +}); + +test("THE TEMPO's PLAN: a stretched part shorter by its factor, the parts after it moved up, its words scaled; every part kept, the gaps the read's", () => { + const p = tempoPlan(item(), { tempo: { 1: 1.5, 3: 1.2 } }); + assert.deepEqual(p.spans.map((s) => [s.k, s.at, s.len, s.factor ?? 1]), [[0, 0, 2.4, 1.5], [1, 3, 3.2, 1], [2, 6.8, 2.583, 1.2]]); + assert.deepEqual(p.parts.map((x) => [x.n, x.start, x.seconds, x.tempo ?? 1]), [[1, 0, 2.4, 1.5], [2, 3, 3.2, 1], [3, 6.8, 2.583, 1.2]]); + // Words: in a stretched part scaled by its factor from the part's start; in an untouched one moved with it. + assert.deepEqual(p.words, [{ w: "The", start: 0.067, end: 0.2 }, { w: "Then", start: 3.1, end: 3.4 }, { w: "That", start: 6.883, end: 7.05 }, { w: "morning", start: 9.05, end: 9.3 }]); + assert.equal(p.seconds, 9.383); + assert.deepEqual(p.steps.map((s) => [s.op, s.tempo, s.params]), [["tempo", { 1: 1.5, 3: 1.2 }, { stretch: "atempo" }]]); + assert.throws(() => tempoPlan(item(), { tempo: { 1: 1 } }), /at that tempo already/); + // The ffmpeg: atempo on the stretched part, padded and trimmed to its length (sample-exact); the untouched as before. + const fc = rejoinArgs("/in.wav", "/o.wav", p, { rate: 24000, layout: "mono" })[8]; + assert.match(fc, /\[0:a\]atrim=start=0:end=3\.6,asetpts=PTS-STARTPTS,aformat=sample_rates=24000:channel_layouts=mono,atempo=1\.5,apad,atrim=end_sample=57600,asetpts=PTS-STARTPTS\[a0\]/); + assert.match(fc, /\[0:a\]atrim=start=4\.2:end=7\.4,asetpts=PTS-STARTPTS,aformat=sample_rates=24000:channel_layouts=mono\[a1\]/); + assert.match(rejoinArgs("/in.wav", "/o.wav", { ...p, stretch: "rubberband" }, { rate: 24000 })[8], /rubberband=tempo=1\.5:transients=mixed:pitchq=quality/); +}); + +test("A RE-TUNE: a tempo on a re-timed take is cut from the take before it (each part stretched once), the parts it does not name keeping theirs", () => { + const e = item(); + const p1 = tempoPlan(e, { tempo: { 1: 1.5, 3: 1.2 } }); + const t1 = { file: "narration/posts/1/take-3.tempo-orpheus.wav", engine: "derived", voice: "leo+zac", seconds: p1.seconds, source: { kind: "take", from: "take-2.orpheus-thread" }, steps: p1.steps, words: p1.words, parts: p1.parts }; + const e2 = { ...e, narration: { ...e.narration, takes: [...e.narration.takes, t1], pick: 1 } }; + assert.deepEqual(validatePostItem(e2), []); + const p2 = tempoPlan(e2, { tempo: { 1: 1.25 } }); + assert.equal(p2.take.file, "narration/posts/1/take-2.orpheus-thread.wav", "cut from the first read"); + assert.deepEqual(p2.spans.map((s) => s.factor ?? 1), [1.25, 1, 1.2]); + assert.deepEqual(p2.tempos, [1.25, 1, 1.2]); + assert.deepEqual(p2.steps[0].tempo, { 1: 1.25, 3: 1.2 }); + // The validator: a part's tempo inside 1-1.6, a step's runs. + const bad = { ...e2, narration: { ...e2.narration, takes: [e2.narration.takes[0], { ...t1, parts: [{ ...t1.parts[0], tempo: 2 }], steps: [{ op: "tempo", tempo: { "1-x": 1.2 } }] }] } }; + assert.deepEqual(validatePostItem(bad).filter((x) => /tempo/.test(x)).length, 2); +}); + +test("RE-TIMED: the file's length the plan's (sample-exact), the derived take picked in ONE write with its parts' tempo and the words scaled; set-item narration.tempo= runs it", async () => { + const p = await project("tempo", [item()]); + const lines = []; + assert.equal(await rereadCommand(p, "p-1", { tempoSpec: "1=1.5,3=1.2", out: (s) => lines.push(s) }), 0); + assert.match(lines.join("\n"), /re-timed p-1's take \(atempo, pitch kept\): parts 1 at 1\.5x, 3 at 1\.2x -- 9\.38 s \(was 11\.30 s\)/); + let e = (await manifest(p)).timeline[0]; + const t = e.narration.takes[1]; + assert.equal(e.narration.pick, 1); + assert.match(t.file, /take-3\.tempo-orpheus\.wav$/); + assert.ok(Math.abs(t.seconds - 9.383) < 0.01, `measured ${t.seconds}`); + assert.deepEqual([t.source.from, t.steps[0].op, t.parts.map((x) => x.tempo ?? 1)], ["take-2.orpheus-thread", "tempo", [1.5, 1, 1.2]]); + assert.deepEqual(validatePostItem(e), []); + // set-item: a re-tune, cut from the first read again. + const out = []; + const code = await postsCommand(["set-item", "tempo", "p-1", "narration.tempo=1-3=1.1"], { root: REPORTS, out: (s) => out.push(s), err: (s) => out.push(s) }); + assert.equal(code, 0, out.join("\n")); + e = (await manifest(p)).timeline[0]; + assert.deepEqual([e.narration.pick, e.narration.takes[2].source.from, e.narration.takes[2].parts.map((x) => x.tempo)], [2, "take-2.orpheus-thread", [1.1, 1.1, 1.1]]); + await undoStructural(p.dir); + assert.ok((await manifest(p)).timeline[0].narration.takes.length < 3, "undone"); +}); diff --git a/umtool/lib/report/postYell.mjs b/umtool/lib/report/postYell.mjs @@ -0,0 +1,393 @@ +// THE CAPS YELLED (operator, 4 Nov: "I feel like allcaps needs to be yelled more"; p-2116771656329019498, "the moment +// that THEY have your Dox ITS ALREADY TOO LATE"): a read's scripts are drafted with his ALL-CAPS words lowercased (a +// stock voice spells a caps word out letter by letter), so the read says them flat. This raises them on the read +// that is there -- no TTS: the words he wrote in caps found in the read's word timings, and the voice over each +// run of them lifted the way a voice is raised, not turned up: louder (+5.5 dB), a presence lift (~3.2 kHz), +// compressed and gently saturated, crossfaded in and out over 50 ms. Its timings are untouched (the yell changes +// no length), so beeps, captions, zooms and slams keep their place. +// +// umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json] +// umtool posts yell <p> [--all | <item…>] [--yell-gain …] [--yell-style …] [--dry-run] [--json] +// +// WHICH WORDS: a word of the read whose SOURCE word -- in his post, or in the piece a part reads (the post he +// answers, the quote, a linked post) -- is ALL CAPS with two letters or more, its script word aligned to it +// (word-zoom.mjs alignWords). Left flat: an acronym or initialism (YELL_ACRONYMS; any caps word with no vowel reads +// as letters: DM, KF, TV, BS), and a slur the cut masks (post-slurs.mjs: beeped anyway). A run of caps words is one +// span (a gap under YELL_MERGE between two merges them). +// +// LOUDNESS: the raised voice is limited (nothing clips) and the take's loudness kept within YELL_LUFS_MAX of the one +// it came from -- over it, the lift is lowered until it fits (an all-caps post keeps the timbre, not the level). +// +// STORED: a derived take, `source: {kind: "take", from}`, `steps: [{op: "yell", spans, params: {gain, style}}]`, +// picked in one write (undoable). It chains with the tempo and the re-join (postReread.mjs) in either order; a yell +// on a yelled take re-yells the take before it (never twice). +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { isNarrated, pickedTake, scriptParts, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration"; +import { partRoles } from "umtool-report-to-video/post-thread"; +import { cutSlurs } from "umtool-report-to-video/post-redact-files"; +import { scriptTokens, slurMatches } from "umtool-report-to-video/post-slurs"; +import { alignWords, normWord } from "umtool-report-to-video/word-zoom"; +import { readManifest } from "../projects/report.mjs"; +import { RereadError, lastLocalStep, writeDerivedTake } from "./postReread.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +export class YellError extends Error { + constructor(message) { + super(message); + this.name = "YellError"; + } +} + +export const YELL_USAGE = [ + "usage: umtool posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", + " umtool posts yell <project> [--all | <item> …] [--yell-gain 5.5] [--yell-style raise|shout|loud] [--dry-run] [--json]", + " THE CAPS YELLED (no TTS): the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the read's", + " word timings and raised -- louder, a presence lift, compressed and gently saturated, 50 ms in and out -- as a new", + " take, picked (one undo point per item). Acronyms (FBI, DM, KF, TV, … and any caps word with no vowel) and slurs the", + " cut masks are left flat. Its timings are kept (beeps, captions, zooms, slams stay right); its loudness within 1 LU", + " of the take it came from. Needs the take's word timings (umtool posts narrate <p> <item> --words). --dry-run lists", + " each item's caps words, those it skips and why, and the items with no word timings. Chains with --tempo-for.", +].join("\n"); + +/** Caps words left flat: acronyms and initialisms (a caps word with no vowel is one by rule: YELL_LETTERS). */ +export const YELL_ACRONYMS = Object.freeze(new Set([ + "FBI", "CIA", "NSA", "DOJ", "IRS", "TOS", "TOU", "USA", "US", "UK", "EU", "UN", "NYC", "LA", "DC", "DM", "DMS", "PM", "PMS", "KF", "OK", "OKAY", "LOL", + "LMAO", "LMFAO", "ROFL", "OMG", "WTF", "IDK", "IIRC", "IMO", "IMHO", "TBH", "BTW", "FYI", "ATM", "ASAP", "ETA", "AKA", "FAQ", "ID", "IDS", "IQ", "AI", + "TV", "IRL", "VR", "AR", "PC", "BS", "CEO", "CEOS", "YT", "TTS", "ASMR", "NSFW", "SFW", "POV", "RIP", "MR", "MRS", "MS", "DR", "ST", "JR", "SR", "PR", + "HR", "PS", "PSA", "OP", "GG", "FPS", "RPG", "MMO", "NPC", "NPCS", "AMA", "URL", "TIL", "LGBT", "LGBTQ", "TLDR", "DIY", "VPN", "IP", "ISP", "API", + "AM", "ET", "PST", "EST", "UTC", "GMT", "OBS", "VOD", "VODS", "DLC", "NFT", "NFTS", "VTUBER", "VTUBERS", "VTUBING", "EN", "JP", "ENVTUBER", "MOD", + "MODS", "QRT", "RT", "QT", "OG", "GOAT", "NGL", "SMH", "JK", "TFW", "MFW", "AFAIK", "ICYMI", "IG", "FB", "X", "XD", "UWU", "OWO", "ADHD", "OCD", + "PTSD", "HIV", "AIDS", "COVID", "NASA", "NATO", "DNA", "GPS", "USB", "CD", "DVD", "HD", "UHD", "PDF", "JPG", "PNG", "GIF", "HTML", "IOS", "MAGA", + "GOP", "POTUS", "SCOTUS", "BLM", "ACAB", "AOC", "DEI", "ESG", "CRT", "SJW", "SJWS", "TERF", "TERFS", "IRA", "LLC", "INC", "LTD", "CO", +])); +/** The ramp in and out of a raised span, seconds (≥ 40 ms: never a click). */ +export const YELL_RAMP = 0.05; +/** Two caps spans closer than this are one (a run read as one). */ +export const YELL_MERGE = 0.35; +/** A span starts this much before its first word's timing (the transcription's starts run late). */ +export const YELL_PAD = Object.freeze({ before: 0.03, after: 0.04 }); +/** The take's loudness may rise at most this much over the take it came from, LU. */ +export const YELL_LUFS_MAX = 1; +/** The styles: the lift (dB) and how the raised voice is shaped. */ +export const YELL_STYLES = Object.freeze({ + // presence/body: EQ lifts (dB) at ~3.2 kHz and ~1.1 kHz; ratio: the compressor's; drive: dB pushed into a tanh + // saturation (and taken back after it). The lift (`gain`) is MEASURED: the raised spans come out that much louder. + raise: Object.freeze({ gain: 5.5, presence: 3, body: 1.5, ratio: 2.5, drive: 3 }), + shout: Object.freeze({ gain: 7, presence: 4.5, body: 2, ratio: 4, drive: 6 }), + loud: Object.freeze({ gain: 5.5, presence: 0, body: 0, ratio: 1, drive: 0 }), +}); +export const YELL_GAIN = Object.freeze([1, 9]); + +const VOWEL_RE = /[AEIOUY]/; +const letters = (w) => String(w ?? "").replace(/['’]S$/i, "").replace(/[^\p{L}]/gu, ""); + +/** Is a source word ALL CAPS, two letters or more (I'LL, ISN'T count; "I" and "10X" do not)? */ +export function isCapsWord(raw) { + const L = letters(raw); + return L.length >= 2 && L === L.toUpperCase() && L !== L.toLowerCase(); +} + +/** Why a caps word is left flat (acronym / letters), or null when it is yelled. */ +export function acronymWhy(raw) { + const L = letters(raw).toUpperCase(); + if (YELL_ACRONYMS.has(L)) return "acronym"; + if (!VOWEL_RE.test(L)) return "letters"; + return null; +} + +/** The source texts a read's words come from: his post, the posts it answers, the quote, a linked post. */ +export function sourcePieces(entry) { + const out = []; + const add = (where, v) => typeof v === "string" && v.trim() && out.push({ where, text: v }); + add("post", entry?.text); + (Array.isArray(entry?.parents) ? entry.parents : []).forEach((p, i) => add(`parent:${i}`, p?.text)); + if (isObj(entry?.quoted)) add("quoted", entry.quoted.text); + (Array.isArray(entry?.links) ? entry.links : []).forEach((l, i) => add(`linked:${i}`, l?.text)); + return out; +} + +/** + * THE CAPS of a read, pure: `{ yell: [{ k, w, src, where }], skip: [{ k, w, src, where, why }], words: boolean, + * error? }` -- `k` the script token's index (= the take's word index), `src` the source word in caps. `slurs` the + * cut's resolved slur filter (post-redact-files.mjs cutSlurs): a slur's word is skipped (it is beeped anyway). + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} take + * @param {Record<string, any> | null} [slurs] + */ +export function capsOfRead(entry, take, slurs = null) { + const script = typeof take?.script === "string" ? take.script : String(entry?.narration?.script ?? ""); + const toks = scriptTokens(script); + const hits = slurs ? slurMatches(script, slurs) : []; + // Each script word's piece (the role of the part reading it: post-thread.mjs partRoles), when the parts tile the + // script: a piece's caps are looked for only in the words that read it -- never a word of his own that happens to + // match a caps word of the post he answers. + const roles = partRoles(entry, take); + const partTexts = Array.isArray(take?.parts) && take.parts.length ? take.parts.map((x) => x?.text) : scriptParts(script).map((x) => x.text); + const counts = partTexts.map((x) => scriptTokens(String(x ?? "")).length); + const roleOfTok = counts.reduce((a, b) => a + b, 0) === toks.length && roles.length === counts.length ? counts.flatMap((n, i) => Array(n).fill(roles[i]?.role ?? null)) : null; + const found = new Map(); + for (const piece of sourcePieces(entry)) { + const src = (piece.text.match(/\S+/g) ?? []).filter((w) => normWord(w)); + if (!src.some(isCapsWord)) continue; + const idx = toks.map((_, k) => k).filter((k) => !roleOfTok || roleOfTok[k] === piece.where || (roleOfTok[k] === null && piece.where === "post")); + if (!idx.length) continue; + const map = alignWords(idx.map((k) => toks[k].w), src); + map.forEach((j, i) => { + const k = idx[i]; + if (j < 0 || !isCapsWord(src[j]) || found.has(k)) return; + // Read in place: a neighbour aligned to its neighbour too (a lone match across unrelated words is not one). + if (!(map[i - 1] === j - 1 || map[i + 1] === j + 1 || src.length === 1)) return; + found.set(k, { k, w: toks[k].w, src: src[j].replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""), where: piece.where }); + }); + } + const yell = []; + const skip = []; + for (const c of [...found.values()].sort((a, b) => a.k - b.k)) { + const t = toks[c.k]; + const why = hits.some((h) => t.end > h.start && t.start < h.end) ? "slur" : acronymWhy(c.src); + (why ? skip : yell).push(why ? { ...c, why } : c); + } + const words = Array.isArray(take?.words) ? take.words : []; + const out = { yell, skip, words: words.length > 0, tokens: toks.length }; + if (yell.length && !words.length) return { ...out, error: `its take ${take?.file ?? ""} has no word timings to find its caps by (umtool posts narrate <p> ${entry?.id ?? "<item>"} --words)` }; + if (yell.length && words.length !== toks.length) return { ...out, error: `its take ${take?.file ?? ""}'s word timings are not of its script (${words.length} timed, ${toks.length} in the script)` }; + return out; +} + +/** The take seconds a read's caps are raised over, pure: each yelled word's timing padded, runs merged. */ +export function yellSpans(words, ks, { merge = YELL_MERGE } = {}) { + const spans = ks + .map((k) => words[k]) + .filter((w) => w && fin(w.start) && fin(w.end)) + .map((w) => [Math.max(0, w.start - YELL_PAD.before), Math.max(w.start, w.end) + YELL_PAD.after]) + .sort((a, b) => a[0] - b[0]); + const out = []; + for (const s of spans) { + const last = out[out.length - 1]; + if (last && s[0] - last[1] < merge) last[1] = Math.max(last[1], s[1]); + else out.push([...s]); + } + return out.map(([a, b]) => [r3(a), r3(b)]); +} + +/** + * THE YELL's PLAN, pure: the take it raises (`take`: the picked one; on a take made by a yell, the one before it), + * its caps and spans, the steps -- the parts, words and script unchanged. Throws YellError when there is nothing to + * yell, no timings to find them by, or a yell further up the chain. + * + * @param {Record<string, any>} entry + * @param {{ slurs?: Record<string, any> | null, gain?: number, style?: string }} [o] + */ +export function yellPlan(entry, { slurs = null, gain = undefined, style = "raise" } = {}) { + const picked = pickedTake(entry); + if (!picked) throw new YellError(`${entry?.id ?? "?"} has no take to yell`); + if (!YELL_STYLES[style]) throw new YellError(`--yell-style ${style}: ${Object.keys(YELL_STYLES).join(", ")}`); + const g = gain === undefined || gain === null ? YELL_STYLES[style].gain : Number(gain); + if (!(fin(g) && g >= YELL_GAIN[0] && g <= YELL_GAIN[1])) throw new YellError(`--yell-gain ${gain}: ${YELL_GAIN.join("–")} dB`); + const takes = entry.narration.takes; + const up = lastLocalStep(takes, picked, ["yell"]); + let take = picked; + if (up) { + if (!up.from) throw new YellError(`${entry.id}'s picked take is yelled already, and the take it came from is gone`); + take = { ...up.from, index: takes.indexOf(up.from) }; + } + // A yell further up its chain (yelled, then re-timed): never raised twice. + for (let cur = take, i = 0; cur && i < 20; i += 1) { + if ((cur.steps ?? []).some((st) => st?.op === "yell")) throw new YellError(`${entry.id}'s picked take was made from a yelled one (${takeIdOf(cur)}): pick the take before the yell, then yell and re-time again`); + const src = takeSourceOf(cur); + cur = src.kind === "take" ? takes.find((x) => takeIdOf(x) === src.from) : null; + } + const caps = capsOfRead(entry, take, slurs); + if (caps.error) throw new YellError(`${entry.id}: ${caps.error}`); + if (!caps.yell.length) throw new YellError(`${entry.id}: no word of its read is in caps in what it reads${caps.skip.length ? ` (left flat: ${caps.skip.map((s) => `${s.src} (${s.why})`).join(", ")})` : ""}`); + const spans = yellSpans(take.words, caps.yell.map((c) => c.k)); + return { + take, picked, caps, spans, style, gain: g, + parts: take.parts, words: take.words, script: typeof take.script === "string" ? take.script : entry.narration.script, seconds: take.seconds, + steps: [{ op: "yell", spans, params: { gain: g, style }, ranAt: new Date().toISOString() }], + }; +} + +/** The envelope over the spans at time t (an ffmpeg expression): 0 outside, 1 inside, YELL_RAMP in and out. */ +export function yellEnvelope(spans, ramp = YELL_RAMP) { + const r = ramp.toFixed(3); + const one = ([a, b]) => `clip(min((t-${(a - ramp).toFixed(3)})/${r},(${(b + ramp).toFixed(3)}-t)/${r}),0,1)`; + // Sums of disjoint trapezoids, each term gated to its own window. + return `clip(${spans.map((s) => `between(t,${(s[0] - ramp).toFixed(3)},${(s[1] + ramp).toFixed(3)})*${one(s)}`).join("+")},0,1)`; +} + +/** The envelope's step: the voice is gained in frames this many samples long (2.7 ms at 24 kHz: a 50 ms ramp is ~18 steps). */ +export const YELL_FRAME = 64; + +/** + * The ffmpeg arguments that raise `plan.spans` of `src` into `out`: the voice split, one branch shaped as a raised + * voice (presence, body, compression, the lift with its measured make-up `plan.trim`, a gentle tanh saturation, + * limited under 0 dBFS -- its latency compensated), the two crossfaded by the spans' envelope (gained in + * YELL_FRAME-sample frames). Its length is the source's. + */ +export function yellArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { + const st = YELL_STYLES[plan.style] ?? YELL_STYLES.raise; + const E = yellEnvelope(plan.spans); + const lift = Math.round((plan.gain + (fin(plan.trim) ? plan.trim : 0)) * 100) / 100; + const shape = [ + st.presence ? `equalizer=f=3200:t=o:w=1.3:g=${st.presence}` : null, + st.body ? `equalizer=f=1100:t=o:w=1:g=${st.body}` : null, + st.ratio > 1 ? `acompressor=threshold=0.063:ratio=${st.ratio}:attack=5:release=90:makeup=1` : null, + `volume=${lift + (st.drive || 0)}dB`, + st.drive ? `asoftclip=type=tanh,volume=-${st.drive}dB` : null, + "alimiter=limit=0.94:attack=2:release=40:level=false:latency=1", + ].filter(Boolean).join(","); + const fc = [ + `[0:a]aformat=sample_fmts=fltp:sample_rates=${rate}:channel_layouts=${layout},asetnsamples=n=${YELL_FRAME}:p=0,asplit=2[yd][yw]`, + `[yw]${shape},asetnsamples=n=${YELL_FRAME}:p=0,volume=volume='${E}':eval=frame[ywet]`, + `[yd]volume=volume='1-(${E})':eval=frame[ydry]`, + `[ydry][ywet]amix=inputs=2:normalize=0:duration=first,atrim=end_sample=${Math.round(Number(plan.seconds) * rate)}[out]`, + ].join(";"); + return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", fc, "-map", "[out]", "-c:a", "pcm_s16le", out]; +} + +/** The RMS (dB) of a file over `spans` joined (ffmpeg astats), or null. */ +export async function spansRms(file, spans) { + const cut = spans.map(([a, b], i) => `[0:a]atrim=start=${a}:end=${b},asetpts=PTS-STARTPTS[s${i}]`); + const fc = `${cut.join(";")};${spans.map((_, i) => `[s${i}]`).join("")}concat=n=${spans.length}:v=0:a=1,astats=measure_perchannel=none:measure_overall=RMS_level[o]`; + try { + const { stderr } = await execFileP(FFMPEG(), ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-filter_complex", fc, "-map", "[o]", "-f", "null", "-"], { maxBuffer: 1 << 24 }); + const v = Number(/RMS level dB:\s*(-?[\d.]+)/.exec(String(stderr))?.[1]); + return fin(v) ? v : null; + } catch { + return null; + } +} + +/** + * @typedef {{ slurs?: Record<string, any> | null, gain?: number, style?: string, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} YellOpts + */ +/** + * YELL post item `e`'s caps (yellPlan's options): the file written, its lift MEASURED over the spans and the make-up + * set so they come out `gain` dB louder (made again once), its loudness held within YELL_LUFS_MAX of the take it came + * from (the lift lowered and the file re-made when over), the take added and picked in one write. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {YellOpts} [o] + */ +export async function yellTake(project, e, { slurs = null, gain = undefined, style = "raise", dryRun = false, measure = undefined } = {}) { + const plan = yellPlan(e, { slurs, gain, style }); + if (dryRun) return { plan }; + const measureOf = measure ?? (await import("./postNarrationCli.mjs")).measureTake; + const path = await import("node:path"); + const srcFile = path.join(project.dir, ...String(plan.take.file).split("/")); + const baseLufs = fin(plan.take.lufs) ? plan.take.lufs : (await measureOf(srcFile)).lufs; + const before = await spansRms(srcFile, plan.spans); + const { take, result } = await writeDerivedTake(project, e, plan, { + op: "yell", verb: "yell", measure: measureOf, + argsOf: (src, out, fmt) => { + plan.fmt = fmt; + plan.src = src; + return yellArgs(src, out, plan, fmt); + }, + after: async (abs, m) => { + const remake = async () => { + await execFileP(FFMPEG(), yellArgs(plan.src, abs, plan, plan.fmt), { maxBuffer: 1 << 24 }); + return measureOf(abs); + }; + let cur = m; + // The lift as heard: the compressor and the saturation take some back -- made up once, by what was measured. + let lifted = fin(before) ? await spansRms(abs, plan.spans) : null; + if (fin(before) && fin(lifted) && Math.abs(lifted - before - plan.gain) > 0.4) { + plan.trim = Math.round(Math.min(12, Math.max(-6, plan.gain - (lifted - before))) * 10) / 10; + cur = await remake(); + lifted = await spansRms(abs, plan.spans); + } + // Over the loudness: the lift lowered by the excess (three times at most), the file made again. + for (let i = 0; i < 3 && fin(cur.lufs) && fin(baseLufs) && cur.lufs - baseLufs > YELL_LUFS_MAX && plan.gain > YELL_GAIN[0]; i += 1) { + plan.gain = Math.max(YELL_GAIN[0], Math.round((plan.gain - 1.6 * (cur.lufs - baseLufs - YELL_LUFS_MAX + 0.15)) * 10) / 10); + cur = await remake(); + lifted = fin(before) ? await spansRms(abs, plan.spans) : null; + } + plan.steps[0].params = { gain: plan.gain, style: plan.style, ...(fin(plan.trim) ? { trim: plan.trim } : {}) }; + plan.lufs = { base: baseLufs, after: cur.lufs }; + plan.lift = fin(before) && fin(lifted) ? Math.round((lifted - before) * 10) / 10 : null; + return cur; + }, + }); + return { plan, take, result }; +} + +const capsLine = (c) => c.yell.map((x) => x.src).join(" "); +const skipLine = (c) => c.skip.map((x) => `${x.src} (${x.why})`).join(", "); + +/** One item's dry-run row, pure: `{ id, yell, skip, needsWords, error? }`, or null for an item with no caps read. */ +export function yellRow(e, slurs) { + if (e?.type !== "post" || !isNarrated(e)) return null; + const t = pickedTake(e); + const caps = capsOfRead(e, t, slurs); + if (!caps.yell.length && !caps.skip.length) return null; + return { id: e.id, take: takeIdOf(t), yell: caps.yell.map((x) => x.src), skip: caps.skip.map((x) => ({ w: x.src, why: x.why })), needsWords: !!caps.yell.length && !caps.words, ...(caps.error ? { error: caps.error } : {}), spans: !caps.error && caps.yell.length ? yellSpans(t.words, caps.yell.map((x) => x.k)).length : 0 }; +} + +/** `umtool posts reread <p> <item> --yell-caps` (and each item of `posts yell`). */ +export async function yellCommand(project, manifest, items, { gain = undefined, style = "raise", dryRun = false, json = false, out = (s) => console.log(s) } = {}) { + const slurs = cutSlurs(manifest); + const rows = []; + for (const e of items) { + if (dryRun) { + const row = yellRow(e, slurs) ?? { id: e.id, yell: [], skip: [], needsWords: false }; + rows.push(row); + continue; + } + try { + const r = await yellTake(project, e, { slurs, gain, style }); + rows.push({ id: e.id, yell: r.plan.caps.yell.map((x) => x.src), skip: r.plan.caps.skip.map((x) => ({ w: x.src, why: x.why })), spans: r.plan.spans, gain: r.plan.gain, lift: r.plan.lift ?? null, lufs: r.plan.lufs ?? null, take: r.take.file, from: takeIdOf(r.plan.take), token: r.result?.token ?? null }); + } catch (err) { + if (items.length === 1 || !(err instanceof YellError || err instanceof RereadError)) throw err; + rows.push({ id: e.id, error: err.message }); + } + } + if (json) { + out(JSON.stringify({ ok: true, dryRun, items: rows }, null, 2)); + return 0; + } + for (const r of rows) { + if (r.error && !r.yell?.length) out(`${r.id}: ${r.error}`); + else if (dryRun) out(`${r.id}: ${r.yell.length ? `would yell ${r.yell.join(" ")}` : "nothing to yell"}${r.skip.length ? `; flat: ${r.skip.map((s) => `${s.w} (${s.why})`).join(", ")}` : ""}${r.needsWords ? " -- NEEDS WORD TIMINGS (posts narrate --words)" : r.error ? ` -- ${r.error}` : ""}`); + else out(`${r.id}: yelled ${r.yell.join(" ")} (${r.spans.length} span(s), +${r.gain} dB asked${r.lift !== null && r.lift !== undefined ? `, +${r.lift} dB measured` : ""}${r.lufs ? `, ${r.lufs.base} → ${r.lufs.after} LUFS` : ""})${r.skip.length ? `; flat: ${r.skip.map((s) => `${s.w} (${s.why})`).join(", ")}` : ""}\n ${r.take} -- picked, from ${r.from} (one undo point: umtool timeline ${project.id} undo)`); + } + return 0; +} + +/** `umtool posts yell <p> [--all | <ids…>]`. */ +export async function yellBatchCommand(project, { ids = [], all = false, gain = undefined, style = "raise", dryRun = false, json = false, out = (s) => console.log(s) } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new YellError(`${project.id} has no manifest`); + const tl = (manifest.timeline ?? []).filter((x) => x?.type === "post"); + let items; + if (ids.length) { + items = ids.map((ref) => tl.find((x) => x.id === ref || x.id === `p-${ref}` || String(x.post ?? "").split("/")[1] === ref) ?? (() => { + throw new YellError(`no post item ${ref} in ${project.id}`); + })()); + } else if (all || dryRun) { + // Every narrated item whose read has a caps word to yell (a dry run lists the ones it would skip too). + const slurs = cutSlurs(manifest); + items = tl.filter((e) => { + const row = yellRow(e, slurs); + return !!row && (dryRun || row.yell.length > 0); + }); + } else throw new YellError("name the items, or --all (every narrated item with a caps word); --dry-run lists them"); + if (!items.length) { + out(json ? JSON.stringify({ ok: true, dryRun, items: [] }) : "no narrated item reads a caps word"); + return 0; + } + return yellCommand(project, manifest, items, { gain, style, dryRun, json, out }); +} + +export { capsLine, skipLine }; diff --git a/umtool/lib/report/postYell.test.mjs b/umtool/lib/report/postYell.test.mjs @@ -0,0 +1,126 @@ +// postYell.mjs: THE CAPS YELLED -- which words (his caps found in the read's word timings, acronyms and slurs left +// flat, a piece's caps only in the words that read it), the spans (padded, a run merged), the plan's refusals and +// chain rules, and the file: its length the source's, the spans louder by the lift (measured), the rest untouched, +// its loudness within 1 LU, a derived take picked in one write; chained with the tempo either way. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { validatePostItem } from "umtool-report-to-video/post-item"; +import { acronymWhy, capsOfRead, isCapsWord, spansRms, yellArgs, yellPlan, yellSpans, yellTake } from "./postYell.mjs"; +import { rereadTake } from "./postReread.mjs"; +import { postsCommand } from "./postsCli.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-yell-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const TEXT = "The moment THEY have your Dox ITS ALREADY TOO LATE, the FBI will not help.\n\nYou can HIDE all you want."; +const SCRIPT = "The moment they have your Dox its already too late, the FBI will not help.\n\nYou can hide all you want."; +// One word a 0.4 s slot from 0.2 s; the second paragraph from 6.2 s. +const words = () => { + const ws = SCRIPT.split(/\s+/); + return ws.map((w, i) => { + const at = i < 15 ? 0.2 + i * 0.4 : 6.2 + (i - 15) * 0.4; + return { w, start: Math.round(at * 1000) / 1000, end: Math.round((at + 0.32) * 1000) / 1000 }; + }); +}; +const item = (o = {}) => ({ + type: "post", id: "p-7", post: "subj-x/7", platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: TEXT, + narration: { script: SCRIPT, takes: [{ file: "narration/posts/7/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 9, script: SCRIPT, words: words(), parts: [{ n: 1, para: 0, text: SCRIPT.split("\n\n")[0], start: 0.2, seconds: 5.8 }, { n: 2, para: 1, text: SCRIPT.split("\n\n")[1], start: 6.2, seconds: 2.4 }] }], pick: 0 }, + ...o, +}); + +test("WHICH WORDS: caps of two letters or more; acronyms and letter-runs left flat; his caps found in the read's words", () => { + assert.deepEqual(["ITS", "I'LL", "ISN'T", "I", "10x", "Dox", "FBI's"].map(isCapsWord), [true, true, true, false, false, false, true]); + assert.deepEqual(["FBI", "DM", "KF", "TV", "BS", "NEVER", "OMG", "PST"].map(acronymWhy), ["acronym", "acronym", "acronym", "acronym", "acronym", null, "acronym", "acronym"]); + assert.equal(acronymWhy("KDR"), "letters"); + const c = capsOfRead(item(), item().narration.takes[0]); + assert.deepEqual(c.yell.map((x) => [x.k, x.src]), [[2, "THEY"], [6, "ITS"], [7, "ALREADY"], [8, "TOO"], [9, "LATE"], [17, "HIDE"]]); + assert.deepEqual(c.skip.map((x) => [x.src, x.why]), [["FBI", "acronym"]]); + // Spans: padded, a run of caps one span. + assert.deepEqual(yellSpans(words(), c.yell.map((x) => x.k)), [[0.97, 1.36], [2.57, 4.16], [6.97, 7.36]]); + // No word timings: refused in the plan's words (the --words pass named). + const bare = item(); + delete bare.narration.takes[0].words; + assert.throws(() => yellPlan(bare), /no word timings to find its caps by \(umtool posts narrate <p> p-7 --words\)/); + assert.throws(() => yellPlan(item({ text: SCRIPT })), /no word of its read is in caps/); +}); + +test("A PIECE's caps are looked for only in the words that read it: a caps word of the post he answers is never his", () => { + const e = item({ text: "you can hide all you want.", parents: [{ id: "9", author: "Other", handle: "other", text: "The moment THEY have your Dox ITS ALREADY TOO LATE, the FBI will not help." }] }); + const t = e.narration.takes[0]; + t.parts[0].role = "parent:0"; + t.parts[1].role = "post"; + const c = capsOfRead(e, t); + assert.deepEqual(c.yell.map((x) => [x.src, x.where]), [["THEY", "parent:0"], ["ITS", "parent:0"], ["ALREADY", "parent:0"], ["TOO", "parent:0"], ["LATE", "parent:0"]]); +}); + +test("the ffmpeg: the voice split, the raised branch shaped and limited, the two crossfaded by the spans' envelope in frames", () => { + const p = yellPlan(item()); + const fc = yellArgs("/in.wav", "/o.wav", p, { rate: 24000, layout: "mono" })[8]; + assert.match(fc, /asetnsamples=n=64:p=0,asplit=2\[yd\]\[yw\]/); + assert.match(fc, /equalizer=f=3200:t=o:w=1\.3:g=3,equalizer=f=1100:t=o:w=1:g=1\.5,acompressor=threshold=0\.063:ratio=2\.5/); + assert.match(fc, /alimiter=limit=0\.94:attack=2:release=40:level=false:latency=1/); + assert.match(fc, /between\(t,0\.920,1\.410\)\*clip\(min\(\(t-0\.920\)\/0\.050,\(1\.410-t\)\/0\.050\),0,1\)/); + assert.match(fc, /amix=inputs=2:normalize=0:duration=first,atrim=end_sample=216000\[out\]/); + assert.deepEqual(p.steps[0].spans, p.spans); +}); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(path.join(dir, "narration", "posts", "7"), { recursive: true }); + // A voice-like read: a 180 Hz buzz with harmonics, syllable-pulsed, at about -21 LUFS. + execFileSync("ffmpeg", ["-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='0.12*(sin(2*PI*180*t)+0.5*sin(2*PI*360*t)+0.3*sin(2*PI*2900*t))*(0.55+0.45*sin(2*PI*4*t))':s=24000:d=9", path.join(dir, "narration", "posts", "7", "take-1.orpheus-zac.wav")]); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +test("YELLED: the file as long as its source, its spans louder by the lift (measured), outside them untouched, loudness within 1 LU; picked; re-yelled from the take before; chained with a tempo either way", async () => { + const p = await project("yell", [item()]); + let e = (await manifest(p)).timeline[0]; + const r = await yellTake(p, e, {}); + const t = r.take; + assert.match(t.file, /take-2\.yell-orpheus\.wav$/); + assert.ok(Math.abs(t.seconds - 9) < 0.01, `length ${t.seconds}`); + assert.deepEqual([t.source.from, t.steps[0].op, t.steps[0].params.style], ["take-1.orpheus-zac", "yell", "raise"]); + assert.deepEqual(t.words, words(), "its timings kept"); + const src = path.join(p.dir, "narration/posts/7/take-1.orpheus-zac.wav"); + const out = path.join(p.dir, t.file); + const lift = (await spansRms(out, r.plan.spans)) - (await spansRms(src, r.plan.spans)); + // A third of this read is caps: the loudness rule (≤ 1 LU over its source) lowers the lift asked for, and says so. + assert.ok(lift > 1.5 && lift < 7 && (r.plan.gain < 5.5 || lift > 3.5), `the spans' lift ${lift} dB at ${r.plan.gain} dB asked`); + assert.equal(t.steps[0].params.gain, r.plan.gain); + const flat = (await spansRms(out, [[4.6, 6.6]])) - (await spansRms(src, [[4.6, 6.6]])); + assert.ok(Math.abs(flat) < 0.2, `outside the spans: ${flat} dB`); + assert.ok(r.plan.lufs.after - r.plan.lufs.base <= 1.05, `loudness ${r.plan.lufs.base} → ${r.plan.lufs.after}`); + e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.pick, 1); + assert.deepEqual(validatePostItem(e), []); + // Yelled again: from the take before (never raised twice). + assert.equal(yellPlan(e).take.file, "narration/posts/7/take-1.orpheus-zac.wav"); + // Then re-timed: the yell's take is cut, the yell kept, the words scaled. + const rt = await rereadTake(p, e, { tempo: { 1: 1.3 } }); + assert.equal(rt.take.source.from, "take-2.yell-orpheus"); + e = (await manifest(p)).timeline[0]; + // A yell further up the chain: refused (pick the take before it). + assert.throws(() => yellPlan(e), /made from a yelled one/); + // The other order: re-timed first, then yelled (posts yell): its spans on the tempo's word timings. + const q = await project("yell2", [item()]); + let e2 = (await manifest(q)).timeline[0]; + await rereadTake(q, e2, { tempo: { 1: 1.3 } }); + const lines = []; + const code = await postsCommand(["yell", "yell2", "p-7"], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + assert.equal(code, 0, lines.join("\n")); + assert.match(lines.join("\n"), /p-7: yelled THEY ITS ALREADY TOO LATE HIDE \(3 span\(s\)/); + e2 = (await manifest(q)).timeline[0]; + const y = e2.narration.takes[e2.narration.pick]; + assert.equal(y.steps[0].op, "yell"); + assert.ok(y.steps[0].spans[1][1] < 4.16 / 1.0 && y.steps[0].spans[1][0] < 2.57, "the spans are the re-timed words'"); + // posts yell --dry-run: the list. + const dry = []; + await postsCommand(["yell", "yell2", "--dry-run"], { root: REPORTS, out: (s) => dry.push(s), err: (s) => dry.push(s) }); + assert.match(dry.join("\n"), /p-7: would yell THEY ITS ALREADY TOO LATE HIDE; flat: FBI \(acronym\)/); +}); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -51,6 +51,10 @@ const REREAD_LINES = [ " a READ RE-JOINED without a piece (no TTS): the picked take's kept parts cut from its own file and joined again, a new", " take that is picked (one undo point) -- the post it answers or quotes left unread, a part by number, a part that is", " only a link. set-item thread.parent.<i>|quoted=context|hidden on a piece the take reads runs it first (--no-reread: refused).", + " umtool posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" [--stretch atempo|rubberband] PER-PART TEMPO (no", + " TTS): the parts named read faster (1-1.6, pitch kept), the rest as they were, the words scaled with them; a new take", + " picked. set-item <item> narration.tempo=\"4-16=1.35\" runs it. --yell-caps [--yell-gain 5.5] [--yell-style raise|shout|loud]:", + " the words he wrote in ALL CAPS raised (acronyms and slurs left), timings kept. umtool posts yell <p> --all|<ids…>: the cut's.", ]; // `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block. @@ -129,8 +133,10 @@ 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 progress <project> [auto|on|off|default] the cut's PROGRESS BAR default (auto: a read of 60 s or more); an item's: set-item progress=", " umtool posts avatar <project> [<handle> <image-file> | <handle> off] [--json]", " an author's PICTURE on every card that draws them (postAvatars): the file copied into posts-media/_avatars/,", " never replaced by the archive's; `off` clears it; no handle lists them. A blurred author never shows one.", @@ -154,7 +160,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", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -437,8 +443,24 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con } const list = (v) => (v === null ? [] : String(v).split(",").map((x) => x.trim()).filter(Boolean)); const dropParts = list(flags.has("--drop-parts") ? str("--drop-parts") : null).map(Number); - return await rereadCommand(await projectOf(projectArg, root), ref, { without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), dryRun, json, out }).catch((e) => { - throw e?.name === "RereadError" ? new CliError(e.message) : e; + const yell = flags.has("--yell-caps") ? { gain: flags.has("--yell-gain") ? Number(str("--yell-gain")) : undefined, style: flags.has("--yell-style") ? str("--yell-style") : undefined } : null; + return await rereadCommand(await projectOf(projectArg, root), ref, { + without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), + tempoSpec: flags.has("--tempo-for") ? str("--tempo-for") : null, tempo: flags.has("--tempo") ? str("--tempo") : null, parts: flags.has("--parts") ? str("--parts") : null, + stretch: flags.has("--stretch") ? str("--stretch") : "atempo", yell, dryRun, json, out, + }).catch((e) => { + throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; + }); + } + if (verb === "yell") { + // THE CAPS YELLED, cut-wide (postYell.mjs): each item's picked take, no TTS, a new take picked per item. + const { YELL_USAGE, yellBatchCommand } = await import("./postYell.mjs"); + if (!projectArg || flags.has("--help")) { + err(YELL_USAGE); + return 2; + } + return await yellBatchCommand(await projectOf(projectArg, root), { ids: words.slice(2), all: flags.has("--all"), gain: flags.has("--yell-gain") ? Number(str("--yell-gain")) : undefined, style: flags.has("--yell-style") ? str("--yell-style") : undefined, dryRun, json, out }).catch((e) => { + throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e; }); } if (verb === "narrate") { @@ -455,7 +477,15 @@ 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 === "progress") { + // THE CUT's PROGRESS BAR default (post-progress.mjs): render.posts.progress; bare, which items draw it. + if (!projectArg || flags.has("--help")) { + err(PROGRESS_USAGE); + return 2; + } + return await progressCommand(await projectOf(projectArg, root), words[2] ?? null, { json, out }); } if (verb === "clock") { const { CLOCK_USAGE, clockCommand } = await import("./postFxCli.mjs"); @@ -710,6 +740,11 @@ export function postItemPatchOf(pairs) { if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw); else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v; else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k); + // Its progress bar (post-progress.mjs): on, off or auto (60 s of read or more); default: the cut's. + else if (k === "progress") { + if (!["on", "off", "auto", "default", ""].includes(v)) throw new CliError("progress= takes on, off, auto or default (the cut's)"); + out.progress = v === "default" || v === "" ? null : v; + } // Its media scene (post-media-scene.mjs): off (never in one), join (joins the scene beside it), auto (by its attachment). else if (k === "scene") { if (!["off", "join", "auto", "on", ""].includes(v) && !OFF.has(v)) throw new CliError("scene= takes off, join or auto"); @@ -920,6 +955,34 @@ async function resolveAttachments(patch, dir) { for (const r of patch.linksAdd ?? []) if (Array.isArray(r.media)) r.media = await fix(r.media); } +const PROGRESS_USAGE = [ + "usage: umtool posts progress <project> [auto|on|off|default] [--json]", + " THE CUT's PROGRESS BAR (render.posts.progress, post-progress.mjs): a thin bar along a card's foot that fills with", + " the item's read (its real seconds: a part read faster moves it faster), ticked at each part. auto: a read of 60 s", + " or more; default: off. One item's: umtool posts set-item <p> <item> progress=on|off|auto|default. Bare: which draw it.", +].join("\n"); + +/** `umtool posts progress <p> [mode]`: the cut's progress bar default, or the items that draw it. */ +async function progressCommand(project, mode, { json, out }) { + const { progressPlan, progressModeOf } = await import("umtool-report-to-video/post-progress"); + const { postItemPlan } = await import("umtool-report-to-video/post-item"); + if (mode !== null) { + if (!["auto", "on", "off", "default"].includes(mode)) throw new CliError("posts progress takes auto, on, off or default"); + const { updatePostProgressRender } = await import("./manifest.mjs"); + await withEditNotes(project, async () => updatePostProgressRender(project.dir, mode === "default" ? null : mode, { token: await manifestToken(project.dir) })); + } + const manifest = await readManifest(project.dir); + const render = manifest?.render ?? {}; + const items = (manifest?.timeline ?? []).filter((e) => e?.type === "post"); + const shown = items.flatMap((e) => { + const pp = progressPlan(e, render, postItemPlan(e, render)); + return pp ? [{ id: e.id, mode: progressModeOf(e, render), from: pp.from, to: pp.to, parts: pp.ticks.length + 1 }] : []; + }); + if (json) out(JSON.stringify({ ok: true, progress: render.posts?.progress ?? null, items: shown }, null, 2)); + else out([`progress bar: the cut's ${render.posts?.progress ?? "off (default)"}; ${shown.length} of ${items.length} post item(s) draw it`, ...shown.slice(0, 60).map((x) => ` ${x.id} ${(x.to - x.from).toFixed(1)} s of read, ${x.parts} part(s)${x.mode !== (render.posts?.progress ?? "off") ? ` (its own: ${x.mode})` : ""}`)].join("\n")); + return 0; +} + /** `posts set-item`: a post item's knobs, through updatePostItem (`fit=read[:linger]`: posts fit, on this item). */ async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread = true }) { const fitPair = pairs.find((p) => /^fit=/.test(p)); @@ -930,6 +993,15 @@ async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread const { fitCommand } = await import("./postNarrationCli.mjs"); return fitCommand(await projectOf(projectArg, root), [ref], { linger: m[1] !== undefined ? Number(m[1]) : null, json, out }); } + // narration.tempo="4-16=1.35,21-25=1.3": the picked take's parts RE-TIMED (postReread.mjs tempoPlan, no TTS), a new take picked. + const tempoPair = pairs.find((p) => p.startsWith("narration.tempo=")); + if (tempoPair) { + if (pairs.length > 1) throw new CliError("narration.tempo= goes alone (it is posts reread --tempo-for on this item)"); + const { rereadCommand } = await import("./postReread.mjs"); + return rereadCommand(await projectOf(projectArg, root), ref, { tempoSpec: tempoPair.slice("narration.tempo=".length).replace(/^"|"$/g, ""), json, out }).catch((e) => { + throw e?.name === "RereadError" ? new CliError(e.message) : e; + }); + } // narration.<knob>=…: this post's narration mix (rate, lead, wet …), through the narration's own writer. const narr = pairs.filter((p) => p.startsWith("narration.")); if (narr.length) { 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. */ @@ -2703,94 +2704,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 @@ -67,6 +67,7 @@ "./post-combo-render": "./post-combo-render.mjs", "./post-item": "./post-item.mjs", "./post-narration": "./post-narration.mjs", + "./post-progress": "./post-progress.mjs", "./post-censor": "./post-censor.mjs", "./post-media-scene": "./post-media-scene.mjs", "./post-redact": "./post-redact.mjs", @@ -81,6 +82,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-item.mjs b/umtool/report-to-video/post-item.mjs @@ -39,6 +39,7 @@ import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePos import { panelSchedule, validatePostThread } from "./post-thread.mjs"; import { joinLayerHtml, validatePostJoin, validatePostJoinRender } from "./post-join.mjs"; import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from "./post-link-visit.mjs"; +import { progressErrors } from "./post-progress.mjs"; import { validatePostMapRender } from "./post-branch-map.mjs"; import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; @@ -554,6 +555,8 @@ export function validatePostItem(e) { errors.push(...validatePostJoin(e)); // Its link visit (post-link-visit.mjs): false (none). errors.push(...validatePostLinkVisit(e)); + // Its progress bar (post-progress.mjs): auto, on or off (absent: the cut's). + errors.push(...progressErrors(e.progress, `timeline ${e?.id ?? "?"}.progress`)); return errors; } diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -57,8 +57,12 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco * read as their source (takeSourceOf). */ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); -/** The ops umtool runs itself on a take's own file (no editor job): `rejoin` -- its kept parts cut out and joined again (lib/report/postReread.mjs). */ -export const POST_LOCAL_OPS = Object.freeze(["rejoin"]); +/** + * The ops umtool runs itself on a take's own file (no editor job, no TTS): `rejoin` -- its kept parts cut out and + * joined again; `tempo` -- named parts time-stretched, pitch kept (lib/report/postReread.mjs); `yell` -- the words + * he wrote in ALL CAPS raised, as a voice raised (lib/report/postYell.mjs). + */ +export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell"]); /** The editor's op route for each. */ export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); @@ -148,6 +152,8 @@ export const POST_NARRATION_LIMITS = Object.freeze({ lufs: [-40, -10], speed: [0.5, 2], rate: [0.8, 1.5], + /** A part's own tempo (a `tempo` step: the part time-stretched in the take's file, its pitch kept). */ + tempo: [1, 1.6], /** A script is the whole post read aloud (operator, 2 Nov: never excerpted); the editor's tts op takes 20,000. */ scriptChars: 20000, takes: 50, @@ -181,9 +187,10 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs"]); -const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's. -const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece"]); +// `tempo`: the part's reading speed in the take's file against its first read (a `tempo` step's; absent: 1). +const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece", "tempo"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; /** Orpheus's expressive tags (narration.mjs NARRATION_TAGS, the editor's list). */ const TAGS = ["laugh", "chuckle", "sigh", "cough", "sniffle", "groan", "yawn", "gasp"]; @@ -643,6 +650,10 @@ export function validatePostNarration(e) { for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); // A re-join's record: what it left out (a piece, "part <n>", "url"). if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`); + // A tempo step's record: each run of parts ("4-16", "21") and the tempo it reads at. + if (st.tempo !== undefined && !(isObj(st.tempo) && Object.keys(st.tempo).length <= 200 && Object.entries(st.tempo).every(([r, v]) => /^\d{1,3}(-\d{1,3})?$/.test(r) && numIn(v, POST_NARRATION_LIMITS.tempo)))) errors.push(`${tw}.steps[${k}].tempo must be {"<part>[-<part>]": ${POST_NARRATION_LIMITS.tempo.join("–")}}`); + // A yell step's record: the take seconds it raised. + if (st.spans !== undefined && !(Array.isArray(st.spans) && st.spans.length <= 500 && st.spans.every((x) => Array.isArray(x) && x.length === 2 && fin(x[0]) && fin(x[1]) && x[0] >= 0 && x[1] > x[0]))) errors.push(`${tw}.steps[${k}].spans must be a list of [from, to] (take seconds)`); } }); } @@ -660,6 +671,7 @@ export function validatePostNarration(e) { if (!(fin(p.start) && p.start >= 0)) errors.push(`${pw}.start must be where it starts in the take, seconds`); if (!(fin(p.seconds) && p.seconds > 0)) errors.push(`${pw}.seconds must be its length`); if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); + if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); }); } diff --git a/umtool/report-to-video/post-progress.mjs b/umtool/report-to-video/post-progress.mjs @@ -0,0 +1,248 @@ +// A POST ITEM's PROGRESS BAR (umtool/docs/report-video.md, "The progress bar"; operator, 4 Nov, a 6.5-minute post: +// "we might want a per-clip progress bar in the engine specifically for clips like this"). +// +// A thin bar along the card's foot -- under its counts row, inside the card -- that fills as the item's read goes: +// the READ's own seconds (the narration schedule: from the narrator's first word to the last), linear in real time, +// so a part read faster (a `tempo` step, postReread.mjs) moves it faster and it never jumps. Subtle ticks mark where +// each part of the read starts. An item with no read fills over its own length. +// +// render.posts.progress = "auto" | "on" | "off" // the cut's default (absent: off) +// entry.progress = "auto" | "on" | "off" // one item's (absent: the cut's) +// auto: on for a read of PROGRESS_AUTO_SECONDS (60 s) or more, as the item plays it (its rate counted) +// +// WHERE: drawn OVER the card, never in it (no data-w, no data-post-block): readInViewErrors never counts it. Its +// place is judged over the read (measureProgressPlace): the card's foot, under the counts row; never over a word, +// and short of the clock (post-clock.mjs) when that sits on the same line. Over a word anywhere, it moves just under +// the card's edge. +// +// Pure but for the DOM functions (mountProgress, measureProgressPlace, setProgressState), SELF-CONTAINED: the +// build passes them to a page to shoot its track and fill, Play and the bench call them on their frame. + +import { mixHex, rgbaOf } from "./post-item.mjs"; +import { partStartOnItem, pickedTake } from "./post-narration.mjs"; + +export const PROGRESS_MODES = Object.freeze(["auto", "on", "off"]); +/** auto: a read this long or longer (item seconds) draws the bar. */ +export const PROGRESS_AUTO_SECONDS = 60; +/** The bar fades in over this, ending as the read starts. */ +export const PROGRESS_FADE = 0.35; +/** Its drawing (bumped when its look changes: the segment key carries it). */ +export const POST_PROGRESS_DRAW_V = 1; +/** At most this many ticks (a read of more parts draws none). */ +export const PROGRESS_TICKS_MAX = 120; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r4 = (v) => Math.round(v * 10000) / 10000; + +/** Every reason an item's `progress` is refused. */ +export function progressErrors(v, where) { + if (v === undefined) return []; + return PROGRESS_MODES.includes(v) ? [] : [`${where} must be ${PROGRESS_MODES.join(", ")}`]; +} + +/** Every reason `render.posts.progress` is refused (post-redact.mjs validatePostsRender calls it). */ +export const validateProgressRender = (v) => progressErrors(v, "render.posts.progress"); + +/** The mode an item plays with: its own, else the cut's, else off. */ +export function progressModeOf(entry, render) { + if (PROGRESS_MODES.includes(entry?.progress)) return entry.progress; + const c = render?.posts?.progress; + return PROGRESS_MODES.includes(c) ? c : "off"; +} + +/** + * THE BAR's PLAN for post item `entry` (its plan, postItemPlan's): `{ from, to, ticks, until, mode }` -- it fills + * from item second `from` to `to` (the read; an item with none: 0 to its length), `ticks` each later part's start + * as a fraction of the bar, `until` when it goes (a stack card's media phase covers the card). Null: no bar. + * + * @param {Record<string, any>} entry + * @param {Record<string, any> | undefined} render + * @param {{ total: number, narration?: Record<string, any> | null, steps?: Array<Record<string, any>>, reading?: number }} plan + * @param {{ stack?: boolean }} [o] + */ +export function progressPlan(entry, render, plan, { stack = false } = {}) { + if (entry?.type !== undefined && entry.type !== "post") return null; + if (!plan || !fin(plan.total) || plan.total <= 0) return null; + const mode = progressModeOf(entry, render); + if (mode === "off") return null; + const sch = isObj(plan.narration) ? plan.narration : null; + const from = sch ? sch.at : 0; + const to = sch ? sch.at + sch.seconds : plan.total; + if (!(to > from)) return null; + if (mode === "auto" && !(sch && sch.seconds >= PROGRESS_AUTO_SECONDS)) return null; + const t = sch ? pickedTake(entry) : null; + const parts = Array.isArray(t?.parts) ? t.parts.filter((p) => fin(p?.start)) : []; + const ticks = parts.length > 1 && parts.length <= PROGRESS_TICKS_MAX + ? parts.slice(1).map((p) => r4((partStartOnItem(sch, p) - from) / (to - from))).filter((x) => x > 0.002 && x < 0.998) + : []; + const until = stack && Array.isArray(plan.steps) && plan.steps.length ? plan.steps[0].at : plan.total; + return { from: r4(from), to: r4(to), ticks, until: r4(until), mode }; +} + +/** How full the bar is at item second `s`, 0–1: linear in the read's real seconds. */ +export function progressAt(pp, s) { + if (!pp) return 0; + return Math.min(1, Math.max(0, (s - pp.from) / (pp.to - pp.from))); +} + +/** Its opacity at item second `s`: faded in over PROGRESS_FADE ending at the read's start, gone at `until`. */ +export function progressOpacityAt(pp, s) { + if (!pp || s >= pp.until) return 0; + const fade = Math.min(PROGRESS_FADE, pp.from); + return fade > 0 ? Math.min(1, Math.max(0, (s - (pp.from - fade)) / fade)) : 1; +} + +/** The fill's ffmpeg expression of `T` (seconds): the bar's width fraction, as progressAt. */ +export const progressExpr = (pp) => `clip((T-${pp.from})/${r4(pp.to - pp.from)},0,1)`; + +// --------------------------------------------------------------------------- +// THE LOOK, and the DOM (self-contained). +// --------------------------------------------------------------------------- + +/** The bar's height in px for a page `height` px tall. */ +export const progressHeight = (height = 1080) => Math.max(3, Math.round(5 * (height / 1080))); + +/** The bar's CSS for a page `height` px tall, in the card's palette. */ +export function progressCss({ height = 1080, palette = {} } = {}) { + const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; + const h = progressHeight(height); + const tick = Math.max(1, Math.round(1.5 * (height / 1080))); + return ` +[data-post-progress-layer] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 60; } +.pprog { position: absolute; left: 0; top: 0; height: ${h}px; border-radius: ${h}px; overflow: hidden; } +.pprog-track { position: absolute; inset: 0; background: ${rgbaOf(pal.fg, 0.13)}; } +.pprog-fill { position: absolute; inset: 0; background: linear-gradient(90deg, ${mixHex(pal.accent, pal.bg, 0.25)}, ${pal.accent}); box-shadow: 0 0 ${h * 2}px ${rgbaOf(pal.accent, 0.35)}; } +.pprog-tick { position: absolute; top: 0; bottom: 0; width: ${tick}px; margin-left: -${tick / 2}px; background: ${rgbaOf(pal.bg, 0.55)}; } +[data-post-progress-layer][data-part="track"] .pprog-fill { display: none; } +[data-post-progress-layer][data-part="fill"] .pprog-track { display: none; } +`; +} + +/** + * Mount the bar over the card page (`{ css, ticks }`), hidden. `part`: "track" or "fill" alone (the build shoots + * each), else both (Play). Returns the bar's element height. + * @param {{ css: string, ticks?: number[], part?: "track" | "fill" | null } | null} arg + * @param {Document} [doc] + */ +export function mountProgress(arg, doc = document) { + doc.querySelectorAll("[data-post-progress-layer], style[data-post-progress-css]").forEach((el) => el.remove()); + if (!arg) return null; + const style = doc.createElement("style"); + style.setAttribute("data-post-progress-css", ""); + style.textContent = arg.css || ""; + doc.head.appendChild(style); + const layer = doc.createElement("div"); + layer.setAttribute("data-post-progress-layer", ""); + if (arg.part) layer.setAttribute("data-part", arg.part); + const bar = doc.createElement("div"); + bar.className = "pprog"; + bar.setAttribute("data-post-progress", ""); + bar.style.opacity = "0"; + const ticks = (arg.ticks || []).map((f) => `<span class="pprog-tick" style="left:${(f * 100).toFixed(3)}%"></span>`).join(""); + bar.innerHTML = `<span class="pprog-track"></span><span class="pprog-fill" data-post-progress-fill=""></span>${ticks}`; + layer.appendChild(bar); + doc.body.appendChild(layer); + return Math.ceil(bar.getBoundingClientRect().height); +} + +/** + * Where the bar goes on the card as drawn: `{ x, y, width, height, place, covers, tries }` -- along the card's foot, + * under its own post's counts row (a threaded card's: the post's tile), inset from the card's rounded corners; its + * right end short of `avoid` boxes on its line (the clock). `fixed`: the places to judge (an earlier call's + * `tries`), only counted here -- placed once, judged over the read; else, over a word, just under the card's edge. + * @typedef {{ x: number, y: number, width: number, height: number, place: string }} ProgressPlace + * @param {{ height: number, inset: number, avoid?: Array<{ x: number, y: number, width: number, height: number }>, fixed?: ProgressPlace[] | null }} arg + * @param {Document} [doc] + * @returns {(ProgressPlace & { covers: number, tries: ProgressPlace[], counts: number[] }) | null} + */ +export function measureProgressPlace(arg, doc = document) { + const card = doc.querySelector("[data-post-card]"); + if (!card || !arg) return null; + const c = card.getBoundingClientRect(); + const h = arg.height; + // The words as SEEN: each clipped to its window (a following card's flow pans words past its window's edge, hidden). + const wins = new Map(); + const winOf = (el) => { + const w = el.closest("[data-post-words]"); + if (!w) return null; + if (!wins.has(w)) wins.set(w, w.getBoundingClientRect()); + return wins.get(w); + }; + const words = Array.from(doc.querySelectorAll("[data-w]")).flatMap((el) => { + const w = winOf(el); + return Array.from(el.getClientRects()).map((r) => (w ? { left: Math.max(r.left, w.left), right: Math.min(r.right, w.right), top: Math.max(r.top, w.top), bottom: Math.min(r.bottom, w.bottom) } : r)); + }).filter((r) => r.right - r.left > 0 && r.bottom - r.top > 0); + const hit = (r) => words.filter((w) => Math.min(r.x + r.width, w.right) - Math.max(r.x, w.left) > 0.5 && Math.min(r.y + r.height + 2, w.bottom) - Math.max(r.y - 2, w.top) > 0.5).length; + /** @type {ProgressPlace[]} */ + const tries = arg.fixed || (() => { + const radius = parseFloat((doc.defaultView || window).getComputedStyle(card).borderTopLeftRadius) || 0; + const side = Math.max(arg.inset, Math.round(radius * 0.9)); + const x = Math.round(c.left + side); + let right = Math.round(c.right - side); + const all = Array.from(card.querySelectorAll(".counts")); + const counts = card.querySelector('[data-thread-tile="post"] .counts') || all[all.length - 1] || null; + const cb0 = counts ? counts.getBoundingClientRect() : null; + // A counts row is the card's foot only when it sits at the foot (a threaded card's is a tile's, in its flow). + const cb = cb0 && cb0.height > 0 && c.bottom - cb0.bottom >= 0 && c.bottom - cb0.bottom <= Math.max(60, 3 * arg.inset) ? cb0 : null; + // Under the counts row: centred in the foot below it (else a little above the card's edge). + const foot = cb ? Math.round((cb.bottom + c.bottom) / 2 - h / 2) : Math.round(c.bottom - h - Math.max(6, arg.inset * 0.5)); + const y = Math.min(Math.round(c.bottom - h - 3), Math.max(foot, cb ? Math.round(cb.bottom + 2) : foot)); + for (const a of arg.avoid || []) { + if (a.y < y + h + 4 && a.y + a.height > y - 4 && a.x < right && a.x + a.width > x) right = Math.min(right, Math.round(a.x - arg.inset * 0.6)); + } + const width = Math.max(40, right - x); + const below = Math.round(c.bottom + Math.max(4, h)); + return [ + { x, y, width, height: h, place: "foot" }, + { x, y: below, width: Math.max(40, Math.round(c.right - side) - x), height: h, place: "under" }, + ]; + })(); + const looked = tries.map((t) => ({ ...t, covers: hit(t) })); + const best = looked.find((t) => !t.covers) || looked.slice().sort((a, b) => a.covers - b.covers)[0]; + return { ...best, tries: looked.map(({ covers: _c, ...t }) => t), counts: looked.map((t) => t.covers) }; +} + +/** + * Set the bar: `{ x, y, width, frac, opacity }` (frac progressAt's), or null to hide. The fill is clipped at its + * leading edge (as the build clips it), never squeezed. + * @param {{ x: number, y: number, width: number, frac: number, opacity?: number } | null} arg + * @param {Document} [doc] + */ +export function setProgressState(arg, doc = document) { + const el = doc.querySelector("[data-post-progress]"); + if (!el) return; + if (!arg) { + el.style.opacity = "0"; + return; + } + el.style.transform = `translate(${Math.round(arg.x)}px, ${Math.round(arg.y)}px)`; + el.style.width = `${Math.round(arg.width)}px`; + el.style.opacity = String(arg.opacity === undefined ? 1 : arg.opacity); + el.setAttribute("data-frac", String(Math.round(arg.frac * 1000) / 1000)); + const fill = el.querySelector("[data-post-progress-fill]"); + if (fill) fill.style.clipPath = `inset(0 ${((1 - Math.min(1, Math.max(0, arg.frac))) * 100).toFixed(3)}% 0 0)`; +} + +/** + * THE BAR's FILTERS for the build (post-render.mjs postSegmentArgs): the track and the fill (each a still the size of + * the bar, inputs `ti` and `fi`, looped over the item) laid over `inLabel` at `x, y` -- the fill's alpha clipped at + * its leading edge, frame by frame (geq on T: progressExpr), both faded in as the read starts and gone at `until`. + * Returns `{ chains, out }`. + * + * @param {{ ti: number, fi: number, inLabel: string, outLabel: string, x: number, y: number, pp: ReturnType<typeof progressPlan>, T: number }} o + */ +export function progressFilters({ ti, fi, inLabel, outLabel, x, y, pp, T }) { + const fade = Math.min(PROGRESS_FADE, pp.from); + const fadeIn = fade > 0 ? `,fade=t=in:st=${r4(pp.from - fade)}:d=${r4(fade)}:alpha=1` : ""; + const enable = pp.until < T - 1e-6 ? `:enable='lt(t,${pp.until})'` : ""; + return { + chains: [ + `[${ti}:v]format=rgba,setsar=1${fadeIn}[pgt]`, + `[${fi}:v]format=rgba,setsar=1,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='alpha(X,Y)*clip(W*${progressExpr(pp)}-X,0,1)'${fadeIn}[pgf]`, + `[${inLabel}][pgt]overlay=x=${x}:y=${y}${enable}[${outLabel}t]`, + `[${outLabel}t][pgf]overlay=x=${x}:y=${y}${enable}[${outLabel}]`, + ], + out: outLabel, + }; +} diff --git a/umtool/report-to-video/post-progress.test.mjs b/umtool/report-to-video/post-progress.test.mjs @@ -0,0 +1,103 @@ +// post-progress.mjs: A POST ITEM's PROGRESS BAR -- which items draw it (on, off, auto: a read of 60 s or more; the +// item's own over the cut's), its timing (the read's REAL seconds: linear, so a part read faster by a tempo step moves +// it faster and it never jumps at a part's edge), its ticks, its fade, the validators, the segment key (an item with +// no bar keeps its key), and the build's filters (ffmpeg: the fill clipped at the read's progress frame by frame). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { postItemPlan, validatePostItem } from "./post-item.mjs"; +import { validatePostsRender } from "./post-redact.mjs"; +import { postFxKeyFields } from "./post-render.mjs"; +import { PROGRESS_AUTO_SECONDS, progressAt, progressFilters, progressModeOf, progressOpacityAt, progressPlan } from "./post-progress.mjs"; + +const DIR = await mkdtemp(path.join(tmpdir(), "umtool-post-progress-")); +after(() => rm(DIR, { recursive: true, force: true })); + +// A read of three parts; the middle one read 1.35x (a tempo step): shorter in the take, so its share of the bar is too. +const take = (seconds = 90) => ({ + file: "narration/posts/1/take-2.tempo-take.wav", engine: "derived", voice: "zac", seconds, + parts: [{ n: 1, para: 0, text: "a", start: 0, seconds: seconds * 0.4 }, { n: 2, para: 1, text: "b", start: seconds * 0.45, seconds: seconds * 0.2, tempo: 1.35 }, { n: 3, para: 2, text: "c", start: seconds * 0.7, seconds: seconds * 0.3 }], +}); +const item = (o = {}, seconds = 90) => ({ type: "post", id: "p-1", post: "subj-x/1", platform: "x", author: "S", handle: "s", date: "2026-10-30T10:00:00.000Z", text: "Words.", narration: { script: "a\n\nb\n\nc", takes: [take(seconds)], pick: 0 }, ...o }); + +test("WHICH ITEMS: the item's own mode over the cut's (absent: off); auto on for a read of 60 s or more as it plays (its rate counted)", () => { + const render = { postNarration: { lead: 0.4 } }; + assert.equal(progressModeOf(item(), render), "off"); + assert.equal(progressModeOf(item(), { posts: { progress: "auto" } }), "auto"); + assert.equal(progressModeOf(item({ progress: "off" }), { posts: { progress: "on" } }), "off"); + const plan = (e, r) => postItemPlan(e, r); + assert.equal(progressPlan(item(), render, plan(item(), render)), null, "the cut's default: off"); + const auto = { posts: { progress: "auto" } }; + assert.ok(progressPlan(item(), auto, plan(item(), auto)), "90 s of read: on"); + assert.equal(progressPlan(item({}, 40), auto, plan(item({}, 40), auto)), null, "40 s: off"); + // A 62 s take read at 1.08: 57.4 s on the item -- under the line. + const fast = { posts: { progress: "auto" }, postNarration: { rate: 1.08 } }; + assert.equal(progressPlan(item({}, 62), fast, plan(item({}, 62), fast)), null); + assert.ok(PROGRESS_AUTO_SECONDS === 60); + // on: any read; an item with no read fills over its own length. + const bare = { ...item({ progress: "on" }), narration: undefined }; + const pb = progressPlan(bare, {}, plan(bare, {})); + assert.deepEqual([pb.from, pb.to, pb.ticks], [0, plan(bare, {}).total, []]); +}); + +test("ITS TIMING: the read's real seconds, linear -- no jump at a part read faster; the ticks at each part's start; faded in to the read's start; gone at a stack card's media", () => { + const render = { posts: { progress: "on" }, postNarration: { lead: 0.4 } }; + const plan = postItemPlan(item(), render); + const pp = progressPlan(item(), render, plan); + assert.deepEqual([pp.from, pp.to], [0.4, 90.4]); + // The ticks: parts 2 and 3 start at 45% and 70% of the read. + assert.deepEqual(pp.ticks, [0.45, 0.7]); + // Linear: the same step of item seconds is the same step of the bar, inside the stretched part and across its edges. + const step = (s) => progressAt(pp, s + 0.1) - progressAt(pp, s); + for (const s of [10, 40.9, 41, 50, 58.9, 59, 63.4, 80]) assert.ok(Math.abs(step(s) - 0.1 / 90) < 1e-9, `at ${s}`); + assert.deepEqual([progressAt(pp, 0), progressAt(pp, 45.4), progressAt(pp, 95)], [0, 0.5, 1]); + // Faded in over 0.35 s ending at the read's start (here 0.4: from 0.05). + assert.equal(progressOpacityAt(pp, 0.05), 0); + assert.ok(Math.abs(progressOpacityAt(pp, 0.225) - 0.5) < 1e-9); + assert.equal(progressOpacityAt(pp, 0.4), 1); + assert.equal(progressOpacityAt({ ...pp, until: 50 }, 50), 0, "gone at its until"); + const stack = progressPlan(item(), render, { ...plan, steps: [{ at: 91, seconds: 3, items: [] }] }, { stack: true }); + assert.equal(stack.until, 91); +}); + +test("THE VALIDATORS and THE KEY: an item's progress and the cut's are on, off or auto; an item with no bar keeps its key, one with a bar adds its plan", () => { + assert.deepEqual(validatePostItem(item({ progress: "on" })), []); + assert.match(validatePostItem(item({ progress: "yes" })).join(" "), /progress must be auto, on, off/); + assert.deepEqual(validatePostsRender({ posts: { progress: "auto" } }), []); + assert.match(validatePostsRender({ posts: { progress: 1 } }).join(" "), /render.posts.progress must be auto, on, off/); + const render = { postNarration: { lead: 0.4 } }; + const plan = postItemPlan(item(), render); + assert.deepEqual(postFxKeyFields(item(), render, null, { plan }), {}, "no bar: nothing added"); + assert.deepEqual(postFxKeyFields(item(), render, null), {}, "no plan given: nothing added"); + const on = { ...render, posts: { progress: "auto" } }; + const k = postFxKeyFields(item(), on, null, { plan: postItemPlan(item(), on) }); + assert.deepEqual(Object.keys(k), ["progress"]); + assert.deepEqual([k.progress.v, k.progress.from, k.progress.to, k.progress.ticks], [1, 0.4, 90.4, [0.45, 0.7]]); +}); + +test("THE BUILD's FILTERS: the track laid, the fill clipped at the read's progress frame by frame, faded in, gone at until (ffmpeg)", async () => { + const track = path.join(DIR, "track.png"); + const fill = path.join(DIR, "fill.png"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x808080:s=200x6", "-frames:v", "1", track]); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0xff8000:s=200x6", "-frames:v", "1", fill]); + const pp = { from: 1, to: 3, ticks: [], until: 3.6, mode: "on" }; + const f = progressFilters({ ti: 1, fi: 2, inLabel: "0:v", outLabel: "o", x: 20, y: 50, pp, T: 4 }); + const out = path.join(DIR, "out.rgb"); + execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=black:s=240x100:r=10:d=4", "-loop", "1", "-framerate", "10", "-t", "4", "-i", track, "-loop", "1", "-framerate", "10", "-t", "4", "-i", fill, "-filter_complex", f.chains.join(";"), "-map", "[o]", "-pix_fmt", "rgb24", "-f", "rawvideo", out]); + const buf = await readFile(out); + const px = (t, x) => { + const i = Math.round(t * 10) * 240 * 100 * 3 + (52 * 240 + 20 + x) * 3; + return [buf[i], buf[i + 1], buf[i + 2]]; + }; + assert.deepEqual(px(0.5, 100), [0, 0, 0], "before its fade: nothing"); + // At 1.5 s a quarter full (50 px of 200): the fill to its edge, the track after. + assert.ok(px(1.5, 40)[0] > 240 && px(1.5, 40)[2] < 10, `fill ${px(1.5, 40)}`); + assert.deepEqual(px(1.5, 55), [128, 128, 128]); + assert.ok(px(2, 90)[0] > 240, "half: the fill at 90 px"); + assert.deepEqual(px(2, 105), [128, 128, 128]); + assert.ok(px(3.2, 190)[0] > 240, "full"); + assert.deepEqual(px(3.7, 100), [0, 0, 0], "gone at its until"); +}); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -31,6 +31,7 @@ import { censorMarkupErrors } from "./post-censor.mjs"; import { BLACKOUT_MARK, SLUR_CSS, decodePlaceholder, hasSlurMarks, maskSlurs, placeholdersHtml, sayFor, slurMatches, slursOn, validateSlursRender } from "./post-slurs.mjs"; import { validateClockRender } from "./post-clock.mjs"; +import { validateProgressRender } from "./post-progress.mjs"; /** The mark a redacted code unit becomes (a private-use character: never typed, never drawn as a letter). */ export const REDACT_MARK = ""; @@ -190,7 +191,8 @@ export function validatePostsRender(render) { if (p === undefined) return []; if (!isObj(p)) return ["render.posts must be an object ({redact, slurs})"]; // Its clock (post-clock.mjs): the cut's default and zone. - return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock)]; + // Its progress bar (post-progress.mjs): the cut's default. + return [...validateRedactTerms(p.redact), ...validateSlursRender(p.slurs), ...validateClockRender(p.clock), ...validateProgressRender(p.progress)]; } /** Every reason a channel's posts-markup.json is refused. */ diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -27,6 +27,9 @@ 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 { POST_PROGRESS_DRAW_V, measureProgressPlace, mountProgress, progressCss, progressFilters, progressHeight, progressPlan, setProgressState } from "./post-progress.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"; @@ -88,7 +91,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 = [], progress = null }) { const fps = render.fps ?? 30; const T = plan.total; const inputs = []; @@ -168,6 +171,15 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render if (c.mark) layer(c.mark, `cpm${ci}`, null); layer(c.chip, `cpc${ci}`, c.slide); }); + // THE PROGRESS BAR (post-progress.mjs): its track and its fill shot alone, laid along the card's foot -- the fill + // clipped at the read's progress frame by frame (real read seconds: a part read faster moves it faster, never a jump). + if (progress) { + const ti = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", progress.track]); + const fi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", progress.fill]); + const next = `b${++n}`; + parts.push(...progressFilters({ ti, fi, inLabel: cur, outLabel: next, x: progress.x, y: progress.y, pp: progress.plan, T }).chains); + cur = next; + } // THE CLOCK (post-clock.mjs): its frames shot alone -- the run from the item before's time, then held -- laid // over the card's corner from the first frame (a stack card's: until its media phase). if (clock) { @@ -310,10 +322,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}]`); @@ -323,7 +355,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", @@ -368,7 +405,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 = [], progress = null }) { await mkdir(dir, { recursive: true }); const fonts = { regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "", @@ -465,8 +502,15 @@ export async function renderPostCards(entry, { box, render, dir, manifestDir, la await ctx.close(); if (zooms.length) out.zooms = await shootZooms(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, zooms, redaction, follow }); if (clock) out.clock = await shootClock(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, clock, redaction, follow, total }); + // The progress bar (post-progress.mjs): along the card's foot, short of the clock on its line. + if (progress) { + const k = box.height / 1080; + const cb = out.clock?.box ? { x: out.clock.box.x + Math.round(240 * k), y: out.clock.box.y, width: out.clock.box.width - Math.round(240 * k), height: out.clock.box.height } : null; + out.progress = await shootProgress(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, progress, redaction, follow, total, avoid: cb ? [cb] : [] }); + } // 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(); } @@ -769,6 +813,177 @@ 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 PROGRESS BAR's STILLS (post-progress.mjs): on the card page as drawn, the bar mounted and placed + * (measureProgressPlace: the card's foot under its counts row, short of `avoid` -- the clock -- judged over the read: + * its start, middle and end, the place covering fewest words), then its track and its fill shot alone on a clear + * page. `{ track, fill, x, y, width, height, place, covers, plan }`. + */ +export async function shootProgress(browser, entry, { box, render, dir, fonts, parentShotUrl, avatars, progress, redaction = null, follow = null, total = 0, avoid = [] }) { + 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])); + try { + const file = path.join(dir, "progress.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 }); + const css = progressCss({ height: box.height, palette: render.palette }); + const h = progressHeight(box.height); + await page.evaluate(mountProgress, { css, ticks: progress.ticks, part: "track" }); + const fpath = follow ? followPath(follow, await page.evaluate(measureFollow)) : null; + const states = follow ? [total, 0, total / 2] : [0]; + const looks = []; + for (const s of states) { + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, s)); + looks.push(await page.evaluate(measureProgressPlace, { height: h, inset: Math.round(22 * k), avoid, fixed: looks[0]?.tries ?? null })); + } + if (!looks[0]) throw new Error(`${entry.id}: the progress bar has no card to sit on`); + // Each place's words over all three states: the fewest wins (the foot first when none). + const at = looks[0].tries.map((t, i) => ({ ...t, covers: looks.reduce((a, l) => a + (l?.counts?.[i] ?? 0), 0) })).sort((a, b) => a.covers - b.covers)[0]; + if (follow) await page.evaluate(applyFollowState, followStateAt(follow, fpath, 0)); + await page.evaluate(() => { + const st = document.createElement("style"); + st.textContent = "html, body { background: transparent !important; } body > *:not([data-post-progress-layer]) { visibility: hidden !important; }"; + document.head.appendChild(st); + }); + const clip = { x: at.x, y: at.y, width: Math.min(box.width - at.x, at.width), height: Math.min(box.height - at.y, h) }; + const shot = async (part) => { + await page.evaluate(mountProgress, { css, ticks: progress.ticks, part }); + await page.evaluate(setProgressState, { x: at.x, y: at.y, width: at.width, frac: 1, opacity: 1 }); + const f = path.join(dir, `progress-${part}.png`); + await page.screenshot({ path: f, clip, omitBackground: true }); + return f; + }; + return { track: await shot("track"), fill: await shot("fill"), x: clip.x, y: clip.y, width: clip.width, height: clip.height, place: at.place, covers: at.covers, plan: progress }; + } finally { + await ctx.close(); + } +} + +/** * 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 @@ -874,6 +1089,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 @@ -882,12 +1098,23 @@ export function postZoomPlan(entry, render, total = Infinity, schedule = undefin */ export const POST_CAPTION_DRAW_V = 2; export const POST_CLOCK_DRAW_V = 1; -export function postFxKeyFields(entry, render, prev = null) { +/** + * 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, { plan = null, layout = 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 }); + // The progress bar (post-progress.mjs): its plan (the read's span, the parts' ticks, when it goes) and its drawing. + const pp = plan ? progressPlan(entry, render, plan, { stack: layout?.mode === "stack" }) : null; + if (pp) out.progress = { v: POST_PROGRESS_DRAW_V, ...pp }; const k = postNarrationKnobs(entry, render); if (isNarrated(entry) && k.pace && k.pace !== "normal") out.pace = { pace: k.pace, lead: k.lead, tail: k.tail, ramp: k.ramp, linger: k.linger }; return out; @@ -925,7 +1152,7 @@ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], ren ...(plan.panel ? { panel: plan.panel } : {}), ...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}), // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them. - ...postFxKeyFields(entry, render, prev), + ...postFxKeyFields(entry, render, prev, { plan, layout }), ...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}), }; } @@ -1030,10 +1257,16 @@ 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)) : [] }); + // Its progress bar (post-progress.mjs): the read's span on the item's clock (a long read's, auto). + const prog = progressPlan(entry, render, plan, { stack: layout.mode === "stack" }); + 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, progress: prog }); // 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). @@ -1067,7 +1300,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 }))), progress: cards.progress ?? null }); try { await exec(ffmpeg, argv, { maxBuffer: 1 << 24 }); } catch (err) { @@ -1078,7 +1311,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); if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record }); emit("note", { @@ -1087,8 +1320,10 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box : `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})`, }); if (cards.follow) emit("note", { message: `${entry.id}: read-follow -- ${plan.follow.blocks.filter((b) => b.start !== null).length} block(s) read, ${cards.follow.path.segments.length ? `the words panned ${cards.follow.path.segments.length} time(s) over ${Math.round(cards.follow.path.max)} px` : "no pan (the words fit)"}; ${cards.follow.shots} shot(s) for ${cards.follow.frames} frames` }); + if (cards.progress) emit("note", { message: `${entry.id}: progress bar over the read ${prog.from}–${prog.to} s (${prog.mode}${prog.ticks.length ? `, ${prog.ticks.length + 1} parts ticked` : ""}), ${cards.progress.place === "foot" ? "along the card's foot" : "under the card"}${cards.progress.covers ? ` -- WARNING: over ${cards.progress.covers} word(s)` : ""}` }); 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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[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;