Archilyzer · Source

archilyzer

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

commit b0251c8609e57e61acd7f9040f69f453c6502892
parent 9ae432d440e35a18fdef9b70fb4172fd481c8e93
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu,  5 Nov 2026 12:14:30 -0500

umtool: a pause's cut moves to the quietest 10 ms its word allows, and each side of the silence is faded 10 ms

lib/report/audioSplice.mjs: sample-level helpers for edits on an approved read (decode/encode PCM, the quietest
cut near a boundary, speech level, speech islands, an equal-power splice, the join-step check). posts reread
--pause now looks for the quiet from 40 ms before the word's timed end up to the next word (or 0.1 s; +-40 ms when
the timings run together) and moves the cut there when it is clearly (~3 dB) quieter than the timing's own; the
ffmpeg graph fades each span out over its last 10 ms before a pause and in over its first 10 ms after one
(sample counts, lengths exact). CLI and JSON unchanged.

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

Diffstat:
Aumtool/lib/report/audioSplice.mjs | 329+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postPause.mjs | 98++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/lib/report/postPause.test.mjs | 22+++++++++++++++++++---
3 files changed, 435 insertions(+), 14 deletions(-)

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) {