// PAUSES IN AN APPROVED READ, no TTS (operator, 5 Nov, a Mr. Obvious cut: "the // "20 10 4 0" words @21:21 should have some spacing since it's a countdown, // though not necessarily real-time spacing" -- the read's delivery is liked, so // it is never re-synthesized): the picked take cut just after each word named // and that much silence put in, everything after it moved on by the same. // // umtool posts reread

--pause "20=0.45,10=0.45,4=0.45" [--target linked:0] [--dry-run] [--json] [--in-take ] // // A word is named as word-zoom names one (word-zoom.mjs normWord: case and the // punctuation at its edges aside; a phrase is its words in a row, the pause after // its last): `[#]=`, `#n` its n-th time in the read (default // the first), seconds 0.05–3. It is found in the take's own word timings // (`narration.takes[i].words`, the script's words as read: `umtool posts narrate //

--words` makes them), so a take without them is refused, naming // that command. `--target ` (a piece role, post-thread.mjs partRoles: // post, parent:0, quoted, linked:0 …) counts only the words of the parts reading // that piece. // // THE CUT is just after the word's end: half way into the quiet before the next // word, at most PAUSE_CUT_INTO_GAP past the end (never into the next word) -- then, // on the take's own audio (audioSplice.mjs quietestCut), moved to the quietest // ~10 ms within the window the word allows (PAUSE_CUT_BACK before its end, up to the // next word's start or PAUSE_CUT_INTO_GAP past it; ±PAUSE_CUT_BACK when the timings // run together) when that is clearly quieter (~3 dB) than the timing's own. Each // side of the silence put in is faded (PAUSE_FADE, ~10 ms), so a pause in normally // paced speech does not click. What // moves: every word after it (by its index -- a word's timing is the take's, // shifted), every part starting after it (a part the cut falls inside grows by // the pause), the take's length. Everything timed ON the read -- word zooms, // captions, slams (their matched word's start), beeps (the slurs' words), the // read-follow blocks (the parts' starts) -- reads those, so it stays on its words. // An effect with a set second (`at`, the operator's nudge) is not moved: the plan // names how many there are. // // A PAUSE IS ABSOLUTE, like a tempo: on a take whose last step is a pause the // plan re-cuts from the take before it, the pauses it had kept and the ones named // now set (a word named again takes the new seconds; `=0` takes a pause away). // On any other take (a re-join, a re-time, a yell) it is cut from that take. // The new take: `source: {kind: "take", from}`, `steps: [{op: "pause", pauses: // [{word, w, at, seconds}]}]` (word: its index in the take's words; at: the cut, // in the source take's seconds), picked in ONE write (one undo point). // // Plain ESM: the CLI runs it under bare node. import path from "node:path"; import { pickedTake, takeIdOf } from "umtool-report-to-video/post-narration"; import { partRoles } from "umtool-report-to-video/post-thread"; import { normWord } from "umtool-report-to-video/word-zoom"; import { RereadError, lastLocalStep, writeDerivedTake } from "./postReread.mjs"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const r3 = (v) => Math.round(v * 1000) / 1000; /** A pause's length, seconds. */ export const PAUSE_LIMITS = Object.freeze({ seconds: [0.05, 3] }); /** The most pauses one take holds. */ export const PAUSE_MAX = 40; /** How far past a word's end the cut may go into the quiet before the next word, seconds. */ export const PAUSE_CUT_INTO_GAP = 0.1; /** How far before a word's timed end the quietest cut may be looked for (an alignment's end is not exact), seconds. */ export const PAUSE_CUT_BACK = 0.04; /** The fade at each side of the silence put in, seconds. */ export const PAUSE_FADE = 0.01; /** How far either side of an @time pause the quietest cut is looked for, seconds. */ export const PAUSE_PIN_WINDOW = 0.15; const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** A pause the plan cannot make (no word timings, the word not read, nothing to change): exit 1, not a usage error. */ export class PauseError extends Error { constructor(message) { super(message); this.name = "PauseError"; } } /** * A PAUSE SPEC as the CLI writes it, pure: `"20=0.45,10=0.45,4#2=0.6"` -- * `[{ match, occurrence, seconds }]`. `seconds` 0 takes a pause away (a re-cut); * else 0.05–3. Refused (RereadError, a usage error): no `=`, no word, a bad * occurrence or seconds. * * @param {string} spec * @returns {Array<{ match: string, occurrence: number, seconds: number }>} */ export function parsePauseSpec(spec) { const [lo, hi] = PAUSE_LIMITS.seconds; const items = String(spec ?? "").split(",").map((x) => x.trim()).filter(Boolean); if (!items.length) throw new RereadError(`--pause names the words and their pause: --pause "20=0.45,10=0.45" ([#]=)`); if (items.length > PAUSE_MAX) throw new RereadError(`--pause: at most ${PAUSE_MAX} pauses`); return items.map((item) => { const eq = item.lastIndexOf("="); if (eq < 0) throw new RereadError(`--pause ${item}: [#]=, e.g. 20=0.45 or 4#2=0.45`); const left = item.slice(0, eq).trim(); const right = item.slice(eq + 1).trim(); // "@71.2=0.45": a pause at a TIME of the take, cut at the quiet nearest it -- for a read whose word timings drift // (a script word said as several, "45" as "forty-five"), where the word's timed end is not where the gap is. if (left.startsWith("@")) { const t = /^\d*\.?\d+$/.test(left.slice(1).trim()) ? Number(left.slice(1).trim()) : NaN; if (!(fin(t) && t > 0)) throw new RereadError(`--pause ${item}: @=, e.g. @71.2=0.45`); const sec = /^\d*\.?\d+$/.test(right) ? Number(right) : NaN; if (!(sec === 0 || (fin(sec) && sec >= lo && sec <= hi))) throw new RereadError(`--pause ${item}: a pause is ${lo}–${hi} seconds (0 takes one away)`); return { at: t, seconds: sec }; } const m = /^(.*?)(?:\s*#\s*(\d+))?$/.exec(left); const match = (m?.[1] ?? "").trim(); if (!match || !match.split(/\s+/).some((w) => normWord(w))) throw new RereadError(`--pause ${item}: name a word (or a phrase) the take reads`); const occurrence = m?.[2] === undefined ? 1 : Number(m[2]); if (!(Number.isInteger(occurrence) && occurrence >= 1 && occurrence <= 999)) throw new RereadError(`--pause ${item}: # is its n-th time in the read, from 1`); const seconds = /^\d*\.?\d+$/.test(right) ? Number(right) : NaN; if (!(seconds === 0 || (fin(seconds) && seconds >= lo && seconds <= hi))) throw new RereadError(`--pause ${item}: a pause is ${lo}–${hi} seconds (0 takes one away)`); return { match, occurrence, seconds }; }); } /** The word indices of `take` a target counts (null: all), by the parts reading that piece. */ export function targetWords(entry, take, target) { if (!target) return null; if (!ROLE_RE.test(target)) throw new RereadError(`--target ${target}: a piece of the read (post, parent:0, quoted, linked:0, media:0)`); const parts = Array.isArray(take.parts) ? take.parts : []; if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds))) throw new PauseError(`${entry.id}'s picked take was read in one go (no timed parts): there are no pieces to tell apart -- drop --target`); const roles = partRoles(entry, take); const spans = parts.map((p, k) => ({ role: roles[k]?.role ?? p.role ?? null, from: p.start - 0.05, to: p.start + p.seconds + 0.05 })).filter((s) => s.role === target); if (!spans.length) throw new PauseError(`${entry.id}'s picked take reads no ${target} (its pieces: ${[...new Set(roles.map((r) => r?.role).filter(Boolean))].join(", ") || "none named"})`); return take.words.map((w, i) => (spans.some((s) => w.start >= s.from && w.start < s.to) ? i : -1)).filter((i) => i >= 0); } /** * Where a named word is in `take`'s words: the index of its LAST word (a phrase's), or a PauseError naming how often it is there. * @param {Record} entry * @param {Array<{ w: string }>} words * @param {number[] | null} among the indices counted (a target's), or null for all * @param {{ match: string, occurrence: number }} p * @param {string | null} target */ export function findPauseWord(entry, words, among, { match, occurrence }, target = null) { return findPhrase(entry, words, among, { match, occurrence }, target).last; } /** * Where a phrase is in `take`'s words (word-zoom's match: case and edge punctuation aside, its words in a row): * `{ first, last }`, the indices of its first and last word -- or a PauseError naming how often it is there. * `flag` names the option in the message. */ export function findPhrase(entry, words, among, { match, occurrence }, target = null, flag = "--pause") { const want = match.split(/\s+/).map(normWord).filter(Boolean); const idx = among ?? words.map((_, i) => i); const hits = []; for (let k = 0; k + want.length <= idx.length; k += 1) { if (want.every((w, j) => normWord(words[idx[k + j]].w) === w)) hits.push({ first: idx[k], last: idx[k + want.length - 1] }); } const where = `${entry.id}'s read${target ? ` (${target})` : ""}`; if (!hits.length) throw new PauseError(`${flag} "${match}": no such word in ${where} (it reads the script's words: ${JSON.stringify(words.slice(0, 8).map((w) => w.w).join(" "))}…)`); if (occurrence > hits.length) throw new PauseError(`${flag} "${match}#${occurrence}": "${match}" is in ${where} ${hits.length} time${hits.length === 1 ? "" : "s"}`); return hits[occurrence - 1]; } /** The cut after word `i` of `words`, take seconds: half way into the quiet before the next word, at most PAUSE_CUT_INTO_GAP past its end. */ export function cutAfter(words, i, seconds = Infinity) { const end = words[i].end; const next = words[i + 1]?.start; const room = fin(next) && next > end ? (next - end) / 2 : fin(next) ? 0 : PAUSE_CUT_INTO_GAP; return r3(Math.min(end + Math.min(room, PAUSE_CUT_INTO_GAP), fin(seconds) ? seconds : Infinity)); } /** * The window the cut after word `i` may move in to find the quiet, take seconds, pure: from PAUSE_CUT_BACK before * its timed end (never before its start) to the next word's start, at most PAUSE_CUT_INTO_GAP past the end; when * the timings run together (no quiet between them), PAUSE_CUT_BACK either side of the end. */ export function cutWindow(words, i, seconds = Infinity) { const w = words[i]; const next = words[i + 1]?.start; const lo = Math.max(w.start + (w.end - w.start) / 2, w.end - PAUSE_CUT_BACK); const hi = fin(next) && next > w.end ? Math.min(next, w.end + PAUSE_CUT_INTO_GAP) : w.end + (fin(next) ? PAUSE_CUT_BACK : PAUSE_CUT_INTO_GAP); const cap = fin(seconds) ? seconds : Infinity; return { lo: r3(Math.min(lo, cap)), hi: r3(Math.min(hi, cap)) }; } /** * THE PAUSE's PLAN, pure: the take it cuts (`take`: the picked one; on a take * whose last step is a pause, the one before it), the pauses after (`pauses`, * `[{ word, w, at, seconds }]` in order), the spans of the source cut between * them (`spans: [{ from, to|null, gap }]`, `gap` the silence before the span), * the words, parts and length moved on, and the steps. * * @param {Record} entry * @param {{ pauses: Array<{ match: string, occurrence: number, seconds: number }>, target?: string | null }} o */ export function pausePlan(entry, { pauses, target = null, cuts = null }) { const picked = pickedTake(entry); if (!picked) throw new PauseError(`${entry?.id ?? "?"} has no take to put a pause in`); const noWords = (t) => !Array.isArray(t?.words) || !t.words.length; if (noWords(picked)) throw new PauseError(`${entry.id}'s picked take (${takeIdOf(picked)}) has no word timings to find the words by: time its words first -- umtool posts narrate

${entry.id} --words (+ --in-take for a take's read; the bench's Get word timings) -- then pause`); const takes = entry.narration.takes; // A re-cut: the take before the pause step, when it is there with the same words. const up = lastLocalStep(takes, picked, ["pause"]); const recut = !!(up?.from && !noWords(up.from) && up.from.words.length === picked.words.length); const take = recut ? { ...up.from, index: takes.indexOf(up.from) } : picked; const words = take.words; /** @type {Map} word index -> seconds */ const had = new Map(recut ? (Array.isArray(up.step.pauses) ? up.step.pauses : []).filter((p) => Number.isInteger(p?.word) && fin(p?.seconds) && p.word < words.length).map((p) => [p.word, p.seconds]) : []); const among = targetWords(entry, take, target); const named = new Map(); /** @type {Map} word index -> a pinned cut (an @time pause, or one kept from the take it re-cuts) */ const pinned = new Map(recut ? (Array.isArray(up.step.pauses) ? up.step.pauses : []).filter((p) => p?.pinned && Number.isInteger(p?.word) && fin(p?.at)).map((p) => [p.word, p.at]) : []); for (const p of pauses) { if (fin(p.at)) { const pool = (among ?? words.map((_, k) => k)).filter((k) => fin(words[k]?.start) && words[k].start <= p.at); if (!pool.length) throw new RereadError(`--pause @${p.at}: no word of the read starts before it`); const i = pool[pool.length - 1]; if (named.has(i) && named.get(i) !== p.seconds) throw new RereadError(`--pause: "${words[i].w}" (word ${i + 1}) is named twice`); named.set(i, p.seconds); pinned.set(i, r3(p.at)); continue; } const i = findPauseWord(entry, words, among, p, target); if (named.has(i) && named.get(i) !== p.seconds) throw new RereadError(`--pause: "${words[i].w}" (word ${i + 1}) is named twice`); named.set(i, p.seconds); } const after = new Map(had); for (const [i, s] of named) { if (s === 0) after.delete(i); else after.set(i, s); } const same = after.size === had.size && [...after].every(([i, s]) => had.get(i) === s); if (same) throw new PauseError(`${entry.id}'s picked take has ${named.size === 1 ? "that pause" : "those pauses"} already: nothing to change`); if (!after.size) throw new PauseError(`${entry.id}: that takes every pause away -- pick the take it was cut from (${takeIdOf(take)}) again: umtool posts narrate

${entry.id} --pick ${take.index + 1}`); if (after.size > PAUSE_MAX) throw new RereadError(`--pause: at most ${PAUSE_MAX} pauses in one take`); const end = fin(take.seconds) ? take.seconds : Infinity; // `cuts` (pauseTake's, from the audio): a word's cut moved to the quiet near it. const list = [...after].sort((a, b) => a[0] - b[0]).map(([i, s]) => ({ word: i, w: words[i].w, at: fin(cuts?.get?.(i)) ? r3(cuts.get(i)) : pinned.has(i) ? pinned.get(i) : cutAfter(words, i, end), seconds: r3(s), ...(pinned.has(i) ? { pinned: true } : {}) })); // The source cut at each pause, the silence before the span after it. const spans = list.map((p, j) => ({ from: j === 0 ? 0 : list[j - 1].at, to: p.at, gap: j === 0 ? 0 : list[j - 1].seconds })); spans.push({ from: list[list.length - 1].at, to: null, gap: list[list.length - 1].seconds }); // What moves: a word after a pause by its index; a time at or after a cut by the pauses before it. const before = (i) => list.reduce((acc, p) => (p.word < i ? acc + p.seconds : acc), 0); const shiftAt = (v, strict = false) => list.reduce((acc, p) => ((strict ? p.at < v : p.at <= v) ? acc + p.seconds : acc), 0); const newWords = words.map((w, i) => { const d = before(i); return { w: w.w, start: r3(w.start + d), end: r3(w.end + d) }; }); const parts = Array.isArray(take.parts) ? take.parts.map((p) => { if (!fin(p?.start) || !fin(p?.seconds)) return p; const a = shiftAt(p.start); const b = shiftAt(p.start + p.seconds, true); const { file: _f, ...rest } = p; // A part a pause falls inside grows by it (its own file, if it had one, no longer is it). return { ...(b > a ? rest : p), start: r3(p.start + a), seconds: r3(p.seconds + Math.max(0, b - a)) }; }) : undefined; const total = list.reduce((acc, p) => acc + p.seconds, 0); const fixedAt = (Array.isArray(entry.fx) ? entry.fx : []).filter((fx) => fin(fx?.at)).length; return { take, picked, recut, target, pauses: list, named: [...named].map(([word, seconds]) => ({ word, w: words[word].w, seconds })), was: had.size ? [...had].map(([word, seconds]) => ({ word, w: words[word].w, seconds })) : [], spans, words: newWords, parts, script: typeof take.script === "string" ? take.script : entry.narration.script, seconds: r3((fin(take.seconds) ? take.seconds : 0) + total), added: r3(total), fixedAt, steps: [{ op: "pause", pauses: list, ranAt: new Date().toISOString() }], }; } /** * The ffmpeg arguments that cut `src` at the plan's pauses and put each one's silence in (the source sample-exact * between): each span faded out over its last PAUSE_FADE before a pause and in over its first after one (sample * counts, so the lengths stay exact). */ export function pauseArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { const chains = []; const labels = []; const fade = Math.max(1, Math.round(PAUSE_FADE * rate)); plan.spans.forEach((s, j) => { if (s.gap > 0) { chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=end_sample=${Math.round(s.gap * rate)}[g${j}]`); labels.push(`[g${j}]`); } const a = Math.round(s.from * rate); const trim = `atrim=start_sample=${a}${s.to === null ? "" : `:end_sample=${Math.round(s.to * rate)}`}`; const len = s.to === null ? null : Math.round(s.to * rate) - a; const fades = [ ...(s.gap > 0 ? [`afade=t=in:ss=0:ns=${fade}`] : []), ...(len !== null && len > fade ? [`afade=t=out:ss=${len - fade}:ns=${fade}`] : []), ]; chains.push(`[0:a]aformat=sample_rates=${rate}:channel_layouts=${layout},${trim},asetpts=PTS-STARTPTS${fades.map((f) => `,${f}`).join("")}[a${j}]`); labels.push(`[a${j}]`); }); chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`); return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", chains.join(";"), "-map", "[out]", "-c:a", "pcm_s16le", out]; } /** * PAUSE post item `e`'s picked take (`pauses`, parsePauseSpec's): the file * cut and the silences put in, measured, added and picked in one write. * `dryRun`: the plan only. Returns `{ plan, take?, result? }`. * * @param {{ id: string, dir: string }} project * @param {Record} e * @param {{ pauses: Array<{ match: string, occurrence: number, seconds: number }>, target?: string | null, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} o */ export async function pauseTake(project, e, { pauses, target = null, dryRun = false, measure = undefined }) { const plan0 = pausePlan(e, { pauses, target }); // The cuts moved to the quiet near them, on the source take's own audio (when it is on disk: else as timed). const cuts = await quietCuts(project, plan0); const plan = cuts.size ? pausePlan(e, { pauses, target, cuts }) : plan0; if (dryRun) return { plan }; const { take, result } = await writeDerivedTake(project, e, plan, { op: "pause", verb: "pause", measure, argsOf: (src, out, fmt) => pauseArgs(src, out, plan, fmt) }); return { plan, take, result }; } /** Each pause's cut moved to the quietest ~10 ms its word allows (audioSplice.mjs quietestCut): word index -> seconds. */ async function quietCuts(project, plan) { const { decodePcm, quietestCut } = await import("./audioSplice.mjs"); const file = path.join(project.dir, ...String(plan.take.file ?? "").split("/")); const rate = 16000; let mono; try { mono = await decodePcm(file, { rate, channels: 1 }); } catch { return new Map(); } const words = plan.take.words; const end = fin(plan.take.seconds) ? plan.take.seconds : Infinity; const out = new Map(); let last = -Infinity; plan.pauses.forEach((p, j) => { const { lo, hi } = p.pinned ? { lo: Math.max(0, p.at - PAUSE_PIN_WINDOW), hi: Math.min(end, p.at + PAUSE_PIN_WINDOW) } : cutWindow(words, p.word, end); const q = quietestCut(mono, rate, { lo, hi, nominal: p.at }); // The cuts stay in order (two pauses on words run together never cross). const next = plan.pauses[j + 1]?.at ?? Infinity; const at = q.moved && q.at > last && q.at < next ? q.at : p.at; if (at !== p.at) out.set(p.word, at); last = at; }); return out; } /** One pause as a line says it: `"20" (word 233, after 61.42 s) +0.45 s`. */ export const pauseLine = (p) => `"${p.w}" (word ${p.word + 1}, after ${p.at.toFixed(2)} s) +${p.seconds} s`;