import { test, after } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { chmod, mkdir, mkdtemp, open, readFile, rm, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/voiceFile.test.ts // // One voice op (`pnpm ops voice-enhance` / `voice-convert`): the body's shape // (umtool's contract), the refusals that come before any job — the stock // target's no-cloning rule first — and whole jobs through the real registry // and the real job queue. Enhance runs the REAL wrapper with rnnoise (ffmpeg // only); convert runs a stub engine (no torch here) behind a shim at VOICE_BIN // that records its argv, its install faked to the pinned sizes with sparse // files, and its target's reference asked of a stubbed tts op. The heavy slot // is bypassed (gate: null). In a temp corpus; nothing here touches a real // transcripts dir or a real engine install. const ROOT = await mkdtemp(path.join(os.tmpdir(), "voice-file-")); after(() => rm(ROOT, { recursive: true, force: true })); const CORPUS = path.join(ROOT, "transcripts"); const OUTSIDE = path.join(ROOT, "outside"); const HOME = path.join(ROOT, "voice-home"); const BIN = path.join(ROOT, "bin"); await mkdir(path.join(CORPUS, "channels", "chan", "data"), { recursive: true }); await mkdir(OUTSIDE, { recursive: true }); await mkdir(HOME, { recursive: true }); await mkdir(BIN, { recursive: true }); const RUNS = path.join(ROOT, "runs.log"); const WRAPPER = path.resolve(import.meta.dirname, "..", "..", "scripts", "voice.mjs"); const shim = path.join(BIN, "voice-shim"); await writeFile( shim, `#!/usr/bin/env node const fs = require("node:fs"); const { spawnSync } = require("node:child_process"); const argv = process.argv.slice(2); fs.appendFileSync(${JSON.stringify(RUNS)}, JSON.stringify(argv) + "\\n"); const kind = argv[argv.indexOf("--engine-kind") + 1]; if (kind === "openvoice" || kind === "seed-vc") { // A converter stand-in: the input, as it is, through the real wrapper's // rnnoise path would need a model; this copies it and says so. const input = argv[argv.indexOf("--input") + 1]; const out = argv[argv.indexOf("--output") + 1]; if (fs.readFileSync(input).length < 100) { console.error("voice: engine exploded"); process.exit(3); } fs.copyFileSync(input, out); const more = argv.includes("--more") ? JSON.parse(argv[argv.indexOf("--more") + 1]) : []; for (const m of more) fs.copyFileSync(m.input, m.output); console.error("voice: " + kind + " converted"); const f0 = argv.includes("--pitch") ? { f0: { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 } } : {}; console.log(JSON.stringify({ op: "convert", engine: kind, sampleRate: 48000, seconds: 1, samples: 48000, engineMs: 5, gainDb: 0, ...f0 })); process.exit(0); } const r = spawnSync(process.execPath, [${JSON.stringify(WRAPPER)}, ...argv], { stdio: "inherit" }); process.exit(r.status ?? 1); `, ); await chmod(shim, 0o755); const SETTINGS_FILE = path.join(ROOT, "settings.json"); await writeFile( SETTINGS_FILE, JSON.stringify({ workers: [], voice: { home: HOME, enhance: { engine: "rnnoise" }, convert: { engine: "openvoice", target: "espeak-ng:en-us" } } }, null, 2), ); // Set before getPaths (which caches) is first reached through the imports. process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = SETTINGS_FILE; process.env.VOICE_BIN = shim; const { VOICE_CONVERT_BODY_KEYS, VOICE_ENHANCE_BODY_KEYS, VOICE_MAX_SECONDS, VOICE_RESULT_MARKER, checkVoiceRequest, enqueueVoiceFile, parseVoiceBody, resolveVoiceRequest, runVoiceEngine, } = await import("./voiceFile"); const { getPaths } = await import("../lib/paths"); const { DEFAULT_VOICE_SETTINGS } = await import("../lib/voiceSettings"); const { OPENVOICE_FILES, SEEDVC_F0_FILES, SEEDVC_FILES, getVoiceEngine, stockTargetPaths, voiceCodeDir } = await import("../lib/voiceApps"); const { VOICE_CODE_MARKER } = await import("../lib/voiceInstall"); const paths = getPaths(); function has(bin: string, flag: string): boolean { try { execFileSync(bin, [flag], { stdio: "ignore" }); return true; } catch { return false; } } const FFMPEG = has("ffmpeg", "-version"); const SKIP = !FFMPEG && "ffmpeg absent"; // A tone of `seconds` at 44.1 kHz stereo: not the format the op writes. async function tone(file: string, seconds: number): Promise { execFileSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", `sine=f=220:d=${seconds}:r=44100`, "-ac", "2", file]); } async function wavHeader(file: string): Promise<{ rate: number; channels: number; bits: number; dataBytes: number }> { const fh = await open(file, "r"); try { const b = Buffer.alloc(44); await fh.read(b, 0, 44, 0); return { channels: b.readUInt16LE(22), rate: b.readUInt32LE(24), bits: b.readUInt16LE(34), dataBytes: b.readUInt32LE(40) }; } finally { await fh.close(); } } async function engineRuns(): Promise { return (await readFile(RUNS, "utf8").catch(() => "")).split("\n").filter(Boolean).map((l) => JSON.parse(l) as string[]); } // --- body ---------------------------------------------------------------------- test("the body keys are umtool's contract", () => { assert.deepEqual([...VOICE_ENHANCE_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts"]); assert.deepEqual([...VOICE_CONVERT_BODY_KEYS], ["file", "path", "out", "engine", "params", "parts", "voice", "target", "pitch", "semitones"]); }); test("the body's shape is judged before the disk", () => { const bad: [Record, RegExp][] = [ [{}, /"file" .* is required/], [{ file: "/a.wav", path: "/a.wav", out: "/b.wav" }, /not both/], [{ file: "rel.wav", out: "/b.wav" }, /"file" must be an absolute path/], [{ file: "/a.wav" }, /"out" .* is required/], [{ file: "/a.wav", out: "/b.mp3" }, /"out" must name a \.wav file/], [{ file: "/a.wav", out: "/b.wav", engine: "" }, /"engine" must be a non-empty string/], [{ file: "/a.wav", out: "/b.wav", parts: [] }, /"parts" must be a non-empty list/], [{ file: "/a.wav", out: "/b.wav", parts: [{ file: "/p.wav", out: "/q.wav", n: 1 }] }, /unknown key\(s\) n/], [{ file: "/a.wav", out: "/b.wav", parts: [{ file: "/p.wav", out: "/b.wav" }] }, /must be a different file/], ]; for (const [body, re] of bad) { const r = parseVoiceBody("enhance", body); assert.ok(!r.ok, JSON.stringify(body)); if (!r.ok) assert.match(r.error, re); } const ok = parseVoiceBody("convert", { path: "/a/take.wav", out: "/a/x.wav", voice: "orpheus:zac", parts: [{ file: "/a/p1.wav", out: "/a/x.parts/p01.wav" }] }); assert.ok(ok.ok); if (ok.ok) { assert.equal(ok.value.file, "/a/take.wav"); assert.equal(ok.value.target, "orpheus:zac"); assert.equal(ok.value.parts!.length, 1); } const both = parseVoiceBody("convert", { file: "/a.wav", out: "/b.wav", voice: "orpheus:zac", target: "orpheus:leah" }); assert.ok(!both.ok); }); test("a convert target is a stock voice: a file, a path or a recording is refused", () => { const v = DEFAULT_VOICE_SETTINGS; for (const target of ["/home/someone/voice.wav", "me.wav", "~/rec.flac", "https://example.com/a.mp3", "file:///x.wav", "orpheus/zac", "C:\\voice.wav", "operator", "user"]) { const r = resolveVoiceRequest("convert", { file: "/a.wav", out: "/b.wav", target }, v); assert.ok(!r.ok, target); if (!r.ok) assert.match(r.error, /STOCK synthetic voice|not a stock voice|refused/, target); } const unknown = resolveVoiceRequest("convert", { file: "/a.wav", out: "/b.wav", target: "orpheus:nobody" }, v); assert.ok(!unknown.ok); if (!unknown.ok) assert.match(unknown.error, /orpheus has no stock voice "nobody"/); const ok = resolveVoiceRequest("convert", { file: "/a.wav", out: "/b.wav", target: "kokoro:am_michael" }, v); assert.ok(ok.ok); if (ok.ok) assert.deepEqual(ok.value.target, { id: "kokoro:am_michael", ttsEngine: "kokoro", voice: "am_michael" }); // The default target is settings.voice.convert.target. const dflt = resolveVoiceRequest("convert", { file: "/a.wav", out: "/b.wav" }, v); assert.ok(dflt.ok); if (dflt.ok) assert.equal(dflt.value.target!.id, "orpheus:zac"); }); test("an engine is the op's own, and its params are checked", () => { const v = DEFAULT_VOICE_SETTINGS; const wrongOp = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "seed-vc" }, v); assert.ok(!wrongOp.ok); if (!wrongOp.ok) assert.match(wrongOp.error, /no enhance engine "seed-vc" — known: deepfilternet, rnnoise/); const badKey = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "rnnoise", params: { strength: 2 } }, v); assert.ok(!badKey.ok); if (!badKey.ok) assert.match(badKey.error, /rnnoise has no param\(s\) strength — its params: lufs, highpass, mix/); const range = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "rnnoise", params: { mix: 2 } }, v); assert.ok(!range.ok); if (!range.ok) assert.match(range.error, /params\.mix must be between 0 and 1 \(got 2\)/); const ok = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", params: { attenLimDb: 24 } }, v); assert.ok(ok.ok); if (ok.ok) { assert.equal(ok.value.engine.id, "deepfilternet"); assert.deepEqual(ok.value.params, { lufs: -20, highpass: 70, attenLimDb: 24, postFilter: false }); } }); test("a pitch is the engine's to follow: openvoice refuses one, seed-vc takes source and contour", () => { const v = DEFAULT_VOICE_SETTINGS; const ask = (b: Record, voice = v) => { const p = parseVoiceBody("convert", { file: "/a.wav", out: "/b.wav", ...b }); assert.ok(p.ok, !p.ok ? p.error : ""); return resolveVoiceRequest("convert", p.ok ? p.value : ({} as never), voice); }; const refused = (b: Record, re: RegExp, voice = v) => { const r = ask(b, voice); assert.ok(!r.ok, JSON.stringify(b)); if (!r.ok) { assert.match(r.error, re); // One sentence. assert.equal(r.error.includes("\n"), false); } }; // Nothing asked: the target's own pitch, on every engine. for (const engine of ["openvoice", "seed-vc"]) { const r = ask({ engine }); assert.ok(r.ok); if (r.ok) assert.deepEqual(r.value.pitch, { pitch: "target", semitones: 0 }); } // An enhance has no pitch at all. const en = resolveVoiceRequest("enhance", { file: "/a.wav", out: "/b.wav", engine: "rnnoise" }, v); assert.ok(en.ok && en.value.pitch === undefined); // OpenVoice has one pitch. refused({ engine: "openvoice", pitch: "source" }, /^OpenVoice v2 \(tone-colour converter\) has no pitch control — .* "pitch" and "semitones" are seed-vc's/); refused({ engine: "openvoice", semitones: 2 }, /has no pitch control/); assert.ok(ask({ engine: "openvoice", pitch: "target", semitones: 0 }).ok); // The values. refused({ engine: "seed-vc", pitch: "up" }, /"pitch" is one of target, source, contour \(got "up"\)/); refused({ engine: "seed-vc", pitch: "source", semitones: 13 }, /"semitones" is a number from -12 to 12 \(got 13\)/); refused({ engine: "seed-vc", pitch: "source", semitones: "2" }, /"semitones" is a number from -12 to 12/); // Semitones move a FOLLOWED pitch. refused({ engine: "seed-vc", semitones: 2 }, /"semitones" moves a followed pitch — give "pitch": "source" or "contour"/); refused({ engine: "seed-vc", pitch: "target", semitones: -1 }, /moves a followed pitch/); const src = ask({ engine: "seed-vc", pitch: "source" }); assert.ok(src.ok); if (src.ok) assert.deepEqual(src.value.pitch, { pitch: "source", semitones: 0 }); const con = ask({ engine: "seed-vc", pitch: "contour", semitones: -1.5 }); assert.ok(con.ok); if (con.ok) assert.deepEqual(con.value.pitch, { pitch: "contour", semitones: -1.5 }); // settings.voice.convert's defaults: for the engine that can follow, and // never a refusal for the one that cannot. const follow = { ...v, convert: { ...v.convert, pitch: "contour" as const, semitones: 2 } }; const d = ask({ engine: "seed-vc" }, follow); assert.ok(d.ok); if (d.ok) assert.deepEqual(d.value.pitch, { pitch: "contour", semitones: 2 }); // A request naming its own followed pitch and no semitones takes the default semitones; 0 says none. const named = ask({ engine: "seed-vc", pitch: "source" }, follow); assert.ok(named.ok); if (named.ok) assert.deepEqual(named.value.pitch, { pitch: "source", semitones: 2 }); const zero = ask({ engine: "seed-vc", pitch: "source", semitones: 0 }, follow); assert.ok(zero.ok); if (zero.ok) assert.deepEqual(zero.value.pitch, { pitch: "source", semitones: 0 }); const over = ask({ engine: "seed-vc", pitch: "target" }, follow); assert.ok(over.ok); if (over.ok) assert.deepEqual(over.value.pitch, { pitch: "target", semitones: 0 }); const ov = ask({ engine: "openvoice" }, follow); assert.ok(ov.ok); if (ov.ok) assert.deepEqual(ov.value.pitch, { pitch: "target", semitones: 0 }); // The argv: nothing new for the target's pitch. const seed = getVoiceEngine("seed-vc")!; const base = { input: "/a.wav", output: "/b.wav", installDir: "/i", params: {}, threads: 4, targetRef: "/r.wav", bins: { ffmpegBin: "ffmpeg", voiceModelsDir: "/m" } }; assert.equal(seed.build({ ...base, pitch: { pitch: "target", semitones: 0 } }).includes("--pitch"), false); assert.deepEqual(seed.build({ ...base, pitch: { pitch: "contour", semitones: 2 } }).slice(-4), ["--pitch", "contour", "--semitones", "2"]); }); // --- the disk checks ----------------------------------------------------------- test("the disk checks: the input, the out, the install", { skip: SKIP }, async () => { const take = path.join(OUTSIDE, "take.wav"); await tone(take, 1); const ctx = { paths, home: HOME }; const req = (b: Record, op: "enhance" | "convert" = "enhance") => { const p = parseVoiceBody(op, b); assert.ok(p.ok); const r = resolveVoiceRequest(op, p.ok ? p.value : ({} as never), { ...DEFAULT_VOICE_SETTINGS, enhance: { engine: "rnnoise" } }); assert.ok(r.ok, !r.ok ? r.error : ""); return r.ok ? r.value : (null as never); }; const fail = async (b: Record, re: RegExp, op: "enhance" | "convert" = "enhance", c: Record = {}) => { const r = await checkVoiceRequest(req(b, op), { ...ctx, ...c }); assert.ok(!r.ok, JSON.stringify(b)); if (!r.ok) assert.match(r.error, re); }; await fail({ file: path.join(OUTSIDE, "missing.wav"), out: path.join(OUTSIDE, "o.wav") }, /does not exist/); await writeFile(path.join(OUTSIDE, "notes.txt"), "not audio"); await fail({ file: path.join(OUTSIDE, "notes.txt"), out: path.join(OUTSIDE, "o.wav") }, /is not audio ffmpeg can read/); await fail({ file: take, out: path.join(OUTSIDE, "o.wav") }, /one op takes at most 1800 s/, "enhance", { probeSeconds: async () => VOICE_MAX_SECONDS + 1 }); await fail({ file: take, out: path.join(CORPUS, "channels", "chan", "data", "o.wav") }, /inside the corpus/); await fail({ file: take, out: take.replace(/\.wav$/, ".WAV").replace(".WAV", ".wav") }, /its input file itself/); await fail({ file: take, out: path.join(OUTSIDE, "nowhere", "o.wav") }, /the directory .* does not exist/); // A part's directory may be made when it sits in the take's own; deeper is refused. const okParts = await checkVoiceRequest(req({ file: take, out: path.join(OUTSIDE, "o.wav"), parts: [{ file: take, out: path.join(OUTSIDE, "o.parts", "p01.wav") }] }), ctx); assert.ok(okParts.ok, !okParts.ok ? okParts.error : ""); await fail({ file: take, out: path.join(OUTSIDE, "o.wav"), parts: [{ file: take, out: path.join(OUTSIDE, "a", "b", "p01.wav") }] }, /parts\[0\]\.out.*does not exist/); // An engine not installed names its setup — the words umtool reads as "not installed". const dfn = parseVoiceBody("enhance", { file: take, out: path.join(OUTSIDE, "o.wav"), engine: "deepfilternet" }); const dr = dfn.ok ? resolveVoiceRequest("enhance", dfn.value, DEFAULT_VOICE_SETTINGS) : null; assert.ok(dr && dr.ok); if (dr && dr.ok) { const r = await checkVoiceRequest(dr.value, ctx); assert.ok(!r.ok); if (!r.ok) assert.match(r.error, /DeepFilterNet 3 is not installed \(.*voice-home\/deepfilternet\): missing deep-filter — run `archilyzer voice setup --engine deepfilternet`/); } }); // --- whole jobs ---------------------------------------------------------------- async function runJob(op: "enhance" | "convert", body: Record, extra: Record = {}) { const res = await enqueueVoiceFile(op, body, { paths, gate: null, ...extra }); if (!res.ok) return { error: res.error }; void res.stream.cancel(); const done = await res.done; const logFile = path.join(paths.jobsDir, `${res.jobId}.log`); let log = ""; for (let i = 0; i < 100; i++) { log = await readFile(logFile, "utf8").catch(() => ""); if (log.includes(VOICE_RESULT_MARKER) || log.includes("[error]")) break; await new Promise((r) => setTimeout(r, 20)); } const line = log.split("\n").find((l) => l.startsWith(VOICE_RESULT_MARKER)); return { status: done.status, log, result: line ? JSON.parse(line.slice(VOICE_RESULT_MARKER.length)) : null }; } test("refusals through the job door start nothing", async () => { const before = (await engineRuns()).length; assert.match((await runJob("enhance", { file: path.join(OUTSIDE, "missing.wav"), out: path.join(OUTSIDE, "o.wav") })).error!, /does not exist/); assert.match((await runJob("convert", { file: path.join(OUTSIDE, "missing.wav"), out: path.join(OUTSIDE, "o.wav"), voice: "/home/me/my-voice.wav" })).error!, /no real person's voice/); assert.match((await runJob("enhance", { file: "/a.wav", out: "/b.wav", engine: "deepfilternet", params: { postFilter: "yes" } })).error!, /params\.postFilter must be true or false/); assert.equal((await engineRuns()).length, before); }); test("an enhance runs the real wrapper: a 48 kHz mono WAV exactly the input's length, parts too", { skip: SKIP }, async () => { const take = path.join(OUTSIDE, "e-take.wav"); const part = path.join(OUTSIDE, "e-part.wav"); await tone(take, 1.5); await tone(part, 0.4); const out = path.join(OUTSIDE, "e-out.wav"); const partOut = path.join(OUTSIDE, "e-out.parts", "p01.wav"); const r = await runJob("enhance", { file: take, out, parts: [{ file: part, out: partOut }] }); assert.equal(r.status, "done", r.log); assert.equal(r.result.op, "enhance"); assert.equal(r.result.engine, "rnnoise"); assert.equal(r.result.wav, out); assert.equal(r.result.samples, 72000); assert.equal(r.result.synthetic, false); assert.equal(r.result.target, undefined); assert.deepEqual(r.result.params, { lufs: -20, highpass: 70, mix: 1 }); assert.deepEqual(r.result.parts, [{ wav: partOut, seconds: 0.4 }]); const h = await wavHeader(out); assert.deepEqual(h, { channels: 1, rate: 48000, bits: 16, dataBytes: 144000 }); assert.equal((await wavHeader(partOut)).dataBytes, 0.4 * 48000 * 2); // No scratch is left beside the result. assert.deepEqual((await import("node:fs")).readdirSync(OUTSIDE).filter((f) => f.includes(".voice-")), []); // One run for the take and its part: one admission, one load. assert.match(r.log, /Running RNNoise \(ffmpeg arnndn\) over the take and its 1 part\(s\) behind the heavy slot \(estimate 300 MB\)/); const runs = (await engineRuns()).filter((a) => a.includes(take)); assert.equal(runs.length, 1); assert.deepEqual(JSON.parse(runs[0][runs[0].indexOf("--more") + 1]), [{ input: part, output: partOut }]); }); // A fake openvoice install at its pinned sizes (sparse files), so the install // check passes without 131 MB on disk. async function fakeOpenvoiceInstall(): Promise { const dir = path.join(HOME, "openvoice"); await mkdir(path.join(dir, "venv", "bin"), { recursive: true }); await writeFile(path.join(dir, "venv", "bin", "python"), ""); await mkdir(voiceCodeDir(dir), { recursive: true }); const engine = getVoiceEngine("openvoice")!; if (engine.setup.kind !== "python-venv") throw new Error("openvoice is a venv engine"); await writeFile(path.join(voiceCodeDir(dir), VOICE_CODE_MARKER), engine.setup.code.commit + "\n"); for (const f of OPENVOICE_FILES) { const p = path.join(dir, f.name); await mkdir(path.dirname(p), { recursive: true }); const fh = await open(p, "w"); await fh.truncate(f.bytes); await fh.close(); } } test("a convert makes its stock target's reference through the tts op once, then reuses it", { skip: SKIP }, async () => { await fakeOpenvoiceInstall(); const asked: Record[] = []; const askTts = async (body: Record) => { asked.push(body); await tone(String(body.out), 2); return { ok: true as const, jobId: "tts-job-1", stream: new ReadableStream(), done: Promise.resolve({ status: "done" as const, jobId: "tts-job-1" }) }; }; const take = path.join(OUTSIDE, "c-take.wav"); await tone(take, 1); const out = path.join(OUTSIDE, "c-out.wav"); const r = await runJob("convert", { file: take, out, voice: "espeak-ng:en-us" }, { askTts }); assert.equal(r.status, "done", r.log); assert.equal(asked.length, 1); assert.equal(asked[0].engine, "espeak-ng"); assert.equal(asked[0].voice, "en-us"); assert.match(String(asked[0].text), /^The North Wind and the Sun were disputing/); const ref = stockTargetPaths(HOME, { ttsEngine: "espeak-ng", voice: "en-us" }); assert.equal(asked[0].out, ref.wav); const side = JSON.parse(await readFile(ref.json, "utf8")); assert.equal(side.synthetic, true); assert.equal(side.target, "espeak-ng:en-us"); assert.equal(side.ttsJob, "tts-job-1"); // The engine was handed the reference and an embedding cache under its install. const run = (await engineRuns()).at(-1)!; assert.equal(run[run.indexOf("--engine-kind") + 1], "openvoice"); assert.equal(run[run.indexOf("--target-ref") + 1], ref.wav); assert.match(run[run.indexOf("--target-se") + 1], /voice-home\/openvoice\/targets\/espeak-ng-en-us\.[0-9a-f]{12}\.se\.pt$/); assert.equal(r.result.target, "espeak-ng:en-us"); assert.equal(r.result.voice, "en-us"); assert.equal(r.result.synthetic, true); assert.equal(r.result.disclosure, "Narration: voice converted to a synthetic voice (OpenVoice v2 (tone-colour converter) · espeak-ng:en-us)"); assert.ok((await stat(out)).size > 44); // Again: the reference is current, so the tts op is not asked. const again = await runJob("convert", { file: take, out: path.join(OUTSIDE, "c-out2.wav"), voice: "espeak-ng:en-us" }, { askTts }); assert.equal(again.status, "done", again.log); assert.equal(asked.length, 1); }); test("an engine that fails fails the job with its words", { skip: SKIP }, async () => { await fakeOpenvoiceInstall(); const tiny = path.join(OUTSIDE, "tiny.wav"); await writeFile(tiny, Buffer.alloc(60)); const r = await runJob("convert", { file: tiny, out: path.join(OUTSIDE, "t-out.wav"), voice: "espeak-ng:en-us" }, { probeSeconds: async () => 1 }); assert.equal(r.status, "failed"); assert.match(r.log, /the voice engine exited 3: voice: engine exploded/); }); // A seed-vc install, faked to the pinned sizes with sparse files; `f0` adds the // optional group a followed pitch runs on. async function fakeSeedVcInstall(f0: boolean): Promise { const dir = path.join(HOME, "seed-vc"); await mkdir(path.join(dir, "venv", "bin"), { recursive: true }); await writeFile(path.join(dir, "venv", "bin", "python"), ""); const seed = getVoiceEngine("seed-vc")!; if (seed.setup.kind !== "python-venv") throw new Error("seed-vc is a venv engine"); await mkdir(voiceCodeDir(dir), { recursive: true }); await writeFile(path.join(voiceCodeDir(dir), VOICE_CODE_MARKER), `${seed.setup.code.commit}\n`); for (const f of [...SEEDVC_FILES, ...(f0 ? SEEDVC_F0_FILES : [])]) { const p = path.join(dir, f.name); await mkdir(path.dirname(p), { recursive: true }); const fh = await open(p, "w"); await fh.truncate(f.bytes); await fh.close(); } return dir; } test("a followed pitch needs seed-vc's f0 model: refused naming the setup command, then run with its own estimate", { skip: SKIP }, async () => { await fakeSeedVcInstall(false); const askTts = async (body: Record) => { await tone(String(body.out), 2); return { ok: true as const, jobId: "tts-job-2", stream: new ReadableStream(), done: Promise.resolve({ status: "done" as const, jobId: "tts-job-2" }) }; }; const take = path.join(OUTSIDE, "p-take.wav"); await tone(take, 1); const before = (await engineRuns()).length; // An install without the f0 files still converts at the target's pitch… const plain = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-plain.wav"), engine: "seed-vc", voice: "espeak-ng:en-us" }, { askTts }); assert.equal(plain.status, "done", plain.log ?? plain.error); assert.equal(plain.result.pitch, "target"); assert.equal("semitones" in plain.result, false); assert.equal("f0" in plain.result, false); assert.match(plain.log!, /estimate 3500 MB/); const plainRun = (await engineRuns()).at(-1)!; assert.equal(plainRun.includes("--pitch"), false); // …and refuses a followed one, in one sentence, before any job. const runs = (await engineRuns()).length; assert.equal(runs, before + 1); const refused = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-src.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "source" }, { askTts }); assert.match( refused.error!, /^pitch "source" needs Seed-VC \(v1, 22 kHz speech\)'s f0 model, which is not installed \(.*voice-home\/seed-vc: missing DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2\.pth; .*rmvpe\.pt; .*\) — run `archilyzer voice setup --engine seed-vc --with f0`$/, ); assert.equal(refused.error!.includes("\n"), false); assert.equal((await engineRuns()).length, runs); // With them: the wrapper is told, the f0 run's estimate is declared, the result says what was done. await fakeSeedVcInstall(true); const r = await runJob("convert", { file: take, out: path.join(OUTSIDE, "p-con.wav"), engine: "seed-vc", voice: "espeak-ng:en-us", pitch: "contour", semitones: 2 }, { askTts }); assert.equal(r.status, "done", r.log ?? r.error); const run = (await engineRuns()).at(-1)!; assert.equal(run[run.indexOf("--pitch") + 1], "contour"); assert.equal(run[run.indexOf("--semitones") + 1], "2"); assert.match(r.log!, /Convert to espeak-ng:en-us \(pitch: contour \+2 st\)/); assert.match(r.log!, new RegExp(`estimate ${getVoiceEngine("seed-vc")!.pitch!.defaultEstimateMB} MB`)); assert.equal(r.result.pitch, "contour"); assert.equal(r.result.semitones, 2); assert.deepEqual(r.result.f0, { targetHz: 200, sourceHz: 150, shiftSemitones: 6.98 }); }); test("a cancelled run stops the engine's whole process group", async () => { const slow = path.join(BIN, "slow-engine"); await writeFile(slow, `#!/bin/sh\nsleep 30 &\nwait\n`); await chmod(slow, 0o755); const ac = new AbortController(); const started = Date.now(); const p = runVoiceEngine({ paths: { ...paths, voiceBin: slow }, argv: [], estimateMB: 0, onLog: () => {}, signal: ac.signal, gate: null, killGraceMs: 500 }); setTimeout(() => ac.abort(), 200); await assert.rejects(p, /cancelled/); assert.ok(Date.now() - started < 5000); }); test("behind the gate, the engine's estimate is declared", async () => { const gate = path.join(BIN, "gate.mjs"); const seen = path.join(ROOT, "gate-argv.json"); await writeFile(gate, `import fs from "node:fs"; fs.writeFileSync(${JSON.stringify(seen)}, JSON.stringify(process.argv.slice(2))); console.log("{}");\n`); await runVoiceEngine({ paths, argv: ["--op", "enhance"], estimateMB: 1600, onLog: () => {}, gate }); assert.deepEqual(JSON.parse(await readFile(seen, "utf8")), ["--heavy", "--estimate", "1600", "--", shim, "--op", "enhance"]); });