// ONE VOICE OP OVER ONE RECORDING, AS AN EDITOR JOB — what `pnpm ops // voice-enhance` / `voice-convert` (`POST /api/ops/voice-enhance|convert`) // enqueue (release 39). ttsFile.ts's twin: a recording is never run through an // engine by hand, the way narration is never synthesized by hand. umtool's // derived takes (umtool/report-to-video/post-narration.mjs, `umtool posts // narrate

--derive --op enhance|convert`) are its caller. // // THE BODY is umtool's contract (umtool/lib/report/postNarrationCli.mjs // deriveTake): `{file, out, engine?, params?, parts?}`, and for convert // `voice?` — the stock target (`target` is the same key's other name; `path` // is `file`'s) — and `pitch?` / `semitones?`: the pitch the conversion lands on // (lib/voiceApps.ts VoicePitch: `target`, the stock voice's own; `source`, the // read's; `contour`, the read's rises and falls at the stock voice's register; // `semitones` moves a followed one; defaults settings.voice.convert). An engine // with one pitch (openvoice) refuses another; a followed pitch whose model is // not installed (seed-vc's optional `f0` files) is refused naming the setup // command. `file` is an absolute path to the recording (any format ffmpeg // reads, at most VOICE_MAX_SECONDS); `out` an absolute `.wav` path the result // is written to — never inside the corpus, its directory existing; `engine` // one of the op's engines (default settings.voice..engine); `params` the // engine's knobs (lib/voiceApps.ts); `parts` a take recorded part by part, // `[{file, out}]`, each run through the same engine after the whole (a part's // `out` directory is made when it sits in `out`'s). Every refusal comes back // before a job exists — the unknown engine or knob, the engine that is not // installed ("… is not installed … run `archilyzer voice setup …`", which umtool // reads as such), the `out` inside the corpus, the TARGET that is not a stock // voice (lib/voiceApps.ts NO_CLONING: a path or a recording is refused, // whatever it holds). // // THE TARGET'S REFERENCE. A converter is prompted with the stock voice reading // VOICE_REFERENCE_TEXT, kept at `/targets/-.wav` // with a sidecar naming the tts cache key it was made under. Missing, or made // under another key (a new model, other Orpheus settings), it is asked of the // `tts` op first — a `tts-file` job on its own queue, waited for — and kept. // // THE RUN. ONE run of `scripts/voice.mjs` (paths.voiceBin) for the take and // all its parts — one model load, one admission — behind the machine's heavy // slot (scripts/queue-lock.mjs --heavy --estimate , // settings.voice.heavyEstimateMB, default the engine's measured peak plus a // margin), in a process group of its own that a cancel stops whole. Nothing // stays resident: the engine is a process per run, and it exits with it. // // THE RESULT is logged as ONE line starting with VOICE_RESULT_MARKER (the // marker umtool's askEditorOp reads): `{op, engine, wav, seconds, samples, // sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, // target?, voice?, pitch?, semitones?, f0?, synthetic, disclosure?}` (`pitch` // on every conversion; `f0` — {targetHz, sourceHz, shiftSemitones}, the medians // the tracker heard and the whole move — on a followed one). `wav` is `out`, 48 kHz mono 16-bit, as // long as the input to the sample. // // WHAT IT TOUCHES: reads `file` and each part (anywhere); writes `out`, each // part's `out` and `/targets/`. Never settings.json, never a // channel. import { spawn, type ChildProcess } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; import { mkdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; import { execa } from "execa"; import type { Paths } from "../lib/paths"; import type { StorageLocation } from "../lib/storageLocations"; import { NO_CLONING, VOICE_REFERENCE_TEXT, describeVoicePitch, getVoiceEngine, parseStockTarget, resolveVoiceParams, resolveVoicePitch, stockTargetPaths, voiceConvertDisclosure, voiceEngineIds, voiceInstallDir, type StockTarget, type VoiceEngine, type VoiceOp, type VoicePitchChoice, } from "../lib/voiceApps"; import { voiceGroupState, voiceInstallState } from "../lib/voiceInstall"; import { DEFAULT_VOICE_SETTINGS, resolveVoiceHome, type VoiceSettings } from "../lib/voiceSettings"; import { getTtsEngine } from "../lib/ttsApps"; import { ttsInstallState } from "../lib/ttsInstall"; import { DEFAULT_TTS_SETTINGS, resolveTtsHome, type TtsSettings } from "../lib/ttsSettings"; import { VOICE_QUEUE } from "../lib/queueKeys"; import { writeJsonAtomic } from "../lib/jsonFile-server"; import { getSettings } from "../lib/settings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { corpusRootContaining, corpusRoots, realpathDeep } from "./transcribeFile"; import { enqueueTtsFile, resolveTtsRequest, ttsCacheKey } from "./ttsFile"; import "../lib/childKillGuard"; export const VOICE_JOB_KIND: Record = { enhance: "voice-enhance", convert: "voice-convert" }; // The log line carrying the result. umtool/report-to-video/narrate-via-editor.mjs // (opResultIn) and scripts/archilyzer-ops.mjs match the same string. export const VOICE_RESULT_MARKER = "@@voice-result "; // The bodies the routes accept; anything else is a 400. export const VOICE_ENHANCE_BODY_KEYS = ["file", "path", "out", "engine", "params", "parts"] as const; export const VOICE_CONVERT_BODY_KEYS = [...VOICE_ENHANCE_BODY_KEYS, "voice", "target", "pitch", "semitones"] as const; // The longest recording one op takes (a post read in full runs ~25 minutes). export const VOICE_MAX_SECONDS = 1800; export const VOICE_MAX_PARTS = 200; type Check = { ok: true; value: T } | { ok: false; error: string }; export type VoicePart = { file: string; out: string }; export type VoiceFileBody = { file: string; out: string; engine?: string; params?: unknown; parts?: VoicePart[]; target?: string; // Convert: as given, judged against the engine by resolveVoiceRequest. pitch?: unknown; semitones?: unknown; }; function absWav(key: string, v: unknown, wav: boolean): Check { if (typeof v !== "string" || !v.trim()) return { ok: false, error: `"${key}" must be a non-empty string` }; if (!path.isAbsolute(v)) return { ok: false, error: `"${key}" must be an absolute path (got "${v}")` }; if (wav && path.extname(v).toLowerCase() !== ".wav") return { ok: false, error: `"${key}" must name a .wav file (got "${v}")` }; return { ok: true, value: path.resolve(v) }; } // The body's shape, judged without touching the disk. Every sentence here is // the refusal an ops caller reads. export function parseVoiceBody(op: VoiceOp, body: Record): Check { if (body.file !== undefined && body.path !== undefined) return { ok: false, error: 'give "file" or "path" (the same thing), not both' }; const fileRaw = body.file ?? body.path; if (fileRaw === undefined) return { ok: false, error: '"file" (an absolute path to the recording) is required' }; const file = absWav("file", fileRaw, false); if (!file.ok) return file; if (body.out === undefined) return { ok: false, error: '"out" (an absolute .wav path the result is written to) is required' }; const out = absWav("out", body.out, true); if (!out.ok) return out; if (body.engine !== undefined && (typeof body.engine !== "string" || !body.engine.trim())) { return { ok: false, error: '"engine" must be a non-empty string' }; } let target: string | undefined; if (op === "convert") { if (body.voice !== undefined && body.target !== undefined && body.voice !== body.target) { return { ok: false, error: '"voice" and "target" name the same thing — give one' }; } const t = body.voice ?? body.target; if (t !== undefined) { if (typeof t !== "string") return { ok: false, error: `the target must be a string: ${NO_CLONING}` }; target = t; } } let parts: VoicePart[] | undefined; if (body.parts !== undefined) { if (!Array.isArray(body.parts) || body.parts.length === 0) return { ok: false, error: '"parts" must be a non-empty list of {file, out}' }; if (body.parts.length > VOICE_MAX_PARTS) return { ok: false, error: `"parts" holds at most ${VOICE_MAX_PARTS}` }; parts = []; for (const [k, p] of body.parts.entries()) { if (!p || typeof p !== "object" || Array.isArray(p)) return { ok: false, error: `parts[${k}] must be {file, out}` }; const extra = Object.keys(p).filter((x) => x !== "file" && x !== "out"); if (extra.length) return { ok: false, error: `parts[${k}] has unknown key(s) ${extra.join(", ")} — a part is {file, out}` }; const pf = absWav(`parts[${k}].file`, (p as VoicePart).file, false); if (!pf.ok) return pf; const po = absWav(`parts[${k}].out`, (p as VoicePart).out, true); if (!po.ok) return po; parts.push({ file: pf.value, out: po.value }); } const outs = new Set([out.value, ...parts.map((p) => p.out)]); if (outs.size !== parts.length + 1) return { ok: false, error: "every part's out (and the take's) must be a different file" }; } return { ok: true, value: { file: file.value, out: out.value, ...(typeof body.engine === "string" ? { engine: body.engine.trim() } : {}), ...(body.params !== undefined ? { params: body.params } : {}), ...(parts ? { parts } : {}), ...(target !== undefined ? { target } : {}), ...(op === "convert" && body.pitch !== undefined ? { pitch: body.pitch } : {}), ...(op === "convert" && body.semitones !== undefined ? { semitones: body.semitones } : {}), }, }; } // --- the request, resolved ----------------------------------------------------- export type VoiceRequest = { op: VoiceOp; engine: VoiceEngine; params: Record; file: string; out: string; parts: VoicePart[]; target?: StockTarget; // Convert: the pitch it lands on (target = the stock voice's own). pitch?: VoicePitchChoice; }; // The body plus settings.voice, resolved against the registry. Pure. export function resolveVoiceRequest( op: VoiceOp, body: VoiceFileBody, voice: Pick, ): Check { const engineId = body.engine ?? voice[op].engine; const engine = getVoiceEngine(engineId); if (!engine || engine.op !== op) { return { ok: false, error: `no ${op} engine "${engineId}" — known: ${voiceEngineIds(op).join(", ")}` }; } const params = resolveVoiceParams(engine, body.params); if (!params.ok) return params; let target: StockTarget | undefined; let pitch: VoicePitchChoice | undefined; if (op === "convert") { const t = parseStockTarget(body.target ?? voice.convert.target); if (!t.ok) return t; target = t.value; const p = resolveVoicePitch(engine, { pitch: body.pitch, semitones: body.semitones }, voice.convert); if (!p.ok) return p; pitch = p.value; } return { ok: true, value: { op, engine, params: params.value, file: body.file, out: body.out, parts: body.parts ?? [], ...(target ? { target } : {}), ...(pitch ? { pitch } : {}), }, }; } // --- the disk checks ----------------------------------------------------------- export type VoiceFileContext = { paths: Paths; home: string; tts?: TtsSettings; locations?: readonly Pick[]; // Injected by tests: a recording's length in seconds (default: ffprobe). probeSeconds?: (file: string) => Promise; }; async function ffprobeSeconds(ffprobe: string, file: string): Promise { try { const { stdout } = await execa(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { timeout: 30_000 }); const s = Number(String(stdout).trim()); return Number.isFinite(s) && s > 0 ? s : null; } catch { return null; } } async function checkInput(key: string, file: string, ctx: VoiceFileContext): Promise> { const st = await stat(file).catch(() => null); if (!st) return { ok: false, error: `"${key}" ${file} does not exist` }; if (!st.isFile()) return { ok: false, error: `"${key}" ${file} is not a file` }; const seconds = await (ctx.probeSeconds ?? ((f) => ffprobeSeconds(ctx.paths.ffprobeBin, f)))(file); if (seconds === null) return { ok: false, error: `"${key}" ${file} is not audio ffmpeg can read` }; if (seconds > VOICE_MAX_SECONDS) { return { ok: false, error: `"${key}" ${file} is ${Math.round(seconds)} s long; one op takes at most ${VOICE_MAX_SECONDS} s — split it` }; } return { ok: true, value: seconds }; } async function checkOut(key: string, out: string, file: string, roots: string[], mayMake: string | null): Promise> { const root = await corpusRootContaining(out, roots); if (root) return { ok: false, error: `"${key}" ${out} is inside the corpus (${root}) — this command never writes there; pick a path outside it` }; if ((await realpathDeep(out)) === (await realpathDeep(file))) return { ok: false, error: `"${key}" is its input file itself` }; if ((await stat(out).catch(() => null))?.isDirectory()) return { ok: false, error: `"${key}" ${out} is a directory; name a file` }; const dir = path.dirname(out); if (!(await stat(dir).catch(() => null))?.isDirectory()) { // A part's directory is made when it sits in the take's own. if (!(mayMake && path.dirname(dir) === mayMake)) return { ok: false, error: `"${key}": the directory ${dir} does not exist` }; } return { ok: true, value: out }; } // The stock target's reference: whether it is in place and current, and the // tts request that makes it. export async function stockReferenceState( target: StockTarget, home: string, tts: TtsSettings, ): Promise<{ wav: string; json: string; key: string; current: boolean }> { const p = stockTargetPaths(home, target); const req = resolveTtsRequest({ engine: target.ttsEngine, voice: target.voice, speed: 1 }, VOICE_REFERENCE_TEXT, tts); if (!req.ok) throw new Error(req.error); const key = ttsCacheKey(req.value, tts); let current = false; try { const [wav, side] = await Promise.all([stat(p.wav), readFile(p.json, "utf8")]); current = wav.isFile() && wav.size > 44 && (JSON.parse(side) as { ttsKey?: string }).ttsKey === key; } catch { current = false; } return { ...p, key, current }; } export async function checkVoiceRequest(req: VoiceRequest, ctx: VoiceFileContext): Promise> { const roots = corpusRoots(ctx.paths, ctx.locations ?? []); const seconds = await checkInput("file", req.file, ctx); if (!seconds.ok) return seconds; const out = await checkOut("out", req.out, req.file, roots, null); if (!out.ok) return out; for (const [k, p] of req.parts.entries()) { const s = await checkInput(`parts[${k}].file`, p.file, ctx); if (!s.ok) return s; const o = await checkOut(`parts[${k}].out`, p.out, p.file, roots, path.dirname(req.out)); if (!o.ok) return o; } const install = voiceInstallState(req.engine, { home: ctx.home, voiceModelsDir: ctx.paths.voiceModelsDir }); if (!install.installed) { return { ok: false, error: `${req.engine.label} is not installed (${install.dir}): missing ${install.missing.join("; ")} — ` + (req.engine.setup.kind === "bundled" ? req.engine.setup.hint : `run \`archilyzer voice setup --engine ${req.engine.id}\``), }; } // A followed pitch runs on the engine's optional model. if (req.pitch && req.pitch.pitch !== "target" && req.engine.pitch) { const group = voiceGroupState(req.engine, req.engine.pitch.group, { home: ctx.home }); if (group && !group.installed) { return { ok: false, error: `pitch "${req.pitch.pitch}" needs ${req.engine.label}'s ${group.id} model, which is not installed (${install.dir}: missing ${group.missing.join("; ")}) — ` + `run \`archilyzer voice setup --engine ${req.engine.id} --with ${group.id}\``, }; } } if (req.target) { const tts = ctx.tts ?? DEFAULT_TTS_SETTINGS; const ref = await stockReferenceState(req.target, ctx.home, tts); if (!ref.current) { // It will be synthesized: the tts engine must be there to do it. const engine = getTtsEngine(req.target.ttsEngine)!; const st = ttsInstallState(engine, { home: resolveTtsHome(tts, ctx.paths), paths: ctx.paths, tts }); if (!st.installed) { return { ok: false, error: `the target ${req.target.id} has no reference yet, and ${engine.label} (which makes it) is not installed ` + `(${st.dir}: missing ${st.missing.join("; ")}) — run \`archilyzer tts setup${engine.id === "kokoro" ? "" : ` --engine ${engine.id}`}\``, }; } } } return { ok: true, value: { ...req, seconds: seconds.value } }; } // --- the target's reference ----------------------------------------------------- export type EnsureReferenceOpts = { paths: Paths; home: string; tts: TtsSettings; onLog: (line: string) => void; // Injected by tests: how the tts op is asked (default enqueueTtsFile). askTts?: (body: Record) => Promise; }; /** The stock target's reference clip, made through the `tts` op when it is missing or stale. */ export async function ensureStockReference(target: StockTarget, o: EnsureReferenceOpts): Promise<{ wav: string; key: string; made: boolean }> { const ref = await stockReferenceState(target, o.home, o.tts); if (ref.current) return { wav: ref.wav, key: ref.key, made: false }; await mkdir(path.dirname(ref.wav), { recursive: true }); o.onLog(`The target ${target.id} has no reference yet: asking the tts op for it (${VOICE_REFERENCE_TEXT.length} characters)…`); const ask = o.askTts ?? ((body) => enqueueTtsFile(body, { paths: o.paths })); const r = await ask({ text: VOICE_REFERENCE_TEXT, engine: target.ttsEngine, voice: target.voice, speed: 1, out: ref.wav }); if (!r.ok) throw new Error(`the tts op refused the reference for ${target.id}: ${r.error}`); void r.stream.cancel(); o.onLog(` tts job ${r.jobId}`); const done = await r.done; if (done.status !== "done") throw new Error(`the tts job ${r.jobId} for ${target.id}'s reference ended ${done.status}`); const st = await stat(ref.wav).catch(() => null); if (!st || st.size <= 44) throw new Error(`the tts job ${r.jobId} finished but ${ref.wav} is not there`); const engine = getTtsEngine(target.ttsEngine)!; await writeJsonAtomic( ref.json, { version: 1, target: target.id, synthetic: true, ttsEngine: engine.id, model: engine.model, voice: target.voice, ttsKey: ref.key, textSha: createHash("sha256").update(VOICE_REFERENCE_TEXT).digest("hex"), ttsJob: r.jobId, createdAt: new Date().toISOString(), }, { indent: 2 }, ); o.onLog(` the reference is ${ref.wav}`); return { wav: ref.wav, key: ref.key, made: true }; } // --- the engine run -------------------------------------------------------------- export type EngineRunResult = { seconds?: number; samples?: number; sampleRate?: number; engineMs?: number; gainDb?: number; // A followed pitch: the medians the tracker heard and the whole move applied. f0?: { targetHz: number | null; sourceHz: number | null; shiftSemitones: number }; // The parts, when the run had more files (scripts/voice.mjs --more). more?: { output: string; seconds: number; samples?: number; gainDb?: number }[]; }; export type RunVoiceEngineOpts = { paths: Paths; argv: string[]; estimateMB: number; onLog: (line: string) => void; signal?: AbortSignal; // scripts/queue-lock.mjs, or null to run the engine directly (a test). gate?: string | null; killGraceMs?: number; }; /** The heavy slot's gate under this checkout, when there is one. */ export function defaultVoiceGate(paths: Pick): string | null { if (!paths.monorepoRoot) return null; const gate = path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs"); return existsSync(gate) ? gate : null; } function killGroup(child: ChildProcess, sig: NodeJS.Signals): void { if (child.pid === undefined) return; try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* gone */ } } } /** * One run of the wrapper, behind the heavy slot, in its own process group: its * stderr to the log line by line, its last stdout line the result. */ export function runVoiceEngine(o: RunVoiceEngineOpts): Promise { const gate = o.gate === undefined ? defaultVoiceGate(o.paths) : o.gate; const [bin, args] = gate ? [process.execPath, [gate, "--heavy", ...(o.estimateMB > 0 ? ["--estimate", String(o.estimateMB)] : []), "--", o.paths.voiceBin, ...o.argv]] : [o.paths.voiceBin, o.argv]; return new Promise((resolve, reject) => { if (o.signal?.aborted) return reject(new Error("cancelled")); const child = spawn(bin, args, { detached: true, stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; let pending = ""; const tail: string[] = []; let killTimer: ReturnType | null = null; const onAbort = () => { killGroup(child, "SIGTERM"); killTimer = setTimeout(() => killGroup(child, "SIGKILL"), o.killGraceMs ?? 10_000); killTimer.unref?.(); }; o.signal?.addEventListener("abort", onAbort, { once: true }); child.stdout?.setEncoding("utf8"); child.stderr?.setEncoding("utf8"); child.stdout?.on("data", (d: string) => (stdout += d)); child.stderr?.on("data", (d: string) => { pending += d; const lines = pending.split("\n"); pending = lines.pop() ?? ""; for (const l of lines) { if (!l.trim()) continue; o.onLog(l.trimEnd()); tail.push(l.trim()); if (tail.length > 3) tail.shift(); } }); child.on("error", (err) => { o.signal?.removeEventListener("abort", onAbort); reject(new Error(`failed to run ${bin}: ${err.message}`)); }); child.on("close", (code, sig) => { o.signal?.removeEventListener("abort", onAbort); if (killTimer) clearTimeout(killTimer); if (pending.trim()) { o.onLog(pending.trimEnd()); tail.push(pending.trim()); } if (o.signal?.aborted) return reject(new Error("cancelled")); if (code !== 0) return reject(new Error(`the voice engine exited ${code ?? sig}${tail.length ? `: ${tail.slice(-2).join(" | ")}` : ""}`)); let res: EngineRunResult = {}; try { res = JSON.parse(stdout.trim().split("\n").pop() ?? "{}") as EngineRunResult; } catch { res = {}; } resolve(res); }); }); } // --- the job --------------------------------------------------------------------- export type VoiceResult = { op: VoiceOp; engine: string; wav: string; seconds: number; samples?: number; sampleRate: number; engineMs: number; durationMs: number; waitedMs: number; gainDb?: number; params: Record; parts?: { wav: string; seconds: number }[]; // Convert: the stock target (`orpheus:zac`) and its voice alone (`zac`, the // shape a umtool take records). target?: string; voice?: string; // Convert: the pitch it landed on, and for a followed one what was heard. pitch?: VoicePitchChoice["pitch"]; semitones?: number; f0?: EngineRunResult["f0"]; synthetic: boolean; disclosure?: string; }; function describe(req: VoiceRequest, seconds: number): string { const followed = describeVoicePitch(req.pitch); const what = req.op === "enhance" ? "Enhance" : `Convert to ${req.target!.id}${followed ? ` (pitch: ${followed})` : ""}`; const parts = req.parts.length ? ` and its ${req.parts.length} part(s)` : ""; return `${what}: ${Math.round(seconds * 10) / 10} s of ${req.file}${parts} with ${req.engine.id}`; } export type EnqueueVoiceOpts = { paths: Paths; // Injected by tests. gate?: string | null; probeSeconds?: (file: string) => Promise; askTts?: (body: Record) => Promise; }; // Validate, then enqueue. Every refusal comes back as `{ ok: false, error }` // BEFORE a job exists, so the ops route answers it as a 400. export async function enqueueVoiceFile(op: VoiceOp, body: Record, opts: EnqueueVoiceOpts): Promise { const parsed = parseVoiceBody(op, body); if (!parsed.ok) return parsed; const settings = getSettings(); const voice: VoiceSettings = settings.voice ?? DEFAULT_VOICE_SETTINGS; const resolved = resolveVoiceRequest(op, parsed.value, voice); if (!resolved.ok) return resolved; const home = resolveVoiceHome(voice, opts.paths); const checked = await checkVoiceRequest(resolved.value, { paths: opts.paths, home, tts: settings.tts, locations: settings.storage?.locations ?? [], ...(opts.probeSeconds ? { probeSeconds: opts.probeSeconds } : {}), }); if (!checked.ok) return checked; const req = checked.value; const installDir = voiceInstallDir(home, req.engine); // A followed pitch is another model's run, with its own estimate. const follows = req.pitch && req.pitch.pitch !== "target" ? req.engine.pitch : undefined; const estimateMB = follows ? (voice.heavyEstimateMB[follows.estimateKey] ?? follows.defaultEstimateMB) : (voice.heavyEstimateMB[req.engine.id] ?? req.engine.defaultEstimateMB); const asked = Date.now(); return runManagedFunction({ kind: VOICE_JOB_KIND[op], queueKey: VOICE_QUEUE, paths: opts.paths, fn: async (onLog, signal) => { const started = Date.now(); onLog(describe(req, req.seconds)); let targetRef: string | undefined; let targetSe: string | undefined; if (req.target) { const ref = await ensureStockReference(req.target, { paths: opts.paths, home, tts: settings.tts, onLog, ...(opts.askTts ? { askTts: opts.askTts } : {}), }); targetRef = ref.wav; if (req.engine.id === "openvoice") { targetSe = path.join(installDir, "targets", `${req.target.ttsEngine}-${req.target.voice}.${ref.key.slice(0, 12)}.se.pt`); await mkdir(path.dirname(targetSe), { recursive: true }); } } // ONE run for the take and its parts: one admission to the heavy slot, // one model load (a parted take may be twenty short files). await mkdir(path.dirname(req.out), { recursive: true }); for (const p of req.parts) await mkdir(path.dirname(p.out), { recursive: true }); const argv = req.engine.build({ input: req.file, output: req.out, ...(req.parts.length ? { more: req.parts.map((p) => ({ input: p.file, output: p.out })) } : {}), installDir, params: req.params, threads: voice.threads, ...(targetRef ? { targetRef } : {}), ...(targetSe ? { targetSe } : {}), ...(req.pitch ? { pitch: req.pitch } : {}), bins: { ffmpegBin: opts.paths.ffmpegBin, voiceModelsDir: opts.paths.voiceModelsDir }, }); onLog(`Running ${req.engine.label}${req.parts.length ? ` over the take and its ${req.parts.length} part(s)` : ""} behind the heavy slot (estimate ${estimateMB} MB)…`); const whole = await runVoiceEngine({ paths: opts.paths, argv, estimateMB, onLog, signal, ...(opts.gate !== undefined ? { gate: opts.gate } : {}) }); for (const f of [req.out, ...req.parts.map((p) => p.out)]) { const st = await stat(f).catch(() => null); if (!st || st.size <= 44) throw new Error(`the ${req.engine.id} run left no audio at ${f}`); } onLog(`Written to ${req.out}${req.parts.length ? ` and ${req.parts.length} part(s)` : ""}`); const parts = req.parts.map((p, k) => ({ wav: p.out, seconds: whole.more?.[k]?.seconds ?? 0 })); const result: VoiceResult = { op, engine: req.engine.id, wav: req.out, seconds: whole.seconds ?? req.seconds, ...(whole.samples ? { samples: whole.samples } : {}), sampleRate: whole.sampleRate ?? 48_000, engineMs: whole.engineMs ?? 0, durationMs: Date.now() - started, waitedMs: started - asked, ...(typeof whole.gainDb === "number" ? { gainDb: whole.gainDb } : {}), params: req.params, ...(parts.length ? { parts } : {}), ...(req.target ? { target: req.target.id, voice: req.target.voice, disclosure: voiceConvertDisclosure(req.engine, req.target) } : {}), ...(req.pitch ? { pitch: req.pitch.pitch, ...(req.pitch.pitch !== "target" ? { semitones: req.pitch.semitones } : {}) } : {}), ...(follows && whole.f0 ? { f0: whole.f0 } : {}), synthetic: op === "convert", }; onLog(`${VOICE_RESULT_MARKER}${JSON.stringify(result)}`); }, }); }