commit f0f84cf1e62dd0708ac327ea789aa1b37a330e18
parent 7d48675c71ee4ac975c10b142ebcea485093d39b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 4 Nov 2026 17:43:39 -0500
Merge lane/long-reads: a long read sped up where it is dull and back to normal where it matters -- per-part tempo on the existing read (posts reread --tempo-for "4-16=1.35,21-25=1.3", pitch kept, words remapped, no TTS); the ALL-CAPS words yelled on the existing read (posts reread --yell-caps / posts yell: a presence lift, body, compression and gain on each caps run, acronyms left flat, loudness within 1 LU); a per-post progress bar for long reads (progress=on|auto, a thin bar at the card's foot that fills over the read's real seconds) (operator, 4 Nov: "dynamic speed over boring parts of a long message", "allcaps needs to be yelled more", "a per-clip progress bar")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
22 files changed, 1728 insertions(+), 80 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
@@ -20,6 +20,7 @@ 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";
// ---------------------------------------------------------------------------
@@ -124,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);
@@ -330,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]">
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,7 @@ 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";
@@ -56,6 +57,9 @@ 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[] };
@@ -487,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;
@@ -511,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);
@@ -770,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);
};
@@ -892,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 (
@@ -916,6 +965,8 @@ export default function PostItemPlayer({
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,6 +85,9 @@ 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**) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -790,6 +790,19 @@ 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
@@ -871,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
@@ -810,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)
@@ -826,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/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/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.
@@ -132,6 +136,7 @@ export const POSTS_USAGE = [
" 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.",
@@ -155,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", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume"]);
+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}$/;
@@ -438,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") {
@@ -458,6 +479,14 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
}
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");
if (!projectArg || flags.has("--help")) {
@@ -711,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");
@@ -921,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));
@@ -931,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/package.json b/umtool/report-to-video/package.json
@@ -66,6 +66,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",
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,7 @@ 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";
@@ -89,7 +90,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, slams = [], slamHitList = [] }) {
+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 = [];
@@ -169,6 +170,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) {
@@ -394,7 +404,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 = [], slams = [] }) {
+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 : "",
@@ -491,6 +501,12 @@ 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 });
@@ -918,6 +934,55 @@ export async function shootSlams(browser, entry, { box, render, dir, fonts, pare
}
/**
+ * 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
@@ -1039,13 +1104,16 @@ export const POST_CLOCK_DRAW_V = 1;
* 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) {
+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;
@@ -1083,7 +1151,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 } : {}),
};
}
@@ -1181,7 +1249,9 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box
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)) : [], slams: slPlan });
+ // 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).
@@ -1215,7 +1285,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, slams: cards.slams ?? [], slamHitList: (cards.slams ?? []).flatMap((sl) => slamHits(sl.fx, sl.span).map((h) => ({ ...h, gain: h.gain * sl.fx.volume }))) });
+ 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) {
@@ -1234,6 +1304,7 @@ 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 ${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" : ""}` });