Archilyzer · Source

archilyzer

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

commit 19d582161cdc5b974df1c672b31fefa8f0743d51
parent 7d48675c71ee4ac975c10b142ebcea485093d39b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 17:36:03 -0500

umtool: a read's parts RE-TIMED and its caps YELLED, no TTS -- posts reread --tempo-for "4-16=1.35,21-25=1.3" time-stretches the parts named (1-1.6, pitch kept: atempo, or --stretch rubberband) and leaves the rest, the words scaled with their part; posts reread --yell-caps / posts yell raise the words he wrote in ALL CAPS (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"; "I feel like allcaps needs to be yelled more")

TEMPO (postReread.mjs tempoPlan, joinParts): each part named is cut from the picked take, stretched, padded and
trimmed to its length (sample-exact: the parts after it land where their word timings say), joined with the read's
pauses; the parts re-timed with each stretched one's `tempo` stored, the words scaled from their part's start. A
derived take, steps [{op: "tempo", tempo: {"4-16": 1.35}, params: {stretch}}], picked in one write. A tempo is
ABSOLUTE: on a re-timed take it re-cuts from the take before (each part stretched once), the parts it does not name
keeping theirs. Chains on a re-joined take. set-item <item> narration.tempo="…" runs it; the route's reread op takes
`tempo`. The re-join's plan is joinParts too (its output unchanged).

YELL (postYell.mjs): the words whose source word -- his post, or the piece a part reads, looked for only in the
words that read it (partRoles), a neighbour aligned too -- is ALL CAPS of 2+ letters, found in the take's word
timings; acronyms (YELL_ACRONYMS; a caps word with no vowel reads as letters) and masked slurs left flat. Each run of
them raised: a presence lift, body, compression, the lift MEASURED over the spans (+5.5 dB, made up once), a gentle
tanh saturation, limited under 0 dBFS, crossfaded over 50 ms ramps (the envelope in 64-sample frames); its length and
timings the source's; its loudness within 1 LU of the source (over it, the lift lowered). steps [{op: "yell", spans,
params: {gain, style}}], picked; re-yells from the take before a yelled one, refuses a yell further up the chain;
chains with the tempo either way. No word timings: refused, naming posts narrate --words; posts yell --dry-run lists
every item's caps, the flat ones and why, and the items that need timings.

The validator: tempo and yell are local ops; a step's tempo runs and spans, a part's tempo (1-1.6).

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

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 16+++++++++++++---
Mumtool/lib/report/postReread.mjs | 299+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/lib/report/postReread.test.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postYell.mjs | 393+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postYell.test.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postsCli.mjs | 35++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/post-narration.mjs | 20++++++++++++++++----
7 files changed, 892 insertions(+), 68 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/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. @@ -155,7 +159,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 +442,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") { @@ -931,6 +951,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/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)`); }); }