// A card's narration, end to end against a FAKE editor: narrate-via-editor's // one batch of `POST /api/ops/tts` asks, the jobs followed to their // `@@tts-result` line, the sound kept and measured in out/narration/; then a // build that puts it under the card -- `seconds: "auto"` measured, the record // beside the segment re-encoding only on change, a card without narration // still `anullsrc`, the disclosure in the cut's metadata. // // The editor is a scripted HTTP server on a loopback port. Its "voice" is an // ffmpeg tone (`sine`), never a TTS engine. Real encodes, kept tiny; skipped // without ffmpeg/ffprobe (and the build tests without ImageMagick). // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { execFile, spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import http from "node:http"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { buildVideo, cardEncodeArgs, narratedCardEncodeArgs, setProgressMode } from "./build-video.mjs"; import { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } from "./brand.mjs"; import { TTS_RESULT_MARKER, narrateCut, ttsBody, ttsResultIn } from "./narrate-via-editor.mjs"; import { narrationKey, narrationsOf } from "./narration.mjs"; import { keepNarration, narrationDir, readNarrationRecord } from "./narration-store.mjs"; const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "narrate-via-editor.mjs"); const haveFf = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0); const haveMagick = spawnSync("magick", ["-version"]).status === 0; const TOKEN = "tok"; /** * The editor's tts door, stubbed: each ask is a job that is queued for one * poll, running for one, then done, its log ending in `@@tts-result`. Words * containing FAIL make a job that fails; a token other than `tok` is a 401. */ async function fakeEditor(dir) { const asks = []; const jobs = new Map(); let n = 0; const server = http.createServer((req, res) => { const send = (status, body) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); }; if (req.headers.authorization !== `Bearer ${TOKEN}`) { req.resume(); return send(401, { ok: false, error: "missing bearer token" }); } const url = new URL(req.url, "http://x"); if (req.method === "POST" && url.pathname === "/api/ops/tts") { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", () => { const body = JSON.parse(raw); asks.push(body); if (body.engine === "piper") return send(400, { ok: false, error: `unknown tts engine "${body.engine}"` }); const id = `tts-${++n}`; const words = String(body.text).split(/\s+/).length; const seconds = Math.round(words * 0.35 * 100) / 100; const wav = path.join(dir, `${id}.wav`); const r = spawnSync("ffmpeg", [ "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `sine=frequency=330:sample_rate=48000:duration=${seconds}`, "-ac", "1", "-c:a", "pcm_s16le", wav, ]); assert.equal(r.status, 0, String(r.stderr)); jobs.set(id, { polls: 0, tails: 0, fail: /FAIL/.test(body.text), result: { wav, seconds, engine: body.engine, voice: body.voice, cached: false, durationMs: 12, waitedMs: 3, sha: "s", sampleRate: 48000, speed: body.speed, disclosure: `Narration: synthetic voice (Kokoro-82M · ${body.voice})` }, }); send(202, { ok: true, jobId: id }); }); return; } const m = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); if (req.method === "GET" && m && jobs.has(m[1])) { req.resume(); const j = jobs.get(m[1]); const tail = url.searchParams.get("tail"); if (!tail) j.polls += 1; else j.tails += 1; const status = j.polls <= 1 ? "queued" : j.polls === 2 ? "running" : j.fail ? "failed" : "done"; // The editor's caveat, played: the first tail of a done job does not // have the result line on disk yet. const lineOnDisk = j.tails > 1; return send(200, { ok: true, job: { id: m[1], kind: "tts-file", status, ...(status === "queued" ? { queue: { key: "tts", position: 1, queued: 2 } } : {}) }, ...(tail ? { tail: j.fail ? ["synthesizing", "kokoro: the model is missing"] : ["synthesizing", ...(lineOnDisk ? [`${TTS_RESULT_MARKER}${JSON.stringify(j.result)}`] : [])] } : {}), }); } req.resume(); send(404, { ok: false, error: "not found" }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const { port } = /** @type {import("node:net").AddressInfo} */ (server.address()); return { asks, url: `http://127.0.0.1:${port}`, close: () => new Promise((r) => server.close(r)) }; } const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; const RENDER = { width: 640, height: 360, fps: 10, transition: 0, preset: "ultrafast", audioRate: 48000, audioChannels: 2, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE, qr: false, }; const MANIFEST = (timeline, render = {}) => ({ slug: "narrated", title: "Narrated", provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, render: { ...RENDER, ...render }, timeline, }); const NARRATED = { id: "k1", type: "card", style: "chapter", heading: "Then", seconds: "auto", narration: { text: "Six months later the county said yes." } }; const PLAIN = { id: "k0", type: "card", style: "chapter", heading: "Now", seconds: 1 }; async function quietly(fn) { const events = []; setProgressMode((e) => events.push(e)); try { return { result: await fn().catch((err) => ({ err })), events }; } finally { setProgressMode("human"); } } const probe = (file, entries) => { const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", entries, "-of", "json", file], { encoding: "utf8" }); return JSON.parse(r.stdout); }; /** The loudest sample of a file's sound, in dB (volumedetect); -91 is digital silence. */ const maxVolume = (file) => { const r = spawnSync("ffmpeg", ["-nostdin", "-hide_banner", "-i", file, "-af", "volumedetect", "-f", "null", "-"], { encoding: "utf8" }); const m = /max_volume:\s*(-?[\d.]+|-inf) dB/.exec(r.stderr); return m ? (m[1] === "-inf" ? -Infinity : Number(m[1])) : NaN; }; test("the ask's body: engine, voice and speed always; a tuning and reading only when the card asks (lane orpheus-tuning)", () => { const plain = { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, key: "k", id: "c1" }; assert.deepEqual(ttsBody(plain), { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1 }); assert.deepEqual(ttsBody({ ...plain, tuning: { temperature: 0.7 }, reading: 2 }), { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, tuning: { temperature: 0.7 }, reading: 2, }); const [n] = narrationsOf({ render: {}, timeline: [{ type: "card", id: "c1", seconds: "auto", narration: { text: "Hi.", engine: "orpheus", voice: "zac", reading: 1 } }] }); assert.deepEqual(ttsBody(n), { text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, reading: 1 }); }); test("a kept narration records what Orpheus made it with (its known tuning fields, the reading, the seed base); one without still reads", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { const root = mkdtempSync(path.join(tmpdir(), "narration-made-with-")); t.after(() => rmSync(root, { recursive: true, force: true })); const dir = narrationDir(root); const src = path.join(root, "editor.wav"); spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=f=220:d=1", "-ar", "48000", "-ac", "1", src]); const n = { id: "c1", key: narrationKey({ text: "Hi.", engine: "orpheus", voice: "zac", speed: 1, reading: 2 }), text: "Hi.", engine: "orpheus", voice: "zac", speed: 1 }; const made = { temperature: 0.7, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; const rec = await keepNarration(dir, n, { wav: src, engine: "orpheus", voice: "zac", tuning: { ...made, someday: 1 }, reading: 2, seedBase: 21_180 }, { jobId: "j1" }); assert.deepEqual({ tuning: rec.tuning, reading: rec.reading, seedBase: rec.seedBase }, { tuning: made, reading: 2, seedBase: 21_180 }); assert.deepEqual((await readNarrationRecord(dir, n.key)).tuning, made); // Kokoro's result carries none: neither does its record, and it reads as before. const k = { ...n, id: "c2", key: narrationKey({ text: "Hi.", engine: "kokoro", voice: "af_heart", speed: 1 }), engine: "kokoro", voice: "af_heart" }; const kr = await keepNarration(dir, k, { wav: src, engine: "kokoro", voice: "af_heart" }); assert.ok(!("tuning" in kr) && !("reading" in kr) && !("seedBase" in kr)); assert.equal((await readNarrationRecord(dir, k.key)).engine, "kokoro"); }); test("the result line is found anywhere on a log line, the last one winning", () => { assert.equal(ttsResultIn(["a", "b"]), null); assert.deepEqual(ttsResultIn([`${TTS_RESULT_MARKER}{"wav":"/a.wav"}`, `[12:00] ${TTS_RESULT_MARKER}{"wav":"/b.wav"}`]), { wav: "/b.wav" }); assert.deepEqual(ttsResultIn([`${TTS_RESULT_MARKER}{broken`, `${TTS_RESULT_MARKER}{"wav":"/c.wav"}`]), { wav: "/c.wav" }); }); test("narrateCut: one batch, engine and voice always named, followed to the result, kept and measured; a kept one is not asked again", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-")); const ed = await fakeEditor(root); t.after(async () => { await ed.close(); rmSync(root, { recursive: true, force: true }); }); const m = MANIFEST([ NARRATED, { ...NARRATED, id: "k2" }, // the same words: one ask { ...NARRATED, id: "k3", narration: { text: "A second voice speaks.", voice: "am_adam" } }, PLAIN, ], { narration: { speed: 1.1 } }); const dir = narrationDir(path.join(root, "out")); const events = []; const recs = await narrateCut({ narrations: narrationsOf(m), dir, editor: { url: ed.url, token: TOKEN }, pollMs: 5, emit: (ev, f) => events.push({ ev, ...f }), }); assert.equal(ed.asks.length, 2, "k1 and k2 share their words, voice and speed"); assert.deepEqual(ed.asks[0], { text: "Six months later the county said yes.", engine: "kokoro", voice: "af_heart", speed: 1.1 }); assert.deepEqual(ed.asks[1], { text: "A second voice speaks.", engine: "kokoro", voice: "am_adam", speed: 1.1 }); assert.deepEqual([...recs.keys()].sort(), ["k1", "k2", "k3"]); const rec = recs.get("k1"); assert.equal(rec.key, narrationKey({ text: NARRATED.narration.text, engine: "kokoro", voice: "af_heart", speed: 1.1 })); assert.ok(Math.abs(rec.seconds - 2.45) < 0.05, `seconds ${rec.seconds}`); assert.ok(rec.lufs < -10 && rec.lufs > -40, `lufs ${rec.lufs}`); assert.match(rec.sha256, /^[0-9a-f]{64}$/); assert.equal(rec.disclosure, "Narration: synthetic voice (Kokoro-82M · af_heart)", "the editor's line, verbatim"); assert.equal(rec.editor.sha, "s"); assert.equal(rec.editor.jobId, "tts-1"); // A copy beside the build, not the editor's file. assert.ok(statSync(path.join(dir, `${rec.key}.wav`)).size > 0); assert.deepEqual(await readNarrationRecord(dir, rec.key), rec); // The wait said the queue place, and each card's narration. assert.ok(events.some((e) => e.ev === "note" && /queued — position 1 of 2 on tts/.test(e.message)), JSON.stringify(events)); assert.equal(events.filter((e) => e.ev === "narrate" && !e.cached).length, 3); // Asked again: everything is kept, nothing is asked. const again = []; await narrateCut({ narrations: narrationsOf(m), dir, editor: { url: ed.url, token: TOKEN }, pollMs: 5, emit: (ev, f) => again.push({ ev, ...f }) }); assert.equal(ed.asks.length, 2); assert.equal(again.filter((e) => e.ev === "narrate" && e.cached).length, 3); }); test("narrateCut: a refusal is the editor's words; a failed job names its card and its log's last lines", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-fail-")); const ed = await fakeEditor(root); t.after(async () => { await ed.close(); rmSync(root, { recursive: true, force: true }); }); const dir = narrationDir(path.join(root, "out")); const editor = { url: ed.url, token: TOKEN }; await assert.rejects( narrateCut({ narrations: [{ id: "k9", text: "Hi.", engine: "piper", voice: "x", speed: 1, key: "a" }], dir, editor, pollMs: 5 }), /the editor refused k9's narration \(HTTP 400\): unknown tts engine "piper"/, ); await assert.rejects( narrateCut({ narrations: narrationsOf(MANIFEST([{ ...NARRATED, narration: { text: "This will FAIL." } }])), dir, editor, pollMs: 5 }), /not every narration was synthesized:\n {2}k1: editor job tts-\d+ failed — synthesizing \/ kokoro: the model is missing/, ); await assert.rejects( narrateCut({ narrations: narrationsOf(MANIFEST([NARRATED])), dir, editor: { url: ed.url, token: "wrong" }, pollMs: 5 }), /HTTP 401\): missing bearer token/, ); }); test("the CLI: NDJSON events, the token from the environment, refused when it is not set", { skip: !haveFf && "needs ffmpeg and ffprobe" }, async (t) => { const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-cli-")); const ed = await fakeEditor(root); t.after(async () => { await ed.close(); rmSync(root, { recursive: true, force: true }); }); const manifest = path.join(root, "video.manifest.json"); writeFileSync(manifest, JSON.stringify(MANIFEST([NARRATED, PLAIN]))); const run = (env) => new Promise((resolve) => { execFile(process.execPath, [SCRIPT, manifest, "--progress", "ndjson"], { env: { ...process.env, NARRATE_VIA_EDITOR_POLL_MS: "5", ARCHILYZER_EDITOR_URL: ed.url, ...env }, }, (err, stdout) => resolve({ code: err ? err.code : 0, events: stdout.split("\n").filter(Boolean).map((l) => JSON.parse(l)) })); }); const ok = await run({ WORKER_TOKEN: TOKEN }); assert.equal(ok.code, 0, JSON.stringify(ok.events)); assert.deepEqual(ok.events.filter((e) => e.ev === "narrate").map((e) => e.id), ["k1"]); assert.equal(ok.events.at(-1).ev, "done"); assert.equal(ok.events.at(-1).narrations, 1); assert.ok(existsSync(path.join(root, "out", "narration"))); const none = await run({ WORKER_TOKEN: "" }); assert.equal(none.code, 1); assert.ok(none.events.some((e) => e.ev === "error" && /WORKER_TOKEN is not set/.test(e.message))); // A manifest the build would refuse is never sent. writeFileSync(manifest, JSON.stringify(MANIFEST([{ ...NARRATED, narration: { text: " hi" } }]))); const bad = await run({ WORKER_TOKEN: TOKEN }); assert.equal(bad.code, 1); assert.ok(bad.events.some((e) => e.ev === "error" && //.test(e.message))); assert.equal(ed.asks.length, 1); }); test("the encode args: a plain card keeps anullsrc; a narrated one reads the WAV through the narration filter", () => { const plain = cardEncodeArgs({ png: "/c.png", seconds: 4, vf: "fps=30,setsar=1", render: { fps: 30, audioRate: 48000, audioChannels: 2 }, outPath: "/s.mp4" }); assert.deepEqual(plain.slice(0, 17), [ "-nostdin", "-v", "error", "-y", "-loop", "1", "-framerate", "30", "-t", "4", "-i", "/c.png", "-f", "lavfi", "-t", "4", "-i", ]); assert.equal(plain[17], "anullsrc=channel_layout=stereo:sample_rate=48000"); assert.equal(plain.at(-2), "-shortest"); const narrated = narratedCardEncodeArgs({ png: "/c.png", wav: "/n.wav", seconds: 4.9, vf: "fps=30,setsar=1", audio: "AUDIO", render: { fps: 30, audioRate: 48000, audioChannels: 2 }, outPath: "/s.mp4" }); assert.ok(!narrated.some((a) => /anullsrc/.test(a))); assert.deepEqual(narrated.slice(narrated.indexOf("/n.wav") - 1, narrated.indexOf("/n.wav") + 5), ["-i", "/n.wav", "-map", "0:v", "-map", "1:a"]); assert.equal(narrated[narrated.indexOf("-af") + 1], "AUDIO"); }); test("a build: the narrated card's sound is the voice, \"auto\" its length, rebuilt only on change; the plain card is silence; the cut discloses", { skip: (!haveFf || !haveMagick) && "needs ffmpeg, ffprobe and ImageMagick" }, async (t) => { const root = mkdtempSync(path.join(tmpdir(), "rtv-narrate-build-")); const ed = await fakeEditor(root); t.after(async () => { await ed.close(); rmSync(root, { recursive: true, force: true }); }); const proj = path.join(root, "proj"); mkdirSync(proj); const manifestPath = path.join(proj, "video.manifest.json"); writeFileSync(manifestPath, JSON.stringify(MANIFEST([PLAIN, NARRATED]))); const opts = { editor: { url: ed.url, token: TOKEN }, narrationPollMs: 5, noXfade: true }; const segs = path.join(proj, "out", "sourced", "segments"); // The whole cut, hard cuts: the build asks the editor itself. const first = await quietly(() => buildVideo({ manifestPath, opts })); assert.ok(!first.result?.err, String(first.result?.err?.stack)); assert.equal(ed.asks.length, 1); const rec = JSON.parse(readFileSync(path.join(segs, "k1.narration.json"), "utf8")); // 2.45 s of voice + 0.8 + 0.8 -> 4.1 s, to the tenth. assert.equal(rec.seconds, 4.1); const dur = Number(probe(path.join(segs, "k1.mp4"), "format=duration").format.duration); assert.ok(Math.abs(dur - 4.1) < 0.12, `k1 is ${dur}s`); assert.ok(maxVolume(path.join(segs, "k1.mp4")) > -30, "the narrated card speaks"); assert.equal(maxVolume(path.join(segs, "k0.mp4")), -91, "a card without narration is digital silence (anullsrc)"); const tags = probe(path.join(proj, "out", "narrated.mp4"), "format_tags=comment").format.tags ?? {}; assert.equal(tags.comment, "Narration: synthetic voice (Kokoro-82M · af_heart)"); // Again, unchanged: no ask, no encode. const before = statSync(path.join(segs, "k1.mp4")).mtimeMs; const second = await quietly(() => buildVideo({ manifestPath, opts: { ...opts }, only: "k1" })); assert.ok(!second.result?.err, String(second.result?.err?.message)); assert.equal(ed.asks.length, 1); assert.ok(second.events.some((e) => e.ev === "note" && /k1: narrated card unchanged/.test(e.message))); assert.equal(statSync(path.join(segs, "k1.mp4")).mtimeMs, before); // New words: a new ask and a new segment. writeFileSync(manifestPath, JSON.stringify(MANIFEST([PLAIN, { ...NARRATED, narration: { text: "Six months later, the county said yes, twice over." } }]))); const third = await quietly(() => buildVideo({ manifestPath, opts, only: "k1" })); assert.ok(!third.result?.err, String(third.result?.err?.message)); assert.equal(ed.asks.length, 2); assert.notEqual(statSync(path.join(segs, "k1.mp4")).mtimeMs, before); // --skip-fetch never asks: a narration not kept refuses, naming the card. writeFileSync(manifestPath, JSON.stringify(MANIFEST([{ ...NARRATED, narration: { text: "Words nobody asked for yet." } }]))); const fourth = await quietly(() => buildVideo({ manifestPath, opts: { ...opts, skipFetch: true }, only: "k1" })); assert.match(String(fourth.result?.err?.message), /k1: its narration has not been synthesized — run narrate-via-editor\.mjs/); assert.equal(ed.asks.length, 2); // An authored seconds too short for the words is refused before anything renders. writeFileSync(manifestPath, JSON.stringify(MANIFEST([{ ...NARRATED, seconds: 2 }]))); const fifth = await quietly(() => buildVideo({ manifestPath, opts, only: "k1" })); assert.match(String(fifth.result?.err?.message), /lint: timeline k1: seconds is 2, and its narration needs 4\.1s/); });