// Where a cut's synthesized narration is kept: `out/narration/`, beside the // build, shared by its variants (a narration is named by its content, not by // the cut that asked for it). // // out/narration/.wav the editor's sound, copied in (48 kHz mono PCM) // out/narration/.json its record: the words, engine, voice and speed it // was asked with, its measured seconds and loudness, // the copy's sha256, the editor job it came from, // and the disclosure line // // `` is narration.mjs's narrationKey: a changed word, voice or speed is a // new file and a new ask; an unchanged one is never asked again. A COPY, not // the editor's path: the editor's cache may be pruned or moved, and a rebuild // must not depend on it. import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { disclosureLine, disclosureLines, narrationsOf } from "./narration.mjs"; import { postNarrationDisclosure } from "./post-narration.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; import { TTS_TUNING_FIELDS } from "yt-dlp-transcript-common/lib/ttsTuning.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; /** `/narration`. */ export const narrationDir = (outRoot) => path.join(outRoot, "narration"); export const narrationWavPath = (dir, key) => path.join(dir, `${key}.wav`); export const narrationRecordPath = (dir, key) => path.join(dir, `${key}.json`); /** One narration's record, or null when it was never kept (or its sound is gone). */ export async function readNarrationRecord(dir, key) { const rec = await readFile(narrationRecordPath(dir, key), "utf8").then(JSON.parse, () => null); if (!rec || rec.key !== key) return null; const st = await stat(narrationWavPath(dir, key)).catch(() => null); return st?.isFile() && st.size > 0 ? rec : null; } /** The records a list of narrations (narrationsOf) already has, by card id. */ export async function readNarrationRecords(dir, narrations) { const out = new Map(); for (const n of narrations) { const rec = await readNarrationRecord(dir, n.key); if (rec) out.set(n.id, rec); } return out; } /** A file's duration in seconds, by ffprobe. */ export async function probeSeconds(file) { const { stdout } = await execFileP(FFPROBE(), [ "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file, ]); const s = Number(stdout.trim()); if (!Number.isFinite(s) || s <= 0) throw new Error(`ffprobe reads no duration from ${file}`); return s; } /** A sound's integrated loudness (EBU R128, LUFS), by ffmpeg's ebur128; null when it has none (silence). */ export async function measureLufs(file) { const { stderr } = await execFileP( FFMPEG(), ["-nostdin", "-hide_banner", "-nostats", "-i", file, "-af", "ebur128=framelog=quiet", "-f", "null", "-"], { maxBuffer: 1 << 24 }, ); // The summary's "I:" is the last one printed. const all = [...String(stderr).matchAll(/\bI:\s+(-?[\d.]+|-inf)\s+LUFS/g)]; const v = all.length ? Number(all.at(-1)[1]) : NaN; return Number.isFinite(v) && v > -70 ? v : null; } const sha256File = async (file) => createHash("sha256").update(await readFile(file)).digest("hex"); /** * Keep one synthesized narration: copy the editor's WAV in (through a rename, * so a half-copied file is never read as kept), measure it, write its record. * * @param {string} dir narrationDir(outRoot) * @param {{ id: string, key: string, text: string, engine: string, voice: string, speed: number }} n * @param {{ wav: string, seconds?: number, engine?: string, voice?: string, cached?: boolean, * durationMs?: number, waitedMs?: number, tuning?: Record, reading?: number, * seedBase?: number }} result the editor's `@@tts-result` * @param {{ jobId?: string }} [meta] * @returns the record */ export async function keepNarration(dir, n, result, { jobId = null } = {}) { if (!result || typeof result.wav !== "string" || !path.isAbsolute(result.wav)) { throw new Error(`${n.id}: the editor's tts result names no absolute wav (${JSON.stringify(result?.wav)})`); } await mkdir(dir, { recursive: true }); const wav = narrationWavPath(dir, n.key); const tmp = tmpPathFor(path.join(dir, `.${n.key}`), { ext: ".wav" }); try { await copyFile(result.wav, tmp); await rename(tmp, wav); } finally { await rm(tmp, { force: true }); } const seconds = await probeSeconds(wav); const lufs = await measureLufs(wav); // The engine and voice the editor says it used: the ones asked for, which // the disclosure names. const engine = result.engine ?? n.engine; const voice = result.voice ?? n.voice; const record = { v: 1, key: n.key, id: n.id, text: n.text, engine, voice, speed: n.speed, seconds: Number(seconds.toFixed(3)), lufs: lufs === null ? null : Number(lufs.toFixed(2)), sha256: await sha256File(wav), wav: path.basename(wav), // What Orpheus made it with, as the editor says (every tuning value, the reading, its seed base), so the reading // can be made again exactly. Absent for another engine, and in a record kept before (it still reads). ...madeWith(result), // The tuning it was ASKED with (lane line-rerun): what the card says to ask this file again -- its key -- when // another reading is picked (umtool narration

--pick ). ...(n.tuning && typeof n.tuning === "object" && Object.keys(n.tuning).length ? { askedTuning: n.tuning } : {}), // ...and the reading it was ASKED at: an engine with no seed (Kokoro) reports none, yet the key holds it. ...(Number.isInteger(n.reading) && n.reading > 0 ? { askedReading: n.reading } : {}), editor: { jobId, cached: result.cached === true, ...(Number.isFinite(Number(result.seconds)) ? { seconds: Number(result.seconds) } : {}), ...(Number.isFinite(Number(result.durationMs)) ? { durationMs: Number(result.durationMs) } : {}), ...(Number.isFinite(Number(result.waitedMs)) ? { waitedMs: Number(result.waitedMs) } : {}), ...(typeof result.sha === "string" ? { sha: result.sha } : {}), }, // The editor's own line, verbatim (it may carry an engine's attribution). disclosure: typeof result.disclosure === "string" && result.disclosure.trim() ? result.disclosure.trim() : disclosureLine(engine, voice), createdAt: new Date().toISOString(), }; const recTmp = tmpPathFor(path.join(dir, `.${n.key}`), { ext: ".json" }); await writeFile(recTmp, JSON.stringify(record, null, 2) + "\n", "utf8"); await rename(recTmp, narrationRecordPath(dir, n.key)); return record; } /** The editor's `tuning` (its known fields), `reading` and `seedBase`, as a record's keys; `{}` when it gave none. */ function madeWith(result) { const tuning = {}; if (result?.tuning && typeof result.tuning === "object") { for (const k of TTS_TUNING_FIELDS) if (typeof result.tuning[k] === "number" && Number.isFinite(result.tuning[k])) tuning[k] = result.tuning[k]; } return { ...(Object.keys(tuning).length ? { tuning } : {}), ...(Number.isInteger(result?.reading) && result.reading >= 0 ? { reading: result.reading } : {}), ...(Number.isInteger(result?.seedBase) ? { seedBase: result.seedBase } : {}), }; } /** * A cut's disclosure, from the narrations it keeps (`out/narration/`): the * editor's lines, each once, joined by `sep`; null when nothing is narrated. * A narration not kept yet says the line its engine and voice would. */ export async function readCutDisclosure(dir, manifest, sep = "\n") { const records = await readNarrationRecords(dir, narrationsOf(manifest)); const lines = disclosureLines(manifest, records); // A narrated post item's (post-narration.mjs): its picked take's engine and voice. for (const e of manifest?.timeline ?? []) { const line = e?.type === "post" ? postNarrationDisclosure(e) : null; if (line && !lines.includes(line)) lines.push(line); } return lines.length ? lines.join(sep) : null; }