#!/usr/bin/env node // A speech recording in, a processed one out: the one wrapper every VOICE // engine runs behind (release 39, the voice ops) — scripts/tts.mjs's twin. // // The app only ever knows a PATH (paths.voiceBin / VOICE_BIN) and the argv the // engine registry (common/lib/voiceApps.ts) builds, so an engine can be added // or swapped without touching a caller, and a test can swap in a fake. // // TWO OPS, FOUR ENGINES, PICKED BY --engine-kind: // enhance rnnoise ffmpeg's `arnndn` with the model bundled beside // this file (scripts/voice-models/sh.rnnn): zero // install, the fallback espeak-ng is for TTS. // deepfilternet DeepFilterNet 3 through its own static binary // (`deep-filter`, the project's release) at 48 kHz, // its delay compensated (-D) so the timing holds. // convert openvoice OpenVoice v2's tone-colour converter // (scripts/voice_openvoice.py, torch on the CPU). // seed-vc Seed-VC v1's 22 kHz speech model, or with // --pitch source|contour its 44.1 kHz f0-conditioned // one, whose output follows the input's pitch // (scripts/voice_seedvc.py, torch on the CPU). // A convert engine is given --target-ref: a STOCK voice's reference clip, // made by our own TTS engines (the controller refuses anything else). // // WHAT IT WRITES is always the same shape whatever the engine: a 48 kHz mono // 16-bit PCM WAV with a bare 44-byte header, EXACTLY as long as the input // (padded or trimmed to its sample count — a derived take lines up with the // one it came from), levelled by ONE static gain (never a compressor or a // limiter, which would move the timing): to --lufs for enhance, to the // input's own loudness for convert, either capped at -1 dBTP. Moved into // place atomically. On stdout, one JSON line: {op, engine, sampleRate, // seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}, and for // a followed pitch {pitch, semitones, f0: {targetHz, sourceHz, shiftSemitones}}. // // SCRATCH lives beside --output (`.voice-/`), never in the OS // temp dir (a RAM tmpfs on this machine), and is removed on every way out. // // Usage: // voice.mjs --op enhance|convert --engine-kind --input --output [options] // // Options: // --params the engine's knobs (see common/lib/voiceApps.ts) // --more more files, [{input, output}], run the same way in the // same run (a parted take's parts: the model loads once); // the result line carries them as `more` // --python

the venv's python [openvoice, seed-vc] // --install

