// 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
- --revoice "[#n]" --say ""
// [--target ] [--voice |auto] [--xfade 0.03] [--dry-run] [--json] [--in-take ]
//
// 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
- --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/.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" (# 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}: # 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 "" (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}: - 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(`(? 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} 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
${entry.id} --words (+ --in-take 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 partSpeed = parts[part]?.speed ?? (parts.length ? null : take.speed ?? null);
const speed = typeof partSpeed === "number" && Number.isFinite(partSpeed) && partSpeed !== 1 && engine !== "orpheus" ? partSpeed : null;
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,
// The speed the part it sits in was synthesized at (its character's preset's, or the read's --speed): the phrase
// put in is asked at it too, so it does not sound slower or faster than the words around it.
say, said: spoken.text, lexicon: spoken.lexicon, voice: v, engine, ...(speed !== null ? { speed } : {}), key: partKey(engine, v, spoken.text, speed), 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} 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" ? `-` : `-`}`);
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, ...(typeof plan.speed === "number" ? { speed: plan.speed } : {}) }, { ...(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 - --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;
}