commit 031917d18cad756a041ba195230a4a2995762fc4
parent 9ae432d440e35a18fdef9b70fb4172fd481c8e93
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 5 Nov 2026 12:23:02 -0500
Merge lane/read-revoice: a phrase of an approved read re-voiced by TTS and spliced in (posts reread --revoice "<phrase>" --say "<words>" [--target] [--splice] [--in-take]): only the phrase synthesized in the part's voice, cut at the quietest point, loudness-matched, equal-power crossfades, everything after moved with it; --pause cuts at the quietest 10 ms with 10 ms fades; the bench's Re-join panel has the re-voice row (operator, 5 Nov: "the spaced 20 10 4 0 is choppy and it's very noticeable")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
14 files changed, 1395 insertions(+), 37 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **umtool: one phrase of an approved read can be re-voiced, and pauses cut into a read no longer click.** A countdown the read gabbled ("20 10 4 0", a quarter second a number) was spaced with `--pause`, and it sounded choppy: the words ran together, so a cut at a word's timed end landed mid-sound. `umtool posts reread <p> <item> --revoice "20 10 4 0" --say "20... 10... 4... 0..."` now synthesizes only the words given by `--say`, through the editor's TTS in the voice that part was read in (`--voice` overrides; the pronunciation lexicon applied; kept in the parts cache, so asking again is free), and splices them in place of the phrase: each cut at the quietest 10 ms near the phrase's edge (looked for further out when the word timings are off, never inside the phrase), the new piece loudness-matched to the speech around it and crossfaded in at equal power (`--xfade`, default 0.03 s). The rest of the read is not touched. Everything after moves by the length difference -- its words, its parts, its length -- so zooms, captions, slams, beeps and the read-follow stay on their words; the new words' timings are estimated from the piece's sound until `posts narrate … --words` times them. It is a new take, picked in one undoable write; `--dry-run` shows the span, both cuts and their levels, the voice and (when cached) the length change without asking for TTS, a cut that still lands in speech is warned of and can be set with `--splice <from>-<to>`, and `--in-take <t>` puts it in a take's read. `--pause` now moves each cut to the quietest 10 ms its word allows and fades 10 ms either side of the silence. The post bench's Options → Re-join the read has **re-voice a phrase** (Preview, Apply), on the take-only bench too. umtool/docs/cli.md, knobs.md.
- **umtool: the post bench's attachment lanes are back on the take-only bench, and a GIF has one.** On `?inTake=<t>` (the only bench of an item a take carries and the cut does not) the bench showed a note where the lanes were, so a video's in and out could only be typed; and the lane covered the first video only. Now every video and GIF of the item has a lane under the player: its whole length as a waveform (a flat line for a GIF or a silent video, which still drags), the in and out as its two handles (never closer than 0.5 s, never past the file), the part the item plays dashed and the playhead, with the bench's clock following a moving edge so the player shows its frame. A handle moves the same draft the **in / out** fields do (they follow at once, as the plan's seconds do) and **Save** writes it -- into the take's patch on a take-only bench, the project's manifest untouched; focused, `[ ]` and `, .` nudge the in and out (Shift coarser) and `← →` the edge last moved. The read's lane (its lead dragged) and **Re-pick best** write the take there too (`/api/report/post-narration` takes `inTake` for set and fit); recording, re-takes and the mix stay on the cut's bench. umtool/docs/knobs.md.
- **A reply that is only a picture is drawn as its message, and a long post on a card alone keeps large text.** A post whose words are only @mentions and links with an attachment (an "@ObviousRises" and a GIF, a reply that is a screenshot of another post) is now picture-only in a report video: its picture is drawn inside its own card where its words would be, at the card's width, with the mention drawn small as a reply-to line, never in the side slot. The GIF that showed beside Mr. Obvious's reply while he was being read now has its own beat first: shown alone in its card for its own length (an image for 2 s, between 1.5 and 4 s), then the read. The read's start moves and the take is not re-made, so word zooms, captions, slams and beeps stay on their words. The render plays the GIF over its place in the card, Play plays it in the card, and the post bench has a **picture-only** block with an auto, on or off setting for the item and for each post it answers or quotes (`umtool posts set-item <p> <item> pictureOnly=on|off|auto`, `parent.<i>.pictureOnly=`, `quoted.pictureOnly=`). `render.posts.pictureReply` sets the beat's length or turns the rule off. A long post on a card alone is now drawn at a reading size and scrolled with the read, where it used to shrink to read-follow's minimum to fit (operator, 5 Nov: "bigger text for the novel"). Posts that are not picture-only, and posts whose words fit their card, render exactly as before.
- **umtool: a pause can be put in after words of an approved read, without reading it again.** A countdown read as "20 10 4 0" in one breath could only be spaced by synthesizing a new read, losing a delivery that was liked. `umtool posts reread <p> <item> --pause "20=0.45,10=0.45,4=0.45"` now cuts the picked take just after each word named (found in its word timings as a word zoom finds one: case and punctuation aside, `#2` its second time, `--target linked:0` one piece's words) and puts that much silence in (0.05–3 s), moving everything after it on -- its words, its parts and its length, so zooms, captions, slams, beeps and the read-follow stay on their words. It is a new take, picked in one undoable write; on a paused take it re-cuts from the take before (`=0` takes a pause away), `--dry-run` shows each cut and the new length, `--in-take <t>` puts it in a take's read, and a take with no word timings is refused naming `umtool posts narrate <p> <item> --words`. The post bench's Options → Re-join the read has **pause after** with Preview and Apply, on the take-only bench too. umtool/docs/cli.md, knobs.md.
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -47,6 +47,8 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?.
// 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
// POST {project, op: "reread", id, pause: "20=0.45,10=0.45", target?, dryRun?} SILENCE PUT IN after the words
+// POST {project, op: "reread", id, revoice: "20 10 4 0", say: "20... 10... 4... 0...", target?, voice?, xfade?, splice?, dryRun?}
+// ONE PHRASE RE-VOICED (postRevoice.mjs: the editor's TTS for --say only, spliced in)
// named (postPause.mjs); dryRun: the plan only, nothing written
// (postReread.mjs: no TTS; a new take, picked, one undo point)
// a reread, set or fit + inTake: <take> the same, scoped to the take's patch (takeScope.mjs, the CLI's
@@ -265,6 +267,22 @@ async function postHere(request: Request) {
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 });
}
+ // `revoice` + `say` (postRevoice.mjs): one phrase synthesized again (the editor's TTS, that phrase only) and spliced in; `dryRun`: no TTS.
+ if (typeof body.revoice === "string" && body.revoice.trim()) {
+ const { parseRevoice, revoiceTake } = await import("@/lib/report/postRevoice.mjs");
+ const target = typeof body.target === "string" && body.target.trim() ? body.target.trim() : null;
+ const ask = parseRevoice({ phrase: body.revoice, say: typeof body.say === "string" ? body.say : "", voice: typeof body.voice === "string" ? body.voice : null, xfade: typeof body.xfade === "number" || typeof body.xfade === "string" ? body.xfade : null, cut: typeof body.splice === "string" ? body.splice : null });
+ const rv = await revoiceTake(r.project, e, { ...ask, target, dryRun: body.dryRun === true });
+ const plan = rv.plan as { first: number; last: number; phrase: string; say: string; said: string; voice: string; engine: string; recut: boolean; xfade: number; fixedAt: number; picked: { seconds?: number }; take: Record<string, unknown> };
+ return Response.json(
+ {
+ ok: true, dryRun: body.dryRun === true, span: { first: plan.first, last: plan.last, phrase: plan.phrase }, cuts: rv.cuts, say: plan.say, said: plan.said, voice: plan.voice, engine: plan.engine,
+ cached: rv.cached, xfade: plan.xfade, piece: rv.piece ?? null, change: rv.finish?.delta ?? null, seconds: rv.take?.seconds ?? rv.finish?.seconds ?? null, was: plan.picked.seconds ?? null,
+ recut: plan.recut, from: takeIdOf(plan.take), fixedAt: plan.fixedAt, take: rv.take ?? null, entry: rv.result?.entry ?? null, token: rv.result?.token ?? null,
+ },
+ { headers: noStore },
+ );
+ }
// `pause`: "20=0.45,10=0.45" (postPause.mjs parsePauseSpec) -- silence put in after the words; `dryRun`: the plan only.
if (typeof body.pause === "string" && body.pause.trim()) {
const target = typeof body.target === "string" && body.target.trim() ? body.target.trim() : null;
@@ -280,7 +298,7 @@ async function postHere(request: Request) {
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" || (err as Error)?.name === "YellError" || (err as Error)?.name === "PauseError") return Response.json({ error: (err as Error).message }, { status: 400 });
+ if (["RereadError", "YellError", "PauseError", "RevoiceError"].includes((err as Error)?.name)) return Response.json({ error: (err as Error).message }, { status: 400 });
throw err;
}
}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -418,12 +418,13 @@ export default function PostNarrationPanel({
return (
<div className="space-y-2 text-[12.5px]" data-post-narration-in-take={inTake}>
<p className="m-0 text-[12px] text-muted" data-post-bench-in-take-note="">
- Recording, re-takes and the mix are made on the cut's bench (edits go to: the cut); take {inTake} keeps the reads it has. The lanes and the pauses here edit the take.
+ Recording, re-takes and the mix are made on the cut's bench (edits go to: the cut); take {inTake} keeps the reads it has. The lanes, the pauses and a re-voiced phrase here edit the take.
</p>
{lanes}
{picked && (
- <Options id="post-reread" label="Re-join the read (no TTS)" hint="pauses after words">
+ <Options id="post-reread" label="Re-join the read (no TTS)" hint="pauses after words · re-voice a phrase">
<PauseAfter post={post} hasWords={!!picked.words?.length} setStatus={setStatus} />
+ {picked.engine !== "recorded" && <RevoicePhrase post={post} hasWords={!!picked.words?.length} setStatus={setStatus} />}
</Options>
)}
{status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>}
@@ -722,7 +723,7 @@ export default function PostNarrationPanel({
{/* RE-JOIN THE PICKED READ, no TTS (postReread.mjs; terminal-only before: posts reread --tempo / --drop-parts /
--drop-urls, posts yell): its parts re-timed, some left out, the URLs dropped, the caps raised -- a new take, picked. */}
{picked && picked.engine !== "recorded" && (
- <Options id="post-reread" label="Re-join the read (no TTS)" hint="re-time parts · drop parts or URLs · raise the caps">
+ <Options id="post-reread" label="Re-join the read (no TTS)" hint="re-time parts · drop parts or URLs · raise the caps · re-voice a phrase">
<span className="flex flex-wrap items-center gap-1.5">
<label className="inline-flex items-center gap-1">
re-time
@@ -747,6 +748,7 @@ export default function PostNarrationPanel({
</button>
</span>
<PauseAfter post={post} hasWords={!!picked.words?.length} setStatus={setStatus} />
+ <RevoicePhrase post={post} hasWords={!!picked.words?.length} setStatus={setStatus} />
</Options>
)}
{status && <p className="m-0 text-text-2" data-post-narration-status="">{status}</p>}
@@ -759,6 +761,78 @@ export default function PostNarrationPanel({
);
}
+type RevoicePlan = {
+ span?: { first: number; last: number; phrase: string };
+ cuts?: { from: number; to: number };
+ said?: string;
+ voice?: string;
+ engine?: string;
+ cached?: boolean;
+ piece?: { seconds: number; gain: number } | null;
+ change?: number | null;
+ seconds?: number | null;
+ was?: number | null;
+ recut?: boolean;
+ from?: string;
+ fixedAt?: number;
+};
+
+/**
+ * RE-VOICE A PHRASE of the picked read (lib/report/postRevoice.mjs; `umtool posts reread … --revoice … --say …`): the
+ * phrase as the read's words show it (`20 10 4 0`, `#2` its second time), what to say instead, Preview (the dry run:
+ * the span, the cuts, the voice; no TTS) and Apply (the editor synthesizes THAT PHRASE ONLY, spliced in at quiet cuts
+ * with crossfades -- a new take, picked). Needs the take's word timings.
+ */
+function RevoicePhrase({ post: send, hasWords, setStatus }: { post: (body: Record<string, unknown>) => Promise<unknown>; hasWords: boolean; setStatus: (s: string | null) => void }) {
+ const post = (b: Record<string, unknown>) => send(b) as Promise<RevoicePlan | null>;
+ const [phrase, setPhrase] = useState("");
+ const [say, setSay] = useState("");
+ const [target, setTarget] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [plan, setPlan] = useState<RevoicePlan | null>(null);
+ const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
+ const ready = !!phrase.trim() && !!say.trim() && !busy;
+ const body = (dryRun: boolean) => ({ op: "reread", revoice: phrase.trim(), say: say.trim(), ...(target.trim() ? { target: target.trim() } : {}), ...(dryRun ? { dryRun: true } : {}) });
+ const said = (j: RevoicePlan) =>
+ `"${j.span?.phrase ?? ""}" (words ${(j.span?.first ?? 0) + 1}-${(j.span?.last ?? 0) + 1}, cut ${Number(j.cuts?.from).toFixed(2)}-${Number(j.cuts?.to).toFixed(2)} s) as "${j.said ?? ""}" in ${j.voice ?? "?"}` +
+ (j.piece ? ` -- ${Number(j.seconds).toFixed(2)} s (was ${Number(j.was ?? 0).toFixed(2)} s, ${Number(j.change) >= 0 ? "+" : ""}${Number(j.change).toFixed(2)} s)` : " -- not synthesized yet") +
+ (j.recut ? `, cut again from ${j.from}` : "") + (j.fixedAt ? ` · ${j.fixedAt} effect(s) with a set second do not move` : "");
+ const run = (dryRun: boolean) => {
+ setBusy(true);
+ if (!dryRun) setStatus("re-voicing: the editor synthesizes the phrase…");
+ void post(body(dryRun))
+ .then((j) => {
+ setPlan(dryRun ? j : null);
+ if (j) setStatus(dryRun ? `would re-voice ${said(j)}` : `re-voiced ${said(j)}: a new take, picked`);
+ })
+ .finally(() => setBusy(false));
+ };
+ return (
+ <span className="mt-1.5 flex flex-wrap items-center gap-1.5" data-post-reread-revoice-row="">
+ <label className="inline-flex items-center gap-1" title="the words as the read's word timings show them; #2 its second time">
+ re-voice a phrase (TTS for the phrase only)
+ <input value={phrase} onChange={(e) => { setPhrase(e.target.value); setPlan(null); }} placeholder="20 10 4 0" className="w-32 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-revoice="" />
+ </label>
+ <label className="inline-flex items-center gap-1">
+ say
+ <input value={say} onChange={(e) => { setSay(e.target.value); setPlan(null); }} placeholder="20... 10... 4... 0..." className="w-40 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-revoice-say="" />
+ </label>
+ <label className="inline-flex items-center gap-1" title="count only the words of one piece of the read (post, parent:0, quoted, linked:0)">
+ in
+ <input value={target} onChange={(e) => { setTarget(e.target.value); setPlan(null); }} placeholder="the whole read" className="w-24 rounded border border-seam bg-ground px-1 py-0.5 font-mono text-[11px]" data-post-reread-revoice-target="" />
+ </label>
+ <button type="button" className={btn} disabled={!ready} onClick={() => run(true)} data-post-reread-revoice-preview="">
+ Preview
+ </button>
+ <button type="button" className={btn} disabled={!ready} onClick={() => run(false)} data-post-reread-revoice-go="">
+ Apply
+ </button>
+ {!hasWords && <span className="text-muted" data-post-reread-revoice-needs-words="">needs the take's word timings (Get word timings, or umtool posts narrate … --words)</span>}
+ {plan?.span && <span className="sr-only" data-post-reread-revoice-plan={plan.span.last - plan.span.first + 1} />}
+ </span>
+ );
+}
+
type PausePlan = { pauses?: Array<{ word: number; w: string; at: number; seconds: number }>; added?: number; seconds?: number; was?: number | null; recut?: boolean; from?: string; fixedAt?: number; dryRun?: boolean };
/**
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -92,7 +92,8 @@ Inbox cannot disagree about what is wrong with one.
| `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) |
| `posts reread <project> <item> --tempo-for "4-16=1.35,21-25=1.3" \| --tempo <x> --parts <runs> [--stretch atempo\|rubberband] [--dry-run] [--json]` | a narrated read's **parts re-timed**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled)): the parts named time-stretched (1–1.6, pitch kept), the rest untouched, joined with the read's pauses (each stretched part padded and trimmed to its length, sample-exact), its words scaled with their part, a derived take (`steps: [{op: "tempo", tempo, params: {stretch}}]`) picked in ONE write. A tempo is absolute: on a re-timed take it re-cuts from the take before. `posts set-item <p> <item> narration.tempo="4-16=1.35"` runs the same. A part outside the take, a tempo outside 1–1.6, nothing changed: **exit 1** |
| `posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run] [--json]` · `posts yell <project> --all \| <item …> [--yell-gain …] [--yell-style …] [--dry-run] [--json]` | a narrated read's **caps yelled**, no TTS ([report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled), `lib/report/postYell.mjs`): his ALL-CAPS words found in the take's word timings and raised (the lift measured, its loudness within 1 LU), acronyms and masked slurs left flat, a derived take (`steps: [{op: "yell", spans, params}]`) picked (one undo point per item). No word timings: **exit 1** naming `posts narrate --words`; `posts yell --dry-run` lists every item's caps, the flat ones and why, and which need word timings |
-| `posts reread <project> <item> --pause "<word>[#<n>]=<seconds>[,…]" [--target post\|parent:0\|quoted\|linked:0] [--dry-run] [--json]` | **pauses put in after words** of a narrated read, no TTS (`lib/report/postPause.mjs`; operator, 5 Nov: a countdown "20 10 4 0" read without a breath): the picked take cut just after each word named (half way into the quiet before the next word, at most 0.1 s past its end) and that much silence (0.05–3 s) put in, everything after moved on -- its words (by index), its parts (one a pause falls in grows), its length -- so word zooms, captions, slams, beeps and the read-follow stay on their words; an effect with a set `at` does not move (the plan counts them). A word is matched as a word zoom's is (case and edge punctuation aside; a phrase pauses after its last word; `#n` its n-th time in the read; `--target` counts only the words of the parts reading that piece). A derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`) picked in ONE write. **Absolute**, like a tempo: on a take whose last step is a pause it re-cuts from the take before (the pauses it had kept, a word named again takes the new seconds, `=0` takes one away). `--in-take <t>` puts it in a take's read. No word timings (**exit 1**, naming `posts narrate <p> <item> --words`), a word not read, an occurrence not there, nothing to change: **exit 1**; a malformed spec, seconds outside 0.05–3, `--pause` with another reread form: **exit 2** |
+| `posts reread <project> <item> --pause "<word>[#<n>]=<seconds>[,…]" [--target post\|parent:0\|quoted\|linked:0] [--dry-run] [--json]` | **pauses put in after words** of a narrated read, no TTS (`lib/report/postPause.mjs`; operator, 5 Nov: a countdown "20 10 4 0" read without a breath): the picked take cut just after each word named (half way into the quiet before the next word, at most 0.1 s past its end) and that much silence (0.05–3 s) put in -- each cut moved to the quietest 10 ms its word allows (40 ms before its timed end up to the next word, ±40 ms when they run together) when that is clearly quieter (~3 dB) than the timing's own, and each side of the silence faded over 10 ms, so a pause in normally paced speech does not click -- everything after moved on -- its words (by index), its parts (one a pause falls in grows), its length -- so word zooms, captions, slams, beeps and the read-follow stay on their words; an effect with a set `at` does not move (the plan counts them). A word is matched as a word zoom's is (case and edge punctuation aside; a phrase pauses after its last word; `#n` its n-th time in the read; `--target` counts only the words of the parts reading that piece). A derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`) picked in ONE write. **Absolute**, like a tempo: on a take whose last step is a pause it re-cuts from the take before (the pauses it had kept, a word named again takes the new seconds, `=0` takes one away). `--in-take <t>` puts it in a take's read. No word timings (**exit 1**, naming `posts narrate <p> <item> --words`), a word not read, an occurrence not there, nothing to change: **exit 1**; a malformed spec, seconds outside 0.05–3, `--pause` with another reread form: **exit 2** |
+| `posts reread <project> <item> --revoice "<phrase>[#<n>]" --say "<what to say instead>" [--target <piece>] [--voice <v>\|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json]` | **one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it "choppy"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: "revoice", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2** |
| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it |
| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) |
| `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -960,7 +960,8 @@ gathers them).
| a read RE-JOINED without a piece (no TTS) — the picked take's kept parts cut from its own file and joined with the read's pauses: a derived take (`steps: [{op: "rejoin", drop}]`), picked | post bench, **thread read**: **Read without it** on a context piece the take reads; the post bench's Options → **Re-join the read (no TTS)**: **leave out parts**, **drop the URLs**, **Re-join** | `umtool posts reread <p> <item> --without parent:0` (`parent:1`, `quoted`) · `--drop-parts 3,4` · `--drop-urls` · `--dry-run`; `umtool posts set-item <p> <item> thread.parent.0=context` re-joins first when the take reads it (the knob alone when it does not; `--no-reread`: refused) | `POST /api/report/post-narration {project, op: "reread", id, without: ["parent:0"], dropParts?, dropUrls?}` |
| a read's PARTS RE-TIMED (no TTS) — the parts named read at a tempo of 1–1.6 (pitch kept: ffmpeg `atempo`, or `rubberband`), the rest untouched, joined with the read's pauses; the words scaled with their part (read-follow, zooms, captions, slams, beeps keep their place); a derived take (`steps: [{op: "tempo", tempo: {"4-16": 1.35}, params: {stretch}}]`, each part's `tempo` stored), picked. A tempo is ABSOLUTE: on a re-timed take it re-cuts from the take before (each part stretched once) | the post bench's Options → **Re-join the read (no TTS)**: **re-time** `4-16=1.35`, **Re-time** | `umtool posts reread <p> <item> --tempo-for "4-16=1.35,21-25=1.3"` · `--tempo 1.3 --parts 4-16,21-25` · `--stretch rubberband` · `--dry-run`; `umtool posts set-item <p> <item> narration.tempo="4-16=1.35"` (the same) | `POST /api/report/post-narration {project, op: "reread", id, tempo: "4-16=1.35", stretch?}` |
| a read's CAPS YELLED (no TTS) — the words he wrote in ALL CAPS (his post, or the piece a part reads) found in the take's word timings and raised: +5.5 dB measured over the spans, a presence lift, compressed, gently saturated, limited, 50 ms ramps; acronyms (`YELL_ACRONYMS`, any caps word with no vowel) and masked slurs left flat; timings kept; loudness within 1 LU of its source; a derived take (`steps: [{op: "yell", spans, params: {gain, style}}]`), picked. Needs the take's word timings (`posts narrate --words`) | the post bench's Options → **Re-join the read (no TTS)**: **Raise the CAPS** | `umtool posts reread <p> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\|shout\|loud] [--dry-run]` · the cut's: `umtool posts yell <p> --all \| <item …> [--dry-run]` (the dry run lists each item's caps, the ones left flat and why, and the items with no word timings) | `POST /api/report/post-narration {project, op: "reread", id, yell: true, yellGain?, yellStyle?}` |
-| PAUSES in a read (no TTS) — the picked take cut just after each word named (half way into the quiet before the next, at most 0.1 s past its end) and 0.05–3 s of silence put in; everything after moved on: its words, its parts (one a pause falls in grows), its length -- word zooms, captions, slams, beeps and the read-follow keep their words (an effect with a set `at` does not move); a derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`), picked. Words matched as a word zoom's (case and edge punctuation aside, `#n` its n-th time, a phrase after its last word). ABSOLUTE: on a paused take it re-cuts from the take before (`=0` takes one away). Needs the take's word timings (`posts narrate --words`) | the post bench's Options → **Re-join the read (no TTS)**: **pause after** `20=0.45,10=0.45` (and **in** a piece, optional), **Preview** (the dry run: each cut, the new length), **Apply**; on the take-only bench (`?inTake=<t>`) too | `umtool posts reread <p> <item> --pause "20=0.45,10=0.45,4#2=0.6" [--target linked:0] [--dry-run] [--json] [--in-take <t>]` | `POST /api/report/post-narration {project, op: "reread", id, pause: "20=0.45", target?, dryRun?, inTake?}` |
+| PAUSES in a read (no TTS) — the picked take cut just after each word named (half way into the quiet before the next, at most 0.1 s past its end; then moved to the quietest 10 ms the word allows when that is clearly quieter) and 0.05–3 s of silence put in, faded 10 ms either side; everything after moved on: its words, its parts (one a pause falls in grows), its length -- word zooms, captions, slams, beeps and the read-follow keep their words (an effect with a set `at` does not move); a derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`), picked. Words matched as a word zoom's (case and edge punctuation aside, `#n` its n-th time, a phrase after its last word). ABSOLUTE: on a paused take it re-cuts from the take before (`=0` takes one away). Needs the take's word timings (`posts narrate --words`) | the post bench's Options → **Re-join the read (no TTS)**: **pause after** `20=0.45,10=0.45` (and **in** a piece, optional), **Preview** (the dry run: each cut, the new length), **Apply**; on the take-only bench (`?inTake=<t>`) too | `umtool posts reread <p> <item> --pause "20=0.45,10=0.45,4#2=0.6" [--target linked:0] [--dry-run] [--json] [--in-take <t>]` | `POST /api/report/post-narration {project, op: "reread", id, pause: "20=0.45", target?, dryRun?, inTake?}` |
+| ONE PHRASE RE-VOICED (TTS for that phrase only) — the phrase found in the picked take's word timings (as a pause finds a word; `#n`; `--target`), cut out at the quietest 10 ms within ±40 ms of each boundary (±0.15 s when that is still speech, never inside the phrase; a cut still in speech is warned of, `--splice <from>-<to>` sets them), `--say` synthesized by the editor in the voice the part was read in (`--voice` overrides; the lexicon applied; cached in `narration/parts-cache/`), loudness-matched to the 2 s about it (±6 dB), spliced in with equal-power crossfades (`--xfade`, default 0.03 s); its words (`estimated`), parts and length moved by the change, so everything timed on the words stays on them; a derived take (`steps: [{op: "revoice", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`), picked. Re-voicing the words a re-voice put in re-cuts from the take before. Needs the take's word timings | the post bench's Options → **Re-join the read (no TTS)**: **re-voice a phrase (TTS for the phrase only)** `20 10 4 0`, **say** `20... 10... 4... 0...` (and **in** a piece, optional), **Preview** (the dry run: span, cuts, voice; no TTS), **Apply**; on the take-only bench (`?inTake=<t>`) too | `umtool posts reread <p> <item> --revoice "20 10 4 0" --say "20... 10... 4... 0..." [--target linked:0] [--voice <v>\|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json] [--in-take <t>]` | `POST /api/report/post-narration {project, op: "reread", id, revoice: "20 10 4 0", say: "…", target?, voice?, xfade?, splice?, dryRun?, inTake?}` |
| the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | the Cut tab's Options → **Reads and voices** → **Queue: gather conversations** (`--write`, a queue step) | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) |
| a post item's `conversation` (the archive row's threadId) and `quoted.via: "link"` (a status link resolved to an archived post) | — | `umtool posts context <p> [--dry-run]` | — (`setPostItemsContext`) |
@@ -1220,6 +1221,7 @@ has the recipe.
| the pick, a new read, a thread read, the mix | `umtool posts narrate <p> <item> --pick <n> \| --take [--thread …] \| --script "…" \| k=v --in-take <t>` | the take's entry; a new read's file in `<p>/narration/` under a number no file or entry has |
| a re-join (no TTS) | `umtool posts reread <p> <item> --without parent:0 … --in-take <t>` | the take's entry, the new take picked there (the project keeps its pick) |
| pauses after words of the read (no TTS) | `umtool posts reread <p> <item> --pause "20=0.45,10=0.45" --in-take <t>` · the post bench's **pause after** on `?inTake=<t>` | the take's entry, the new take picked there (the project keeps its pick) |
+| one phrase of the read re-voiced (TTS for that phrase only) | `umtool posts reread <p> <item> --revoice "20 10 4 0" --say "20... 10... 4... 0..." --in-take <t>` · the post bench's **re-voice a phrase** on `?inTake=<t>` | the take's entry, the new take picked there (the project keeps its pick); the piece in the project's `narration/parts-cache/` |
| an effect | `umtool posts fx <p> <item> add caption … --in-take <t>` | the take's entry's `fx` |
| look, check, take back | `umtool timeline <p> --take <t>` · `umtool lint <p> --take <t>` (exit 0 clean) · `umtool timeline <p> --take <t> undo` | — / — / the take's newest edit, byte for byte |
diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts
@@ -1,5 +1,6 @@
import { test, expect, type Page } from "@playwright/test";
import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -46,8 +47,10 @@ test.beforeEach(() => {
copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
rmSync(path.join(DIR, "notes.json"), { force: true });
- for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav", "take-2.convert-zac.wav", "take-3.convert-zac.wav", "take-2.pause-orpheus.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true });
+ for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav", "take-2.convert-zac.wav", "take-3.convert-zac.wav", "take-2.pause-orpheus.wav", "take-2.revoice-orpheus.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true });
rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true });
+ // The parts cache a re-voice's phrase lands in (the fixture has none of its own).
+ rmSync(path.join(DIR, "narration", "parts-cache"), { recursive: true, force: true });
rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true });
rmSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"), { recursive: true, force: true });
});
@@ -355,6 +358,82 @@ test("PAUSE AFTER (operator, 5 Nov: a countdown read in one breath): Get word ti
expect(n.takes[1].words?.[2].start).toBe(n.takes[0].words?.[2].start);
});
+test("RE-VOICE A PHRASE (operator, 5 Nov: the countdown gabbled, pauses cut into it choppy): Get word timings, then Options -> Re-join the read: re-voice speaks as \"talks loudly\", Preview asks no TTS, Apply asks the editor for the phrase only and makes a new take, picked, its later words moved by the length change", async ({ page }) => {
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-11"));
+ const zoom = page.locator('[data-post-zoom-panel="p-11"]');
+ await zoom.locator("[data-post-zoom-get-words]").click();
+ await expect(zoom.locator("[data-post-zoom-words-state]")).toHaveText(/the take is timed \(5 words\)/, { timeout: 20_000 });
+ await page.reload();
+ const opts = page.locator('[data-panel-id="post-reread"]');
+ await opts.locator("summary").click();
+ const row = opts.locator("[data-post-reread-revoice-row]");
+ await expect(row).toContainText("TTS for the phrase only");
+ await expect(row.locator("[data-post-reread-revoice-needs-words]")).toHaveCount(0);
+ await row.locator("[data-post-reread-revoice]").fill("speaks");
+ await row.locator("[data-post-reread-revoice-say]").fill("talks loudly");
+ const ttsAsked = () => (JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; text?: string; voice?: string; engine?: string }[]).filter((r) => r.route === "tts" && r.text === "talks loudly");
+ const before = ttsAsked().length;
+ await row.locator("[data-post-reread-revoice-preview]").click();
+ const status = page.locator("[data-post-narration-status]");
+ await expect(status).toContainText('would re-voice "speaks" (words 3-3');
+ await expect(status).toContainText("not synthesized yet");
+ expect(narr("p-11").takes).toHaveLength(1);
+ expect(ttsAsked()).toHaveLength(before);
+ await row.locator("[data-post-reread-revoice-go]").click();
+ await expect(status).toContainText("a new take, picked", { timeout: 30_000 });
+ expect(ttsAsked().slice(before).map((r) => [r.voice, r.engine])).toEqual([["zac", "orpheus"]]);
+ const n = narr("p-11") as { takes: Array<Take & { words?: Array<{ w: string; start: number; estimated?: boolean }>; steps?: Array<{ op: string; revoice?: { from: number; to: number; seconds: number } }> }>; pick?: number };
+ expect(n.takes).toHaveLength(2);
+ expect(n.pick).toBe(1);
+ expect(n.takes[1].file).toMatch(/take-2\.revoice-orpheus\.wav$/);
+ const st = n.takes[1].steps?.[0];
+ expect(st?.op).toBe("revoice");
+ expect(n.takes[1].words?.map((w) => w.w)).toEqual(["The", "video", "talks", "loudly", "for", "itself."]);
+ expect(n.takes[1].words?.[2].estimated).toBe(true);
+ const delta = (st?.revoice?.seconds ?? 0) - ((st?.revoice?.to ?? 0) - (st?.revoice?.from ?? 0));
+ expect(n.takes[1].words?.[4].start).toBeCloseTo((n.takes[0].words?.[3].start ?? 0) + delta, 2);
+ expect(n.takes[1].words?.[1].start).toBe(n.takes[0].words?.[1].start);
+ expect(n.takes[1].seconds).toBeCloseTo(n.takes[0].seconds + delta, 1);
+});
+
+test("RE-VOICE ON THE TAKE-ONLY BENCH (?inTake=): the phrase re-voiced into the take's patch, the project's manifest untouched", async ({ page }) => {
+ // p-11's take timed (as Get word timings leaves it), then a draft take of the cut with no patch yet.
+ const doc = JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Array<Entry & { narration?: { takes?: Array<Take & { words?: unknown }> } }> };
+ const words = [["The", 0.1, 0.3], ["video", 0.35, 0.7], ["speaks", 0.75, 1.1], ["for", 1.15, 1.3], ["itself.", 1.35, 1.8]].map(([w, start, end]) => ({ w, start, end }));
+ doc.timeline.find((e) => e.id === "p-11")!.narration!.takes![0].words = words;
+ writeFileSync(MANIFEST, JSON.stringify(doc, null, 2));
+ const projectText = readFileSync(MANIFEST, "utf8");
+ const takes = path.join(DIR, "takes");
+ rmSync(takes, { recursive: true, force: true });
+ mkdirSync(path.join(takes, "t1"), { recursive: true });
+ writeFileSync(path.join(takes, "t1", "take.json"), JSON.stringify({
+ id: "t1", group: "takes", order: 1, label: "Take one", kind: "different", summary: "", changes: [], preview: "preview.mp4", seconds: null, builtAt: null,
+ style: null, patch: null, window: null, draft: true, draftedAt: "2026-11-05T00:00:00.000Z", baseHash: createHash("sha256").update(projectText).digest("hex"),
+ }, null, 2) + "\n");
+ try {
+ await page.setViewportSize({ width: 1500, height: 1100 });
+ await page.goto(`${urls.postBenchHref(PROJECT, "p-11")}?inTake=t1`);
+ await expect(page.locator("[data-post-narration-in-take=t1]")).toBeVisible();
+ const opts = page.locator('[data-panel-id="post-reread"]');
+ await opts.locator("summary").click();
+ const row = opts.locator("[data-post-reread-revoice-row]");
+ await row.locator("[data-post-reread-revoice]").fill("speaks");
+ await row.locator("[data-post-reread-revoice-say]").fill("talks loudly");
+ await row.locator("[data-post-reread-revoice-go]").click();
+ const status = page.locator("[data-post-narration-status]");
+ await expect(status).toContainText("a new take, picked", { timeout: 30_000 });
+ const t1 = JSON.parse(readFileSync(path.join(takes, "t1", "take.json"), "utf8")) as { patch?: { timeline?: Entry[] } };
+ const n = t1.patch?.timeline?.find((e) => e?.id === "p-11")?.narration as { takes: Array<Take & { steps?: Array<{ op: string }> }>; pick?: number };
+ expect(n.takes).toHaveLength(2);
+ expect(n.pick).toBe(1);
+ expect(n.takes[1].steps?.[0]?.op).toBe("revoice");
+ expect(readFileSync(MANIFEST, "utf8")).toBe(projectText);
+ } finally {
+ rmSync(takes, { recursive: true, force: true });
+ }
+});
+
test("READ-FOLLOW (operator, 3 Nov: \"highlight the current paragraph and panning down as needed\"): a long post read part by part -- the second block brightens at its part's start, the others dim, and the card pans so a late block is in view; the bench shows the block map", async ({ page }) => {
// p-13 made long: ten paragraphs, a take read paragraph by paragraph (a part every 2 s of the take).
const para = (i: number) => `Paragraph ${i + 1} begins here and it goes on for a while, ${"saying the same kind of thing again and again, ".repeat(3)}until it ends with mark ${i + 1}.`;
diff --git a/umtool/lib/report/audioSplice.mjs b/umtool/lib/report/audioSplice.mjs
@@ -0,0 +1,329 @@
+// SAMPLE-LEVEL SPLICING of a take, for the edits umtool makes on an approved
+// read without re-synthesizing it (postPause.mjs: silence put in; postRevoice.mjs:
+// one phrase re-voiced): where a cut is quiet, how loud a stretch of speech is,
+// where the words of a short TTS piece are, and an equal-power splice of a new
+// piece into the take. Pure over Float32Array PCM, except decodePcm / writeWav16.
+//
+// Why: a read's word timings come from an alignment, and in a run-together read
+// ("20 10 4 0" in one breath, operator 5 Nov) a word's end is somewhere inside
+// the next one's sound. A cut placed at the timing lands mid-sound and clicks;
+// the lowest-energy ~10 ms near it is where the voice is quietest.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { execFile } from "node:child_process";
+import { writeFile } from "node:fs/promises";
+import { promisify } from "node:util";
+
+const execFileP = promisify(execFile);
+const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg";
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** The window a cut's quiet is measured over, seconds. */
+export const CUT_WINDOW = 0.01;
+/** A quieter window only moves a cut when it is this much quieter than the timing's own (RMS ratio, ~3 dB). */
+export const CUT_TIE = 0.7;
+/** Below this a 10 ms frame is not speech (dBFS). */
+export const SPEECH_GATE_DB = -45;
+
+/**
+ * A sound file as raw PCM at `rate` and `channels` (ffmpeg, f32le): `Float32Array`, interleaved.
+ * @param {string} file
+ * @param {{ rate: number, channels: number }} fmt
+ */
+export async function decodePcm(file, { rate, channels }) {
+ const { stdout } = await execFileP(FFMPEG(), ["-nostdin", "-v", "error", "-i", file, "-f", "f32le", "-acodec", "pcm_f32le", "-ar", String(rate), "-ac", String(channels), "pipe:1"], { encoding: "buffer", maxBuffer: 1 << 30 });
+ const buf = Buffer.from(stdout);
+ return new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)).slice();
+}
+
+/** Interleaved PCM as a 16-bit WAV file's bytes, pure. */
+export function wav16(samples, rate, channels) {
+ const n = samples.length;
+ const buf = Buffer.alloc(44 + n * 2);
+ buf.write("RIFF", 0, "ascii");
+ buf.writeUInt32LE(36 + n * 2, 4);
+ buf.write("WAVE", 8, "ascii");
+ buf.write("fmt ", 12, "ascii");
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(channels, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * channels * 2, 28);
+ buf.writeUInt16LE(channels * 2, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36, "ascii");
+ buf.writeUInt32LE(n * 2, 40);
+ for (let i = 0; i < n; i += 1) {
+ const v = Math.max(-1, Math.min(1, samples[i]));
+ buf.writeInt16LE(Math.round(v < 0 ? v * 32768 : v * 32767), 44 + i * 2);
+ }
+ return buf;
+}
+
+/** Write interleaved PCM to `file` as 16-bit WAV. */
+export async function writeWav16(file, samples, rate, channels) {
+ await writeFile(file, wav16(samples, rate, channels));
+}
+
+/** Interleaved PCM mixed down to one channel, pure (mono: the same array). */
+export function toMono(x, channels) {
+ if (channels <= 1) return x;
+ const n = Math.floor(x.length / channels);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i += 1) {
+ let s = 0;
+ for (let c = 0; c < channels; c += 1) s += x[i * channels + c];
+ out[i] = s / channels;
+ }
+ return out;
+}
+
+/** The RMS of `mono` over samples [a, b), pure (0 for an empty range). */
+export function rmsOf(mono, a, b) {
+ const lo = Math.max(0, Math.floor(a));
+ const hi = Math.min(mono.length, Math.floor(b));
+ if (hi <= lo) return 0;
+ let s = 0;
+ for (let i = lo; i < hi; i += 1) s += mono[i] * mono[i];
+ return Math.sqrt(s / (hi - lo));
+}
+
+const db = (v) => (v > 0 ? 20 * Math.log10(v) : -Infinity);
+
+/**
+ * THE QUIETEST CUT near a boundary, pure: the centre of the lowest-RMS `win`-second window whose centre is inside
+ * [lo, hi] (seconds), stepped by 1 ms -- kept at `nominal` (the timing's own) unless the quietest is at least
+ * CUT_TIE quieter than the window there. Returns `{ at, moved, rmsDb, nominalDb }` (seconds; dBFS).
+ *
+ * @param {Float32Array} mono
+ * @param {number} rate
+ * `perSecondDb`: a nearer quiet preferred -- each window scored its level + this many dB per second off `nominal`.
+ *
+ * @param {{ lo: number, hi: number, nominal: number, win?: number, tie?: number, perSecondDb?: number }} o
+ */
+export function quietestCut(mono, rate, { lo, hi, nominal, win = CUT_WINDOW, tie = CUT_TIE, perSecondDb = 0 }) {
+ const half = (win * rate) / 2;
+ const total = mono.length / rate;
+ const a = Math.max(0, Math.min(lo, hi));
+ const b = Math.min(total, Math.max(lo, hi));
+ const at0 = Math.max(0, Math.min(total, nominal));
+ const rmsAt = (t) => rmsOf(mono, t * rate - half, t * rate + half);
+ const n0 = rmsAt(at0);
+ let best = at0;
+ let bestRms = n0;
+ const score = (r, t) => db(Math.max(r, 1e-9)) + perSecondDb * Math.abs(t - at0);
+ let bestScore = score(n0, at0);
+ const step = 0.001;
+ for (let t = a; t <= b + 1e-9; t += step) {
+ const r = rmsAt(t);
+ const sc = score(r, t);
+ if (sc < bestScore) {
+ bestScore = sc;
+ bestRms = r;
+ best = t;
+ }
+ }
+ const moved = bestRms < n0 * tie;
+ const at = Math.round((moved ? best : at0) * 1000) / 1000;
+ return { at, moved, rmsDb: Math.round(db(moved ? bestRms : n0) * 10) / 10, nominalDb: Math.round(db(n0) * 10) / 10 };
+}
+
+/**
+ * HOW LOUD the speech in samples [a, b) of `mono` is, pure: the RMS of its 10 ms frames above SPEECH_GATE_DB (the
+ * quiet between words left out, so a pause does not make a stretch read as soft). null when none is speech.
+ */
+export function speechRms(mono, rate, a, b, { gateDb = SPEECH_GATE_DB } = {}) {
+ const frame = Math.max(1, Math.round(rate * 0.01));
+ const gate = 10 ** (gateDb / 20);
+ let s = 0;
+ let n = 0;
+ for (let i = Math.max(0, Math.floor(a)); i + frame <= Math.min(mono.length, Math.floor(b)); i += frame) {
+ const r = rmsOf(mono, i, i + frame);
+ if (r >= gate) {
+ s += r * r * frame;
+ n += frame;
+ }
+ }
+ return n ? Math.sqrt(s / n) : null;
+}
+
+/** The gain (dB) that brings `piece` to `ref` loudness, clamped to ±`limit` dB; 0 when either has no speech. Pure. */
+export function matchGainDb(ref, piece, limit = 6) {
+ if (!fin(ref) || !fin(piece) || !(ref > 0) || !(piece > 0)) return 0;
+ const g = 20 * Math.log10(ref / piece);
+ return Math.round(Math.max(-limit, Math.min(limit, g)) * 10) / 10;
+}
+
+/**
+ * WHERE THE SPEECH IS in `mono`, pure: runs of 10 ms frames above the gate, a gap shorter than `minGap` bridged,
+ * a run shorter than `minLen` dropped -- `[{ start, end }]` in seconds.
+ */
+export function speechIslands(mono, rate, { gateDb = SPEECH_GATE_DB, minGap = 0.08, minLen = 0.04 } = {}) {
+ const frame = Math.max(1, Math.round(rate * 0.01));
+ const gate = 10 ** (gateDb / 20);
+ const runs = [];
+ let cur = null;
+ for (let i = 0; i + frame <= mono.length; i += frame) {
+ const on = rmsOf(mono, i, i + frame) >= gate;
+ if (on) {
+ if (cur && i / rate - cur.end <= minGap) cur.end = (i + frame) / rate;
+ else {
+ if (cur) runs.push(cur);
+ cur = { start: i / rate, end: (i + frame) / rate };
+ }
+ }
+ }
+ if (cur) runs.push(cur);
+ return runs.filter((r) => r.end - r.start >= minLen).map((r) => ({ start: Math.round(r.start * 1000) / 1000, end: Math.round(r.end * 1000) / 1000 }));
+}
+
+/**
+ * The span of `mono` worth keeping, pure: from just before its first speech to just after its last (`pad` seconds
+ * either side) -- a TTS piece's lead-in and tail of silence cut. `{ a, b }` in samples (the whole when it has no speech).
+ */
+export function speechBounds(mono, rate, { gateDb = SPEECH_GATE_DB, pad = 0.03 } = {}) {
+ const isl = speechIslands(mono, rate, { gateDb, minGap: 1e9, minLen: 0 });
+ if (!isl.length) return { a: 0, b: mono.length };
+ return { a: Math.max(0, Math.floor((isl[0].start - pad) * rate)), b: Math.min(mono.length, Math.ceil((isl[isl.length - 1].end + pad) * rate)) };
+}
+
+/**
+ * THE SPLICE, pure: interleaved `src` with frames [from, to) taken out and `piece` (interleaved, the same channels)
+ * put in their place, an EQUAL-POWER crossfade `xf` frames wide centred on each join. The length is exact: frames
+ * `from + piece + (srcFrames - to)` -- each fade mixes the edge of the cut-out audio (fading out) with the piece
+ * (fading in from nothing), so nothing overlaps and no time is lost.
+ *
+ * @param {Float32Array} src
+ * @param {Float32Array} piece
+ * @param {number} channels
+ * @param {number} from first frame cut out
+ * @param {number} to first frame kept after
+ * @param {number} xf crossfade width, frames
+ */
+export function spliceEqualPower(src, piece, channels, from, to, xf) {
+ const ch = Math.max(1, channels);
+ const N = Math.floor(src.length / ch);
+ const L = Math.floor(piece.length / ch);
+ const f = Math.max(0, Math.min(N, from));
+ const t = Math.max(f, Math.min(N, to));
+ const out = new Float32Array((f + L + (N - t)) * ch);
+ out.set(src.subarray(0, f * ch), 0);
+ out.set(piece.subarray(0, L * ch), f * ch);
+ out.set(src.subarray(t * ch, N * ch), (f + L) * ch);
+ const h = Math.max(0, Math.floor(xf / 2));
+ if (h > 0) {
+ const S = (i, c) => (i >= 0 && i < N ? src[i * ch + c] : 0);
+ const P = (i, c) => (i >= 0 && i < L ? piece[i * ch + c] : 0);
+ // Join A, output frames [f-h, f+h): the source going out (its frames run on into what is cut), the piece coming in.
+ for (let i = -h; i < h; i += 1) {
+ const o = f + i;
+ if (o < 0 || o >= f + L + (N - t)) continue;
+ const th = ((i + h) / (2 * h)) * (Math.PI / 2);
+ for (let c = 0; c < ch; c += 1) out[o * ch + c] = S(f + i, c) * Math.cos(th) + P(i, c) * Math.sin(th);
+ }
+ // Join B, output frames [f+L-h, f+L+h): the piece going out, the source coming in (its frames from before `to`).
+ for (let i = -h; i < h; i += 1) {
+ const o = f + L + i;
+ if (o < 0 || o >= f + L + (N - t)) continue;
+ const th = ((i + h) / (2 * h)) * (Math.PI / 2);
+ for (let c = 0; c < ch; c += 1) out[o * ch + c] = P(L + i, c) * Math.cos(th) + S(t + i, c) * Math.sin(th);
+ }
+ }
+ return out;
+}
+
+/** `x` (interleaved) scaled by `gainDb`, pure (a new array). */
+export function withGain(x, gainDb) {
+ const g = 10 ** (gainDb / 20);
+ const out = new Float32Array(x.length);
+ for (let i = 0; i < x.length; i += 1) out[i] = x[i] * g;
+ return out;
+}
+
+/**
+ * The loudest jump between neighbouring `win`-second windows' RMS across [a, b) seconds of `mono`, dB, pure -- a
+ * join that clicks or steps shows as a jump (the proof's continuity check). Windows quieter than the gate are
+ * treated as the gate (silence to speech is not a click).
+ */
+export function maxRmsJumpDb(mono, rate, a, b, { win = 0.02, gateDb = SPEECH_GATE_DB } = {}) {
+ const w = Math.max(1, Math.round(win * rate));
+ const floor = gateDb;
+ let prev = null;
+ let worst = 0;
+ for (let i = Math.max(0, Math.floor(a * rate)); i + w <= Math.min(mono.length, Math.floor(b * rate)); i += w) {
+ const d = Math.max(floor, db(rmsOf(mono, i, i + w)));
+ if (prev !== null) worst = Math.max(worst, Math.abs(d - prev));
+ prev = d;
+ }
+ return Math.round(worst * 10) / 10;
+}
+
+/**
+ * THE STEP AT A JOIN, dB, pure: the speech level in the `win` seconds before `at` against the `win` after (each
+ * floored at the gate) -- a splice that clicks or lands in a louder or softer voice shows here.
+ */
+export function joinStepDb(mono, rate, at, { win = 0.02, gateDb = SPEECH_GATE_DB } = {}) {
+ const i = Math.round(at * rate);
+ const w = Math.max(1, Math.round(win * rate));
+ const a = Math.max(gateDb, db(rmsOf(mono, i - w, i)));
+ const b = Math.max(gateDb, db(rmsOf(mono, i, i + w)));
+ return Math.round(Math.abs(a - b) * 10) / 10;
+}
+
+/**
+ * `n` WORDS IN A SHORT PIECE, pure, when its speech islands do not count `n` (a TTS voice drawing its words out
+ * rather than pausing between them): the speech's extent split at its `n - 1` deepest valleys (10 ms frames, smoothed
+ * over 30 ms; at least `minGap` seconds apart and from the extent's edges), each word then trimmed to its frames above
+ * the gate. `[{ start, end }]` in seconds, or null when there is no speech or too few valleys.
+ */
+export function wordsByValleys(mono, rate, n, { gateDb = SPEECH_GATE_DB, minGap = 0.2 } = {}) {
+ if (!(n >= 1)) return null;
+ const frame = Math.max(1, Math.round(rate * 0.01));
+ const nf = Math.floor(mono.length / frame);
+ const lv = Array.from({ length: nf }, (_, i) => Math.max(-100, db(rmsOf(mono, i * frame, (i + 1) * frame))));
+ const sm = lv.map((_, i) => (lv[Math.max(0, i - 1)] + lv[i] + lv[Math.min(nf - 1, i + 1)]) / 3);
+ const on = (i) => lv[i] >= gateDb;
+ let a = 0;
+ while (a < nf && !on(a)) a += 1;
+ let b = nf - 1;
+ while (b >= 0 && !on(b)) b -= 1;
+ if (a > b) return null;
+ const sec = (i) => (i * frame) / rate;
+ const edge = Math.ceil((minGap * rate) / frame);
+ // A run of quiet frames is ONE valley (at its middle, its depth the run's lowest); in speech, each local minimum.
+ const cands = [];
+ const depth = new Map();
+ for (let i = a; i <= b; i += 1) {
+ if (!on(i)) {
+ let j = i;
+ let low = lv[i];
+ while (j + 1 <= b && !on(j + 1)) low = Math.min(low, lv[(j += 1)]);
+ const m = Math.round((i + j) / 2);
+ if (m >= a + edge && m <= b - edge) {
+ cands.push(m);
+ depth.set(m, low);
+ }
+ i = j;
+ } else if (i >= a + edge && i <= b - edge && sm[i] <= sm[i - 1] && sm[i] <= sm[i + 1] && on(i - 1) && on(i + 1)) {
+ cands.push(i);
+ depth.set(i, sm[i]);
+ }
+ }
+ cands.sort((x, y) => depth.get(x) - depth.get(y));
+ const cuts = [];
+ for (const i of cands) {
+ if (cuts.length >= n - 1) break;
+ if (cuts.every((j) => Math.abs(j - i) >= edge)) cuts.push(i);
+ }
+ if (cuts.length < n - 1) return null;
+ cuts.sort((x, y) => x - y);
+ const bounds = [a, ...cuts, b + 1];
+ const r = (v) => Math.round(v * 1000) / 1000;
+ return bounds.slice(0, -1).map((s, k) => {
+ let lo = s;
+ let hi = bounds[k + 1] - 1;
+ while (lo < hi && !on(lo)) lo += 1;
+ while (hi > lo && !on(hi)) hi -= 1;
+ return { start: r(sec(lo)), end: r(sec(hi + 1)) };
+ });
+}
diff --git a/umtool/lib/report/postPause.mjs b/umtool/lib/report/postPause.mjs
@@ -17,7 +17,13 @@
// 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). What
+// 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,
@@ -35,6 +41,7 @@
// 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";
@@ -49,6 +56,10 @@ export const PAUSE_LIMITS = Object.freeze({ seconds: [0.05, 3] });
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;
const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/;
/** A pause the plan cannot make (no word timings, the word not read, nothing to change): exit 1, not a usage error. */
@@ -90,7 +101,7 @@ export function parsePauseSpec(spec) {
}
/** The word indices of `take` a target counts (null: all), by the parts reading that piece. */
-function targetWords(entry, take, target) {
+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 : [];
@@ -110,15 +121,24 @@ function targetWords(entry, take, target) {
* @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(idx[k + want.length - 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(`--pause "${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(`--pause "${match}#${occurrence}": "${match}" is in ${where} ${hits.length} time${hits.length === 1 ? "" : "s"}`);
+ 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];
}
@@ -131,6 +151,20 @@ export function cutAfter(words, i, 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
@@ -140,7 +174,7 @@ export function cutAfter(words, i, seconds = Infinity) {
* @param {Record<string, any>} entry
* @param {{ pauses: Array<{ match: string, occurrence: number, seconds: number }>, target?: string | null }} o
*/
-export function pausePlan(entry, { pauses, target = null }) {
+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;
@@ -170,7 +204,8 @@ export function pausePlan(entry, { pauses, target = null }) {
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 <p> ${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;
- const list = [...after].sort((a, b) => a[0] - b[0]).map(([i, s]) => ({ word: i, w: words[i].w, at: cutAfter(words, i, end), seconds: r3(s) }));
+ // `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)) : cutAfter(words, i, end), seconds: r3(s) }));
// 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 });
@@ -202,17 +237,28 @@ export function pausePlan(entry, { pauses, target = null }) {
};
}
-/** The ffmpeg arguments that cut `src` at the plan's pauses and put each one's silence in (the source sample-exact between). */
+/**
+ * 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 trim = `atrim=start_sample=${Math.round(s.from * rate)}${s.to === null ? "" : `:end_sample=${Math.round(s.to * rate)}`}`;
- chains.push(`[0:a]aformat=sample_rates=${rate}:channel_layouts=${layout},${trim},asetpts=PTS-STARTPTS[a${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]`);
@@ -229,11 +275,41 @@ export function pauseArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}
* @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 plan = pausePlan(e, { pauses, target });
+ 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 } = 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`;
diff --git a/umtool/lib/report/postPause.test.mjs b/umtool/lib/report/postPause.test.mjs
@@ -11,8 +11,9 @@ import path from "node:path";
import { after, test } from "node:test";
import { validatePostItem } from "umtool-report-to-video/post-item";
import { wordZoomTimes } from "umtool-report-to-video/word-zoom";
-import { PauseError, cutAfter, parsePauseSpec, pauseArgs, pausePlan, pauseTake } from "./postPause.mjs";
+import { PauseError, cutAfter, cutWindow, parsePauseSpec, pauseArgs, pausePlan, pauseTake } from "./postPause.mjs";
import { RereadError } from "./postReread.mjs";
+import { writeWav16 } from "./audioSplice.mjs";
import { postsCommand } from "./postsCli.mjs";
import { undoStructural } from "./manifest.mjs";
@@ -109,10 +110,25 @@ test("THE REFUSALS (exit 1): no word timings names posts narrate --words; a word
assert.equal(pausePlan(e, { pauses: parsePauseSpec("4=0.4"), target: "quoted" }).pauses[0].word, 13);
});
-test("THE ffmpeg: the source cut sample-exact at each pause, the silence between, the last span to the end", () => {
+test("THE ffmpeg: the source cut sample-exact at each pause, the silence between, the last span to the end; 10 ms fades either side of the silence", () => {
const p = pausePlan(item(), { pauses: parsePauseSpec("20=0.45") });
const fc = pauseArgs("/in.wav", "/o.wav", p, { rate: 24000, layout: "mono" })[8];
- assert.equal(fc, "[0:a]aformat=sample_rates=24000:channel_layouts=mono,atrim=start_sample=0:end_sample=56400,asetpts=PTS-STARTPTS[a0];anullsrc=r=24000:cl=mono,atrim=end_sample=10800[g1];[0:a]aformat=sample_rates=24000:channel_layouts=mono,atrim=start_sample=56400,asetpts=PTS-STARTPTS[a1];[a0][g1][a1]concat=n=3:v=0:a=1[out]");
+ assert.equal(fc, "[0:a]aformat=sample_rates=24000:channel_layouts=mono,atrim=start_sample=0:end_sample=56400,asetpts=PTS-STARTPTS,afade=t=out:ss=56160:ns=240[a0];anullsrc=r=24000:cl=mono,atrim=end_sample=10800[g1];[0:a]aformat=sample_rates=24000:channel_layouts=mono,atrim=start_sample=56400,asetpts=PTS-STARTPTS,afade=t=in:ss=0:ns=240[a1];[a0][g1][a1]concat=n=3:v=0:a=1[out]");
+});
+
+test("THE QUIET CUT: the window a word allows (40 ms back from its end, up to the next word or 0.1 s; ±40 ms when they run together); on a take whose quiet is off the timing, the cut moves there", async () => {
+ const w = [{ w: "a", start: 0, end: 1 }, { w: "b", start: 1.5, end: 2 }, { w: "c", start: 2, end: 2.08 }, { w: "d", start: 2.08, end: 2.2 }];
+ assert.deepEqual(cutWindow(w, 0), { lo: 0.96, hi: 1.1 });
+ assert.deepEqual(cutWindow(w, 2), { lo: 2.04, hi: 2.12 }, "run together: about the end, never before the word's middle");
+ // A synthetic read: tone everywhere but 30 ms of near-silence at 2.27-2.30 (the timing says 2.35 is "20,"'s cut: 2.30 + 0.05).
+ const p = await project("quiet", [item()]);
+ const f = path.join(p.dir, "narration", "posts", "1", "take-2.orpheus-thread.wav");
+ const sig = new Float32Array(Math.round(6.4 * 24000)).map((_, i) => (i / 24000 >= 2.27 && i / 24000 < 2.3 ? 0.0001 : 0.2) * Math.sin((2 * Math.PI * 220 * i) / 24000));
+ await writeWav16(f, sig, 24000, 1);
+ const e = (await manifest(p)).timeline[0];
+ const r = await pauseTake(p, e, { pauses: parsePauseSpec("20=0.45,10=0.45"), dryRun: true });
+ assert.ok(Math.abs(r.plan.pauses[0].at - 2.285) <= 0.006, `cut moved into the quiet: ${r.plan.pauses[0].at}`);
+ assert.equal(r.plan.pauses[1].at, 2.61, "a uniform tone: the cut stays at its timing");
});
async function project(name, timeline) {
diff --git a/umtool/lib/report/postReread.mjs b/umtool/lib/report/postReread.mjs
@@ -40,6 +40,7 @@ export const REREAD_USAGE = [
" 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]",
" umtool posts reread <project> <item> --pause \"20=0.45,10=0.45,4#2=0.6\" [--target post|parent:0|quoted|linked:0] [--dry-run] [--json]",
+ " umtool posts reread <project> <item> --revoice \"20 10 4 0\"[#n] --say \"20... 10... 4... 0...\" [--target linked:0] [--voice <v>|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json]",
" (any form, + --in-take <take> or --take <take>: the new take picked in a take's patch, the project's pick kept)",
" 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",
@@ -50,6 +51,13 @@ export const REREAD_USAGE = [
" phrase pauses after its last word), found in the take's word timings (posts narrate --words makes them): the take",
" cut just after the word, everything after moved on (words, parts, so zooms, captions, slams, beeps keep their",
" words). On a paused take it re-cuts from the take before (=0 takes a pause away). --target counts one piece's words.",
+ " Each cut moves to the quietest 10 ms its word allows, and each side of the silence is faded (10 ms).",
+ " --revoice: ONE PHRASE RE-VOICED (TTS for --say only, the editor's; the rest of the read untouched): the phrase found",
+ " in the take's word timings, the original cut at the quietest 10 ms within 40 ms of each boundary, --say synthesized",
+ " in the voice the piece was read in (--voice overrides; the project's lexicon applied; kept in narration/parts-cache/),",
+ " loudness-matched to the 2 s about it (±6 dB) and spliced in with equal-power crossfades (--xfade, 0-0.2 s). Words,",
+ " parts and all timed on them move by the length change; the new words' timings are estimated. --dry-run: no TTS;",
+ " it names each cut's level -- a cut still in speech is warned of (the timings off there): --splice 65.03-66.00 sets them.",
].join("\n");
export class RereadError extends Error {
@@ -289,7 +297,7 @@ export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono", stre
}
/** A file's sample rate and channel layout (ffprobe). */
-async function audioFormat(file) {
+export async function audioFormat(file) {
const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels", "-of", "default=noprint_wrappers=1", file]);
const rate = Number(/sample_rate=(\d+)/.exec(String(stdout))?.[1]) || 48000;
const ch = Number(/channels=(\d+)/.exec(String(stdout))?.[1]) || 1;
@@ -305,9 +313,12 @@ async function audioFormat(file) {
* @param {{ id: string, dir: string }} project
* @param {Record<string, any>} e
* @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
+ * `make(src, out, fmt)` in place of `argsOf`: the file written by the caller (postRevoice.mjs: a splice made in
+ * memory). `voice`: the take's voice label (default the source's).
+ *
+ * @param {{ op: string, argsOf?: (src: string, out: string, fmt: { rate: number, layout: string }) => string[], make?: (src: string, out: string, fmt: { rate: number, layout: string }) => Promise<void>, voice?: 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 writeDerivedTake(project, e, plan, { op, argsOf, measure = undefined, verb = "re-join", after = undefined }) {
+export async function writeDerivedTake(project, e, plan, { op, argsOf = undefined, make = undefined, voice = undefined, measure = undefined, verb = "re-join", after = undefined }) {
const t = plan.take;
const pid = postIdOf(e);
const dir = path.join(project.dir, ...takesDirOf(pid).split("/"));
@@ -318,10 +329,12 @@ export async function writeDerivedTake(project, e, plan, { op, argsOf, measure =
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(), argsOf(src, abs(rel), fmt), { maxBuffer: 1 << 24 });
+ if (make) await make(src, abs(rel), fmt);
+ else if (argsOf) await execFileP(FFMPEG(), argsOf(src, abs(rel), fmt), { maxBuffer: 1 << 24 });
+ else throw new Error("no way to write it (argsOf or make)");
} catch (err) {
await rm(abs(rel), { force: true });
- throw new RereadError(`ffmpeg could not ${verb} ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`);
+ throw new RereadError(`${make ? "could not" : "ffmpeg could not"} ${verb} ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`);
}
const measureOf = measure ?? (await import("./postNarrationCli.mjs")).measureTake;
let m = await measureOf(abs(rel));
@@ -329,7 +342,7 @@ export async function writeDerivedTake(project, e, plan, { op, argsOf, measure =
const take = {
file: rel,
engine: "derived",
- voice: t.voice ?? "?",
+ voice: voice ?? t.voice ?? "?",
seconds: fin(m.seconds) && m.seconds > 0 ? m.seconds : plan.seconds,
source: { kind: "take", from: takeIdOf(t) },
steps: plan.steps,
@@ -375,7 +388,7 @@ export function piecesHidden(e, thread) {
}
/** `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, pause = null, target = null, dryRun = false, json = false, out = (s) => console.log(s) } = {}) {
+export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, tempoSpec = null, tempo = null, parts = null, stretch = "atempo", yell = null, pause = null, target = null, revoice = null, say = null, voice = null, xfade = null, cut = 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}`));
@@ -385,11 +398,18 @@ export async function rereadCommand(project, ref, { without = [], dropParts = []
const { yellCommand } = await import("./postYell.mjs");
return yellCommand(project, manifest, [e], { ...yell, dryRun, json, out });
}
+ if (revoice !== null || say !== null) {
+ if (revoice === null) throw new RereadError("--say goes with --revoice \"<phrase>\" (the words it says instead)");
+ if (pause !== null || tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--revoice goes alone: re-voice the phrase, then pause, re-join or re-time that take (it is picked) -- or the other way round");
+ const { revoiceCommand } = await import("./postRevoice.mjs");
+ return revoiceCommand(project, e, { revoice, say, voice, xfade, cut, target, dryRun, json, out });
+ }
+ if (voice !== null || xfade !== null || cut !== null) throw new RereadError("--voice, --xfade and --splice go with --revoice");
if (pause !== null) {
if (tempoSpec !== null || tempo !== null || without.length || dropParts.length || dropUrls) throw new RereadError("--pause goes alone: re-join or re-time first, then pause that take (it is picked) -- or the other way round");
return pauseCommand(project, e, { pause, target, dryRun, json, out });
}
- if (target !== null) throw new RereadError("--target names the piece --pause counts its words in");
+ if (target !== null) throw new RereadError("--target names the piece --pause or --revoice counts its words in");
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;
diff --git a/umtool/lib/report/postRevoice.mjs b/umtool/lib/report/postRevoice.mjs
@@ -0,0 +1,437 @@
+// ONE PHRASE OF AN APPROVED READ, RE-VOICED (operator, 5 Nov, a Mr. Obvious cut:
+// "the "20 10 4 0" words @21:21 should have some spacing since it's a countdown";
+// with pauses cut in after each number: "the spaced 20 10 4 0 is choppy and it's
+// very noticeable" -- the read gabbles the countdown, ~0.26 s a number, the words
+// run together, so a cut at a word's end lands mid-sound). The read is liked, so
+// it is NOT re-synthesized: only the phrase named is, and spliced in its place.
+//
+// umtool posts reread <p> <item> --revoice "<phrase as the words show it>[#n]" --say "<what to say instead>"
+// [--target <piece role>] [--voice <v>|auto] [--xfade 0.03] [--dry-run] [--json] [--in-take <t>]
+//
+// THE SPAN: the phrase found in the picked take's word timings as --pause finds a
+// word (postPause.mjs findPhrase: word-zoom's match, case and edge punctuation
+// aside; `#n` its n-th time; --target counts one piece's words). A take without
+// word timings is refused, naming `umtool posts narrate <p> <item> --words`. The
+// phrase must be inside one part of the read.
+//
+// THE NEW PIECE: --say, as a voice says it (post-redact.mjs spokenRead: the
+// project's pronunciation lexicon, the redaction, the slur filter), synthesized by
+// the EDITOR's tts op (narrate-via-editor.mjs askEditorTts; it finds WORKER_TOKEN
+// itself) in the voice and engine the piece was read in -- the part's `voice` in
+// the take's parts, the root take's engine; --voice overrides -- and kept in the
+// project's PARTS CACHE as a thread read's parts are (postThreadRead.mjs
+// partKey: narration/parts-cache/<sha1(voice|text)>.wav), so asking again is
+// free. Its lead-in and tail of silence are trimmed (REVOICE_PAD kept).
+//
+// THE SPLICE (audioSplice.mjs): the original cut from just before the span's
+// first word to just after its last -- each cut at the quietest ~10 ms within
+// ±REVOICE_REACH of the boundary (the middle of the quiet between two words, or
+// the word's edge when they run together) -- the piece loudness-matched to the
+// speech in the 2 s either side (gain within ±6 dB), and put in with EQUAL-POWER
+// crossfades (--xfade, default 0.03 s) centred on both joins. The length is exact:
+// the old take − the span cut + the new piece. Sample rate and layout: the take's.
+//
+// WHAT MOVES (as a pause moves it): every word after the span, by the length
+// difference; the part holding it grows or shrinks by it; every later part moves
+// on. So everything timed ON the read -- word zooms, captions, slams, beeps,
+// read-follow -- stays on its words. The new words are timed from the piece's own
+// sound (its speech islands, one a word when they count the same; else the piece
+// split at its deepest valleys; else spread by length) and marked `estimated: true` (the editor's tts returns no word
+// timings): a later `posts narrate … --words` refines them. The part's text and
+// the take's script say --say in the phrase's place.
+//
+// A RE-VOICE AGAIN of exactly the words a re-voice put in is cut from the take
+// before it (one splice, never a splice of a splice). The new take: `source:
+// {kind: "take", from}`, `steps: [{op: "revoice", revoice: {word, count, words,
+// phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`,
+// picked in ONE write (one undo point). --dry-run: the span, the cut points, what
+// is said and in which voice, and the length change when the piece is cached --
+// no TTS.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { mkdir, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { POST_NARRATION_ENGINES, pickedTake, postNarrationKnobs, rootTakeOf, takeIdOf, takeSourceOf } from "umtool-report-to-video/post-narration";
+import { spokenRead } from "umtool-report-to-video/post-redact";
+import { normWord } from "umtool-report-to-video/word-zoom";
+import { PauseError, findPhrase, targetWords } from "./postPause.mjs";
+import { RereadError, audioFormat, lastLocalStep, writeDerivedTake } from "./postReread.mjs";
+import { PARTS_CACHE, partKey } from "./postThreadRead.mjs";
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const str = (v) => (typeof v === "string" ? v : "");
+
+/** How far either side of a boundary the quietest cut is looked for, seconds. */
+export const REVOICE_REACH = 0.04;
+/**
+ * When there is no quiet within REVOICE_REACH (the alignment's timings off, the words run together), how far it is
+ * looked for then -- a nearer quiet preferred (REVOICE_NEAR_DB dB a second off the boundary) -- seconds.
+ */
+export const REVOICE_REACH_WIDE = 0.15;
+export const REVOICE_NEAR_DB = 40;
+/** A cut is in QUIET at or below this level (dBFS), or this far below the speech about it (dB). */
+export const REVOICE_QUIET = Object.freeze({ db: -40, below: 15 });
+/** The quiet kept before and after the new piece's speech, seconds. */
+export const REVOICE_PAD = 0.03;
+/** The speech either side of the span the new piece is loudness-matched to, seconds. */
+export const REVOICE_CONTEXT = 2;
+/** --xfade's range and default, seconds; --say's longest. */
+export const REVOICE_LIMITS = Object.freeze({ xfade: [0, 0.2], xfadeDefault: 0.03, say: 400, gainDb: 6 });
+const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/;
+
+/** A re-voice the plan cannot make (no word timings, a recorded read, the phrase across two parts): exit 1. */
+export class RevoiceError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "RevoiceError";
+ }
+}
+
+/**
+ * THE ASK as the CLI writes it, pure: `--revoice "20 10 4 0#2"`, `--say "20... 10... 4... 0..."`, `--voice`,
+ * `--xfade` -- `{ match, occurrence, say, voice, xfade }`. Refused (RereadError, a usage error): no phrase, no
+ * --say, a bad occurrence, voice or crossfade.
+ *
+ * @param {{ phrase: string, say: string, voice?: string | null, xfade?: number | string | null, cut?: string | null }} o
+ */
+export function parseRevoice({ phrase, say, voice = null, xfade = null, cut = null }) {
+ const m = /^(.*?)(?:\s*#\s*(\d+))?$/.exec(str(phrase).trim());
+ const match = (m?.[1] ?? "").trim();
+ if (!match || !match.split(/\s+/).some((w) => normWord(w))) throw new RereadError(`--revoice names the phrase as the read's words show it: --revoice "20 10 4 0" (#<n> its n-th time)`);
+ const occurrence = m?.[2] === undefined ? 1 : Number(m[2]);
+ if (!(Number.isInteger(occurrence) && occurrence >= 1 && occurrence <= 999)) throw new RereadError(`--revoice ${phrase}: #<n> is its n-th time in the read, from 1`);
+ const s = str(say).replace(/\s+/g, " ").trim();
+ if (!s || !/[\p{L}\p{N}]/u.test(s)) throw new RereadError(`--revoice needs --say "<what to say instead>" (e.g. --say "20... 10... 4... 0...")`);
+ if (s.length > REVOICE_LIMITS.say) throw new RereadError(`--say: at most ${REVOICE_LIMITS.say} characters (it re-voices a phrase, not a read)`);
+ const v = voice === null || voice === undefined || voice === "" || voice === "auto" ? null : String(voice);
+ if (v !== null && !VOICE_RE.test(v)) throw new RereadError(`--voice ${voice}: a stock voice's id (or auto: the voice the piece was read in)`);
+ const [lo, hi] = REVOICE_LIMITS.xfade;
+ const xf = xfade === null || xfade === undefined || xfade === "" ? REVOICE_LIMITS.xfadeDefault : Number(xfade);
+ if (!(fin(xf) && xf >= lo && xf <= hi)) throw new RereadError(`--xfade ${xfade}: ${lo}–${hi} seconds`);
+ return { match, occurrence, say: s, voice: v, xfade: xf, cut: parseCut(cut) };
+}
+
+/** `--splice "65.03-66.00"` (either side may be left out: "65.03-", "-66.00"): the source take's seconds the cut is SET at, the quiet not looked for. Pure. */
+/** @param {string | null | undefined} cut */
+export function parseCut(cut) {
+ if (cut === null || cut === undefined || cut === "") return null;
+ const m = /^\s*(\d+(?:\.\d+)?)?\s*-\s*(\d+(?:\.\d+)?)?\s*$/.exec(String(cut));
+ if (!m || (m[1] === undefined && m[2] === undefined)) throw new RereadError(`--splice ${cut}: <from>-<to> in the take's seconds (either may be left out: 65.03-, -66.00)`);
+ const from = m[1] === undefined ? null : Number(m[1]);
+ const to = m[2] === undefined ? null : Number(m[2]);
+ if (from !== null && to !== null && !(to > from)) throw new RereadError(`--splice ${cut}: its end is after its start`);
+ return { from, to };
+}
+
+/** The part of `take` a word starting at `t` is read in (its index), as targetWords counts a word its part's. */
+const partAt = (parts, t) => parts.findIndex((p) => fin(p?.start) && fin(p?.seconds) && t >= p.start - 0.05 && t < p.start + p.seconds + 0.05);
+
+/** A regex finding a phrase's words in a text: its words in a row, anything not a letter or digit between, case aside. */
+function phraseRe(ws) {
+ const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return new RegExp(`(?<![\\p{L}\\p{N}])${ws.map((w) => esc(normWord(w))).join("[^\\p{L}\\p{N}]+")}(?![\\p{L}\\p{N}])[.,!?…;:]*`, "giu");
+}
+
+/**
+ * `text` with the `n`-th (0-based) time the phrase is in it said as `say` (the phrase's closing punctuation taken
+ * with it when `say` ends in its own, else kept); null when it is not there that often. Pure.
+ */
+export function replaceNth(text, ws, n, say) {
+ const re = phraseRe(ws);
+ let k = 0;
+ let out = null;
+ str(text).replace(re, (m0, at) => {
+ if (k++ === n && out === null) {
+ const tail = /[\p{P}]$/u.test(say) ? "" : /[.,!?…;:]*$/.exec(m0)?.[0] ?? "";
+ out = str(text).slice(0, at) + say + tail + str(text).slice(at + m0.length);
+ }
+ return m0;
+ });
+ return out;
+}
+
+/** The voice a piece was read in: the part's, else the take's when it is one voice, else the item's narrator. */
+function voiceOf(entry, take, part, render) {
+ if (VOICE_RE.test(str(part?.voice))) return part.voice;
+ if (VOICE_RE.test(str(take.voice)) && !take.voice.includes("+")) return take.voice;
+ return entry.narration?.voice ?? postNarrationKnobs(entry, render ?? {}).voice;
+}
+
+/**
+ * THE RE-VOICE's PLAN, pure (no sound read): the take it cuts (`take`: the picked one; a re-voice again of the words a
+ * re-voice put in, the take before it), the span (`first`, `last` word indices; `phrase` its words), the cut's
+ * boundaries (`nominal: { from, to }`) and the windows each may move in (`windows: { from: {lo, hi}, to: {lo, hi} }`),
+ * what is said (`say`; `said`: as the voice says it, the lexicon applied) and how (`voice`, `engine`, `key`: the parts
+ * cache's), the part it is in (`part`), and how many effects have a set second (`fixedAt`).
+ *
+ * @param {Record<string, any>} entry
+ * @param {{ match: string, occurrence: number, say: string, voice?: string | null, xfade?: number, target?: string | null, red?: any, render?: any }} o
+ */
+export function revoicePlan(entry, { match, occurrence = 1, say, voice = null, xfade = REVOICE_LIMITS.xfadeDefault, target = null, red = null, render = null }) {
+ const picked = pickedTake(entry);
+ if (!picked) throw new RevoiceError(`${entry?.id ?? "?"} has no take to re-voice`);
+ const noWords = (t) => !Array.isArray(t?.words) || !t.words.length;
+ if (noWords(picked)) throw new RevoiceError(`${entry.id}'s picked take (${takeIdOf(picked)}) has no word timings to find the phrase by: time its words first -- umtool posts narrate <p> ${entry.id} --words (+ --in-take <t> for a take's read; the bench's Get word timings) -- then re-voice`);
+ const takes = entry.narration.takes;
+ const root = rootTakeOf(takes, picked);
+ if (root.engine === "recorded" || takeSourceOf(root).kind === "recorded") throw new RevoiceError(`${entry.id}'s picked take is a RECORDED read (a person's own voice): a synthetic phrase is not spliced into it -- record the phrase again`);
+ const engine = POST_NARRATION_ENGINES.includes(root.engine) ? root.engine : "orpheus";
+ const among = targetWords(entry, picked, target);
+ const hit = findPhrase(entry, picked.words, among, { match, occurrence }, target, "--revoice");
+ // A re-voice again of exactly what the last re-voice put in: cut from the take before it.
+ const up = lastLocalStep(takes, picked, ["revoice"]);
+ const rv = up?.step?.revoice;
+ const recut = !!(up?.from && !noWords(up.from) && rv && hit.first === rv.word && hit.last - hit.first + 1 === rv.words && rv.word + rv.count <= up.from.words.length);
+ const take = recut ? { ...up.from, index: takes.indexOf(up.from) } : picked;
+ const first = recut ? rv.word : hit.first;
+ const last = recut ? rv.word + rv.count - 1 : hit.last;
+ const words = take.words;
+ const parts = Array.isArray(take.parts) ? take.parts : [];
+ const part = parts.length ? partAt(parts, words[first].start) : -1;
+ if (parts.length && part !== partAt(parts, words[last].start)) throw new RevoiceError(`--revoice "${match}": the phrase runs across two parts of the read (parts ${part + 1} and ${partAt(parts, words[last].start) + 1}) -- re-voice each part's words on its own`);
+ const total = fin(take.seconds) ? take.seconds : Infinity;
+ const a = words[first];
+ const b = words[last];
+ const prev = words[first - 1];
+ const next = words[last + 1];
+ const mid = (w) => w.start + (w.end - w.start) / 2;
+ // The boundaries: the middle of the quiet between two words (at most 0.1 s off the word), or the word's edge when they run together.
+ const from = prev && prev.end < a.start ? Math.max(a.start - 0.1, (prev.end + a.start) / 2) : a.start;
+ const to = next && next.start > b.end ? Math.min(b.end + 0.1, (b.end + next.start) / 2) : b.end;
+ const windows = {
+ from: { lo: r3(Math.max(0, from - REVOICE_REACH, prev ? mid(prev) : 0)), hi: r3(Math.min(from + REVOICE_REACH, mid(a))) },
+ to: { lo: r3(Math.max(to - REVOICE_REACH, mid(b))), hi: r3(Math.min(total, to + REVOICE_REACH, next ? mid(next) : total)) },
+ };
+ // The wide windows: never inside the phrase as timed (a quiet there is between two of its own words), never past the
+ // word before's start or the word after's end.
+ const wide = {
+ from: { lo: r3(Math.max(0, from - REVOICE_REACH_WIDE, prev ? prev.start : 0)), hi: r3(Math.max(Math.min(from, a.start), Math.min(from + REVOICE_REACH_WIDE, a.start))) },
+ to: { lo: r3(Math.min(Math.max(to, b.end), Math.max(to - REVOICE_REACH_WIDE, b.end))), hi: r3(Math.min(total, to + REVOICE_REACH_WIDE, next ? next.end : total)) },
+ };
+ const v = voice ?? voiceOf(entry, take, parts[part], render);
+ const spoken = red ? spokenOf(say, entry, red) : { text: say, lexicon: [] };
+ const fixedAt = (Array.isArray(entry.fx) ? entry.fx : []).filter((fx) => fin(fx?.at)).length;
+ return {
+ take, picked, recut, target, first, last, phrase: words.slice(first, last + 1).map((w) => w.w).join(" "),
+ nominal: { from: r3(from), to: r3(Math.min(total, to)) }, windows, wide,
+ say, said: spoken.text, lexicon: spoken.lexicon, voice: v, engine, key: partKey(engine, v, spoken.text), part, xfade, fixedAt,
+ };
+}
+
+/** --say as the voice says it (post-redact.mjs spokenRead: the lexicon, the redaction, the slur filter). */
+function spokenOf(say, entry, red) {
+ const s = spokenRead(say, entry, red);
+ return { text: str(s.text).replace(/\s+/g, " ").trim() || say, lexicon: s.lexicon ?? [] };
+}
+
+/**
+ * The new words' times inside the piece, pure: one speech island a word when they count the same, else the speech's
+ * extent (or the whole piece) shared out by each word's length. Seconds from the piece's start.
+ */
+export function pieceWordTimes(ws, seconds, islands = []) {
+ if (islands.length === ws.length && ws.length) return islands.map((x) => ({ start: x.start, end: x.end }));
+ const a = islands.length ? islands[0].start : 0;
+ const b = islands.length ? islands[islands.length - 1].end : seconds;
+ const len = ws.map((w) => Math.max(1, normWord(w).length));
+ const sum = len.reduce((x, y) => x + y, 0);
+ let t = a;
+ return ws.map((_, i) => {
+ const d = ((b - a) * len[i]) / sum;
+ const out = { start: t, end: t + d };
+ t += d;
+ return out;
+ });
+}
+
+/**
+ * THE RE-VOICED TAKE's TIMES, pure: `plan` (revoicePlan's) with the cuts made (`from`, `to`: the source take's
+ * seconds, as cut), the new piece's length (`seconds`), its speech islands and gain -- the words (before the span as
+ * they were, the new ones timed in the piece and `estimated`, after it moved by the length difference), the parts
+ * (the one holding the span grown or shrunk, its own file no longer it, its text saying --say; later ones moved), the
+ * script, the take's length, `delta`, and the steps.
+ */
+export function revoiceFinish(plan, { from, to, seconds, islands = [], gain = 0 }) {
+ const t = plan.take;
+ const delta = seconds - (to - from);
+ const ws = plan.say.split(/\s+/).filter(Boolean);
+ const times = pieceWordTimes(ws, seconds, islands);
+ const before = t.words.slice(0, plan.first).map((w) => ({ ...w, start: r3(Math.min(w.start, from)), end: r3(Math.min(w.end, from)) }));
+ const added = ws.map((w, i) => ({ w, start: r3(from + times[i].start), end: r3(from + times[i].end), estimated: true }));
+ const after = t.words.slice(plan.last + 1).map((w) => ({ ...w, start: r3(Math.max(w.start, to) + delta), end: r3(Math.max(w.end, to) + delta) }));
+ const words = [...before, ...added, ...after];
+ // The phrase's words, the n-th time in the part (and in the script) the words before it say.
+ const want = t.words.slice(plan.first, plan.last + 1).map((w) => w.w);
+ const key = want.map(normWord).join(" ");
+ const seenIn = (lo) => {
+ let n = 0;
+ for (let i = lo; i + want.length <= plan.first; i += 1) if (t.words.slice(i, i + want.length).map((w) => normWord(w.w)).join(" ") === key) n += 1;
+ return n;
+ };
+ const parts = Array.isArray(t.parts)
+ ? t.parts.map((p, j) => {
+ if (j < plan.part || !fin(p?.start) || !fin(p?.seconds)) return p;
+ if (j > plan.part) return { ...p, start: r3(p.start + delta) };
+ const { file: _f, ...rest } = p;
+ const start = Math.min(p.start, from);
+ const end = p.start + p.seconds > to ? p.start + p.seconds + delta : from + seconds;
+ const firstInPart = t.words.findIndex((w) => partAt(t.parts, w.start) === j);
+ const text = replaceNth(p.text, want, seenIn(Math.max(0, firstInPart)), plan.say);
+ return { ...rest, ...(text !== null ? { text } : {}), start: r3(start), seconds: r3(end - start) };
+ })
+ : undefined;
+ const script0 = typeof t.script === "string" ? t.script : null;
+ const script = script0 === null ? undefined : replaceNth(script0, want, seenIn(0), plan.say) ?? script0;
+ const newSeconds = r3((fin(t.seconds) ? t.seconds : to) + delta);
+ const voices = str(t.voice).split("+").filter(Boolean);
+ const takeVoice = voices.length && !voices.includes(plan.voice) && `${t.voice}+${plan.voice}`.length <= 64 ? `${t.voice}+${plan.voice}` : t.voice ?? plan.voice;
+ return {
+ words, parts, script, seconds: newSeconds, delta: r3(delta), takeVoice,
+ steps: [{
+ op: "revoice",
+ revoice: { word: plan.first, count: plan.last - plan.first + 1, words: ws.length, phrase: plan.phrase, say: plan.say, said: plan.said, voice: plan.voice, engine: plan.engine, from: r3(from), to: r3(to), seconds: r3(seconds), gain, xfade: plan.xfade, key: plan.key },
+ ranAt: new Date().toISOString(),
+ }],
+ };
+}
+
+const fileThere = async (f) => !!(await stat(f).catch(() => null))?.isFile();
+
+/**
+ * RE-VOICE a phrase of post item `e`'s picked take: see the head of this file. `ask` (askEditorTts's shape) and
+ * `red` (projectRedaction's) are the tests' to stub. Returns `{ plan, cuts, cached, piece?, finish?, take?, result? }`
+ * -- `cuts: { from, to, moved }` (take seconds), `piece: { seconds, gain, islands }` when it was synthesized or cached.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} e
+ * @param {{ match: string, occurrence?: number, say: string, voice?: string | null, xfade?: number, target?: string | null, dryRun?: boolean,
+ * cut?: { from: number | null, to: number | null } | null, ask?: Function | null, red?: any, render?: any, editor?: any, emit?: (ev: string, f?: any) => void, measure?: any }} o
+ */
+export async function revoiceTake(project, e, o) {
+ const { dryRun = false, ask = null, editor = null, emit = () => {}, measure = undefined } = o;
+ let red = o.red;
+ let render = o.render ?? null;
+ if (red === undefined || render === null) {
+ const { readManifest } = await import("../projects/report.mjs");
+ const manifest = await readManifest(project.dir);
+ render = render ?? manifest?.render ?? {};
+ if (red === undefined) red = await (await import("./postRedaction.mjs")).projectRedaction(project.dir, manifest ?? {});
+ }
+ const plan = revoicePlan(e, { ...o, red, render });
+ const { decodePcm, toMono, quietestCut, speechBounds, speechIslands, speechRms, matchGainDb, withGain, spliceEqualPower, wordsByValleys, writeWav16 } = await import("./audioSplice.mjs");
+ const src = path.join(project.dir, ...str(plan.take.file).split("/"));
+ if (!(await fileThere(src))) throw new RereadError(`${e.id}'s take is not on disk: ${plan.take.file}`);
+ const fmt = await audioFormat(src);
+ const ch = fmt.layout === "stereo" ? 2 : 1;
+ const pcm = await decodePcm(src, { rate: fmt.rate, channels: ch });
+ const mono = toMono(pcm, ch);
+ // Each cut: SET (--splice), or the quietest 10 ms within ±40 ms of the boundary -- and, when that is not quiet, within
+ // ±0.15 s (a nearer quiet preferred). A cut still in speech is said (`warnings`): the timings may be off there.
+ const warnings = [];
+ const speechDb = (t) => {
+ const r = speechRms(mono, fmt.rate, (t - 0.3) * fmt.rate, (t + 0.3) * fmt.rate);
+ return r ? 20 * Math.log10(r) : -Infinity;
+ };
+ const quiet = (q, t) => q.rmsDb <= REVOICE_QUIET.db || q.rmsDb <= speechDb(t) - REVOICE_QUIET.below;
+ const cutAt = (side) => {
+ const set = o.cut?.[side];
+ const nominal = plan.nominal[side];
+ if (fin(set)) {
+ const q = quietestCut(mono, fmt.rate, { lo: set, hi: set, nominal: set });
+ return { ...q, at: r3(set), set: true, wide: false };
+ }
+ const q = quietestCut(mono, fmt.rate, { ...plan.windows[side], nominal });
+ if (quiet(q, q.at)) return { ...q, set: false, wide: false };
+ const w = quietestCut(mono, fmt.rate, { ...plan.wide[side], nominal, perSecondDb: REVOICE_NEAR_DB });
+ const pick = w.rmsDb < q.rmsDb ? { ...w, wide: true } : { ...q, wide: false };
+ if (!quiet(pick, pick.at)) warnings.push(`the cut at the ${side === "from" ? "start" : "end"} (${pick.at.toFixed(3)} s, ${pick.rmsDb} dB) is in speech: the word timings may be off there -- listen to the dry run's span and set it: --splice ${side === "from" ? `<s>-` : `-<s>`}`);
+ return { ...pick, set: false };
+ };
+ const qa = cutAt("from");
+ const qb = cutAt("to");
+ const fromS = Math.round(qa.at * fmt.rate);
+ const toS = Math.max(fromS + 1, Math.round(qb.at * fmt.rate));
+ const cuts = {
+ from: r3(fromS / fmt.rate), to: r3(toS / fmt.rate), moved: { from: qa.moved || qa.set, to: qb.moved || qb.set }, db: { from: qa.rmsDb, to: qb.rmsDb },
+ how: { from: qa.set ? "set" : qa.wide ? "wide" : qa.moved ? "quiet" : "timing", to: qb.set ? "set" : qb.wide ? "wide" : qb.moved ? "quiet" : "timing" }, warnings,
+ };
+ const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/"));
+ const wav = path.join(cacheDir, `${plan.key}.wav`);
+ const cached = await fileThere(wav);
+ // The piece: its silence trimmed, loudness-matched to the speech about the span.
+ const pieceOf = async () => {
+ const raw = await decodePcm(wav, { rate: fmt.rate, channels: ch });
+ const pm = toMono(raw, ch);
+ const { a, b } = speechBounds(pm, fmt.rate, { pad: REVOICE_PAD });
+ const trimmed = raw.slice(a * ch, b * ch);
+ const ctx = Math.round(REVOICE_CONTEXT * fmt.rate);
+ const ra = speechRms(mono, fmt.rate, fromS - ctx, fromS);
+ const rb = speechRms(mono, fmt.rate, toS, toS + ctx);
+ const refs = [ra, rb].filter((x) => fin(x));
+ const ref = refs.length ? Math.sqrt(refs.reduce((s, x) => s + x * x, 0) / refs.length) : null;
+ const gain = matchGainDb(ref, speechRms(toMono(trimmed, ch), fmt.rate, 0, trimmed.length / ch), REVOICE_LIMITS.gainDb);
+ const out = withGain(trimmed, gain);
+ const L = Math.floor(out.length / ch);
+ // Its words: one speech island each, else split at the piece's deepest valleys (a voice that draws its words out).
+ const om = toMono(out, ch);
+ const n = plan.say.split(/\s+/).filter(Boolean).length;
+ const isl = speechIslands(om, fmt.rate);
+ const islands = isl.length === n ? isl : wordsByValleys(om, fmt.rate, n) ?? isl;
+ return { samples: out, seconds: r3(L / fmt.rate), frames: L, gain, islands };
+ };
+ if (dryRun) {
+ const piece = cached ? await pieceOf() : null;
+ return { plan, cuts, cached, ...(piece ? { piece: { seconds: piece.seconds, gain: piece.gain, islands: piece.islands }, finish: revoiceFinish(plan, { from: cuts.from, to: cuts.to, seconds: piece.seconds, islands: piece.islands, gain: piece.gain }) } : {}) };
+ }
+ let jobId = null;
+ if (!cached) {
+ await mkdir(cacheDir, { recursive: true });
+ await writeFile(path.join(cacheDir, `${plan.key}.txt`), plan.said);
+ const askTts = ask ?? (await import("umtool-report-to-video/narrate-via-editor")).askEditorTts;
+ emit("note", { message: `re-voicing "${plan.phrase}" as "${plan.said}" (${plan.engine} · ${plan.voice}): asking the editor…` });
+ try {
+ ({ jobId = null } = (await askTts({ text: plan.said, engine: plan.engine, voice: plan.voice, out: wav }, { ...(editor ? { editor } : {}), emit })) ?? {});
+ } catch (err) {
+ throw new RevoiceError(`"${plan.said}" (${plan.voice}) was not synthesized: ${err instanceof Error ? err.message : err}`);
+ }
+ if (!(await fileThere(wav))) throw new RevoiceError(`the editor's job ${jobId ?? "?"} finished but ${PARTS_CACHE}/${plan.key}.wav is not there`);
+ }
+ const piece = await pieceOf();
+ const xf = Math.round(plan.xfade * fmt.rate);
+ const spliced = spliceEqualPower(pcm, piece.samples, ch, fromS, toS, xf);
+ const finish = revoiceFinish(plan, { from: fromS / fmt.rate, to: toS / fmt.rate, seconds: piece.frames / fmt.rate, islands: piece.islands, gain: piece.gain });
+ const full = { ...plan, ...finish, take: plan.take };
+ const { take, result } = await writeDerivedTake(project, e, full, {
+ op: "revoice", verb: "re-voice", voice: finish.takeVoice, measure,
+ make: async (_src, out) => writeWav16(out, spliced, fmt.rate, ch),
+ });
+ return { plan, cuts, cached, jobId, piece: { seconds: piece.seconds, gain: piece.gain, islands: piece.islands }, finish, take, result };
+}
+
+/** `umtool posts reread <p> <item> --revoice … --say …` (postReread.mjs routes it here): the dry run's plan, or the take made. */
+export async function revoiceCommand(project, e, { revoice, say, voice = null, xfade = null, cut = null, target = null, dryRun = false, json = false, out = (s) => console.log(s) }) {
+ const ask = parseRevoice({ phrase: revoice, say, voice, xfade, cut });
+ const r = await revoiceTake(project, e, { ...ask, target, dryRun, emit: (_ev, f) => !json && f?.message && out(` ${f.message.trim()}`) });
+ const p = r.plan;
+ const span = { first: p.first, last: p.last, phrase: p.phrase, start: p.take.words[p.first].start, end: p.take.words[p.last].end };
+ const was = Number(p.picked.seconds);
+ const change = r.finish ? r.finish.delta : null;
+ if (json) {
+ out(JSON.stringify({
+ ok: true, id: e.id, dryRun, from: takeIdOf(p.take), recut: p.recut, target: p.target, span, cuts: r.cuts, say: p.say, said: p.said, voice: p.voice, engine: p.engine,
+ key: p.key, cached: r.cached, xfade: p.xfade, piece: r.piece ?? null, change, seconds: r.take?.seconds ?? r.finish?.seconds ?? null, was, fixedAt: p.fixedAt,
+ take: r.take ?? null, token: r.result?.token ?? null,
+ }, null, 2));
+ return 0;
+ }
+ out(`${dryRun ? "would re-voice" : "re-voiced"} ${e.id}'s take${p.recut ? `, cut again from ${takeIdOf(p.take)} (one splice)` : ` (${takeIdOf(p.take)})`}: "${p.phrase}" -- words ${p.first + 1}-${p.last + 1}, ${span.start.toFixed(2)}-${span.end.toFixed(2)} s`);
+ const how = { set: "set by --splice", wide: "the quiet found wider", quiet: "the quietest 10 ms by it", timing: "the timing's own" };
+ out(` cut ${r.cuts.from.toFixed(3)}-${r.cuts.to.toFixed(3)} s (${(r.cuts.to - r.cuts.from).toFixed(3)} s): start ${r.cuts.db.from} dB, ${how[r.cuts.how.from]}; end ${r.cuts.db.to} dB, ${how[r.cuts.how.to]}`);
+ for (const w of r.cuts.warnings) out(` warning: ${w}`);
+ out(` says "${p.said}"${p.said !== p.say ? ` (written "${p.say}")` : ""} in ${p.voice} (${p.engine}), ${p.xfade} s equal-power crossfades`);
+ if (r.piece) out(` the new piece: ${r.piece.seconds.toFixed(2)} s, gain ${r.piece.gain >= 0 ? "+" : ""}${r.piece.gain.toFixed(1)} dB -- the take ${(r.take?.seconds ?? r.finish.seconds).toFixed(2)} s (was ${was.toFixed(2)} s, ${change >= 0 ? "+" : ""}${change.toFixed(3)} s)`);
+ else out(` not synthesized yet (no TTS in a dry run): the length changes by the new piece's length - ${(r.cuts.to - r.cuts.from).toFixed(3)} s`);
+ if (p.fixedAt) out(` note: ${p.fixedAt} effect(s) of this item have a set second (at) -- they do not move with the words; check them`);
+ if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo); the new words' timings are estimated (posts narrate … --words refines them)`);
+ return 0;
+}
diff --git a/umtool/lib/report/postRevoice.test.mjs b/umtool/lib/report/postRevoice.test.mjs
@@ -0,0 +1,288 @@
+// postRevoice.mjs + audioSplice.mjs: ONE PHRASE OF AN APPROVED READ RE-VOICED --
+// the ask parsed, the span found (#n, a target's words), the cut at the quietest
+// 10 ms near each boundary, the splice's length exact and its joins equal-power,
+// the loudness match, the new words timed from the piece's speech, everything
+// after moved on, the refusals; the take written (TTS stubbed: the parts cache or
+// a fake editor) and picked in ONE write, undoable; the CLI.
+import assert from "node:assert/strict";
+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 { wordZoomTimes } from "umtool-report-to-video/word-zoom";
+import { decodePcm, joinStepDb, matchGainDb, quietestCut, speechIslands, spliceEqualPower, wordsByValleys, writeWav16 } from "./audioSplice.mjs";
+import { PauseError } from "./postPause.mjs";
+import { RereadError } from "./postReread.mjs";
+import { RevoiceError, parseRevoice, pieceWordTimes, replaceNth, revoiceFinish, revoicePlan, revoiceTake } from "./postRevoice.mjs";
+import { PARTS_CACHE } from "./postThreadRead.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { undoStructural } from "./manifest.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-revoice-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const REPORTS = path.join(ROOT, "reports");
+const RATE = 24000;
+
+// "I'll give you 45 seconds. 20, 10, 4, 0. Alright." (part 1, zac) then "Who are you? 4 more." (part 2, leo).
+const TEXT = "I'll give you 45 seconds. 20, 10, 4, 0. Alright.\n\nWho are you? 4 more.";
+const words = () => [
+ { w: "I'll", start: 0.1, end: 0.3 }, { w: "give", start: 0.35, end: 0.55 }, { w: "you", start: 0.6, end: 0.7 }, { w: "45", start: 0.75, end: 1.2 }, { w: "seconds.", start: 1.25, end: 1.7 },
+ { w: "20,", start: 2.0, end: 2.3 }, { w: "10,", start: 2.4, end: 2.6 }, { w: "4,", start: 2.62, end: 2.8 }, { w: "0.", start: 3.1, end: 3.4 }, { w: "Alright.", start: 3.6, end: 4.0 },
+ { w: "Who", start: 4.6, end: 4.8 }, { w: "are", start: 4.85, end: 5.0 }, { w: "you?", start: 5.05, end: 5.3 }, { w: "4", start: 5.5, end: 5.7 }, { w: "more.", start: 5.75, end: 6.1 },
+];
+const parts = () => [
+ { n: 1, para: 0, text: "I'll give you 45 seconds. 20, 10, 4, 0. Alright.", start: 0, seconds: 4.2, file: "narration/parts-cache/a.wav", role: "post", voice: "zac" },
+ { n: 2, para: 1, text: "Who are you? 4 more.", start: 4.5, seconds: 1.8, role: "post", voice: "leo" },
+];
+const item = (o = {}) => ({
+ type: "post", id: "p-1", post: "subj-x/1", platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: TEXT,
+ narration: { script: TEXT, takes: [{ file: "narration/posts/1/take-2.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: 6.4, slurs: "said", script: TEXT, words: words(), parts: parts() }], pick: 0 },
+ ...o,
+});
+const ASK = { match: "20 10 4 0", occurrence: 1, say: "20... 10... 4... 0..." };
+
+/** A tone (amplitude `amp`) inside each span, near-silence elsewhere: a read whose words are where the timings say. */
+function tones(seconds, spans, { amp = 0.2, freq = 220 } = {}) {
+ const x = new Float32Array(Math.round(seconds * RATE));
+ for (let i = 0; i < x.length; i += 1) {
+ const t = i / RATE;
+ const on = spans.some(([a, b]) => t >= a && t < b);
+ x[i] = (on ? amp : 0.0005) * Math.sin((2 * Math.PI * freq * i) / RATE);
+ }
+ return x;
+}
+
+test("THE ASK: the phrase and #n, --say, --voice (auto: the piece's own), --xfade 0-0.2 (default 0.03); the refusals are usage errors", () => {
+ assert.deepEqual(parseRevoice({ phrase: "20 10 4 0", say: " 20... 10... " }), { match: "20 10 4 0", occurrence: 1, say: "20... 10...", voice: null, xfade: 0.03, cut: null });
+ assert.deepEqual(parseRevoice({ phrase: "4#2", say: "four", voice: "auto", xfade: "0.05" }), { match: "4", occurrence: 2, say: "four", voice: null, xfade: 0.05, cut: null });
+ // --splice: the cuts set by hand (either side), the take's seconds.
+ assert.deepEqual(parseRevoice({ phrase: "4", say: "four", cut: "65.03-66" }).cut, { from: 65.03, to: 66 });
+ assert.deepEqual(parseRevoice({ phrase: "4", say: "four", cut: "-66.2" }).cut, { from: null, to: 66.2 });
+ for (const bad of ["x", "-", "3-2"]) assert.throws(() => parseRevoice({ phrase: "4", say: "four", cut: bad }), RereadError, bad);
+ assert.equal(parseRevoice({ phrase: "4", say: "four", voice: "tara" }).voice, "tara");
+ for (const bad of [{ phrase: "", say: "x" }, { phrase: "20", say: "" }, { phrase: "20", say: "..." }, { phrase: "20#0", say: "x" }, { phrase: "20", say: "x", xfade: "0.5" }, { phrase: "20", say: "x", voice: "a/b" }, { phrase: "20", say: "x".repeat(401) }]) {
+ assert.throws(() => parseRevoice(bad), RereadError, JSON.stringify(bad));
+ }
+});
+
+test("THE SPAN: found as a pause finds a word (#n, a target's words); the boundaries in the quiet between words, each with a ±40 ms window; the voice the part was read in, the root take's engine", () => {
+ const p = revoicePlan(item(), ASK);
+ assert.deepEqual([p.first, p.last, p.phrase, p.part, p.voice, p.engine], [5, 8, "20, 10, 4, 0.", 0, "zac", "orpheus"]);
+ assert.deepEqual(p.nominal, { from: 1.9, to: 3.5 });
+ assert.deepEqual(p.windows, { from: { lo: 1.86, hi: 1.94 }, to: { lo: 3.46, hi: 3.54 } });
+ // The wide windows (no quiet within 40 ms): 0.15 s, never inside the phrase as timed nor past the words about it.
+ assert.deepEqual(p.wide, { from: { lo: 1.75, hi: 2 }, to: { lo: 3.4, hi: 3.65 } });
+ assert.match(p.key, /^[0-9a-f]{40}$/);
+ assert.equal(revoicePlan(item(), { ...ASK, voice: "tara" }).voice, "tara");
+ assert.equal(revoicePlan(item(), { match: "4", occurrence: 2, say: "four" }).first, 13);
+ // Run together (no quiet between): the boundary is the word's edge, the window never past either word's middle.
+ const e = item();
+ e.narration.takes[0].words[7] = { w: "4,", start: 2.6, end: 2.8 };
+ assert.deepEqual(revoicePlan(e, { match: "4", say: "four" }).windows.from, { lo: 2.56, hi: 2.64 });
+ // A lexicon (the redaction's `say`): what the voice says, and its key.
+ const red = { say: [{ word: "seconds", say: "secs" }] };
+ const q = revoicePlan(item(), { match: "45 seconds", say: "45 seconds", red });
+ assert.equal(q.said, "45 secs");
+ assert.notEqual(q.key, revoicePlan(item(), { match: "45 seconds", say: "45 seconds" }).key);
+});
+
+test("THE REFUSALS (exit 1): no word timings names posts narrate --words; the phrase not read; across two parts; a recorded read", () => {
+ const nw = item();
+ delete nw.narration.takes[0].words;
+ assert.throws(() => revoicePlan(nw, ASK), (err) => err instanceof RevoiceError && /no word timings.*umtool posts narrate <p> p-1 --words/.test(err.message));
+ assert.throws(() => revoicePlan(item(), { ...ASK, match: "twenty" }), (err) => err instanceof PauseError && /--revoice "twenty": no such word/.test(err.message));
+ assert.throws(() => revoicePlan(item(), { ...ASK, match: "alright who" }), /runs across two parts/);
+ const rec = item();
+ rec.narration.takes[0].engine = "recorded";
+ assert.throws(() => revoicePlan(rec, ASK), /RECORDED read/);
+ assert.throws(() => revoicePlan(item(), { ...ASK, target: "quoted" }), /reads no quoted/);
+});
+
+test("THE QUIET CUT on a synthetic signal: the lowest-energy 10 ms in the window, kept at the timing when nothing is clearly quieter", () => {
+ // Speech 0-1 s, a 20 ms dip at 1.015-1.035, speech on.
+ const x = tones(2, [[0, 1.015], [1.035, 2]]);
+ const q = quietestCut(x, RATE, { lo: 0.96, hi: 1.04, nominal: 1 });
+ assert.equal(q.moved, true);
+ assert.ok(Math.abs(q.at - 1.025) <= 0.006, `at ${q.at}`);
+ assert.ok(q.rmsDb < q.nominalDb - 20, `${q.rmsDb} vs ${q.nominalDb}`);
+ // A steady tone: no window clearly quieter -- the timing's own.
+ assert.deepEqual([quietestCut(tones(2, [[0, 2]]), RATE, { lo: 0.96, hi: 1.04, nominal: 1 }).at, quietestCut(tones(2, [[0, 2]]), RATE, { lo: 0.96, hi: 1.04, nominal: 1 }).moved], [1, false]);
+});
+
+test("TIMINGS OFF (the alignment late, the words run together): no quiet within 40 ms -- the cut found in the quiet up to 0.15 s off, never in a gap inside the phrase; still in speech, a warning naming --splice; --splice sets a cut", async () => {
+ // The read's words sound 0.2 s EARLIER than timed; "0." runs on into "Alright." with no quiet.
+ const e = item();
+ const p = await project("off", [e]);
+ const shift = (w) => [w.start - 0.2, w.end - 0.2];
+ const spans = words().map(shift);
+ spans[8] = [2.9, 3.6]; // "0." run into "Alright."
+ await writeWav16(path.join(p.dir, "narration", "posts", "1", "take-2.orpheus-thread.wav"), tones(6.4, spans), RATE, 1);
+ const r = await revoiceTake(p, e, { match: "20 10 4", say: "twenty ten four", red: null, dryRun: true });
+ // The start: the quiet before "20," (1.5-1.8 as sounded), not the gap between "20," and "10," (2.1-2.2, inside the phrase).
+ assert.equal(r.cuts.how.from, "wide");
+ assert.ok(r.cuts.from >= 1.75 && r.cuts.from <= 1.8, `start ${r.cuts.from}`);
+ assert.deepEqual(r.cuts.warnings, []);
+ // The end: in the quiet between "4," (to 2.6) and "0." (from 2.9).
+ assert.ok(r.cuts.to >= 2.6 && r.cuts.to <= 2.9, `end ${r.cuts.to} (${r.cuts.how.to})`);
+ // "0." to "Alright." run together: the end in speech -- warned.
+ const q = await revoiceTake(p, e, { match: "0", say: "zero", red: null, dryRun: true });
+ assert.equal(q.cuts.warnings.length, 1, JSON.stringify(q.cuts));
+ assert.match(q.cuts.warnings[0], /the cut at the end .* is in speech.*--splice -<s>/);
+ const set = await revoiceTake(p, e, { match: "0", say: "zero", red: null, dryRun: true, cut: { from: 2.95, to: 3.2 } });
+ assert.deepEqual([set.cuts.from, set.cuts.to, set.cuts.how.from, set.cuts.how.to, set.cuts.warnings.length], [2.95, 3.2, "set", "set", 0]);
+});
+
+test("THE SPLICE: its length the source's - the span + the piece, exactly; equal-power joins (cos/sin), the source untouched outside them; the gain clamped to ±6 dB", () => {
+ const src = new Float32Array(1000).fill(0.5);
+ const piece = new Float32Array(300).fill(-0.5);
+ const out = spliceEqualPower(src, piece, 1, 400, 600, 40);
+ assert.equal(out.length, 1000 - 200 + 300);
+ assert.equal(out[379], 0.5, "before the first join: the source");
+ assert.ok(Math.abs(out[400] - (0.5 * Math.cos(Math.PI / 4) - 0.5 * Math.sin(Math.PI / 4))) < 1e-6, "the join's middle: half power each");
+ assert.equal(out[500], -0.5, "the piece");
+ assert.equal(out[720], 0.5, "after the second join: the source from `to` on");
+ // Stereo: frames, not samples.
+ assert.equal(spliceEqualPower(new Float32Array(2000), new Float32Array(600), 2, 400, 600, 40).length, (1000 - 200 + 300) * 2);
+ assert.equal(matchGainDb(0.1, 0.05), 6);
+ assert.equal(matchGainDb(0.01, 0.5), -6);
+ assert.equal(matchGainDb(0.1, 0.1), 0);
+ assert.equal(matchGainDb(null, 0.1), 0);
+});
+
+test("THE NEW WORDS: one speech island a word when they count the same, else split at the piece's deepest valleys, else shared out by length; marked estimated", () => {
+ const isl = speechIslands(tones(2, [[0.1, 0.3], [0.6, 0.8], [1.1, 1.3], [1.6, 1.8]]), RATE);
+ assert.equal(isl.length, 4);
+ assert.ok(Math.abs(isl[1].start - 0.6) <= 0.011 && Math.abs(isl[1].end - 0.8) <= 0.011, JSON.stringify(isl[1]));
+ assert.deepEqual(pieceWordTimes(["a", "b"], 2, [{ start: 0.1, end: 0.5 }, { start: 1, end: 1.5 }]), [{ start: 0.1, end: 0.5 }, { start: 1, end: 1.5 }]);
+ // A voice that draws its words out: two islands for four words -- split at the deepest valleys.
+ const drawn = tones(2.4, [[0.1, 0.5], [0.6, 1.2], [1.4, 2.3]]);
+ for (let i = Math.round(1.8 * RATE); i < Math.round(1.84 * RATE); i += 1) drawn[i] *= 0.05;
+ const v = wordsByValleys(drawn, RATE, 4);
+ assert.equal(v.length, 4);
+ assert.deepEqual(v.map((x) => Math.round(x.end * 10) / 10), [0.5, 1.2, 1.8, 2.3]);
+ assert.deepEqual(wordsByValleys(drawn, RATE, 1), [{ start: 0.1, end: 2.3 }], "one word: the speech's extent");
+ assert.equal(wordsByValleys(new Float32Array(RATE), RATE, 2), null, "no speech");
+ const spread = pieceWordTimes(["ab", "abcd"], 3, []);
+ assert.deepEqual(spread.map((x) => [x.start, x.end]), [[0, 1], [1, 3]]);
+});
+
+test("WHAT MOVES: the words after by the length change, the part holding it grows (its file dropped, its text and the script saying --say), later parts moved; a zoom stays on its word", () => {
+ const e = item({ fx: [{ kind: "word-zoom", match: "Who" }] });
+ const p = revoicePlan(e, ASK);
+ const f = revoiceFinish(p, { from: 1.9, to: 3.5, seconds: 2.4, islands: [{ start: 0.03, end: 0.3 }, { start: 0.7, end: 0.95 }, { start: 1.3, end: 1.5 }, { start: 1.9, end: 2.35 }], gain: 1.5 });
+ assert.equal(f.delta, 0.8);
+ assert.equal(f.seconds, 7.2);
+ assert.equal(f.words.length, 15);
+ assert.deepEqual(f.words.slice(4, 10).map((w) => [w.w, w.start, w.end, w.estimated ?? false]), [["seconds.", 1.25, 1.7, false], ["20...", 1.93, 2.2, true], ["10...", 2.6, 2.85, true], ["4...", 3.2, 3.4, true], ["0...", 3.8, 4.25, true], ["Alright.", 4.4, 4.8, false]]);
+ assert.deepEqual(f.parts.map((x) => [x.start, x.seconds, x.file ?? null, x.text]), [[0, 5, null, "I'll give you 45 seconds. 20... 10... 4... 0... Alright."], [5.3, 1.8, null, "Who are you? 4 more."]]);
+ assert.equal(f.script, "I'll give you 45 seconds. 20... 10... 4... 0... Alright.\n\nWho are you? 4 more.");
+ assert.equal(f.steps[0].op, "revoice");
+ assert.deepEqual(Object.keys(f.steps[0].revoice).sort(), ["count", "engine", "from", "gain", "key", "phrase", "said", "say", "seconds", "to", "voice", "word", "words", "xfade"]);
+ const t = { file: "narration/posts/1/take-3.revoice-orpheus.wav", engine: "derived", voice: f.takeVoice, seconds: f.seconds, source: { kind: "take", from: "take-2.orpheus-thread" }, steps: f.steps, words: f.words, parts: f.parts, script: f.script };
+ const e2 = { ...e, narration: { ...e.narration, takes: [...e.narration.takes, t], pick: 1 } };
+ assert.deepEqual(validatePostItem(e2), []);
+ assert.ok(Math.abs(wordZoomTimes(e2)[0].t - wordZoomTimes(e)[0].t - 0.8) < 0.01, "the zoom on Who moved with its word");
+ // The validator: a bad re-voice record, a word's estimated not true.
+ const bad = { ...e2, narration: { ...e2.narration, takes: [e2.narration.takes[0], { ...t, steps: [{ op: "revoice", revoice: { word: 1, count: 0, from: 2, to: 1, seconds: 1, say: "x", voice: "zac" } }], words: [{ w: "a", start: 0, end: 1, estimated: false }] }] } };
+ const errs = validatePostItem(bad);
+ assert.equal(errs.filter((x) => /revoice must be/.test(x)).length, 1, errs.join("\n"));
+ assert.equal(errs.filter((x) => /words\[0\]/.test(x)).length, 1, errs.join("\n"));
+});
+
+async function project(name, timeline) {
+ const dir = path.join(REPORTS, name);
+ await mkdir(path.join(dir, "narration", "posts", "1"), { recursive: true });
+ // The read: a tone in each word's span, near-silence between.
+ await writeWav16(path.join(dir, "narration", "posts", "1", "take-2.orpheus-thread.wav"), tones(6.4, words().map((w) => [w.start, w.end])), RATE, 1);
+ 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"));
+/** The fake editor's voice: four bursts, 0.2 s of silence before them, quieter than the read (the gain brings it up). */
+const fakeVoice = () => tones(2, [[0.2, 0.4], [0.7, 0.9], [1.2, 1.4], [1.7, 1.9]], { amp: 0.1, freq: 262 });
+
+test("RE-VOICED: the editor asked for --say only (the part's voice, the engine), the piece cached, trimmed and gained; the take's length old - cut + piece, a derived take picked in ONE write, undoable", async () => {
+ const p = await project("revoice", [item()]);
+ const e = (await manifest(p)).timeline[0];
+ const asked = [];
+ const ask = async (body) => {
+ asked.push(body);
+ await writeWav16(body.out, fakeVoice(), 48000 / 2, 1);
+ return { jobId: "stub-1", result: { wav: body.out } };
+ };
+ const dry = await revoiceTake(p, e, { ...ASK, dryRun: true, ask, red: null });
+ assert.equal(asked.length, 0, "a dry run asks nothing");
+ assert.equal(dry.cached, false);
+ assert.deepEqual([dry.cuts.from, dry.cuts.to], [1.9, 3.5]);
+ const r = await revoiceTake(p, e, { ...ASK, ask, red: null });
+ assert.deepEqual(asked.map((b) => [b.text, b.engine, b.voice, path.relative(p.dir, b.out)]), [["20... 10... 4... 0...", "orpheus", "zac", `${PARTS_CACHE}/${r.plan.key}.wav`]]);
+ assert.match(r.take.file, /^narration\/posts\/1\/take-3\.revoice-orpheus\.wav$/);
+ // The piece trimmed to its speech (0.2-1.9 s) + 30 ms either side; gained up (the read is twice as loud), at most +6 dB.
+ assert.ok(Math.abs(r.piece.seconds - 1.76) <= 0.02, `piece ${r.piece.seconds}`);
+ assert.ok(r.piece.gain > 5 && r.piece.gain <= 6, `gain ${r.piece.gain}`);
+ const pcm = await decodePcm(path.join(p.dir, r.take.file), { rate: RATE, channels: 1 });
+ const expect = Math.round(6.4 * RATE) - (Math.round(3.5 * RATE) - Math.round(1.9 * RATE)) + Math.round(r.piece.seconds * RATE);
+ assert.ok(Math.abs(pcm.length - expect) <= 2, `${pcm.length} samples, want ${expect}`);
+ // The joins land in quiet: no step there.
+ assert.ok(joinStepDb(pcm, RATE, 1.9) < 3 && joinStepDb(pcm, RATE, 1.9 + r.piece.seconds) < 3);
+ const now = (await manifest(p)).timeline[0];
+ assert.equal(now.narration.pick, 1);
+ const t = now.narration.takes[1];
+ assert.deepEqual([t.engine, t.source, t.steps[0].op, t.slurs, t.voice], ["derived", { kind: "take", from: "take-2.orpheus-thread" }, "revoice", "said", "leo+zac"]);
+ assert.deepEqual(t.words.slice(5, 9).map((w) => w.w), ["20...", "10...", "4...", "0..."]);
+ assert.ok(t.words.slice(5, 9).every((w) => w.estimated === true));
+ assert.deepEqual(validatePostItem(now), []);
+ // Asked again (the same words in the same voice): the parts cache has it -- the dry run knows its length, nothing asked.
+ const again = await revoiceTake(p, e, { ...ASK, ask, red: null, dryRun: true });
+ assert.deepEqual([again.cached, asked.length, again.finish.delta], [true, 1, r.finish.delta]);
+ await undoStructural(p.dir);
+ assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "undone");
+});
+
+test("A RE-VOICE AGAIN of the words a re-voice put in is cut from the take before it (one splice)", async () => {
+ const p = await project("again", [item()]);
+ const ask = async (body) => {
+ await writeWav16(body.out, fakeVoice(), RATE, 1);
+ return { jobId: "stub" };
+ };
+ await revoiceTake(p, (await manifest(p)).timeline[0], { ...ASK, ask, red: null });
+ const e = (await manifest(p)).timeline[0];
+ const r = await revoiceTake(p, e, { match: "20 10 4 0", say: "20, 10, 4, 0", ask, red: null, dryRun: true });
+ assert.equal(r.plan.recut, true);
+ assert.equal(r.plan.take.file, "narration/posts/1/take-2.orpheus-thread.wav");
+ assert.deepEqual([r.plan.first, r.plan.last], [5, 8]);
+});
+
+test("THE CLI: posts reread --revoice --say --dry-run writes nothing (no TTS), --json the plan; a piece in the parts cache is applied with no ask; the refusals' exits", async () => {
+ const p = await project("cli", [item()]);
+ const cli = async (args) => {
+ const lines = [];
+ const errs = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) });
+ return { code, out: lines.join("\n"), err: errs.join("\n") };
+ };
+ const dry = await cli(["reread", "cli", "p-1", "--revoice", "20 10 4 0", "--say", "20... 10... 4... 0...", "--dry-run"]);
+ assert.equal(dry.code, 0, dry.err);
+ assert.match(dry.out, /would re-voice p-1's take \(take-2\.orpheus-thread\): "20, 10, 4, 0\." -- words 6-9, 2\.00-3\.40 s/);
+ assert.match(dry.out, /cut 1\.900-3\.500 s/);
+ assert.match(dry.out, /says "20\.\.\. 10\.\.\. 4\.\.\. 0\.\.\." in zac \(orpheus\), 0\.03 s equal-power crossfades/);
+ assert.match(dry.out, /not synthesized yet/);
+ assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "a dry run writes nothing");
+ const js = JSON.parse((await cli(["reread", "cli", "p-1", "--revoice", "20 10 4 0", "--say", "20... 10... 4... 0...", "--dry-run", "--json"])).out);
+ assert.deepEqual([js.ok, js.dryRun, js.span.first, js.span.last, js.voice, js.cached, js.change, js.take], [true, true, 5, 8, "zac", false, null, null]);
+ // The piece put in the parts cache by hand (a read made it before): applied, nothing asked of an editor.
+ await mkdir(path.join(p.dir, PARTS_CACHE), { recursive: true });
+ await writeWav16(path.join(p.dir, PARTS_CACHE, `${js.key}.wav`), fakeVoice(), RATE, 1);
+ const dry2 = await cli(["reread", "cli", "p-1", "--revoice", "20 10 4 0", "--say", "20... 10... 4... 0...", "--dry-run"]);
+ assert.match(dry2.out, /the new piece: 1\.7\d s, gain \+\d\.\d dB -- the take 6\.\d\d s \(was 6\.40 s, \+0\.1\d\d s\)/);
+ const go = await cli(["reread", "cli", "p-1", "--revoice", "20 10 4 0", "--say", "20... 10... 4... 0..."]);
+ assert.equal(go.code, 0, go.err);
+ assert.match(go.out, /take-3\.revoice-orpheus\.wav -- picked/);
+ assert.equal((await manifest(p)).timeline[0].narration.pick, 1);
+ assert.equal((await cli(["reread", "cli", "p-1", "--revoice", "twenty", "--say", "x"])).code, 1, "not read: exit 1");
+ assert.equal((await cli(["reread", "cli", "p-1", "--revoice", "20"])).code, 2, "no --say: usage");
+ assert.equal((await cli(["reread", "cli", "p-1", "--say", "x"])).code, 2, "--say alone: usage");
+ assert.equal((await cli(["reread", "cli", "p-1", "--revoice", "20", "--say", "x", "--pause", "20=0.4"])).code, 2, "a re-voice goes alone");
+ assert.equal((await cli(["reread", "cli", "p-1", "--pause", "20=0.4", "--xfade", "0.1"])).code, 2, "--xfade goes with --revoice");
+});
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -55,6 +55,8 @@ const REREAD_LINES = [
" 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.",
+ " --pause \"20=0.45\": silence after words (no TTS). --revoice \"20 10 4 0\" --say \"20... 10... 4... 0...\": ONE PHRASE re-voiced",
+ " (TTS for that phrase only), spliced in at quiet cuts with crossfades, the rest of the read untouched (posts reread --help).",
];
// `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block.
@@ -183,7 +185,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(["--in-take", "--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", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--parents", "--skip-parent", "--voice-for", "--item"]);
+const VALUED = new Set(["--in-take", "--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", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item"]);
/** The valued flags that may be given more than once (each value kept, in order). */
const MULTI = new Set(["--skip-parent", "--voice-for"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
@@ -489,9 +491,11 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
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,
- pause: flags.has("--pause") ? str("--pause") : null, target: flags.has("--target") ? str("--target") : null, dryRun, json, out,
+ pause: flags.has("--pause") ? str("--pause") : null, target: flags.has("--target") ? str("--target") : null,
+ revoice: flags.has("--revoice") ? str("--revoice") : null, say: flags.has("--say") ? str("--say") : null,
+ voice: flags.has("--voice") ? str("--voice") : null, xfade: flags.has("--xfade") ? str("--xfade") : null, cut: flags.has("--splice") ? str("--splice") : null, dryRun, json, out,
}).catch((e) => {
- // A pause the plan cannot make (PauseError: no word timings, the word not read) is exit 1; a malformed ask, 2.
+ // A pause or re-voice the plan cannot make (PauseError, RevoiceError: no word timings, the word not read, TTS failed) is exit 1; a malformed ask, 2.
throw e?.name === "RereadError" || e?.name === "YellError" ? new CliError(e.message) : e;
});
}
diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs
@@ -62,9 +62,10 @@ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]);
* 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); `pause` -- silence put in after words named,
- * everything after moved on (lib/report/postPause.mjs).
+ * everything after moved on (lib/report/postPause.mjs); `revoice` -- ONE phrase of it synthesized again (the editor's
+ * TTS, that phrase only) and spliced in its place, the rest of the read untouched (lib/report/postRevoice.mjs).
*/
-export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell", "pause"]);
+export const POST_LOCAL_OPS = Object.freeze(["rejoin", "tempo", "yell", "pause", "revoice"]);
/** The editor's op route for each. */
export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" });
@@ -189,7 +190,7 @@ 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", "lexicon", "read"]);
-const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses"]);
+const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop", "tempo", "spans", "pauses", "revoice"]);
// `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's.
// `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"]);
@@ -647,9 +648,10 @@ export function validatePostNarration(e) {
if (t.words !== undefined) {
// Its script's words, timed in take seconds (the editor's transcription, aligned: word-zoom.mjs scriptWordTimes).
const ws = t.words;
- const bad = !Array.isArray(ws) || ws.length > 20000 ? -2 : ws.findIndex((x) => !isObj(x) || typeof x.w !== "string" || !fin(x.start) || !fin(x.end) || x.start < 0 || x.end < x.start || Object.keys(x).some((kk) => kk !== "w" && kk !== "start" && kk !== "end"));
+ // `estimated: true`: a word a re-voice put in, timed from its piece's sound, not aligned (a later --words refines it).
+ const bad = !Array.isArray(ws) || ws.length > 20000 ? -2 : ws.findIndex((x) => !isObj(x) || typeof x.w !== "string" || !fin(x.start) || !fin(x.end) || x.start < 0 || x.end < x.start || (x.estimated !== undefined && x.estimated !== true) || Object.keys(x).some((kk) => kk !== "w" && kk !== "start" && kk !== "end" && kk !== "estimated"));
if (bad === -2) errors.push(`${tw}.words must be a list of { w, start, end } (its words, timed; at most 20000)`);
- else if (bad >= 0) errors.push(`${tw}.words[${bad}] must be { w, start, end } (take seconds, end ≥ start)`);
+ else if (bad >= 0) errors.push(`${tw}.words[${bad}] must be { w, start, end, estimated? } (take seconds, end ≥ start)`);
}
if (t.steps !== undefined) {
if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`);
@@ -664,6 +666,17 @@ export function validatePostNarration(e) {
// 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)`);
// A pause step's record: each pause, after word <word> (its index in the take's words), cut at <at> (the source take's seconds).
+ // A re-voice's record: the words it replaced (from word <word>, <count> of them: <phrase>), what it said instead, in
+ // which voice, the source take's seconds cut out [from, to), the new piece's length, its gain and crossfade.
+ if (st.revoice !== undefined) {
+ const rv = st.revoice;
+ const ok = isObj(rv) && Number.isInteger(rv.word) && rv.word >= 0 && Number.isInteger(rv.count) && rv.count >= 1 && fin(rv.from) && fin(rv.to) && rv.from >= 0 && rv.to > rv.from &&
+ fin(rv.seconds) && rv.seconds > 0 && rv.seconds <= 60 && typeof rv.say === "string" && rv.say.length <= 2000 && (rv.phrase === undefined || typeof rv.phrase === "string") &&
+ (rv.said === undefined || typeof rv.said === "string") && typeof rv.voice === "string" && VOICE_RE.test(rv.voice) && (rv.engine === undefined || typeof rv.engine === "string") &&
+ (rv.gain === undefined || numIn(rv.gain, [-6, 6])) && (rv.xfade === undefined || numIn(rv.xfade, [0, 0.2])) && (rv.key === undefined || typeof rv.key === "string") &&
+ (rv.words === undefined || (Number.isInteger(rv.words) && rv.words >= 0));
+ if (!ok) errors.push(`${tw}.steps[${k}].revoice must be {word, count, phrase, say, said, voice, engine, from, to, seconds, gain (±6 dB), xfade (0–0.2 s)}`);
+ }
if (st.pauses !== undefined && !(Array.isArray(st.pauses) && st.pauses.length <= 200 && st.pauses.every((x) => isObj(x) && Number.isInteger(x.word) && x.word >= 0 && fin(x.at) && x.at >= 0 && numIn(x.seconds, [0.05, 3]) && (x.w === undefined || typeof x.w === "string")))) errors.push(`${tw}.steps[${k}].pauses must be a list of {word, w, at, seconds} (seconds 0.05–3)`);
}
});