the engine's install dir [deepfilternet, openvoice, seed-vc] // --code the engine's pinned checkout [openvoice, seed-vc] // --target-ref the stock target's reference clip [convert] // --target-se where openvoice caches the target's embedding // --pitch target (default: the stock voice's own pitch), source // (the input's pitch) or contour (the input's intonation // at the stock voice's register) [seed-vc] // --semitones moves a followed pitch, -12 to 12 [seed-vc, with --pitch source|contour] // --model the rnnoise model [rnnoise] // --threads CPU threads for torch (default 4) // --lufs enhance's level when params has no `lufs` (default -20) // --ffmpeg ffmpeg binary (FFMPEG_BIN, ffmpeg) // -h, --help import { spawn } from "node:child_process"; import { mkdir, open, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; const SAMPLE_RATE = 48_000; const TRUE_PEAK_CAP = -1; const RNNOISE_DELAY = 480; const ENGINES = { enhance: ["rnnoise", "deepfilternet"], convert: ["openvoice", "seed-vc"] }; function fail(msg, code = 2) { process.stderr.write(`voice: ${msg}\n`); process.exit(code); } const argv = process.argv.slice(2); if (argv.includes("-h") || argv.includes("--help")) { process.stdout.write("voice.mjs --op enhance|convert --engine-kind --input --output [options]\nSee the header of this file.\n"); process.exit(0); } function arg(flag, fallback) { const i = argv.indexOf(flag); return i < 0 || i === argv.length - 1 ? fallback : argv[i + 1]; } const op = arg("--op", ""); const kind = arg("--engine-kind", ""); if (!ENGINES[op]) fail(`--op must be enhance or convert (got '${op}')`); if (!ENGINES[op].includes(kind)) fail(`--engine-kind for ${op} is one of ${ENGINES[op].join(", ")} (got '${kind}')`); const input = arg("--input", ""); const output = arg("--output", ""); if (!input || !output) fail("--input and --output are required"); let params = {}; try { params = JSON.parse(arg("--params", "{}")); } catch { fail("--params must be JSON"); } // More files run the same way in the same run (a parted take's parts): one // engine load, one admission to the heavy slot. let extra = []; try { extra = JSON.parse(arg("--more", "[]")); } catch { fail("--more must be JSON"); } if (!Array.isArray(extra) || !extra.every((x) => x && typeof x.input === "string" && typeof x.output === "string")) { fail("--more is a list of {input, output}"); } const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg"); const threads = String(Math.max(1, Number(arg("--threads", "4")) || 4)); // The pitch a conversion lands on (seed-vc; scripts/voice_seedvc.py's header). const PITCH_MODES = ["target", "source", "contour"]; const pitch = arg("--pitch", "target"); const semitones = Number(arg("--semitones", "0")); if (!PITCH_MODES.includes(pitch)) fail(`--pitch is one of ${PITCH_MODES.join(", ")} (got '${pitch}')`); if (!Number.isFinite(semitones) || semitones < -12 || semitones > 12) fail(`--semitones is a number from -12 to 12 (got '${arg("--semitones", "")}')`); if (pitch !== "target" && kind !== "seed-vc") fail(`--pitch ${pitch} is seed-vc's: ${kind} has no pitch control`); if (semitones !== 0 && pitch === "target") fail("--semitones moves a followed pitch: it needs --pitch source or contour"); const lufs = typeof params.lufs === "number" ? params.lufs : Number(arg("--lufs", "-20")); const out = path.resolve(output); const work = `${out}.voice-${process.pid}`; let child = null; const cleanup = () => rm(work, { recursive: true, force: true }).catch(() => {}); for (const sig of ["SIGTERM", "SIGINT"]) { process.on(sig, () => { // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) if (child?.pid !== undefined) child.kill("SIGTERM"); void cleanup().finally(() => process.exit(143)); }); } // Run a command; resolve with {stdout, stderr}, reject with its stderr's tail. function run(cmd, args, { quiet = false, env } = {}) { return new Promise((resolve, reject) => { let stdout = ""; let stderr = ""; child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], ...(env ? { env: { ...process.env, ...env } } : {}) }); child.stdout.setEncoding("utf8"); child.stderr.setEncoding("utf8"); child.stdout.on("data", (d) => (stdout += d)); child.stderr.on("data", (d) => { stderr += d; if (!quiet) process.stderr.write(d); }); child.on("error", (err) => reject(new Error(`failed to run ${cmd}: ${err.message}`))); child.on("close", (code, signal) => { child = null; if (code === 0) resolve({ stdout, stderr }); else { const tail = stderr.trim().split("\n").slice(-3).join(" | "); reject(new Error(`${path.basename(cmd)} exited ${code ?? signal}${tail ? `: ${tail}` : ""}`)); } }); }); } const BITEXACT = ["-map_metadata", "-1", "-fflags", "+bitexact", "-flags:a", "+bitexact"]; const ff = (args, o) => run(ffmpeg, ["-nostdin", "-hide_banner", "-v", "error", "-y", ...args], o); // The data chunk's size in bytes, from the header. async function dataBytes(file) { const fh = await open(file, "r"); try { const head = Buffer.alloc(4096); const { bytesRead } = await fh.read(head, 0, head.length, 0); const buf = head.subarray(0, bytesRead); if (buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE") throw new Error(`${file} is not a WAV`); let off = 12; while (off + 8 <= buf.length) { const id = buf.toString("ascii", off, off + 4); const size = buf.readUInt32LE(off + 4); if (id === "data") return size; off += 8 + size + (size % 2); } throw new Error(`${file} has no data chunk`); } finally { await fh.close(); } } // Integrated loudness and true peak (ffmpeg's loudnorm, measuring only). async function measure(file) { const { stderr } = await run(ffmpeg, ["-nostdin", "-hide_banner", "-v", "info", "-i", file, "-af", "loudnorm=print_format=json", "-f", "null", "-"], { quiet: true }); const m = stderr.slice(stderr.lastIndexOf("{")); try { const j = JSON.parse(m.slice(0, m.indexOf("}") + 1)); const i = Number(j.input_i); const tp = Number(j.input_tp); return { lufs: Number.isFinite(i) ? i : null, tp: Number.isFinite(tp) ? tp : null }; } catch { return { lufs: null, tp: null }; } } const num = (v, d) => (typeof v === "number" && Number.isFinite(v) ? v : d); // One item: the input normalized, and what the engine reads. async function prepare(item, k) { const in48 = path.join(work, `in-${k}.wav`); await ff(["-i", path.resolve(item.input), "-ac", "1", "-ar", String(SAMPLE_RATE), "-c:a", "pcm_s16le", ...BITEXACT, "-f", "wav", in48]); const samples = (await dataBytes(in48)) / 2; if (!(samples > 0)) throw new Error(`${item.input} has no audio`); return { ...item, k, in48, raw: path.join(work, `engine-${k}.wav`), samples, before: await measure(in48) }; } // The enhance engines, one item at a time (each is a process per file anyway). async function enhanceOne(it) { if (kind === "rnnoise") { const model = arg("--model", ""); if (!model) throw new Error("missing --model (the rnnoise model)"); const mix = Math.min(1, Math.max(0, num(params.mix, 1))); // ffmpeg's filter args escape ':' and '\'; the path is ours (no quotes in it). const m = model.replace(/\\/g, "\\\\").replace(/:/g, "\\:"); // arnndn answers one 10 ms frame late (480 samples at 48 kHz, measured), // and its last, flushed frame is garbage that differs run to run (ffmpeg // 9.0, up to full scale): the input is padded with two frames of silence, // the late frame trimmed off the front and the flush off the end. const pad = RNNOISE_DELAY * 2; await ff([ "-i", it.in48, "-af", `apad=pad_len=${pad},highpass=f=${num(params.highpass, 70)},arnndn=m='${m}':mix=${mix},atrim=start_sample=${RNNOISE_DELAY}:end_sample=${it.samples + RNNOISE_DELAY}`, "-c:a", "pcm_s16le", it.raw, ]); return; } const install = arg("--install", ""); const dfOut = path.join(work, `df-${it.k}`); await mkdir(dfOut, { recursive: true }); await run(path.join(install, "deep-filter"), [ "-D", "-a", String(Math.min(100, Math.max(0, num(params.attenLimDb, 100)))), ...(params.postFilter === true ? ["--pf"] : []), "-o", dfOut, it.in48, ]); const made = (await readdir(dfOut)).filter((f) => f.endsWith(".wav")); if (made.length !== 1) throw new Error(`deep-filter wrote ${made.length} files`); // DeepFilterNet's own highpass is gentle; the rumble below speech goes too. await ff(["-i", path.join(dfOut, made[0]), "-af", `highpass=f=${num(params.highpass, 70)}`, "-c:a", "pcm_s16le", it.raw]); } // The convert engines: ONE python process for every item, so the model loads // once (a parted take is many short files of one performance). async function convertAll(items) { const python = arg("--python", ""); const code = arg("--code", ""); const install = arg("--install", ""); const ref = arg("--target-ref", ""); if (!python || !code || !install) throw new Error(`missing --python, --code or --install (the install \`archilyzer voice setup --engine ${kind}\` made)`); if (!ref) throw new Error("missing --target-ref (the stock target's reference clip)"); const batch = path.join(work, "batch.json"); await writeFile(batch, JSON.stringify(items.map((it) => ({ input: it.in48, output: it.raw })))); const env = { HF_HUB_OFFLINE: "1", TRANSFORMERS_OFFLINE: "1", HF_HOME: path.join(install, ".hf"), OMP_NUM_THREADS: threads }; if (kind === "openvoice") { await run(python, [ path.join(import.meta.dirname, "voice_openvoice.py"), "--code", code, "--ckpt", path.join(install, "converter", "checkpoint.pth"), "--config", path.join(install, "converter", "config.json"), "--batch", batch, "--target-ref", ref, ...(arg("--target-se", "") ? ["--target-se", arg("--target-se", "")] : []), "--tau", String(Math.min(1, Math.max(0, num(params.tau, 0.3)))), "--threads", threads, ], { env }); } else { const { stdout } = await run(python, [ path.join(import.meta.dirname, "voice_seedvc.py"), "--code", code, // A followed pitch is the f0-conditioned model's (44.1 kHz, its own // vocoder, RMVPE): the optional files `voice setup --engine seed-vc // --with f0` fetches (common/lib/voiceApps.ts SEEDVC_F0_FILES). ...(pitch === "target" ? [ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"), "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"), "--bigvgan", path.join(install, "bigvgan"), ] : [ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth"), "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml"), "--bigvgan", path.join(install, "bigvgan-44k"), "--rmvpe", path.join(install, "rmvpe.pt"), "--pitch", pitch, "--semitones", String(semitones), ]), "--whisper", path.join(install, "whisper-small"), "--campplus", path.join(install, "campplus_cn_common.bin"), "--batch", batch, "--target-ref", ref, "--steps", String(Math.round(Math.min(100, Math.max(1, num(params.steps, 10))))), "--cfg-rate", String(Math.min(1, Math.max(0, num(params.cfgRate, 0.7)))), "--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))), "--threads", threads, ], { env }); // A followed pitch: what the tracker heard and how far the curve was moved. try { const said = JSON.parse(stdout.trim().split("\n").pop() ?? "{}"); if (pitch !== "target" && said.f0 && typeof said.f0 === "object") return { pitch, semitones, f0: said.f0 }; } catch { /* the result line is the wrapper's own */ } } return {}; } // One static gain (enhance to --lufs, convert to the input's own loudness; // never above -1 dBTP), then 48 kHz mono 16-bit exactly `samples` long, moved // into place. async function finish(it) { if (!((await stat(it.raw).catch(() => null))?.size > 44)) throw new Error(`the ${kind} engine produced no audio for ${it.input}`); const mid = await measure(it.raw); const goal = op === "enhance" ? lufs : it.before.lufs; let gainDb = 0; if (mid.lufs !== null && goal !== null && Number.isFinite(goal)) gainDb = goal - mid.lufs; if (mid.tp !== null) gainDb = Math.min(gainDb, TRUE_PEAK_CAP - mid.tp); gainDb = Math.round(gainDb * 100) / 100; const tmp = path.join(work, `out-${it.k}.wav`); await ff([ "-i", it.raw, "-af", `volume=${gainDb}dB,aresample=${SAMPLE_RATE},apad=whole_len=${it.samples},atrim=end_sample=${it.samples}`, "-ac", "1", "-ar", String(SAMPLE_RATE), "-c:a", "pcm_s16le", ...BITEXACT, "-f", "wav", tmp, ]); const got = (await dataBytes(tmp)) / 2; if (got !== it.samples) throw new Error(`the output is ${got} samples, the input ${it.samples}`); const after = await measure(tmp); const dest = path.resolve(it.output); await mkdir(path.dirname(dest), { recursive: true }); await rename(tmp, dest); return { output: dest, seconds: Math.round((it.samples / SAMPLE_RATE) * 1000) / 1000, samples: it.samples, gainDb, inputLufs: it.before.lufs, outputLufs: after.lufs, }; } try { await mkdir(work, { recursive: true }); const items = []; for (const [k, item] of [{ input, output }, ...extra].entries()) items.push(await prepare(item, k)); const started = Date.now(); const engineSaid = {}; if (op === "enhance") for (const it of items) await enhanceOne(it); else Object.assign(engineSaid, await convertAll(items)); const engineMs = Date.now() - started; const done = []; for (const it of items) done.push(await finish(it)); await cleanup(); const [first, ...rest] = done; const result = { op, engine: kind, sampleRate: SAMPLE_RATE, seconds: first.seconds, samples: first.samples, engineMs, gainDb: first.gainDb, inputLufs: first.inputLufs, outputLufs: first.outputLufs, ...engineSaid, ...(rest.length ? { more: rest } : {}), }; process.stdout.write(JSON.stringify(result) + "\n"); process.stderr.write(`voice: ${op}/${kind} ${result.seconds}s${rest.length ? ` and ${rest.length} more` : ""} in ${(engineMs / 1000).toFixed(2)}s -> ${out}\n`); } catch (err) { await cleanup(); fail(err instanceof Error ? err.message : String(err), 1); }