// 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)) }; }); }