// A narrated post item's writers and CLI (postNarrationCli.mjs, manifest.mjs // updatePostNarration / updatePostNarrations / fitPostItems), the best-part // scan (postFit.mjs), and the authors' pictures (posts avatar / avatars). import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { after, test } from "node:test"; import { postsCommand } from "./postsCli.mjs"; import { importPatches, makeTake, mixPatchOf, pitchFlags, tunedOfResult, tuningFlags } from "./postNarrationCli.mjs"; import { fitPostItem, rmsFrames, scanAttachment, scoreWindows } from "./postFit.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; import { postItemPlan } from "umtool-report-to-video/post-item"; const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-narration-")); after(() => rm(ROOT, { recursive: true, force: true })); const REPORTS = path.join(ROOT, "reports"); const CH = path.join(ROOT, "channels"); const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]); /** A take: `secs` of a tone. */ const wav = (f, secs) => ff(["-f", "lavfi", "-i", `sine=f=220:d=${secs}`, "-ar", "48000", "-ac", "1", f]); /** A video whose sound is quiet but for a loud burst from 6 to 8 s (of 12). */ const burst = (f) => ff(["-f", "lavfi", "-i", "testsrc=s=96x64:d=12", "-f", "lavfi", "-i", "sine=f=440:d=12", "-filter_complex", "[1:a]volume='if(between(t,6,8),1,0.02)':eval=frame[a]", "-map", "0:v", "-map", "[a]", "-c:v", "libx264", "-c:a", "aac", "-shortest", f]); const item = (id, o = {}) => ({ type: "post", id: `p-${id}`, post: `subj-x/${id}`, platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: `@someone post ${id} & more w/ plan(s)`, ...o, }); async function project(name, timeline) { const dir = path.join(REPORTS, name); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-x", channelsDir: CH }, render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, timeline, }, null, 2)); return { id: name, dir }; } const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); const cli = async (args) => { const lines = []; const errs = []; const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); return { code, out: lines.join("\n"), err: errs.join("\n") }; }; test("--import reads narration/posts/index.json into the cut in ONE write; a re-run adds only new takes", async () => { const p = await project("imp", [item("1"), item("2"), item("3")]); for (const id of ["1", "2"]) { await mkdir(path.join(p.dir, "narration", "posts", id), { recursive: true }); wav(path.join(p.dir, "narration", "posts", id, "take-1.orpheus-zac.wav"), 1.5); } const rows = [ { id: "1", entry: "p-1", script: "post one", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1.5 }], pick: 0 }, { id: "2", entry: "p-2", script: "post two", takes: [{ file: "narration/posts/2/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 1.5 }], pick: 0 }, { id: "9", entry: "p-9", script: "gone", takes: [] }, ]; await writeFile(path.join(p.dir, "narration", "posts", "index.json"), JSON.stringify(rows)); const r = await cli(["narrate", "imp", "--import"]); assert.equal(r.code, 0, r.err); assert.match(r.out, /imported 2 take\(s\) into 2 post item\(s\)/); assert.match(r.out, /1 row\(s\) name no post item of the cut: p-9/); const m = await manifest(p); const one = m.timeline[0].narration; assert.equal(one.script, "post one"); assert.equal(one.pick, 0); assert.equal(one.takes[0].engine, "orpheus"); assert.ok(Math.abs(one.takes[0].seconds - 1.5) < 0.05); assert.ok(Number.isFinite(one.takes[0].lufs)); assert.equal(m.timeline[2].narration, undefined); const revs = await readdir(path.join(p.dir, "revisions")); assert.equal(revs.filter((f) => f.includes("post-narration-import")).length, 1); assert.match((await cli(["narrate", "imp", "--import"])).out, /nothing new to import/); // The plan reads it: narrated, the read and the linger. assert.equal(postItemPlan(m.timeline[0]).total, Math.round((0.4 + one.takes[0].seconds + 0.3 + 1.8) * 1000) / 1000); }); test("importPatches merges by file: a take already there is kept, a new one appended, the pick only for a new item", async () => { const m = { timeline: [item("1", { narration: { script: "mine", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 2 }], pick: 0 } })] }; const { patches, takes } = await importPatches(m, [{ id: "1", script: "theirs", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav" }, { file: "narration/posts/1/take-2.orpheus-zac.wav" }], pick: 1 }], async () => ({ seconds: 3, lufs: -20 })); assert.equal(takes, 1); assert.deepEqual(patches.map((x) => Object.keys(x.patch)), [["addTake", "keepPick"]]); }); test("the writers: the script, a take (picked), the pick and the approval -- a new script or pick takes the approval away", async () => { const p = await project("w", [item("1")]); await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); const take = (n) => ({ file: `narration/posts/1/take-${n}.orpheus-zac.wav`, engine: "orpheus", voice: "zac", seconds: 2 + n, script: "s", at: "2026-11-02T00:00:00Z" }); await updatePostNarration(p.dir, "p-1", { script: "first words", addTake: take(1) }); await updatePostNarration(p.dir, "p-1", { addTake: take(2) }); let n = (await manifest(p)).timeline[0].narration; assert.equal(n.pick, 1); assert.match((await cli(["narrate", "w", "p-1", "--pick", "1"])).out, /▶ #1/); assert.equal((await cli(["narrate", "w", "p-1", "--approve"])).code, 0); assert.equal((await manifest(p)).timeline[0].narration.approved, true); await cli(["narrate", "w", "p-1", "--script", "new words "]); n = (await manifest(p)).timeline[0].narration; assert.equal(n.script, "new words "); assert.equal(n.approved, undefined); await cli(["narrate", "w", "p-1", "--approve"]); await cli(["narrate", "w", "p-1", "--pick", "2"]); assert.equal((await manifest(p)).timeline[0].narration.approved, undefined); // Refused in the build's words, nothing written. const bad = await cli(["narrate", "w", "p-1", "--script", "hi "]); assert.equal(bad.code, 1); assert.match(bad.err, / is not an expressive tag/); // The mix's knobs, and off. assert.equal((await cli(["narrate", "w", "p-1", "wet=0.2", "short=loop", "attach=after", "linger=3"])).code, 0); n = (await manifest(p)).timeline[0].narration; assert.deepEqual([n.wet, n.short, n.attach, n.linger], [0.2, "loop", "after", 3]); await cli(["narrate", "w", "p-1", "--off"]); assert.equal((await manifest(p)).timeline[0].narration.off, true); await cli(["narrate", "w", "p-1", "--on"]); assert.equal((await manifest(p)).timeline[0].narration.off, undefined); assert.deepEqual(mixPatchOf(["fit=read:2"]), { linger: 2, clip: null }); // The cut's mix. assert.equal((await cli(["narrate", "w", "--cut", "wet=0.25", "clip=full"])).code, 0); assert.deepEqual((await manifest(p)).render.postNarration, { wet: 0.25, clip: "full" }); // The read's rate: the cut's, a post's own (posts narrate, and set-item's narration.rate=), refused out of 0.8-1.5. assert.equal((await cli(["narrate", "w", "--cut", "rate=1.08"])).code, 0); assert.equal((await manifest(p)).render.postNarration.rate, 1.08); assert.equal((await cli(["narrate", "w", "p-1", "rate=1.2"])).code, 0); assert.equal((await manifest(p)).timeline[0].narration.rate, 1.2); assert.equal((await cli(["set-item", "w", "p-1", "narration.rate=1.15"])).code, 0); assert.equal((await manifest(p)).timeline[0].narration.rate, 1.15); assert.equal((await cli(["set-item", "w", "p-1", "narration.rate="])).code, 0); assert.equal((await manifest(p)).timeline[0].narration.rate, undefined); const fast = await cli(["narrate", "w", "--cut", "rate=3"]); assert.equal(fast.code, 1); assert.match(fast.err, /rate must be 0\.8–1\.5/); }); test("--all --draft-scripts: every post's words verbatim (cleaned to be spoken), in one write", async () => { const p = await project("d", [item("1"), item("2", { text: "x ".repeat(120) })]); const r = await cli(["narrate", "d", "--all", "--draft-scripts"]); assert.equal(r.code, 0, r.err); const m = await manifest(p); assert.equal(m.timeline[0].narration.script, "post 1 and more with plans"); assert.equal(m.timeline[1].narration.script.split(" ").length, 120); assert.match((await cli(["narrate", "d", "--all", "--draft-scripts"])).out, /nothing to draft/); }); test("a take with direction: asked of the editor (stubbed), written into the project's layout, appended and picked with its note", async () => { const p = await project("t", [item("1", { narration: { script: "read me" } })]); const asked = []; const ask = async (body) => { asked.push(body); wav(body.out, 1.2); return { jobId: "job-1", result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1.2 } }; }; const m = await manifest(p); const r = await makeTake(p, m.timeline[0], { note: "angrier, a sigh first", script: " read me", ask }); assert.equal(asked[0].engine, "orpheus"); assert.equal(asked[0].voice, "zac"); assert.equal(asked[0].text, " read me"); assert.ok(asked[0].out.endsWith(path.join("narration", "posts", "1", "take-1.orpheus-zac.wav"))); assert.equal(r.take.note, "angrier, a sigh first"); const n = (await manifest(p)).timeline[0].narration; assert.equal(n.script, " read me"); assert.equal(n.takes.length, 1); assert.equal(n.pick, 0); assert.equal(n.takes[0].jobId, "job-1"); const r2 = await makeTake(p, (await manifest(p)).timeline[0], { ask }); assert.equal(r2.take.file, "narration/posts/1/take-2.orpheus-zac.wav"); }); test("ANOTHER READING, TUNED (lane orpheus-tuning): --reading and the tuning are sent as asked, the take records what the editor says, and an ask without them is the ask it always was", async () => { const p = await project("tr", [item("1", { narration: { script: "read me" } })]); const asked = []; const made = { temperature: 0.7, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; const ask = async (body) => { asked.push(body); wav(body.out, 1.2); // The editor's report (ttsFile.ts): every value it was made with, the reading and its seed base. return { jobId: `job-${asked.length}`, result: { wav: body.out, engine: body.engine, voice: body.voice, seconds: 1.2, ...(body.engine === "orpheus" ? { tuning: { ...made, ...(body.tuning ?? {}), temperature: body.tuning?.temperature ?? 0.55 }, reading: body.reading ?? 0, seedBase: 1234 + 9973 * (body.reading ?? 0) } : {}) } }; }; const plain = await makeTake(p, (await manifest(p)).timeline[0], { ask }); assert.deepEqual(Object.keys(asked[0]).sort(), ["engine", "out", "text", "voice"], "no tuning asked: none sent"); assert.deepEqual(plain.take.tuning, { ...made, temperature: 0.55 }); assert.equal(plain.take.reading, 0); const r = await makeTake(p, (await manifest(p)).timeline[0], { tuning: { temperature: 0.7 }, reading: 2, ask }); assert.deepEqual(asked[1].tuning, { temperature: 0.7 }); assert.equal(asked[1].reading, 2); assert.deepEqual(r.take.tuning, made); assert.equal(r.take.reading, 2); const n = (await manifest(p)).timeline[0].narration; assert.deepEqual({ tuning: n.takes[1].tuning, reading: n.takes[1].reading }, { tuning: made, reading: 2 }); // The card's own words are never the read's: untouched. assert.equal((await manifest(p)).timeline[0].text, item("1").text); // A take's tuning is checked in the editor's ranges when it is written. await assert.rejects( updatePostNarration(p.dir, "p-1", { addTake: { ...n.takes[1], file: "narration/posts/1/take-9.orpheus-zac.wav", tuning: { temperature: 9 }, reading: -1 } }, { token: await manifestToken(p.dir) }), (err) => /takes\[2\]\.tuning\.temperature must be a number from 0\.1 to 1\.5 \(got 9\)/.test(JSON.stringify(err.errors ?? err.message)) && /takes\[2\]\.reading must be a whole number from 0 to 99999/.test(JSON.stringify(err.errors ?? err.message)), ); // An engine without a sampler: the editor's note is said, the take records no tuning. const notes = []; const k = await makeTake(p, (await manifest(p)).timeline[0], { engine: "kokoro", voice: "af_heart", reading: 1, ask: async (body) => { const x = await ask(body); return { ...x, result: { ...x.result, note: "Kokoro-82M has no sampler or seed: the tuning and reading were ignored" } }; }, emit: (_ev, f) => notes.push(f.message) }); assert.equal(k.take.tuning, undefined); assert.equal(k.take.reading, undefined); assert.ok(notes.some((m) => /has no sampler or seed/.test(m)), notes.join("\n")); }); test("a field a later editor adds to its tuning is not copied: the take is still written (its validator knows only today's)", async () => { const made = { temperature: 0.7, top_p: 0.85, top_k: 50, min_p: 0, repeat_penalty: 1.2, takes: 3 }; // An unknown field is left out, and so is a known one that is not a number. const { top_k: _k, ...noTopK } = made; assert.deepEqual(tunedOfResult({ tuning: { ...made, mirostat: 2, top_k: "50" }, reading: 1 }), { tuning: noTopK, reading: 1 }); assert.deepEqual(tunedOfResult({ reading: -1 }), {}); assert.deepEqual(tunedOfResult(null), {}); const p = await project("tn", [item("1", { narration: { script: "read me" } })]); const ask = async (body) => { wav(body.out, 1); return { jobId: "j", result: { wav: body.out, engine: "orpheus", voice: "zac", seconds: 1, tuning: { ...made, mirostat: 2 }, reading: 0, seedBase: 1234 } }; }; const r = await makeTake(p, (await manifest(p)).timeline[0], { ask }); assert.deepEqual(r.take.tuning, made); assert.deepEqual((await manifest(p)).timeline[0].narration.takes[0].tuning, made); }); test("the tuning flags are quantised as the editor quantises them", () => { const s = (o) => (f) => o[f] ?? null; assert.deepEqual(tuningFlags(s({ "--temperature": "0.7000000000000001", "--min-p": "-0" })).tuning, { temperature: 0.7, min_p: 0 }); assert.equal(tuningFlags(s({ "--temperature": "1.5004" })).tuning.temperature, 1.5); }); test("the tuning flags: refused out of range in the flag's words, and anywhere but one item's --take (a thread read takes them since lane line-rerun; --for/--tuned are a thread read's)", async () => { await project("tf", [item("1", { narration: { script: "read me" } })]); for (const [args, re] of [ [["narrate", "tf", "p-1", "--take", "--top-p", "3"], /--top-p must be a number from 0\.05 to 1 \(got 3\)/], [["narrate", "tf", "p-1", "--take", "--chunk-takes", "2.5"], /--chunk-takes must be a whole number from 1 to 6/], [["narrate", "tf", "p-1", "--take", "--reading", "-2"], /--reading must be a whole number from 0 to 99999/], [["narrate", "tf", "p-1", "--reading", "1"], /--reading go with one item's --take/], [["narrate", "tf", "p-1", "--take", "--reading", "soon"], /--reading must be a whole number from 0 to 99999 .*got soon -- or next/], [["narrate", "tf", "p-1", "--take", "--for", "post", "--reading", "1"], /--for and --tuned are a thread read's/], [["narrate", "tf", "--all", "--take", "--reading", "1"], /--reading go with one item's --take .*--all --take does not take them/], ]) { const r = await cli(args); assert.notEqual(r.code, 0, args.join(" ")); assert.match(r.err, re, `${args.join(" ")}: ${r.err}`); } }); test("THE BEST PART: the scorer prefers a loud burst in the middle over the start, and snaps to a cut near it", () => { const rms = Array.from({ length: 120 }, (_, i) => (i >= 60 && i < 80 ? 0.5 : 0.01)); const w = scoreWindows({ rms, duration: 12, L: 3 }); assert.ok(w.start >= 5 && w.start <= 6.5, JSON.stringify(w)); assert.match(w.reason, /dB/); const snapped = scoreWindows({ rms, duration: 12, L: 3, cuts: [5.5] }); assert.equal(snapped.start, 5.5); assert.match(snapped.reason, /start on a scene cut/); // Flat: the start wins (the early bias). assert.equal(scoreWindows({ rms: Array(120).fill(0.1), duration: 12, L: 3 }).start, 0); assert.equal(scoreWindows({ rms, duration: 2, L: 3 }).reason, "the whole attachment fits the read"); assert.deepEqual(rmsFrames(new Float32Array([1, 1, 0, 0]), 20, 0.1), [1, 0]); }); test("the scan of a real file: the burst wins; posts fit writes the window and why, in one write", async () => { const p = await project("f", [item("1", { media: [{ src: "posts-media/subj-x/1/1_1.mp4", kind: "video", seconds: 12, width: 96, height: 64, audio: true }] })]); await mkdir(path.join(p.dir, "posts-media", "subj-x", "1"), { recursive: true }); burst(path.join(p.dir, "posts-media", "subj-x", "1", "1_1.mp4")); const w = await scanAttachment(path.join(p.dir, "posts-media", "subj-x", "1", "1_1.mp4"), { duration: 12, L: 3.5 }); assert.ok(w.start >= 4.4 && w.start <= 6.3, JSON.stringify(w)); await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); wav(path.join(p.dir, "narration", "posts", "1", "take-1.orpheus-zac.wav"), 1); await updatePostNarration(p.dir, "p-1", { script: "x", addTake: { file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 1, engine: "orpheus", voice: "zac" } }, { token: await manifestToken(p.dir) }); const before = postItemPlan((await manifest(p)).timeline[0]).total; assert.equal(before, 3.5); const fit = await fitPostItem((await manifest(p)).timeline[0], {}, p.dir); assert.equal(fit.L, 3.5); const r = await cli(["fit", "f", "--all"]); assert.equal(r.code, 0, r.err); assert.match(r.out, /p-1 {2}3\.5 s -> 3\.5 s {2}window/); const e = (await manifest(p)).timeline[0]; assert.ok(e.media[0].start >= 4.4, JSON.stringify(e.media[0])); assert.equal(e.narration.window.media, 0); assert.ok(e.narration.window.reason.length > 10); const plan = postItemPlan(e); assert.equal(plan.steps[0].srcFrom, e.media[0].start); assert.equal(plan.total, 3.5); // set-item fit=read:: the same, on one item, with its linger. assert.equal((await cli(["set-item", "f", "p-1", "fit=read:3"])).code, 0); const e2 = (await manifest(p)).timeline[0]; assert.equal(e2.narration.linger, 3); assert.equal(postItemPlan(e2).total, 4.7); }); test("the authors' pictures: posts avatar sets one (copied in), posts avatars copies the archive's", async () => { const p = await project("av", [item("1", { post: "subj-x/1", parents: [{ id: "0", author: "Org", handle: "BigOrg", badge: "gold", text: "hi" }] })]); const pic = path.join(ROOT, "pic.png"); ff(["-f", "lavfi", "-i", "color=c=blue:s=32x32", "-frames:v", "1", pic]); assert.equal((await cli(["avatar", "av", "Subject", pic])).code, 0); let m = await manifest(p); assert.deepEqual(m.postAvatars.Subject, { src: "posts-media/_avatars/Subject-manual.png", source: "manual" }); const store = path.join(CH, "subj-x", "posts-media", "_avatars"); await mkdir(store, { recursive: true }); ff(["-f", "lavfi", "-i", "color=c=green:s=32x32", "-frames:v", "1", path.join(store, "BigOrg.png")]); ff(["-f", "lavfi", "-i", "color=c=green:s=32x32", "-frames:v", "1", path.join(store, "subject.png")]); await writeFile(path.join(store, "avatars.json"), JSON.stringify({ BigOrg: { file: "BigOrg.png", url: "https://pbs.twimg.com/x.png", capturedAt: "2026-11-02T00:00:00Z" }, subject: { file: "subject.png" } })); const r = await cli(["avatars", "av"]); assert.equal(r.code, 0, r.err); m = await manifest(p); assert.equal(m.postAvatars.BigOrg.source, "archive"); assert.equal(m.postAvatars.BigOrg.src, "posts-media/_avatars/BigOrg.png"); // The manual one is never replaced. assert.equal(m.postAvatars.Subject.source, "manual"); assert.equal((await cli(["avatar", "av", "BigOrg", "off"])).code, 0); assert.equal((await manifest(p)).postAvatars.BigOrg, undefined); }); test("a RECORDING kept part by part: each trimmed of its silence, joined with the pauses, levelled, picked", async () => { const { keepRecording, trimSpan } = await import("./postRecord.mjs"); assert.deepEqual(trimSpan([{ s: 0, e: 0.5 }, { s: 1.5, e: 2 }], 2), { from: 0.42, to: 1.65 }); assert.deepEqual(trimSpan([], 2), { from: 0, to: 2 }); const p = await project("rec", [item("1", { narration: { script: "one.\n\ntwo.", takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", engine: "orpheus", voice: "zac", seconds: 2, lufs: -21.3 }] } })]); const parts = []; for (const k of [1, 2]) { const f = path.join(ROOT, `rec-${k}.wav`); ff(["-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono:d=0.6", "-f", "lavfi", "-i", "sine=f=300:d=1:r=44100", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=mono:d=0.6", "-filter_complex", "[1:a]volume=0.1[s];[0:a][s][2:a]concat=n=3:v=0:a=1", f]); parts.push({ file: f, text: k === 1 ? "one." : "two.", para: k - 1 }); } const r = await keepRecording(p, (await manifest(p)).timeline[0], parts, { manifest: await manifest(p) }); assert.equal(r.take.file, "narration/posts/1/take-2.recorded-operator.wav"); assert.equal(r.take.engine, "recorded"); assert.equal(r.target, -21.3); assert.equal(r.take.parts.length, 2); assert.equal(r.take.parts[1].gapBefore, 0.6); // Two 1 s words with a breath of room each, and the paragraph's pause. assert.ok(r.take.seconds > 2.6 && r.take.seconds < 3.1, String(r.take.seconds)); assert.ok(Math.abs(r.take.lufs - -21.3) < 1.5, String(r.take.lufs)); const n = (await manifest(p)).timeline[0].narration; assert.equal(n.pick, 1); assert.equal(n.takes[1].voice, "operator"); assert.equal(postItemPlan((await manifest(p)).timeline[0]).narration.seconds, r.take.seconds); }); test("a DERIVED take: run through the editor's op into a new take, the original kept; not installed says so; delete is soft", async () => { const { deriveTake, deleteTake } = await import("./postNarrationCli.mjs"); const p = await project("der", [item("1")]); await mkdir(path.join(p.dir, "narration", "posts", "1"), { recursive: true }); wav(path.join(p.dir, "narration", "posts", "1", "take-1.recorded-operator.wav"), 1.5); await updatePostNarration(p.dir, "p-1", { script: "x", addTake: { file: "narration/posts/1/take-1.recorded-operator.wav", engine: "recorded", voice: "operator", seconds: 1.5, source: { kind: "recorded", voice: "operator" } } }); const asked = []; const ask = async (route, body) => { asked.push({ route, body }); wav(body.out, 1.4); return { jobId: "job-d", result: null }; }; const r = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "convert", engine: "rvc", voice: "stock-a", ask }); assert.equal(asked[0].route, "/api/ops/voice-convert"); assert.ok(asked[0].body.file.endsWith("take-1.recorded-operator.wav")); assert.equal(r.take.file, "narration/posts/1/take-2.convert-rvc.wav"); assert.deepEqual(r.take.source, { kind: "take", from: "take-1.recorded-operator" }); assert.equal(r.take.steps[0].op, "convert"); const n = (await manifest(p)).timeline[0].narration; assert.equal(n.takes.length, 2); assert.equal(n.pick, 1); const { postNarrationDisclosure, rootTakeOf } = await import("umtool-report-to-video/post-narration"); assert.equal(rootTakeOf(n.takes, n.takes[1]), n.takes[0]); assert.equal(postNarrationDisclosure((await manifest(p)).timeline[0]), "Narration: voice converted to a synthetic voice (rvc · stock-a)"); // Enhance takes no voice (the editor refuses the key); the engine the editor // chose by default is recorded from its result line. const e1 = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "enhance", voice: "ignored", ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-e", result: { op: "enhance", engine: "deepfilternet" } }; }, }); assert.equal(asked.at(-1).route, "/api/ops/voice-enhance"); assert.equal("voice" in asked.at(-1).body, false); assert.equal("pitch" in asked.at(-1).body, false); assert.equal(e1.take.voice, "operator"); assert.deepEqual([e1.take.steps[0].op, e1.take.steps[0].engine, e1.take.steps[0].voice], ["enhance", "deepfilternet", undefined]); // A convert that named no target: the stock voice the editor landed on. const c1 = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "convert", ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-c", result: { op: "convert", engine: "openvoice", target: "orpheus:zac", voice: "zac" } }; }, }); assert.equal("voice" in asked.at(-1).body, false); assert.equal(c1.take.voice, "zac"); assert.deepEqual([c1.take.steps[0].engine, c1.take.steps[0].voice], ["openvoice", "zac"]); // A convert's PITCH goes as asked, and the step keeps what the editor says it ran. const c2 = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "convert", engine: "seed-vc", voice: "kokoro:af_bella", pitch: "contour", semitones: 2, ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-p", result: { op: "convert", engine: "seed-vc", voice: "af_bella", pitch: "contour", semitones: 2, f0: { targetHz: 197.5, sourceHz: 208.8, shiftSemitones: 1.04 } } }; }, }); assert.deepEqual([asked.at(-1).body.pitch, asked.at(-1).body.semitones], ["contour", 2]); assert.deepEqual([c2.take.steps[0].pitch, c2.take.steps[0].semitones, c2.take.voice], ["contour", 2, "af_bella"]); // Asked of an enhance, a pitch is not sent; the flags' values are checked in their own names. const e2 = await deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "enhance", pitch: "source", semitones: 2, ask: async (route, body) => { asked.push({ route, body }); wav(body.out, 1.5); return { jobId: "job-e2", result: { op: "enhance", engine: "deepfilternet" } }; }, }); assert.deepEqual(["pitch" in asked.at(-1).body, "semitones" in asked.at(-1).body, "pitch" in e2.take.steps[0]], [false, false, false]); const flag = (o) => pitchFlags((k) => o[k] ?? null); assert.deepEqual(flag({}), {}); assert.deepEqual(flag({ "--pitch": "source", "--semitones": "-2.5" }), { pitch: "source", semitones: -2.5 }); assert.throws(() => flag({ "--pitch": "up" }), /--pitch is one of target, source, contour \(got up\)/); assert.throws(() => flag({ "--semitones": "20" }), /--semitones is a number from -12 to 12 \(got 20\)/); assert.throws(() => flag({ "--semitones": "" }), /--semitones is a number/); for (const k of [5, 4, 3, 2]) await deleteTake(p, (await manifest(p)).timeline[0], k); // An op the editor has no engine for. const { OpNotInstalled } = await import("umtool-report-to-video/narrate-via-editor"); await assert.rejects( deriveTake(p, (await manifest(p)).timeline[0], { from: 0, op: "enhance", ask: async (route) => { throw new OpNotInstalled(route, "no such op"); } }), /no engine for \/api\/ops\/voice-enhance yet \(not installed/, ); // Delete, softly: moved to .trash, out of the list, the pick following. await deleteTake(p, (await manifest(p)).timeline[0], 1); const after = (await manifest(p)).timeline[0].narration; assert.equal(after.takes.length, 1); assert.equal(after.pick, 0); const trash = await readdir(path.join(p.dir, "narration", "posts", "1", ".trash")); assert.ok(trash.some((f) => f.endsWith("take-2.convert-rvc.wav"))); }); test("the recording session's store: each part on disk as it is kept, a re-split starts over, finish makes the take and clears it", async () => { const { savePart, discardPart, readSession, finishSession, sessionDirOf } = await import("./recordSession.mjs"); const p = await project("sess", [item("1", { narration: { script: "one.\n\ntwo." } })]); const e = () => manifest(p).then((m) => m.timeline[0]); const bytes = async (k) => { const f = path.join(ROOT, `sess-${k}.wav`); ff(["-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono:d=0.3", "-f", "lavfi", "-i", "sine=f=300:d=0.8:r=48000", "-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1", f]); return new Uint8Array(await readFile(f)); }; await assert.rejects(finishSession(p, await e()), /nothing recorded yet/); let s = await savePart(p.dir, await e(), { n: 1, count: 2, text: "one.", para: 0, bytes: await bytes(1), type: "audio/wav" }); assert.deepEqual(Object.keys(s.parts), ["1"]); assert.equal((await readSession(p.dir, await e())).parts["1"].file, "p01.wav"); await assert.rejects(finishSession(p, await e()), /parts 2 of 2 are not recorded yet/); // Redo: dropped, then kept again. s = await discardPart(p.dir, await e(), 1); assert.deepEqual(s.parts, {}); await savePart(p.dir, await e(), { n: 1, count: 2, text: "one.", para: 0, bytes: await bytes(1), type: "audio/wav" }); await savePart(p.dir, await e(), { n: 2, count: 2, text: "two.", para: 1, bytes: await bytes(2), type: "audio/wav" }); const kept = await finishSession(p, await e(), { manifest: await manifest(p) }); assert.equal(kept.take.file, "narration/posts/1/take-1.recorded-operator.wav"); assert.equal(kept.take.parts.length, 2); assert.equal((await manifest(p)).timeline[0].narration.pick, 0); await assert.rejects(readdir(sessionDirOf(p.dir, await e(), "operator"))); // A different split (the script was edited): the parts kept before no longer line up. await savePart(p.dir, await e(), { n: 1, count: 2, text: "a", para: 0, bytes: await bytes(1), type: "audio/wav" }); s = await savePart(p.dir, await e(), { n: 1, count: 3, text: "a", para: 0, bytes: await bytes(1), type: "audio/wav" }); assert.equal(s.count, 3); assert.deepEqual(Object.keys(s.parts), ["1"]); await assert.rejects(savePart(p.dir, await e(), { n: 4, count: 3, text: "", para: 0, bytes: await bytes(1) }), /n of count/); });