Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Clean up voice: one tool in Audio and Apps, a before/after player, and a switch on voice slots

Adarsh3486a9ef40f2
diff --git a/scripts/gen-clean-voice-demo.mjs b/scripts/gen-clean-voice-demo.mjs
new file mode 100644
index 00000000..a9823c27
--- /dev/null
+++ b/scripts/gen-clean-voice-demo.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+/**
+ * Makes Clean up voice's demo pairs (public/samples/clean-voice/) with the final ComfyUI-RE-USE pack, on a ComfyUI that
+ * you name (it never guesses one): NVIDIA's sample at its own rate, and the same speech as an 8 kHz phone line restored
+ * to 48 kHz. Needs ffmpeg on PATH for the AAC files.
+ *
+ * node scripts/gen-clean-voice-demo.mjs --comfy http://127.0.0.1:8190 --sample path/to/mic_test2.wav [--out public/samples/clean-voice]
+ * node scripts/gen-clean-voice-demo.mjs --from <folder> [--out <folder>]
+ *
+ * --from takes pairs already made (noisy-mic-before.wav, noisy-mic-after.wav, phone-before.wav, phone-after.wav) and only
+ * finishes them. Finishing a pair: the lead-in before the first word is cut to 0.2 s (found on the clean side, whose
+ * gaps are silent), and both sides get the same gain, to about -18 LUFS on the louder one, so their levels still match.
+ *
+ * A person listens to the pairs before they ship (noise and the whine gone, no robotic sound, no seams, the phone pair
+ * fuller and not harsh), then sets DEMO_READY in src/lib/av/clean-voice.ts.
+ */
+import { execFileSync, spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const args = Object.fromEntries(process.argv.slice(2).reduce((a, v, i, all) => (v.startsWith('--') ? [...a, [v.slice(2), all[i + 1]]] : a), []));
+const comfy = args.comfy?.replace(/\/$/, '');
+if (!args.from && (!comfy || !args.sample)) {
+ console.error('Usage: node scripts/gen-clean-voice-demo.mjs --comfy <ComfyUI URL> --sample <mic_test2.wav> [--out <folder>]\n node scripts/gen-clean-voice-demo.mjs --from <folder with the four WAVs> [--out <folder>]');
+ process.exit(2);
+}
+const out = path.resolve(args.out ?? path.join(HERE, '..', 'public', 'samples', 'clean-voice'));
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'clean-voice-demo-'));
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const ffmpeg = (...a) => execFileSync('ffmpeg', ['-nostdin', '-loglevel', 'error', '-y', ...a]);
+/** ffmpeg's report (stderr) for an analysis pass. */
+const analyse = (file, filter) => spawnSync('ffmpeg', ['-nostdin', '-hide_banner', '-i', file, '-af', filter, '-f', 'null', '-'], { encoding: 'utf8' }).stderr;
+
+const LEAD_IN = 0.2;
+const TARGET_LUFS = -18;
+
+async function upload(file) {
+ const form = new FormData();
+ form.append('image', new Blob([fs.readFileSync(file)]), path.basename(file));
+ form.append('type', 'input');
+ form.append('overwrite', 'true');
+ const r = await fetch(`${comfy}/upload/image`, { method: 'POST', body: form });
+ if (!r.ok) throw new Error(`upload ${r.status}`);
+ return (await r.json()).name;
+}
+
+/** One clean on the ComfyUI: the FLAC it saved, written to `dest`. */
+async function clean(input, rate, dest) {
+ const graph = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'workflows', 'comfyui', 'voice-clean-reuse.json'), 'utf8'));
+ graph['1'].inputs.audio = await upload(input);
+ graph['3'].inputs.rate = rate;
+ graph['4'].inputs.filename_prefix = 'fuobe/clean-voice-demo';
+ const r = await fetch(`${comfy}/prompt`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: graph }) });
+ if (!r.ok) throw new Error(`prompt ${r.status}: ${await r.text()}`);
+ const { prompt_id: id } = await r.json();
+ for (;;) {
+ await sleep(1000);
+ const h = (await (await fetch(`${comfy}/history/${id}`)).json())[id];
+ if (!h) continue;
+ if (h.status?.status_str === 'error') throw new Error(JSON.stringify(h.status.messages ?? h.status));
+ const f = h.outputs?.['4']?.audio?.[0];
+ if (!f) continue;
+ console.log('report', h.outputs['5']?.text?.[0]);
+ const q = new URLSearchParams({ filename: f.filename, subfolder: f.subfolder ?? '', type: f.type });
+ fs.writeFileSync(dest, Buffer.from(await (await fetch(`${comfy}/view?${q}`)).arrayBuffer()));
+ return;
+ }
+}
+
+/** Seconds before the first word: where the clean side's first silence (under -50 dB, 0.3 s or more) at the start ends. */
+function speechStart(cleanFile) {
+ const log = analyse(cleanFile, 'silencedetect=noise=-50dB:d=0.3');
+ const first = /silence_start: (-?[\d.]+)[\s\S]*?silence_end: ([\d.]+)/.exec(log);
+ return first && Number(first[1]) <= 0.05 ? Number(first[2]) : 0;
+}
+
+/** Integrated loudness (LUFS) of a file. */
+function loudness(file) {
+ const m = /I:\s+(-?[\d.]+) LUFS/.exec(analyse(file, 'ebur128=framelog=quiet'));
+ return m ? Number(m[1]) : NaN;
+}
+
+/** A pair, finished: the same cut and the same gain on both sides, as AAC-LC 192 kb/s. */
+function finish(name, before, after) {
+ const start = Math.max(0, speechStart(after) - LEAD_IN);
+ const cut = (src, dest) => ffmpeg('-ss', start.toFixed(3), '-i', src, '-c:a', 'pcm_f32le', dest);
+ const b = path.join(tmp, `${name}-before-cut.wav`);
+ const a = path.join(tmp, `${name}-after-cut.wav`);
+ cut(before, b);
+ cut(after, a);
+ const loudest = Math.max(loudness(b), loudness(a));
+ const gain = Number.isFinite(loudest) ? TARGET_LUFS - loudest : 0;
+ for (const [src, side] of [[b, 'before'], [a, 'after']]) {
+ ffmpeg('-i', src, '-af', `volume=${gain.toFixed(2)}dB,alimiter=limit=0.89:level=false`, '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', path.join(out, `${name}-${side}.m4a`));
+ }
+ console.log(`${name}: cut ${start.toFixed(2)} s of lead-in, gain ${gain.toFixed(1)} dB on both sides`);
+}
+
+fs.mkdirSync(out, { recursive: true });
+const src = args.from ? path.resolve(args.from) : tmp;
+if (!args.from) {
+ const phone = path.join(tmp, 'phone-before.wav');
+ ffmpeg('-i', args.sample, '-ac', '1', '-ar', '8000', phone);
+ ffmpeg('-i', args.sample, path.join(tmp, 'noisy-mic-before.wav'));
+ await clean(args.sample, 'source', path.join(tmp, 'noisy-mic-after.flac'));
+ await clean(phone, '48000', path.join(tmp, 'phone-after.flac'));
+ ffmpeg('-i', path.join(tmp, 'noisy-mic-after.flac'), path.join(tmp, 'noisy-mic-after.wav'));
+ ffmpeg('-i', path.join(tmp, 'phone-after.flac'), path.join(tmp, 'phone-after.wav'));
+}
+finish('noisy-mic', path.join(src, 'noisy-mic-before.wav'), path.join(src, 'noisy-mic-after.wav'));
+finish('phone', path.join(src, 'phone-before.wav'), path.join(src, 'phone-after.wav'));
+fs.rmSync(tmp, { recursive: true, force: true });
+console.log(`Wrote the demo pairs to ${out}. Listen to them before they ship.`);
diff --git a/src/app/(studio)/apps/[id]/page.tsx b/src/app/(studio)/apps/[id]/page.tsx
index 5fd06add..b190bf75 100644
--- a/src/app/(studio)/apps/[id]/page.tsx
+++ b/src/app/(studio)/apps/[id]/page.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { Studio } from "@/components/studio/studio";
+import { CleanVoiceTool } from "@/components/audio-tools/clean-voice-tool";
import { APPS, getModel, getPreset } from "@/lib/catalog";
import { withRecipe } from "@/lib/catalog/preset-recipes";
import { appStudio } from "@/lib/studios";
@@ -20,6 +21,8 @@ async function AppStudio({ params }: { params: PageProps<"/apps/[id]">["params"]
const { id } = await params;
const preset = getPreset(id);
if (!preset || preset.type !== "app") notFound();
+ // An app that is a tool of its own (Clean up voice): the same tool as its Audio mode, under the app's name.
+ if (preset.tool === "clean-voice") return <CleanVoiceTool app={{ name: preset.name, description: preset.description }} />;
// The app opens on the model its preview was made with, its own route one pick away.
return <Studio config={withRecipe(appStudio(preset), (m) => !!getModel(m))} />;
}
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.ts
index 1ebfafd1..cbd955d3 100644
--- a/src/app/api/audio-tools/route.ts
+++ b/src/app/api/audio-tools/route.ts
@@ -12,14 +12,15 @@ const MESSAGES: Record<string, string> = {
crossfade: "Keep the crossfade between 0 and 10 seconds",
};
-/** Audio → Loop / extend, Join and Split soundtrack (and a split's mix put back on its video): start a run; `?preview=1` only plans and prices it. */
+/** Audio → Loop / extend, Join, Split soundtrack and Clean up voice (and a split's mix put back on its video): start a run; `?preview=1` only plans and prices it. */
async function post(request: Request) {
const raw: unknown = await request.json().catch(() => null);
const parsed = AudioToolBody.safeParse(raw);
if (!parsed.success) {
const path = parsed.error.issues[0]?.path.join(".") ?? "";
- const remux = (raw as { tool?: unknown } | null)?.tool === "remux";
- const msg = path.startsWith("clips") ? "Add 2 to 10 audio clips to join" : remux && path === "audio" ? "Export the mix first" : (MESSAGES[path] ?? "Check the settings");
+ const tool = (raw as { tool?: unknown } | null)?.tool;
+ const remux = tool === "remux";
+ const msg = path.startsWith("clips") ? "Add 2 to 10 audio clips to join" : remux && path === "audio" ? "Export the mix first" : tool === "clean" && path === "media" ? "Add the audio or video to clean" : (MESSAGES[path] ?? "Check the settings");
return Response.json({ error: msg }, { status: 400 });
}
const preview = new URL(request.url).searchParams.get("preview") === "1";
diff --git a/src/components/audio-tools/before-after-audio.tsx b/src/components/audio-tools/before-after-audio.tsx
new file mode 100644
index 00000000..274ced06
--- /dev/null
+++ b/src/components/audio-tools/before-after-audio.tsx
@@ -0,0 +1,407 @@
+"use client";
+
+import { Loader2, Pause, Play } from "lucide-react";
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Slider } from "@/components/ui/slider";
+import { clock } from "@/lib/av/audio-tools";
+import { cn } from "@/lib/utils";
+
+/**
+ * Before / after for a voice: both files play from one shared playhead, each through its own gain, and the Before | After
+ * switch (keys B and A, Space to play) crossfades the two in 30 ms, so the switch happens at the same moment in the
+ * speech. Over it, a spectrogram of both (an FFT of 1024 points in the browser, drawn once), with a divider that shows
+ * the before on its left and the after on its right; the divider follows the switch and can be dragged.
+ *
+ * The comparison is only fair at the same level: the node matches the after's speech level to the before's, and the
+ * demo pairs are made that way.
+ */
+
+/** Files bigger than this are compared with two plain players (decoding both would take too much memory). */
+const DECODE_MAX_BYTES = 96 * 1024 * 1024;
+const FFT = 1024;
+const COLUMNS = 480;
+const ROWS = 160;
+
+async function sizeOf(url: string): Promise<number | undefined> {
+ try {
+ const r = await fetch(url, { headers: { Range: "bytes=0-0" } });
+ const total = Number(/\/(\d+)\s*$/.exec(r.headers.get("content-range") ?? "")?.[1] ?? r.headers.get("content-length"));
+ await r.body?.cancel().catch(() => {});
+ return total > 0 ? total : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** In-place radix-2 FFT of (re, im), n a power of two. */
+function fft(re: Float32Array, im: Float32Array) {
+ const n = re.length;
+ for (let i = 1, j = 0; i < n; i++) {
+ let bit = n >> 1;
+ for (; j & bit; bit >>= 1) j ^= bit;
+ j ^= bit;
+ if (i < j) {
+ [re[i], re[j]] = [re[j], re[i]];
+ [im[i], im[j]] = [im[j], im[i]];
+ }
+ }
+ for (let len = 2; len <= n; len <<= 1) {
+ const ang = (-2 * Math.PI) / len;
+ const wr = Math.cos(ang);
+ const wi = Math.sin(ang);
+ for (let i = 0; i < n; i += len) {
+ let cr = 1;
+ let ci = 0;
+ for (let k = 0; k < len / 2; k++) {
+ const a = i + k;
+ const b = a + len / 2;
+ const tr = re[b] * cr - im[b] * ci;
+ const ti = re[b] * ci + im[b] * cr;
+ re[b] = re[a] - tr;
+ im[b] = im[a] - ti;
+ re[a] += tr;
+ im[a] += ti;
+ const nr = cr * wr - ci * wi;
+ ci = cr * wi + ci * wr;
+ cr = nr;
+ }
+ }
+ }
+}
+
+/** A dark-to-bright colour for a level 0…1 (black, violet, orange, pale yellow). */
+function heat(v: number): [number, number, number] {
+ const stops: [number, number, number, number][] = [
+ [0, 4, 4, 12],
+ [0.35, 84, 26, 128],
+ [0.65, 222, 82, 66],
+ [1, 252, 246, 186],
+ ];
+ const x = Math.max(0, Math.min(1, v));
+ for (let i = 1; i < stops.length; i++) {
+ if (x <= stops[i][0]) {
+ const [p0, r0, g0, b0] = stops[i - 1];
+ const [p1, r1, g1, b1] = stops[i];
+ const t = (x - p0) / (p1 - p0);
+ return [r0 + (r1 - r0) * t, g0 + (g1 - g0) * t, b0 + (b1 - b0) * t];
+ }
+ }
+ return [252, 246, 186];
+}
+
+/** The spectrogram of a buffer (its channels mixed), COLUMNS x ROWS, frequency rising upwards, linear to the Nyquist rate. */
+export function spectrogram(buf: AudioBuffer, columns = COLUMNS, rows = ROWS): ImageData | null {
+ if (typeof ImageData === "undefined") return null;
+ const n = buf.length;
+ const mono = new Float32Array(n);
+ for (let c = 0; c < buf.numberOfChannels; c++) {
+ const d = buf.getChannelData(c);
+ for (let i = 0; i < n; i++) mono[i] += d[i] / buf.numberOfChannels;
+ }
+ const img = new ImageData(columns, rows);
+ const win = new Float32Array(FFT).map((_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FFT - 1)));
+ const re = new Float32Array(FFT);
+ const im = new Float32Array(FFT);
+ const bins = FFT / 2;
+ for (let x = 0; x < columns; x++) {
+ const start = Math.floor((x / columns) * Math.max(0, n - FFT));
+ for (let i = 0; i < FFT; i++) {
+ re[i] = (mono[start + i] ?? 0) * win[i];
+ im[i] = 0;
+ }
+ fft(re, im);
+ for (let y = 0; y < rows; y++) {
+ // Each row averages its bins (rows < bins).
+ const b0 = Math.floor((y / rows) * bins);
+ const b1 = Math.max(b0 + 1, Math.floor(((y + 1) / rows) * bins));
+ let p = 0;
+ for (let b = b0; b < b1; b++) p += re[b] * re[b] + im[b] * im[b];
+ const db = 10 * Math.log10(p / (b1 - b0) / (FFT * FFT) + 1e-12);
+ const [r, g, bl] = heat((db + 110) / 90);
+ const o = ((rows - 1 - y) * columns + x) * 4;
+ img.data[o] = r;
+ img.data[o + 1] = g;
+ img.data[o + 2] = bl;
+ img.data[o + 3] = 255;
+ }
+ }
+ return img;
+}
+
+type Side = "before" | "after";
+
+function silence(nodes: AudioBufferSourceNode[]) {
+ for (const n of nodes) {
+ n.onended = null;
+ try {
+ n.stop();
+ } catch {}
+ }
+}
+
+type PlayerProps = {
+ before: string;
+ after: string;
+ labels?: { before: string; after: string };
+ className?: string;
+ autoFocus?: boolean;
+};
+
+/** One player per pair: a new pair starts from a fresh one (its own audio context, decoded files and playhead). */
+export function BeforeAfterAudio(props: PlayerProps) {
+ return <Player key={`${props.before}|${props.after}`} {...props} />;
+}
+
+function Player({ before, after, labels = { before: "Before", after: "After" }, className, autoFocus }: PlayerProps) {
+ const ctx = useRef<AudioContext | null>(null);
+ const gains = useRef<Partial<Record<Side, GainNode>>>({});
+ const sources = useRef<AudioBufferSourceNode[]>([]);
+ const started = useRef<{ at: number; offset: number } | null>(null);
+ const [buffers, setBuffers] = useState<Partial<Record<Side, AudioBuffer>>>({});
+ const [failed, setFailed] = useState<string | null>(null);
+ const [plain, setPlain] = useState(false);
+ const [side, setSide] = useState<Side>("after");
+ const [divider, setDivider] = useState(0.5);
+ const [playing, setPlaying] = useState(false);
+ const [position, setPosition] = useState(0);
+ const canvas = useRef<HTMLCanvasElement>(null);
+ const box = useRef<HTMLDivElement>(null);
+ const switchId = useId();
+
+ // One audio context per pair, both files decoded once (or two plain players for files too big to decode here).
+ useEffect(() => {
+ let live = true;
+ let ac: AudioContext | null = null;
+ try {
+ ac = new AudioContext();
+ } catch {
+ // No WebAudio here: two plain players.
+ queueMicrotask(() => live && setPlain(true));
+ return () => {
+ live = false;
+ };
+ }
+ ctx.current = ac;
+ for (const s of ["before", "after"] as const) {
+ const g = ac.createGain();
+ g.gain.value = s === "after" ? 1 : 0;
+ g.connect(ac.destination);
+ gains.current[s] = g;
+ }
+ void (async () => {
+ const sizes = await Promise.all([sizeOf(before), sizeOf(after)]);
+ if (!live) return;
+ if (sizes.some((n) => n && n > DECODE_MAX_BYTES)) return void setPlain(true);
+ for (const [s, url] of [
+ ["before", before],
+ ["after", after],
+ ] as const)
+ void fetch(url)
+ .then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.arrayBuffer();
+ })
+ .then((data) => ac!.decodeAudioData(data))
+ .then((buf) => live && setBuffers((b) => ({ ...b, [s]: buf })))
+ .catch(() => live && setFailed("Couldn't load the audio in the browser — download it instead"));
+ })();
+ return () => {
+ live = false;
+ silence(sources.current);
+ sources.current = [];
+ started.current = null;
+ ctx.current = null;
+ gains.current = {};
+ void ac?.close();
+ };
+ }, [before, after]);
+
+ const ready = !!buffers.before && !!buffers.after;
+ const length = useMemo(() => Math.max(buffers.before?.duration ?? 0, buffers.after?.duration ?? 0), [buffers]);
+
+ // The spectrograms, drawn once per pair, then cut at the divider.
+ const images = useMemo(() => (ready ? { before: spectrogram(buffers.before!), after: spectrogram(buffers.after!) } : null), [ready, buffers]);
+ useEffect(() => {
+ const c = canvas.current;
+ const g = c?.getContext("2d");
+ if (!c || !g || !images?.before || !images.after) return;
+ const cut = Math.round(divider * COLUMNS);
+ g.putImageData(images.after, 0, 0);
+ g.putImageData(images.before, 0, 0, 0, 0, cut, ROWS);
+ }, [images, divider]);
+
+ const stop = useCallback(() => {
+ if (started.current && ctx.current) setPosition(Math.min(length, started.current.offset + ctx.current.currentTime - started.current.at));
+ silence(sources.current);
+ sources.current = [];
+ started.current = null;
+ setPlaying(false);
+ }, [length]);
+
+ const play = useCallback(
+ (from?: number) => {
+ const ac = ctx.current;
+ if (!ac || !ready) return;
+ silence(sources.current);
+ void ac.resume();
+ const offset = Math.max(0, Math.min(from ?? position, length - 0.05));
+ const when = ac.currentTime + 0.02;
+ sources.current = (["before", "after"] as const).map((s) => {
+ const src = ac.createBufferSource();
+ src.buffer = buffers[s]!;
+ src.connect(gains.current[s]!);
+ src.start(when, Math.min(offset, src.buffer.duration));
+ return src;
+ });
+ const longest = sources.current.reduce((a, b) => ((b.buffer?.duration ?? 0) > (a.buffer?.duration ?? 0) ? b : a));
+ longest.onended = () => {
+ started.current = null;
+ sources.current = [];
+ setPlaying(false);
+ setPosition(0);
+ };
+ started.current = { at: when, offset };
+ setPosition(offset);
+ setPlaying(true);
+ },
+ [buffers, length, position, ready],
+ );
+
+ // The playhead, about 20 times a second while playing.
+ useEffect(() => {
+ if (!playing) return;
+ const t = setInterval(() => {
+ if (started.current && ctx.current) setPosition(Math.max(0, Math.min(length, started.current.offset + ctx.current.currentTime - started.current.at)));
+ }, 50);
+ return () => clearInterval(t);
+ }, [playing, length]);
+
+ /** Switch sides: a 30 ms crossfade at this very moment, and the divider shows that side whole. */
+ const pick = useCallback((s: Side) => {
+ setSide(s);
+ setDivider(s === "before" ? 1 : 0);
+ const ac = ctx.current;
+ if (!ac) return;
+ for (const k of ["before", "after"] as const) gains.current[k]?.gain.setTargetAtTime(k === s ? 1 : 0, ac.currentTime, 0.01);
+ }, []);
+
+ const onKey = (e: React.KeyboardEvent) => {
+ if (e.target instanceof HTMLElement && e.target.closest("input, textarea, [role=slider]")) return;
+ const k = e.key.toLowerCase();
+ if (k === "b") pick("before");
+ else if (k === "a") pick("after");
+ else if (k === " ") {
+ e.preventDefault();
+ if (playing) stop();
+ else play();
+ } else return;
+ };
+
+ const dragTo = (clientX: number) => {
+ const r = box.current?.getBoundingClientRect();
+ if (!r || r.width <= 0) return;
+ setDivider(Math.max(0, Math.min(1, (clientX - r.left) / r.width)));
+ };
+
+ if (plain)
+ return (
+ <div className={cn("grid gap-3 sm:grid-cols-2", className)}>
+ {(["before", "after"] as const).map((s) => (
+ <div key={s} className="min-w-0 space-y-1">
+ <p className="text-[12px] font-medium text-muted-foreground">{labels[s]}</p>
+ <audio src={s === "before" ? before : after} controls preload="metadata" className="h-9 w-full min-w-0" aria-label={labels[s]} />
+ </div>
+ ))}
+ </div>
+ );
+
+ const at = length ? position / length : 0;
+ return (
+ <div className={cn("min-w-0 space-y-2 rounded-2xl outline-none focus-visible:ring-2 focus-visible:ring-ring", className)} tabIndex={0} onKeyDown={onKey} autoFocus={autoFocus} aria-label="Before and after player: B for before, A for after, Space to play">
+ <div
+ ref={box}
+ className="relative h-36 w-full touch-none overflow-hidden rounded-xl bg-[#04040c] select-none sm:h-44"
+ onPointerDown={(e) => {
+ if ((e.target as HTMLElement).dataset.handle) {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ return;
+ }
+ const r = box.current!.getBoundingClientRect();
+ const t = ((e.clientX - r.left) / r.width) * length;
+ if (playing) play(t);
+ else setPosition(t);
+ }}
+ onPointerMove={(e) => (e.buttons & 1 && (e.target as HTMLElement).dataset.handle ? dragTo(e.clientX) : undefined)}
+ >
+ <canvas ref={canvas} width={COLUMNS} height={ROWS} className="absolute inset-0 h-full w-full" aria-hidden />
+ {!ready && !failed && (
+ <span className="absolute inset-0 grid place-items-center text-[12px] text-white/70">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ )}
+ <span className="pointer-events-none absolute top-2 left-2 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white">{labels.before}</span>
+ <span className="pointer-events-none absolute top-2 right-2 rounded-full bg-black/55 px-2 py-0.5 text-[11px] font-medium text-white">{labels.after}</span>
+ <span className="pointer-events-none absolute inset-y-0 w-px bg-white/90" style={{ left: `${at * 100}%` }} aria-hidden />
+ <div
+ data-handle="1"
+ role="slider"
+ tabIndex={0}
+ aria-label="Divider between before and after"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(divider * 100)}
+ onKeyDown={(e) => {
+ if (e.key === "ArrowLeft") setDivider((d) => Math.max(0, d - 0.05));
+ else if (e.key === "ArrowRight") setDivider((d) => Math.min(1, d + 0.05));
+ }}
+ className="absolute inset-y-0 z-10 w-6 -translate-x-1/2 cursor-ew-resize outline-none focus-visible:ring-2 focus-visible:ring-white"
+ style={{ left: `${divider * 100}%` }}
+ >
+ <span data-handle="1" className="absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white shadow-[0_0_6px_rgba(0,0,0,0.6)]" />
+ <span data-handle="1" className="absolute top-1/2 left-1/2 size-5 -translate-1/2 rounded-full border-2 border-white bg-black/60" />
+ </div>
+ </div>
+ {failed && (
+ <p className="text-[12px] text-destructive" role="alert">
+ {failed}
+ </p>
+ )}
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <Button size="sm" className="rounded-full" disabled={!ready} onClick={() => (playing ? stop() : play())} aria-label={playing ? "Pause" : "Play"}>
+ {!ready ? <Loader2 className="size-3.5 animate-spin" /> : playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}
+ {playing ? "Pause" : "Play"}
+ </Button>
+ <div role="radiogroup" aria-label="Hear" id={switchId} className="inline-flex gap-0.5 rounded-full bg-muted p-0.5">
+ {(["before", "after"] as const).map((s) => (
+ <button
+ key={s}
+ type="button"
+ role="radio"
+ aria-checked={side === s}
+ onClick={() => pick(s)}
+ className={cn("h-8 rounded-full px-3 text-[13px] font-medium transition", side === s ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}
+ >
+ {labels[s]}
+ <kbd className="ml-1.5 hidden font-mono text-[10px] text-muted-foreground sm:inline">{s === "before" ? "B" : "A"}</kbd>
+ </button>
+ ))}
+ </div>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">
+ {clock(position)} / {clock(length)}
+ </span>
+ <Slider
+ min={0}
+ max={Math.max(0.1, length)}
+ step={0.05}
+ value={[Math.min(position, length)]}
+ onValueChange={([v]) => (playing ? play(v) : setPosition(v))}
+ disabled={!ready}
+ aria-label="Position"
+ aria-valuetext={`${clock(position)} of ${clock(length)}`}
+ className="min-w-[7rem] flex-1 basis-32"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/audio-tools/clean-voice-switch.tsx b/src/components/audio-tools/clean-voice-switch.tsx
new file mode 100644
index 00000000..71751869
--- /dev/null
+++ b/src/components/audio-tools/clean-voice-switch.tsx
@@ -0,0 +1,416 @@
+"use client";
+
+import { AudioLines, Loader2, Sparkles } from "lucide-react";
+import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Switch } from "@/components/ui/switch";
+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { askToSignUp, useEngineMode, useIsGuest, useStatus } from "@/lib/api";
+import { CLEAN_FEATURE } from "@/lib/av/clean-voice";
+import type { Generation } from "@/lib/catalog/types";
+import { responseError } from "@/lib/refusals";
+import { cn } from "@/lib/utils";
+import { toast } from "sonner";
+import { BeforeAfterAudio } from "./before-after-audio";
+
+/**
+ * "Clean up voice" beside a voice slot or the voice recorder (Lipsync and avatars, apps with a voice, Voice change,
+ * clone samples, Elements, Faceless and Explainer narration). When it is on and an audio file lands in the slot, the file
+ * is cleaned at once on the open engine (RE-USE: Full strength, matched level, Auto quality, nothing kept but the voice)
+ * and the slot's file becomes the clean one, so the person hears it before a paid lipsync or clone is made from it. The
+ * chip under the slot plays the original against the clean one. A failure leaves the original in the slot and says why.
+ *
+ * The switch shows where the open engine can run: the owner (unless the install is cloud only), an account with its own
+ * GPU, and a guest (turning it on opens "Create a free account"). It is off by default and remembered in this browser.
+ */
+
+const PREF_KEY = "fuobe.cleanVoice";
+const prefListeners = new Set<() => void>();
+
+function readPref(): boolean {
+ try {
+ return localStorage.getItem(PREF_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+function writePref(on: boolean) {
+ try {
+ localStorage.setItem(PREF_KEY, on ? "1" : "0");
+ } catch {}
+ prefListeners.forEach((l) => l());
+}
+
+/** The remembered switch (every slot on the page follows it). */
+export function useCleanVoicePref(): [boolean, (on: boolean) => void] {
+ const on = useSyncExternalStore(
+ (cb) => {
+ prefListeners.add(cb);
+ return () => prefListeners.delete(cb);
+ },
+ readPref,
+ () => false,
+ );
+ return [on, writePref];
+}
+
+/** Where the switch shows: "guest" (it asks to sign up), "ok", or "hidden" (cloud-only install, or an account without its GPU). */
+export function useCleanVoiceAvailability(): "ok" | "guest" | "hidden" {
+ const guest = useIsGuest();
+ const mode = useEngineMode();
+ const viewer = useStatus().data?.viewer;
+ if (guest) return "guest";
+ if (viewer?.kind === "account") return viewer.gpu.connected ? "ok" : "hidden";
+ return mode === "cloud" ? "hidden" : "ok";
+}
+
+// How many cleans are running on this page: a studio's Generate waits for them (useVoiceCleaning).
+let running = 0;
+const runListeners = new Set<() => void>();
+const bump = (d: number) => {
+ running = Math.max(0, running + d);
+ runListeners.forEach((l) => l());
+};
+
+/** True while a slot's voice is being cleaned on this page (Generate waits: "Waiting for the clean voice"). */
+export function useVoiceCleaning(): boolean {
+ return useSyncExternalStore(
+ (cb) => {
+ runListeners.add(cb);
+ return () => runListeners.delete(cb);
+ },
+ () => running > 0,
+ () => false,
+ );
+}
+
+/** A slot's file after cleaning: the clean file, with the original kept for "Hear original". */
+export type CleanedSlot = SlotValue & { original?: string };
+
+async function post<T>(body: unknown): Promise<T> {
+ const res = await fetch("/api/audio-tools", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const j = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw responseError(res, j.error ?? `Clean up voice failed (${res.status})`);
+ return j;
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** How long a slot waits for its clean voice before it keeps the original. */
+export const CLEAN_WAIT_MS = 10 * 60_000;
+
+/** Follow a generation until it is done (its own events aren't needed here: a clean takes seconds to a minute). */
+async function settle(id: string, signal: AbortSignal, limitMs = CLEAN_WAIT_MS): Promise<Generation> {
+ const until = Date.now() + limitMs;
+ for (let wait = 800; ; wait = Math.min(3000, wait * 1.3)) {
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError");
+ if (Date.now() > until) throw new Error("it didn't finish in 10 minutes (is your ComfyUI running?)");
+ const res = await fetch(`/api/generations/${id}`, { signal });
+ if (res.ok) {
+ const g = (await res.json()) as Generation;
+ if (g.status === "succeeded") return g;
+ if (g.status === "failed" || g.status === "canceled") throw new Error(g.error ?? "Couldn't clean the voice");
+ }
+ await sleep(wait);
+ }
+}
+
+/** "Take 2.wav" -> "Take 2 · cleaned". */
+export const cleanedName = (name?: string) => `${(name ?? "Recording").replace(/\.[a-z0-9]{2,4}$/i, "")} · cleaned`;
+
+/** Clean one audio file on the open engine; resolves with the clean file's address. */
+export async function cleanVoiceFile(media: string, name: string | undefined, signal: AbortSignal): Promise<{ url: string; generation: Generation }> {
+ const run = await post<{ result: Generation }>({ tool: "clean", engine: "open", media, kind: "audio", ...(name && { name: name.slice(0, 200) }), strength: "full", level: "match", quality: "auto", background: "remove" });
+ const g = await settle(run.result.id, signal);
+ const out = g.outputs.find((o) => o.kind === "audio");
+ if (!out) throw new Error("The clean voice didn't come back");
+ return { url: out.url, generation: g };
+}
+
+/**
+ * Clean the files a slot takes while the switch is on. `take(v)` returns the value to show now (the original, marked as
+ * cleaning) and calls `onCleaned` with the clean value, or `onFailed` with the reason (the original stays).
+ */
+export function useCleanVoice(opts: { enabled: boolean; onCleaned: (v: CleanedSlot) => void; onFailed?: (why: string) => void }) {
+ const [busy, setBusy] = useState<{ ref: string } | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const ctl = useRef<AbortController | null>(null);
+ const cb = useRef(opts);
+ useEffect(() => {
+ cb.current = opts;
+ });
+ useEffect(() => () => ctl.current?.abort(), []);
+ // Counted while busy, so a studio's Generate waits for it.
+ const isBusy = !!busy;
+ useEffect(() => {
+ if (!isBusy) return;
+ bump(1);
+ return () => bump(-1);
+ }, [isBusy]);
+
+ const take = useCallback(
+ (v: SlotValue | null): boolean => {
+ ctl.current?.abort();
+ setError(null);
+ if (!v || v.kind !== "audio" || v.uploading || !v.ref?.startsWith("/api/files/") || !cb.current.enabled) {
+ setBusy(null);
+ return false;
+ }
+ const c = new AbortController();
+ ctl.current = c;
+ setBusy({ ref: v.ref });
+ void cleanVoiceFile(v.ref, v.name, c.signal)
+ .then(({ url }) => {
+ if (c.signal.aborted) return;
+ setBusy(null);
+ cb.current.onCleaned({ ...v, ref: url, preview: url, name: cleanedName(v.name), original: v.ref });
+ })
+ .catch((e: Error) => {
+ if (c.signal.aborted || e.name === "AbortError") return;
+ setBusy(null);
+ setError(e.message);
+ cb.current.onFailed?.(e.message);
+ });
+ return true;
+ },
+ [],
+ );
+ const cancel = useCallback(() => {
+ ctl.current?.abort();
+ setBusy(null);
+ }, []);
+ return { take, cancel, busy: !!busy, error };
+}
+
+/**
+ * For a sample row's upload (clone samples, Elements, narration): while the switch is on, an uploaded file is cleaned
+ * before it is handed over; a failure hands over the original and says why.
+ */
+export function useMaybeClean() {
+ const [on] = useCleanVoicePref();
+ const where = useCleanVoiceAvailability();
+ const ok = on && where === "ok";
+ const [busy, setBusy] = useState(false);
+ const ctl = useRef<{ c: AbortController; skip: () => void } | null>(null);
+ useEffect(() => () => ctl.current?.c.abort(), []);
+ const run = useCallback(
+ async (v: SlotValue, done: (v: CleanedSlot) => void) => {
+ if (!ok || v.kind !== "audio" || !v.ref?.startsWith("/api/files/")) return done(v);
+ ctl.current?.c.abort();
+ const c = new AbortController();
+ let skipped = false;
+ ctl.current = {
+ c,
+ skip: () => {
+ skipped = true;
+ c.abort();
+ },
+ };
+ setBusy(true);
+ try {
+ const { url } = await cleanVoiceFile(v.ref, v.name, c.signal);
+ done({ ...v, ref: url, preview: url, name: cleanedName(v.name), original: v.ref });
+ } catch (e) {
+ // Unmounted or replaced: nothing to hand over. Skipped: the original, quietly.
+ if (c.signal.aborted && !skipped) return;
+ if (!skipped) toast.error(`Couldn't clean the voice, so the original is kept: ${(e as Error).message}`);
+ done(v);
+ } finally {
+ if (ctl.current?.c === c) {
+ ctl.current = null;
+ setBusy(false);
+ }
+ }
+ },
+ [ok],
+ );
+ /** Stop waiting and hand over the original. */
+ const skip = useCallback(() => ctl.current?.skip(), []);
+ return { run, busy, skip };
+}
+
+type SlotStatus = { busy: boolean; error: string | null; value: CleanedSlot | null; cancel: () => void };
+let slotStatus: SlotStatus | null = null;
+const statusListeners = new Set<() => void>();
+const setSlotStatus = (s: SlotStatus | null) => {
+ slotStatus = s;
+ statusListeners.forEach((l) => l());
+};
+/** The voice slot's clean on this page (CleanVoiceSlot reports it; the switch beside it says it in words). */
+function useSlotStatus(): SlotStatus | null {
+ return useSyncExternalStore(
+ (cb) => {
+ statusListeners.add(cb);
+ return () => statusListeners.delete(cb);
+ },
+ () => slotStatus,
+ () => null,
+ );
+}
+
+/**
+ * The switch itself ("Clean up voice"), with a one-line hint. `status`: beside a composer's voice slot, the hint gives way
+ * to what the slot's clean is doing ("Cleaning the voice…", "Clean voice · Hear original", or why the original was kept).
+ */
+export function CleanVoiceSwitch({ className, hint, status }: { className?: string; hint?: string; status?: boolean }) {
+ const id = useId();
+ const [on, setOn] = useCleanVoicePref();
+ const where = useCleanVoiceAvailability();
+ const slot = useSlotStatus();
+ if (where === "hidden") return null;
+ const live = status && slot && (slot.busy || slot.error || slot.value?.original) ? slot : null;
+ return (
+ <div className={cn("flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1", className)}>
+ <Switch
+ id={id}
+ checked={on && where === "ok"}
+ onCheckedChange={(v) => {
+ if (where === "guest") return askToSignUp("run");
+ setOn(v);
+ }}
+ />
+ <label htmlFor={id} className="min-w-0 text-[12px] leading-tight">
+ <span className="font-medium">Clean up voice</span>
+ {!live && <span className="text-muted-foreground"> {hint ?? "noise, echo and room sound removed first (free, on your GPU)"}</span>}
+ </label>
+ {live && <CleanVoiceStatus value={live.value} busy={live.busy} error={live.error} onCancel={live.cancel} />}
+ </div>
+ );
+}
+
+/** Under a slot: "Cleaning the voice…", then "Clean voice · Hear original" (a popover with the before / after player). */
+export function CleanVoiceStatus({ value, busy, error, className, onCancel }: { value: CleanedSlot | null; busy: boolean; error: string | null; className?: string; onCancel?: () => void }) {
+ if (busy)
+ return (
+ <p className={cn("inline-flex flex-wrap items-center gap-1.5 text-[12px] text-muted-foreground", className)} role="status">
+ <Loader2 className="size-3 animate-spin" /> Cleaning the voice… about 20 s
+ {onCancel && (
+ <button type="button" className="font-medium text-foreground underline underline-offset-2" onClick={onCancel}>
+ Use the original
+ </button>
+ )}
+ </p>
+ );
+ if (error)
+ return (
+ <p className={cn("text-[12px] text-destructive", className)} role="alert">
+ Kept the original: {error}
+ </p>
+ );
+ if (!value?.original) return null;
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button type="button" className={cn("inline-flex items-center gap-1.5 rounded-full bg-success/15 px-2.5 py-1 text-[12px] font-medium text-success", className)}>
+ <Sparkles className="size-3" /> Clean voice · Hear original
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[min(92vw,440px)] p-3" collisionPadding={12}>
+ <p className="mb-2 inline-flex items-center gap-1.5 text-[13px] font-medium">
+ <AudioLines className="size-3.5" /> Original and clean voice
+ </p>
+ <BeforeAfterAudio before={value.original} after={value.ref} labels={{ before: "Original", after: "Clean" }} />
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/**
+ * Clean every new file a slot gets (an upload once it has landed, a recording, a Library pick) while the switch is on,
+ * and put the clean file in the slot when it's back (unless the slot holds something else by then).
+ */
+export function useAutoClean(value: CleanedSlot | null, set: (v: CleanedSlot) => void) {
+ const [on] = useCleanVoicePref();
+ const where = useCleanVoiceAvailability();
+ const enabled = on && where === "ok";
+ const current = useRef(value?.ref);
+ useEffect(() => {
+ current.current = value?.ref;
+ }, [value?.ref]);
+ const handled = useRef<string | null>(null);
+ const setRef = useRef(set);
+ useEffect(() => {
+ setRef.current = set;
+ });
+ const clean = useCleanVoice({ enabled, onCleaned: (v) => current.current === v.original && setRef.current(v) });
+ const { take, cancel } = clean;
+ const was = useRef(enabled);
+ useEffect(() => {
+ const turnedOff = was.current && !enabled;
+ was.current = enabled;
+ if (!enabled) {
+ handled.current = null;
+ if (!turnedOff) return;
+ // Switched off: stop a clean in progress, and the slot goes back to the file as it was added.
+ cancel();
+ if (value?.original && !value.uploading) setRef.current({ ...value, ref: value.original, preview: value.original, name: value.name?.replace(/ · cleaned$/, ""), original: undefined });
+ return;
+ }
+ if (!value?.ref || value.uploading || value.original || handled.current === value.ref) return;
+ // Only a file it took counts: with the switch off it waits, and turning the switch on cleans it.
+ if (take(value)) handled.current = value.ref;
+ }, [value, take, cancel, enabled]);
+ return clean;
+}
+
+/** A composer's voice slot with "Clean up voice": the tile, a spinner while it cleans, then a badge to hear the original. */
+export function CleanVoiceSlot({
+ slotKey,
+ label,
+ required,
+ value,
+ onChange,
+ onFile,
+}: {
+ slotKey: string;
+ label: string;
+ required?: boolean;
+ value: CleanedSlot | null;
+ onChange: (v: SlotValue | null) => void;
+ onFile?: (f: File) => void;
+}) {
+ const clean = useAutoClean(value, onChange);
+ const { busy, error, cancel } = clean;
+ useEffect(() => {
+ setSlotStatus({ busy, error, value: value?.original ? value : null, cancel });
+ }, [busy, error, value, cancel]);
+ useEffect(() => () => setSlotStatus(null), []);
+ return (
+ <div className="relative shrink-0">
+ <MediaSlot slotKey={slotKey} label={label} kind="audio" required={required} caption value={value} onChange={onChange} onFile={onFile} />
+ {clean.busy && (
+ <div className="pointer-events-none absolute inset-0 grid place-items-center rounded-xl bg-background/70" role="status" aria-label="Cleaning the voice">
+ <Loader2 className="size-4 animate-spin" />
+ </div>
+ )}
+ {(value?.original || clean.error) && !clean.busy && (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ aria-label={clean.error ? "Clean up voice failed" : "Clean voice: hear the original"}
+ className={cn("absolute -bottom-1.5 -left-1.5 grid size-5 place-items-center rounded-full shadow-soft", clean.error ? "bg-destructive text-white" : "bg-success text-white")}
+ >
+ <Sparkles className="size-3" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[min(92vw,440px)] p-3" collisionPadding={12}>
+ {clean.error ? (
+ <p className="text-[13px] text-destructive">Kept the original: {clean.error}</p>
+ ) : (
+ <>
+ <p className="mb-2 inline-flex items-center gap-1.5 text-[13px] font-medium">
+ <AudioLines className="size-3.5" /> Clean voice · hear the original
+ </p>
+ <BeforeAfterAudio before={value!.original!} after={value!.ref} labels={{ before: "Original", after: "Clean" }} />
+ </>
+ )}
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ );
+}
+
+export { CLEAN_FEATURE };
diff --git a/src/components/audio-tools/clean-voice-tool.tsx b/src/components/audio-tools/clean-voice-tool.tsx
new file mode 100644
index 00000000..6572540f
--- /dev/null
+++ b/src/components/audio-tools/clean-voice-tool.tsx
@@ -0,0 +1,520 @@
+"use client";
+
+import { AudioLines, ChevronRight, Clapperboard, Cpu, Download, FileVideo, Library, Loader2, Mic2, Sparkles, Upload, UserRound, X } from "lucide-react";
+import Link from "next/link";
+import { nanoid } from "nanoid";
+import { useCallback, useEffect, useId, useMemo, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Switch } from "@/components/ui/switch";
+import { Feed } from "@/components/studio/feed";
+import { ACCEPT, kindOfFile, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";
+import { VoiceRecorder } from "@/components/studio/voice-recorder";
+import { Segmented } from "@/components/faceless/controls";
+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
+import { useGeneration } from "@/components/av/use-generation";
+import { useAskBeforeUpload, useEngine, useGenerations } from "@/lib/api";
+import type { AudioToolPreview } from "@/lib/av/audio-tools";
+import {
+ BACKGROUND_LABELS,
+ CLEAN_FEATURE,
+ CLEAN_NOTES,
+ CLEAN_REMUX_FEATURE,
+ CLOUD_ONLY_CLEAN_PROBLEM,
+ CLOUD_CLEAN_PROBLEM,
+ cleanDefaults,
+ DEMO_CREDIT,
+ DEMO_PAIRS,
+ DEMO_READY,
+ durationWords,
+ khz,
+ LEVEL_LABELS,
+ QUALITY_HINTS,
+ QUALITY_LABELS,
+ REUSE_LABELS,
+ reportLine,
+ scanHint,
+ STRENGTH_LABELS,
+ type CleanBackground,
+ type CleanLevel,
+ type CleanQuality,
+ type CleanStrength,
+ type ReuseModel,
+} from "@/lib/av/clean-voice";
+import { clock } from "@/lib/av/audio-tools";
+import type { Generation, OutputFile } from "@/lib/catalog/types";
+import { downloadHref } from "@/lib/library";
+import { cn } from "@/lib/utils";
+import { toastError } from "@/lib/refusals";
+import { BeforeAfterAudio } from "./before-after-audio";
+import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";
+import { uploadSource } from "./split-tool";
+
+/**
+ * Clean up voice ("kinda like an app"): one tool, at /audio/clean and as the Clean up voice app. Drop a recording or a
+ * video; NVIDIA RE-USE cleans the voice on your ComfyUI (free, CPU or GPU) and the before/after player plays your own
+ * before and after from one playhead. Before anything is added, the demo player (once DEMO_READY) plays NVIDIA's own
+ * sample, cleaned, so everyone (guests too) hears what it does at once. There's no hosted RE-USE, so the cloud engine says so.
+ */
+
+type Source = SlotValue & { kind: "audio" | "video"; duration?: number; channels?: number };
+
+const baseName = (s: { name?: string }) => (s.name ?? "Recording").replace(/\.[a-z0-9]{2,4}$/i, "");
+const money = (p: AudioToolPreview) => (p.demo ? "Demo · free" : "Free · runs on your ComfyUI");
+const onDevice = (device?: string) => (device === "cuda" ? "on your GPU" : device ? "on your CPU" : "on a CPU");
+
+/** ?audio= / ?video= from a Library result's "Clean up voice" (or Split's "Clean the dialogue", with background=keep), read once after hydration. */
+function useHandoff(take: (s: Source, keep?: boolean) => void) {
+ useEffect(() => {
+ const q = new URLSearchParams(window.location.search);
+ for (const kind of ["video", "audio"] as const) {
+ const url = q.get(kind);
+ if (url?.startsWith("/api/files/")) return take({ ref: url, preview: url, kind, id: nanoid(8), name: decodeURIComponent(url.split("/").pop() ?? "") }, q.get("background") === "keep");
+ }
+ // Once, on arrival.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+}
+
+/** The guest demo: NVIDIA's sample in two pairs, played from static files (no run). */
+function DemoPlayer({ onTry }: { onTry: (before: string, label: string) => void }) {
+ const [pair, setPair] = useState(DEMO_PAIRS[0].id);
+ const p = DEMO_PAIRS.find((x) => x.id === pair) ?? DEMO_PAIRS[0];
+ return (
+ <Panel
+ title={
+ <span className="inline-flex items-center gap-1.5">
+ <Sparkles className="size-3.5" /> Hear it first
+ </span>
+ }
+ aside={<Segmented label="Sample" value={pair} onChange={setPair} options={DEMO_PAIRS.map((d) => ({ value: d.id, label: d.label, hint: d.hint }))} />}
+ >
+ <p className="mb-2 text-[12px] text-muted-foreground">{p.hint}. Switch Before and After while it plays: both run from the same moment, at the same level.</p>
+ <BeforeAfterAudio key={p.id} before={p.before} after={p.after} />
+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
+ <span>
+ {DEMO_CREDIT.text} ·{" "}
+ <a className="underline underline-offset-2" href={DEMO_CREDIT.model} target="_blank" rel="noreferrer">
+ model
+ </a>{" "}
+ ·{" "}
+ <a className="underline underline-offset-2" href={DEMO_CREDIT.licence} target="_blank" rel="noreferrer">
+ licence
+ </a>
+ </span>
+ {/* Always there (server and client agree): for a guest it opens "create an account". */}
+ <button type="button" className="ml-auto font-medium text-foreground underline underline-offset-2" onClick={() => onTry(p.before, p.label)}>
+ Try the sample yourself
+ </button>
+ </div>
+ </Panel>
+ );
+}
+
+function AddMedia({ onPick, onUpdate }: { onPick: (s: Source) => void; onUpdate: (next: (cur: Source | null) => Source | null) => void }) {
+ const [over, setOver] = useState(false);
+ const [picking, setPicking] = useState(false);
+ const askFirst = useAskBeforeUpload();
+ const inputId = useId();
+ const take = (f: File | undefined) => {
+ if (!f || askFirst()) return;
+ const kind = kindOfFile(f);
+ if (kind !== "audio" && kind !== "video") return void toast("Audio or video only — drop a recording or a clip here");
+ void uploadSource(f, kind, onPick, onUpdate);
+ };
+ return (
+ <div
+ className={cn(
+ "flex flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed border-border-strong bg-background px-4 py-8 text-center transition-colors sm:py-10",
+ over && "border-primary bg-brand-faint",
+ )}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setOver(false);
+ take(e.dataTransfer.files?.[0]);
+ }}
+ >
+ <span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">{over ? <Upload className="size-5" /> : <AudioLines className="size-5" />}</span>
+ <div>
+ <p className="text-[15px] font-medium">Add a voice recording or a video to clean</p>
+ <p className="mt-1 text-[13px] text-muted-foreground">Speech in any language, up to 200 MB · audio or video</p>
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-1.5">
+ <Button size="sm" className="rounded-full" onClick={() => askFirst() || document.getElementById(inputId)?.click()}>
+ <Upload className="size-3.5" /> Upload
+ </Button>
+ <VoiceRecorder max={300} onRecorded={(v) => onPick({ ...v, id: nanoid(8), kind: "audio", name: "Recording" })} />
+ <Popover open={picking} onOpenChange={setPicking}>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="sm" className="rounded-full">
+ <Library className="size-3.5" /> Pick from Library
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[min(92vw,360px)] p-2" collisionPadding={12}>
+ <p className="px-1 pb-2 text-[13px] font-medium">From your library</p>
+ {picking && (
+ <LibraryGrid
+ kinds={["audio", "video"]}
+ onPick={(v) => {
+ onPick({ ...v, kind: v.kind === "video" ? "video" : "audio" });
+ setPicking(false);
+ }}
+ />
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
+ <input
+ id={inputId}
+ type="file"
+ accept={`${ACCEPT.audio},${ACCEPT.video}`}
+ hidden
+ onChange={(e) => {
+ take(e.target.files?.[0]);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ );
+}
+
+function SourcePanel({ source, onDuration, onRemove }: { source: Source; onDuration: (s: number) => void; onRemove: () => void }) {
+ const meta = (e: React.SyntheticEvent<HTMLMediaElement>) => Number.isFinite(e.currentTarget.duration) && e.currentTarget.duration > 0 && onDuration(e.currentTarget.duration);
+ return (
+ <Panel
+ title={
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ {source.kind === "video" ? <FileVideo className="size-3.5 shrink-0" /> : <AudioLines className="size-3.5 shrink-0" />}
+ <span className="truncate">{baseName(source)}</span>
+ </span>
+ }
+ aside={
+ <>
+ {source.duration ? <span className="font-mono text-[12px] text-muted-foreground tabular-nums">{clock(source.duration)}</span> : null}
+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Remove the recording" onClick={onRemove}>
+ <X className="size-4" />
+ </Button>
+ </>
+ }
+ >
+ {source.uploading ? (
+ <p className="inline-flex items-center gap-2 text-[13px] text-muted-foreground" role="status">
+ <Loader2 className="size-3.5 animate-spin" /> Uploading…
+ </p>
+ ) : source.kind === "video" ? (
+ <video key={source.preview} src={source.preview} controls playsInline preload="metadata" onLoadedMetadata={meta} className="max-h-[36vh] w-full rounded-xl bg-media object-contain" />
+ ) : (
+ <audio key={source.preview} src={source.preview} controls preload="metadata" onLoadedMetadata={meta} className="h-9 w-full min-w-0" aria-label={`Play ${baseName(source)}`} />
+ )}
+ </Panel>
+ );
+}
+
+function Row({ label, children, hint }: { label: string; children: React.ReactNode; hint?: string }) {
+ return (
+ <div className="space-y-1">
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <span className="w-24 shrink-0 text-[13px]">{label}</span>
+ {children}
+ </div>
+ {hint && <p className="text-[12px] text-muted-foreground sm:pl-[6.5rem]">{hint}</p>}
+ </div>
+ );
+}
+
+const cleanOf = (g?: Generation | null): OutputFile | undefined => g?.outputs.find((o) => o.kind === "audio");
+const reportOf = (g?: Generation | null): string | undefined => g?.outputs.find((o) => o.kind === "text")?.text;
+
+export function CleanVoiceTool({ tabs, app }: { tabs?: React.ReactNode; app?: { name: string; description: string } }) {
+ const [engine, setEngine, mode] = useEngine();
+ const run = useAudioToolRun();
+ const [source, setSource] = useState<Source | null>(null);
+ const [model, setModel] = useState<ReuseModel>("voice");
+ const [quality, setQuality] = useState<CleanQuality>("auto");
+ const [strength, setStrength] = useState<CleanStrength | null>(null);
+ const [background, setBackground] = useState<CleanBackground | null>(null);
+ const [level, setLevel] = useState<CleanLevel>("match");
+ const [remux, setRemux] = useState(true);
+ const [resultId, setResultId] = useState<string | null>(null);
+ const [videoId, setVideoId] = useState<string | null>(null);
+ const result = useGeneration(resultId);
+ const onVideo = useGeneration(videoId);
+ const remuxId = useId();
+ const take = useCallback((s: Source, keep?: boolean) => {
+ setSource(s);
+ setResultId(null);
+ setVideoId(null);
+ setStrength(null);
+ setBackground(keep ? "keep" : null);
+ }, []);
+ useHandoff(take);
+ const askFirst = useAskBeforeUpload();
+ const tryDemo = async (url: string, label: string) => {
+ if (askFirst()) return;
+ try {
+ const blob = await (await fetch(url)).blob();
+ await uploadSource(new File([blob], `${label}.m4a`, { type: blob.type || "audio/mp4" }), "audio", take, setSource);
+ } catch (e) {
+ toastError(e, "Couldn't add the sample");
+ }
+ };
+
+ const kind = source?.kind ?? "audio";
+ const d = cleanDefaults(kind);
+ const pickedStrength = strength ?? d.strength;
+ const pickedBackground = background ?? d.background;
+ const ready = source && !source.uploading && source.ref ? source : null;
+ const body: AudioToolBody | null = useMemo(
+ () =>
+ ready
+ ? {
+ tool: "clean",
+ engine,
+ media: ready.ref,
+ kind: ready.kind,
+ name: baseName(ready),
+ model,
+ quality,
+ strength: pickedStrength,
+ background: pickedBackground,
+ level,
+ ...(ready.kind === "video" && { remux }),
+ ...(ready.channels && { channels: ready.channels }),
+ ...(ready.duration && { sourceDuration: ready.duration }),
+ }
+ : null,
+ [ready, engine, model, quality, pickedStrength, pickedBackground, level, remux],
+ );
+ const preview = useAudioToolPreview(useSettled(engine === "open" ? body : null));
+ const p = preview.data;
+ const cloudProblem = mode === "cloud" ? CLOUD_ONLY_CLEAN_PROBLEM : CLOUD_CLEAN_PROBLEM;
+ const blocker = !source ? "Add a recording to clean" : source.uploading ? "Uploading…" : engine === "cloud" ? cloudProblem : null;
+ const error = preview.error ? (preview.error as Error).message : null;
+ const g = result.data;
+ const busy = run.isPending || g?.status === "queued" || g?.status === "running" || onVideo.data?.status === "queued" || onVideo.data?.status === "running";
+ const go = () => {
+ if (blocker) return void toast(blocker);
+ if (error) return void toast.error(error);
+ run.mutate(body!, {
+ onSuccess: (r) => {
+ const clean = r.items.find((x) => x.feature === CLEAN_FEATURE) ?? r.result;
+ setResultId(clean.id);
+ setVideoId(r.items.find((x) => x.feature === CLEAN_REMUX_FEATURE)?.id ?? null);
+ toast.success("Cleaning on your ComfyUI");
+ },
+ onError: (e) => toastError(e),
+ });
+ };
+ const putBack = () => {
+ const out = cleanOf(g);
+ if (!source || !out) return;
+ run.mutate(
+ { tool: "remux", engine: "open", video: source.ref, audio: out.url, name: baseName(source) },
+ { onSuccess: (r) => (setVideoId(r.result.id), toast.success("Putting the clean voice on your video (picture copied as it is)")), onError: (e) => toastError(e) },
+ );
+ };
+ const out = g?.status === "succeeded" ? cleanOf(g) : undefined;
+ const line = reportLine(reportOf(g));
+ const hint = scanHint(reportOf(g));
+ const installed = p?.reuse?.installed;
+ const laughterMissing = installed && !installed.includes("laughter");
+
+ return (
+ <ToolShell
+ title={app ? "Apps" : "Audio"}
+ tabs={tabs}
+ header={
+ app ? (
+ <nav aria-label="Breadcrumb" className="hidden items-center gap-1 text-[13px] text-muted-foreground sm:flex">
+ <Link href="/apps" className="hover:text-foreground">
+ Apps
+ </Link>
+ <ChevronRight className="size-3.5" />
+ <span className="text-foreground">{app.name}</span>
+ </nav>
+ ) : undefined
+ }
+ >
+ {!source && (
+ <ToolHero
+ title={app?.name ?? "Clean up voice"}
+ subtitle="Removes noise, echo and room sound, and fixes clipping, muffled or phone-quality audio and bad mics. Keeps the main speaker, in any language. Free, on your own computer, with NVIDIA RE-USE."
+ />
+ )}
+ <div className={cn("mx-auto max-w-[860px] space-y-3", source ? "pt-4" : "mt-6")}>
+ {!source && DEMO_READY && <DemoPlayer onTry={(url, label) => void tryDemo(url, label)} />}
+ {!source ? (
+ <AddMedia onPick={take} onUpdate={setSource} />
+ ) : (
+ <SourcePanel
+ source={source}
+ onDuration={(duration) => setSource((s) => (s ? { ...s, duration } : s))}
+ onRemove={() => {
+ setSource(null);
+ setResultId(null);
+ setVideoId(null);
+ }}
+ />
+ )}
+ {source && engine === "cloud" && (
+ <Panel>
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <p className="min-w-0 flex-1 text-[13px] text-muted-foreground">
+ <span className="font-medium text-foreground">Clean up voice runs on your GPU (open source).</span>{" "}
+ {mode === "cloud"
+ ? "This install is set to paid cloud APIs only (Settings → Engine mode), and NVIDIA RE-USE isn't hosted on fal or Replicate."
+ : "NVIDIA RE-USE isn't hosted on fal or Replicate, so the cloud engine can't clean a voice."}
+ </p>
+ {mode === "both" ? (
+ <Button variant="outline" size="sm" className="shrink-0 rounded-full" onClick={() => setEngine("open")}>
+ <Cpu className="size-3.5" /> Use open source
+ </Button>
+ ) : null}
+ </div>
+ </Panel>
+ )}
+ {source && engine === "open" && (
+ <Panel title="Options">
+ <div className="space-y-3">
+ <Row label="Strength" hint={pickedStrength === "full" ? CLEAN_NOTES.gaps : "Leaves a little of the room under the voice, so pauses sound natural."}>
+ <Segmented label="Strength" value={pickedStrength} onChange={setStrength} options={(["full", "natural", "light"] as const).map((s) => ({ value: s, label: STRENGTH_LABELS[s] }))} />
+ </Row>
+ <Row label="Model" hint={model === "laughter" ? "Keep laughter keeps laughs and breaths a little more." : laughterMissing ? "Keep laughter isn't installed on your ComfyUI (models/reuse/NemotronLabs-RE-USE-laughter.safetensors)." : undefined}>
+ <Segmented
+ label="Model"
+ value={model}
+ onChange={(m) => (m === "laughter" && laughterMissing ? toast("Keep laughter isn't installed — copy its download from Workflows → Clean up voice") : setModel(m))}
+ options={(["voice", "laughter"] as const).map((m) => ({ value: m, label: `${REUSE_LABELS[m]}${m === "laughter" && laughterMissing ? " · not installed" : ""}` }))}
+ />
+ </Row>
+ <Row label="Quality" hint={QUALITY_HINTS[quality]}>
+ <Segmented label="Quality" value={quality} onChange={setQuality} options={(["auto", "full", "fast"] as const).map((q) => ({ value: q, label: QUALITY_LABELS[q] }))} />
+ </Row>
+ <Row label="Background" hint={pickedBackground === "keep" ? CLEAN_NOTES.keepNoise : CLEAN_NOTES.speaker}>
+ <Segmented label="Background" value={pickedBackground} onChange={setBackground} options={(["remove", "keep"] as const).map((b) => ({ value: b, label: BACKGROUND_LABELS[b] }))} />
+ </Row>
+ <Row label="Level">
+ <Segmented label="Level" value={level} onChange={setLevel} options={(["match", "voice"] as const).map((l) => ({ value: l, label: LEVEL_LABELS[l] }))} />
+ </Row>
+ {source.kind === "video" && (
+ <div className="flex items-center gap-2 sm:pl-[6.5rem]">
+ <Switch id={remuxId} checked={remux} onCheckedChange={setRemux} />
+ <label htmlFor={remuxId} className="text-[13px]">
+ Put back on the video <span className="text-muted-foreground">(the picture is copied as it is)</span>
+ </label>
+ </div>
+ )}
+ </div>
+ </Panel>
+ )}
+ {source && (
+ <div className="space-y-2">
+ {!blocker && !error && p && (
+ <div className="space-y-1 text-[13px] text-muted-foreground" aria-live="polite">
+ <p>{p.summary}</p>
+ {p.notes.map((n) => (
+ <p key={n} className="text-[12px]">
+ {n}
+ </p>
+ ))}
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-3">
+ <p className={cn("min-w-0 flex-1 text-[13px]", error && !blocker ? "text-destructive" : "text-muted-foreground")} aria-live="polite">
+ {blocker && engine !== "cloud" ? (
+ blocker
+ ) : engine === "cloud" ? (
+ mode === "cloud" ? (
+ "Not available on this install: it is set to paid cloud APIs only"
+ ) : (
+ "Switch to the open engine to clean a voice"
+ )
+ ) : error ? (
+ error
+ ) : p ? (
+ <>
+ <span className="font-mono text-foreground">{money(p)}</span>
+ {p.estimate && !p.demo ? ` · ${durationWords(p.estimate)} ${onDevice(p.device)}` : ""}
+ {p.reuse?.rate && !p.demo ? ` · ${khz(p.reuse.rate)}` : ""}
+ </>
+ ) : (
+ "Checking…"
+ )}
+ </p>
+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={busy}>
+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Clean up voice
+ </Button>
+ </div>
+ </div>
+ )}
+ {g && (g.status === "queued" || g.status === "running") && (
+ <Panel>
+ <p className="inline-flex items-center gap-2 text-[13px] text-muted-foreground" role="status">
+ <Loader2 className="size-3.5 animate-spin" /> {g.message ?? "Cleaning the voice"}…{g.progress ? ` ${Math.round(g.progress * 100)}%` : ""}
+ </p>
+ </Panel>
+ )}
+ {g?.status === "failed" && (
+ <p className="text-[13px] text-destructive" role="alert">
+ {g.error ?? "Cleaning failed"}
+ </p>
+ )}
+ {source && out && (
+ <Panel
+ title="Your before and after"
+ aside={line ? <span className="hidden text-[12px] text-muted-foreground sm:inline">{line}</span> : undefined}
+ >
+ <BeforeAfterAudio key={out.url} before={source.preview} after={out.url} labels={{ before: "Original", after: "Clean" }} />
+ {hint && <p className="mt-2 text-[12px] text-muted-foreground">{hint}</p>}
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <Button variant="outline" size="sm" className="rounded-full" asChild>
+ <a href={downloadHref(out.url, `${baseName(source)} · clean.flac`)} download>
+ <Download className="size-3.5" /> Download
+ </a>
+ </Button>
+ <Button variant="outline" size="sm" className="rounded-full" asChild>
+ <Link href={`/lipsync?audio=${encodeURIComponent(out.url)}`}>
+ <Mic2 className="size-3.5" /> Use in Lipsync
+ </Link>
+ </Button>
+ <Button variant="outline" size="sm" className="rounded-full" asChild>
+ <Link href={`/audio?voice=${encodeURIComponent(out.url)}`}>
+ <UserRound className="size-3.5" /> Use as a voice sample
+ </Link>
+ </Button>
+ {source.kind === "video" && !videoId && (
+ <Button size="sm" className="rounded-full" disabled={busy} onClick={putBack}>
+ <Clapperboard className="size-3.5" /> Put back on the video
+ </Button>
+ )}
+ {onVideo.data?.status === "succeeded" && <span className="text-[12px] text-success">The clean video is in your Library.</span>}
+ </div>
+ </Panel>
+ )}
+ </div>
+ <Results />
+ </ToolShell>
+ );
+}
+
+/** Earlier cleans (and videos with their clean soundtrack). */
+function Results() {
+ const cleans = useGenerations({ features: [CLEAN_FEATURE], limit: 12 });
+ const videos = useGenerations({ features: [CLEAN_REMUX_FEATURE], limit: 12 });
+ const items = [...(videos.data ?? []), ...(cleans.data ?? [])].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
+ if (!items.length) return null;
+ return (
+ <section className="mx-auto mt-10 max-w-[1040px]" aria-labelledby="clean-results">
+ <h3 id="clean-results" className="mb-3 font-heading text-[22px]">
+ Your clean voices
+ </h3>
+ <Feed items={items} />
+ </section>
+ );
+}
diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.ts
index 942aa127..1f49c160 100644
--- a/src/components/audio-tools/hooks.ts
+++ b/src/components/audio-tools/hooks.ts
@@ -10,6 +10,22 @@ export type AudioToolBody =
| { tool: "loop"; engine: Engine; audio: string; name?: string; duration: number; sourceDuration?: number; crossfade?: number; curve?: "equal-power" | "linear" }
| { tool: "join"; engine: Engine; clips: { url: string; name?: string; duration?: number }[]; crossfade?: number; curve?: "equal-power" | "linear" }
| { tool: "split"; engine: Engine; media: string; kind: "audio" | "video"; name?: string; quality?: "fast" | "best"; stereo?: boolean; channels?: number; sourceDuration?: number }
+ | {
+ tool: "clean";
+ engine: Engine;
+ media: string;
+ kind: "audio" | "video";
+ name?: string;
+ model?: "voice" | "laughter";
+ quality?: "auto" | "full" | "fast";
+ strength?: "full" | "natural" | "light";
+ background?: "remove" | "keep";
+ level?: "match" | "voice";
+ remux?: boolean;
+ stereo?: boolean;
+ channels?: number;
+ sourceDuration?: number;
+ }
| { tool: "remux"; engine: Engine; video: string; audio: string; name?: string };
async function post<T>(url: string, body: AudioToolBody): Promise<T> {
diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsx
index 4f497e7a..66300726 100644
--- a/src/components/audio-tools/split-tool.tsx
+++ b/src/components/audio-tools/split-tool.tsx
@@ -2,6 +2,7 @@
import { AudioLines, Clapperboard, Cpu, Download, FileVideo, Headphones, Library, Loader2, Pause, Play, Save, SlidersVertical, Upload, Volume2, VolumeX, X } from "lucide-react";
import { nanoid } from "nanoid";
+import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
@@ -641,6 +642,11 @@ function Mixer({ stems, source, engine }: { stems: Stem[]; source: Source; engin
{busy === "remux" ? <Loader2 className="size-4 animate-spin" /> : <Clapperboard className="size-4" />} Put back on the video{remuxCost ? ` · ${remuxCost}` : ""}
</Button>
)}
+ <Button variant="ghost" className="rounded-full" asChild>
+ <Link href={`/audio/clean?${source.kind}=${encodeURIComponent(source.ref)}&background=keep`}>
+ <AudioLines className="size-4" /> Clean the dialogue
+ </Link>
+ </Button>
<span className="text-[12px] text-muted-foreground">{mixName(mix)}</span>
</div>
</section>
diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsx
index dab98d73..6a27d836 100644
--- a/src/components/canvas/nodes.tsx
+++ b/src/components/canvas/nodes.tsx
@@ -1501,7 +1501,7 @@ const CloneVoiceNode = memo(function CloneVoiceNode({ id, data, selected }: Node
{!readOnly && !wired && (
<div className="flex flex-wrap gap-1">
<div className={NO_DRAG}>
- <VoiceRecorder onRecorded={(v) => actions.update(id, { url: v.ref, name: v.name ?? "Recording", elementId: undefined })} className={chip} />
+ <VoiceRecorder clean onRecorded={(v) => actions.update(id, { url: v.ref, name: v.name ?? "Recording", elementId: undefined })} className={chip} />
</div>
<button className={chip} onClick={() => file.current?.click()}>
<Upload className="size-3" /> {data.url ? "Replace" : "Upload"}
@@ -1767,6 +1767,7 @@ export const NODE_TYPES = {
"bg-remove": GeneratorNode,
tts: GeneratorNode,
"voice-change": GeneratorNode,
+ "clean-voice": GeneratorNode,
"clone-voice": CloneVoiceNode,
translate: GeneratorNode,
concat: GeneratorNode,
diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsx
index 2aa3e0c6..3effda9c 100644
--- a/src/components/elements-view.tsx
+++ b/src/components/elements-view.tsx
@@ -27,6 +27,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { ELEMENT_ICONS } from "@/components/studio/prompt-input";
import { VoiceRecorder } from "@/components/studio/voice-recorder";
+import { useMaybeClean } from "@/components/audio-tools/clean-voice-switch";
import { SelfHostNote } from "@/components/self-host-note";
import { useEdgeFade } from "@/components/studio/use-edge-fade";
import { useDeleteElement, useElements, useIsVisitor, useSaveElement } from "@/lib/api";
@@ -219,6 +220,8 @@ function ElementForm({ onOpenChange, element, defaultKind = "character", onSaved
/** One voice recording: record it here or upload a file, then listen back. */
function VoiceSample({ value, onChange }: { value?: SlotValue; onChange: (v: SlotValue | null) => void }) {
+ // "Clean up voice": the saved voice keeps the clean file (references[0]), so every clone made from it is cleaner.
+ const clean = useMaybeClean();
return value?.ref ? (
<div className="flex items-center gap-2 rounded-xl border bg-muted/40 p-2">
<audio src={value.preview} controls className="h-9 flex-1" />
@@ -227,9 +230,19 @@ function VoiceSample({ value, onChange }: { value?: SlotValue; onChange: (v: Slo
</Button>
</div>
) : (
- <div className="flex items-center gap-2">
- <VoiceRecorder onRecorded={onChange} />
- <MediaSlot label="Upload" kind="audio" value={null} onChange={(v) => v && !v.uploading && onChange(v)} />
+ <div className="space-y-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <VoiceRecorder onRecorded={onChange} clean />
+ <MediaSlot label="Upload" kind="audio" value={null} onChange={(v) => v && !v.uploading && void clean.run(v, onChange)} />
+ </div>
+ {clean.busy && (
+ <p className="inline-flex items-center gap-1.5 text-[12px] text-muted-foreground" role="status">
+ <Loader2 className="size-3 animate-spin" /> Cleaning the voice…
+ <button type="button" className="font-medium text-foreground underline underline-offset-2" onClick={clean.skip}>
+ Use the original
+ </button>
+ </p>
+ )}
</div>
);
}
diff --git a/src/components/faceless/narrator.tsx b/src/components/faceless/narrator.tsx
index f3b6cc65..dbadbd78 100644
--- a/src/components/faceless/narrator.tsx
+++ b/src/components/faceless/narrator.tsx
@@ -8,6 +8,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { fileToSlot } from "@/components/studio/media-slot";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
import { VoiceRecorder } from "@/components/studio/voice-recorder";
+import { useMaybeClean } from "@/components/audio-tools/clean-voice-switch";
import { useElements } from "@/lib/api";
import type { NarratorVoice, PickerData } from "@/lib/catalog/faceless";
import type { Engine } from "@/lib/catalog/types";
@@ -95,6 +96,8 @@ export function NarratorList({ engine, voices, value, onChange }: { engine: Engi
const file = useRef<HTMLInputElement>(null);
const [q, setQ] = useState("");
const [uploading, setUploading] = useState(false);
+ // "Clean up voice" on the sample: the narration is cloned from the clean file (Faceless and Explainer both).
+ const clean = useMaybeClean();
const p = usePlayer();
const list = voices.filter((v) => !q || `${v.name} ${v.hint ?? ""}`.toLowerCase().includes(q.toLowerCase()));
const own = value?.kind === "sample" && !saved.some((e) => e.references[0] === value.url) ? value : null;
@@ -164,14 +167,14 @@ export function NarratorList({ engine, voices, value, onChange }: { engine: Engi
{own && row(`own:${own.url}`, own, own.name ?? "Your recording", "Recorded or uploaded", async () => own.url)}
</div>
<div className="flex flex-wrap items-center gap-1.5 px-1 pt-2">
- <VoiceRecorder onRecorded={(v) => onChange({ kind: "sample", url: v.ref, name: v.name ?? "Your recording" })} />
+ <VoiceRecorder clean onRecorded={(v) => onChange({ kind: "sample", url: v.ref, name: v.name ?? "Your recording" })} />
<button
type="button"
onClick={() => file.current?.click()}
disabled={uploading}
className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent disabled:opacity-60"
>
- {uploading ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} Upload
+ {uploading || clean.busy ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} {clean.busy ? "Cleaning…" : "Upload"}
</button>
<input
ref={file}
@@ -186,7 +189,7 @@ export function NarratorList({ engine, voices, value, onChange }: { engine: Engi
f,
(v) => {
setUploading(!!v?.uploading);
- if (v && !v.uploading) onChange({ kind: "sample", url: v.ref, name: f.name.replace(/\.[^.]+$/, "") });
+ if (v && !v.uploading) void clean.run(v, (c) => onChange({ kind: "sample", url: c.ref, name: `${f.name.replace(/\.[^.]+$/, "")}${c.original ? " · cleaned" : ""}` }));
},
"audio",
);
diff --git a/src/components/studio/audio-controls.tsx b/src/components/studio/audio-controls.tsx
index 4b9fa946..99649364 100644
--- a/src/components/studio/audio-controls.tsx
+++ b/src/components/studio/audio-controls.tsx
@@ -10,6 +10,7 @@ import type { GenParams, ModelDef } from "@/lib/catalog/types";
import { cn } from "@/lib/utils";
import { fileToSlot, type SlotValue } from "./media-slot";
import { VoiceRecorder } from "./voice-recorder";
+import { useMaybeClean } from "@/components/audio-tools/clean-voice-switch";
const chip = "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors";
const idle = "bg-secondary text-secondary-foreground hover:bg-accent";
@@ -71,6 +72,7 @@ export function VoicePicker({
};
// Someone whose upload would be refused (a guest, an account with no GPU or key) gets its card, not the file chooser.
const askFirst = useAskBeforeUpload();
+ const clean = useMaybeClean();
const upload = () => {
if (!askFirst()) return file.current?.click();
setOpen(false);
@@ -87,7 +89,7 @@ export function VoicePicker({
{clone && (
<Section title="Clone a voice">
<div className="flex flex-wrap gap-1.5 px-2 pb-1">
- <VoiceRecorder onRecorded={(v) => pick({ kind: "sample", value: v })} />
+ <VoiceRecorder clean onRecorded={(v) => pick({ kind: "sample", value: v })} />
<button type="button" onClick={upload} className={cn(chip, idle)}>
<Upload className="size-3.5" /> Upload
</button>
@@ -98,12 +100,12 @@ export function VoicePicker({
hidden
onChange={(e) => {
const f = e.target.files?.[0];
- if (f) void fileToSlot(f, (v) => v && !v.uploading && pick({ kind: "sample", value: v }), "audio");
+ if (f) void fileToSlot(f, (v) => v && !v.uploading && void clean.run(v, (c) => pick({ kind: "sample", value: c })), "audio");
e.target.value = "";
}}
/>
</div>
- <p className="px-2 pb-1 text-[11px] text-muted-foreground">10–60 s of clean speech works best.</p>
+ <p className="px-2 pb-1 text-[11px] text-muted-foreground">{clean.busy ? "Cleaning the voice…" : "10–60 s of clean speech works best. Clean samples make cleaner clones: a clone copies room noise."}</p>
</Section>
)}
{clone && (
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index e9252146..1e2f70a3 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -95,6 +95,7 @@ import { SketchTools } from "./sketch-tools";
import { RECENT_MODELS, useStoredList } from "./stored-list";
import { usePresetUrl, useStartRequest, useStudio, type Draft } from "./studio-context";
import { useEdgeFade } from "./use-edge-fade";
+import { CleanVoiceSlot, CleanVoiceSwitch, useVoiceCleaning } from "@/components/audio-tools/clean-voice-switch";
import { useSignature } from "../palettes/use-signature";
import { placeholdersOn } from "@/lib/demo-mode";
@@ -511,6 +512,7 @@ export function Composer({ docked }: { docked: boolean }) {
[baseSlots, model?.options.imageLabels, config.multiRef?.label, draft.refs.length],
);
const slots = named.slots;
+ const hasCleanVoice = slots.some((s) => s.cleanVoice && s.accept === "audio");
// Clips: ComfyUI joins 4 at a time. Images: what the model takes beyond the fixed image slots, for the operation the run
// will be (a painted mask makes it an inpaint, which Qwen-Image 2.1 runs on the picture alone).
const refOp = studioOp ?? (draft.slots.mask?.ref && model && routesFor(model, "inpaint").length ? "inpaint" : undefined);
@@ -560,6 +562,8 @@ export function Composer({ docked }: { docked: boolean }) {
const askedSlots = framesOn ? framesSlots(slots) : slots;
const missing = firstMissingSlot(askedSlots, draft.slots, anyOf);
const uploading = Object.values(draft.slots).some((v) => v?.uploading) || draft.refs.some((r) => r.uploading) || (framesOn && framesUploading(draft.frames));
+ // A voice slot's "Clean up voice" is cleaning the file that just landed: Generate waits for the clean one.
+ const cleaningVoice = useVoiceCleaning();
// Export without a ComfyUI to write it (none connected, or the install runs cloud APIs only): say so and offer the cloud route.
// A cloud-only install refuses open models, and without placeholder results nothing else runs it, so Generate says why.
const comfyMissing = !!config.comfyOnly && !!status && (engineMode === "cloud" || !status.providers.comfyui?.configured);
@@ -617,6 +621,7 @@ export function Composer({ docked }: { docked: boolean }) {
frames: framesOn && model ? (framesBlocker(model, draft.frames!.length) ?? (framesGap ? { message: framesGap } : null)) : null,
missing,
uploading,
+ cleaning: cleaningVoice,
maskMissing: needsMask(model, config.sketch, draft.slots),
planError,
promptMissing,
@@ -1024,19 +1029,32 @@ export function Composer({ docked }: { docked: boolean }) {
)}
{showAttachments && !collapsed && !framesOn && (
<div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-2">
- {slots.map((s) => (
- <MediaSlot
- key={s.key}
- slotKey={s.key}
- label={s.label}
- kind={s.accept}
- required={s.required}
- caption
- value={draft.slots[s.key] ?? null}
- onChange={(v) => attach.setSlotValue(s.key, v)}
- onFile={(f) => attach.uploadToSlot(s.key, f, s.accept)}
- />
- ))}
+ {slots.map((s) =>
+ s.cleanVoice && s.accept === "audio" ? (
+ <CleanVoiceSlot
+ key={s.key}
+ slotKey={s.key}
+ label={s.label}
+ required={s.required}
+ value={draft.slots[s.key] ?? null}
+ onChange={(v) => attach.setSlotValue(s.key, v)}
+ onFile={(f) => attach.uploadToSlot(s.key, f, s.accept)}
+ />
+ ) : (
+ <MediaSlot
+ key={s.key}
+ slotKey={s.key}
+ label={s.label}
+ kind={s.accept}
+ required={s.required}
+ caption
+ value={draft.slots[s.key] ?? null}
+ onChange={(v) => attach.setSlotValue(s.key, v)}
+ onFile={(f) => attach.uploadToSlot(s.key, f, s.accept)}
+ />
+ ),
+ )}
+ {hasCleanVoice && <CleanVoiceSwitch status className="hidden max-w-[16rem] shrink-0 sm:flex" hint="first, free on your GPU" />}
{config.sketch && draft.slots.image?.ref && !draft.slots.image.uploading && (
<SketchTools modes={config.sketch} image={draft.slots.image.ref} autoOpen={config.sketchAutoOpen} />
)}
@@ -1070,6 +1088,8 @@ export function Composer({ docked }: { docked: boolean }) {
)}
</div>
)}
+ {/* On a phone the slot row scrolls sideways, so the switch gets its own line under it. */}
+ {showAttachments && !collapsed && !framesOn && hasCleanVoice && <CleanVoiceSwitch status className="px-3 pb-2 sm:hidden" hint="first, free on your GPU" />}
{showPrompt && (
<PromptInput
diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsx
index 98d3c0db..f8f9c2c3 100644
--- a/src/components/studio/mode-switch-studio.tsx
+++ b/src/components/studio/mode-switch-studio.tsx
@@ -30,6 +30,7 @@ import { RemoveObjectTool } from "@/components/remove-object/remove-object-tool"
import { EvolutionTool } from "@/components/evolution/evolution-tool";
import { AudioJoinTool, AudioLoopTool } from "@/components/audio-tools/audio-tools";
import { SplitSoundtrackTool } from "@/components/audio-tools/split-tool";
+import { CleanVoiceTool } from "@/components/audio-tools/clean-voice-tool";
import { ModeStudio, ModeTabs } from "./mode-studio";
import type { StudioConfig } from "./studio-context";
@@ -54,13 +55,14 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {
},
};
-/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Remove object, Evolution, Captions, Trim). */
+/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Clean up voice, Remove object, Evolution, Captions, Trim). */
const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {
audio: {
translate: ({ tabs }) => <DubStudio tabs={tabs} />,
loop: ({ tabs }) => <AudioLoopTool tabs={tabs} />,
join: ({ tabs }) => <AudioJoinTool tabs={tabs} />,
split: ({ tabs }) => <SplitSoundtrackTool tabs={tabs} />,
+ clean: ({ tabs }) => <CleanVoiceTool tabs={tabs} />,
},
"video-tools": {
"remove-object": ({ tabs }) => <RemoveObjectTool tabs={tabs} />,
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 18b36e73..8e581a12 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -26,6 +26,7 @@ import {
Share2,
SlidersHorizontal,
SlidersVertical,
+ AudioWaveform,
Sparkles,
Trash2,
UserRoundPlus,
@@ -89,6 +90,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
"voice-change": AudioLines,
"loop-audio": Repeat,
"split-soundtrack": SlidersVertical,
+ "clean-voice": AudioWaveform,
"copy-text": Copy,
"view-3d": Box,
download: Download,
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index d5aa0dab..9499316b 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -79,6 +79,8 @@ function initialDraft(
}
if (sp.get("video")) slots.video = slot(sp.get("video"));
if (sp.get("audio")) slots.audio = slot(sp.get("audio"));
+ // A voice sample handed over (Clean up voice → "Use as a voice sample"): the voice a cloning model speaks with.
+ if (sp.get("voice")) slots.voiceAudio = slot(sp.get("voice"));
// An output format handed over in the link (Export → "ProRes in the cloud"), when the model writes it.
const format = model?.options.formats?.find((f) => f === sp.get("format"));
return {
diff --git a/src/components/studio/voice-recorder.tsx b/src/components/studio/voice-recorder.tsx
index e173a70e..e7bbb2fb 100644
--- a/src/components/studio/voice-recorder.tsx
+++ b/src/components/studio/voice-recorder.tsx
@@ -7,6 +7,7 @@ import { uploadFile, useAskBeforeUpload } from "@/lib/api";
import { cn } from "@/lib/utils";
import { toastError } from "@/lib/refusals";
import type { SlotValue } from "./media-slot";
+import { cleanVoiceFile, CleanVoiceSwitch, useCleanVoiceAvailability, useCleanVoicePref } from "@/components/audio-tools/clean-voice-switch";
/** Decode any recording the browser made and re-encode it as 16-bit mono WAV — every voice API takes WAV. */
export async function toWav(blob: Blob): Promise<File> {
@@ -40,17 +41,26 @@ export async function toWav(blob: Blob): Promise<File> {
}
}
-/** Mic button: record a voice sample, convert it to WAV and upload it. Whoever the upload would refuse is asked first. */
-export function VoiceRecorder({ onRecorded, max = 60, className }: { onRecorded: (v: SlotValue) => void; max?: number; className?: string }) {
- const [state, setState] = useState<"idle" | "recording" | "saving">("idle");
+/**
+ * Mic button: record a voice sample, convert it to WAV and upload it. Whoever the upload would refuse is asked first.
+ * `clean`: a "Clean up voice" switch sits beside it, and while it is on the recording is cleaned (RE-USE, open engine)
+ * before it is handed over, named "Recording · cleaned" (the original rides along to compare).
+ */
+export function VoiceRecorder({ onRecorded, max = 60, className, clean }: { onRecorded: (v: SlotValue & { original?: string }) => void; max?: number; className?: string; clean?: boolean }) {
+ const [state, setState] = useState<"idle" | "recording" | "saving" | "cleaning">("idle");
+ const [cleanOn] = useCleanVoicePref();
+ const cleanHere = useCleanVoiceAvailability() === "ok" && !!clean && cleanOn;
const [secs, setSecs] = useState(0);
const rec = useRef<MediaRecorder | null>(null);
const timer = useRef<ReturnType<typeof setInterval> | null>(null);
+ // The clean in progress: aborted when the recorder goes away, or by "Use the original" (skipped).
+ const cleaning = useRef<{ c: AbortController; skipped: boolean } | null>(null);
useEffect(
() => () => {
if (timer.current) clearInterval(timer.current);
rec.current?.stream.getTracks().forEach((t) => t.stop());
+ cleaning.current?.c.abort();
},
[],
);
@@ -79,6 +89,23 @@ export function VoiceRecorder({ onRecorded, max = 60, className }: { onRecorded:
try {
const file = await toWav(new Blob(chunks, { type: r.mimeType }));
const asset = await uploadFile(file);
+ if (cleanHere) {
+ setState("cleaning");
+ const job = { c: new AbortController(), skipped: false };
+ cleaning.current = job;
+ try {
+ const { url } = await cleanVoiceFile(asset.url, "Recording", job.c.signal);
+ onRecorded({ ref: url, preview: url, kind: "audio", name: "Recording · cleaned", original: asset.url });
+ } catch (e) {
+ // Gone from the page: nothing to hand over. Skipped: the original, quietly. Failed: the original, and why.
+ if (job.c.signal.aborted && !job.skipped) return;
+ if (!job.skipped) toastError(e, "Couldn't clean the voice, so the original is kept");
+ onRecorded({ ref: asset.url, preview: asset.url, kind: "audio", name: "Recording" });
+ } finally {
+ if (cleaning.current === job) cleaning.current = null;
+ }
+ return;
+ }
onRecorded({ ref: asset.url, preview: asset.url, kind: "audio", name: "Recording" });
} catch (e) {
toastError(e, "Couldn't save the recording");
@@ -97,19 +124,34 @@ export function VoiceRecorder({ onRecorded, max = 60, className }: { onRecorded:
}, 1000);
};
- return (
+ const skipClean = () => {
+ const job = cleaning.current;
+ if (!job) return;
+ job.skipped = true;
+ job.c.abort();
+ };
+
+ const button = (
<button
type="button"
- onClick={state === "recording" ? stop : start}
+ onClick={state === "recording" ? stop : state === "cleaning" ? skipClean : start}
disabled={state === "saving"}
+ title={state === "cleaning" ? "Use the original recording now" : undefined}
className={cn(
"inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium transition-colors",
state === "recording" ? "bg-destructive text-white" : "bg-secondary text-secondary-foreground hover:bg-accent",
className,
)}
>
- {state === "saving" ? <Loader2 className="size-3.5 animate-spin" /> : state === "recording" ? <Square className="size-3 fill-current" /> : <Mic className="size-3.5" />}
- {state === "recording" ? `Stop · 0:${String(secs).padStart(2, "0")}` : state === "saving" ? "Saving…" : "Record"}
+ {state === "saving" || state === "cleaning" ? <Loader2 className="size-3.5 animate-spin" /> : state === "recording" ? <Square className="size-3 fill-current" /> : <Mic className="size-3.5" />}
+ {state === "recording" ? `Stop · ${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, "0")}` : state === "saving" ? "Saving…" : state === "cleaning" ? "Cleaning… · Skip" : "Record"}
</button>
);
+ if (!clean) return button;
+ return (
+ <span className="inline-flex flex-wrap items-center gap-2">
+ {button}
+ <CleanVoiceSwitch hint="" />
+ </span>
+ );
}
diff --git a/src/lib/av/audio-tools.ts b/src/lib/av/audio-tools.ts
index 830be530..2049131f 100644
--- a/src/lib/av/audio-tools.ts
+++ b/src/lib/av/audio-tools.ts
@@ -66,6 +66,8 @@ export interface AudioToolPreview {
installed?: ("fast" | "best")[];
/** The file's channel count from its header, when the server could read it (the page then needn't decode the file). */
channels?: number;
+ /** Clean up voice: the RE-USE files the host has (when it said), the rate the model would run at, and the file's length. */
+ reuse?: { installed?: ("voice" | "laughter")[]; rate: number; seconds?: number };
}
export interface LoopInput {
diff --git a/src/lib/av/clean-voice.ts b/src/lib/av/clean-voice.ts
index c8772b2b..6f07f091 100644
--- a/src/lib/av/clean-voice.ts
+++ b/src/lib/av/clean-voice.ts
@@ -29,6 +29,7 @@ export const CLOUD_ONLY_CLEAN_PROBLEM = "Clean up voice runs on your GPU (open s
export const CLEAN_NOTES = {
speaker: "It keeps the main speaker. Other voices, music and effects are removed unless you keep music & effects.",
gaps: "Gaps between words come out silent at Full strength.",
+ keepNoise: "DBS splits the soundtrack first and only the dialogue is cleaned. The music and effects go back under it, with any background noise in them.",
};
// ---------------------------------------------------------------------------
@@ -210,7 +211,9 @@ export interface CleanPlan extends ToolPlan {
/** Defaults: audio is cleaned Full with nothing kept; a video keeps its music and effects at Natural strength and goes back on the picture. */
export function cleanDefaults(kind: "audio" | "video"): { strength: CleanStrength; background: CleanBackground; remux: boolean } {
- return kind === "video" ? { strength: "natural", background: "keep", remux: true } : { strength: "full", background: "remove", remux: false };
+ // A video too removes everything but the voice by default: "Keep music & effects" brings back the original minus the
+ // speech, and the noise with it (and it needs ComfyUI-DBS).
+ return kind === "video" ? { strength: "natural", background: "remove", remux: true } : { strength: "full", background: "remove", remux: false };
}
const titleOf = (i: { name?: string; kind: "audio" | "video" }) => `Clean voice · ${i.name?.trim() || (i.kind === "video" ? "video soundtrack" : "recording")}`;
@@ -275,9 +278,8 @@ export function planClean(i: CleanInput): CleanPlan {
background === "keep"
? `Splits ${what} with DBS, cleans the dialogue with RE-USE and puts the music and effects back under it${remux ? ", then puts it back on the picture (copied as it is)" : ""}.`
: `Cleans ${what} with RE-USE${remux ? ", then puts it back on the picture (copied as it is)" : ""}.`,
+ // The speaker and silent-gap notes show under Background and Strength, so they aren't repeated here.
notes: [
- ...(background === "keep" ? [] : [CLEAN_NOTES.speaker]),
- ...(strength === "full" ? [CLEAN_NOTES.gaps] : []),
...(surround ? [`This file has ${i.channels} channels: it is cleaned in mono, as ComfyUI saves mono or stereo only.`] : []),
],
};
@@ -332,8 +334,13 @@ export interface DemoPair {
}
export const DEMO_DIR = "/samples/clean-voice";
+/**
+ * The demo player shows once a person has listened to the pairs (scripts/gen-clean-voice-demo.mjs makes them into
+ * public/samples/clean-voice, with the licence and notice beside them) and said yes. Until then the tool opens on Add.
+ */
+export const DEMO_READY = false;
export const DEMO_PAIRS: DemoPair[] = [
{ id: "noisy-mic", label: "Noisy mic", hint: "Hiss, hum and a whine from a cheap mic, cleaned at the source's rate", before: `${DEMO_DIR}/noisy-mic-before.m4a`, after: `${DEMO_DIR}/noisy-mic-after.m4a` },
- { id: "phone", label: "Phone line → full band", hint: "The same speech squeezed into a phone line, then restored to 48 kHz", before: `${DEMO_DIR}/phone-before.m4a`, after: `${DEMO_DIR}/phone-after.m4a` },
+ { id: "phone", label: "Phone line", hint: "The same speech squeezed into a phone line, then restored to 48 kHz", before: `${DEMO_DIR}/phone-before.m4a`, after: `${DEMO_DIR}/phone-after.m4a` },
];
export const DEMO_CREDIT = { text: "Sample and model: NVIDIA RE-USE (OpenMDW-1.1)", model: "https://huggingface.co/nvidia/NVIDIA-NemotronLabs-RE-USE", licence: `${DEMO_DIR}/LICENSE-OpenMDW-1.1.txt` };
diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.ts
index 8b102cf5..6d15c122 100644
--- a/src/lib/catalog/apps.ts
+++ b/src/lib/catalog/apps.ts
@@ -43,7 +43,7 @@ const OUTPAINT_OPEN: PresetRoute = {
const photo: InputSlot = { key: "image", label: "Photo", accept: "image", required: true };
const product: InputSlot = { key: "image", label: "Product", hint: "A clear photo of the product", accept: "image", required: true };
const portrait: InputSlot = { key: "image", label: "Portrait", hint: "A clear, front-facing photo", accept: "image", required: true };
-const voice: InputSlot = { key: "audio", label: "Voice audio", hint: "Speech or whisper track (record, upload or make one in Audio)", accept: "audio", required: true };
+const voice: InputSlot = { key: "audio", label: "Voice audio", hint: "Speech or whisper track (record, upload or make one in Audio)", accept: "audio", required: true, cleanVoice: true };
const second = (label: string, hint?: string): InputSlot => ({ key: "image2", label, hint, accept: "image", required: true });
const third = (label: string, hint?: string): InputSlot => ({ key: "image3", label, hint, accept: "image", required: false });
@@ -73,6 +73,7 @@ type AppSpec = {
open?: Partial<PresetRoute> | null;
badges?: Preset["badges"];
parity?: string;
+ tool?: Preset["tool"];
};
function slug(s: string) {
@@ -101,6 +102,7 @@ function app(a: AppSpec): Preset {
cloud: cloud as PresetRoute | null,
open: open as PresetRoute | null,
parity: a.parity,
+ ...(a.tool && { tool: a.tool }),
};
}
@@ -1714,6 +1716,22 @@ export const APPS: Preset[] = [
open: { modelId: "oss-video-matte-birefnet", op: "bg-remove-video" },
parity: "Cuts the subject out of every frame into a transparent video. To keep one object you name, use Video tools → Remove background with SAM 3.",
}),
+ // Clean up voice (NVIDIA RE-USE): an app that is the Audio tool itself (src/components/audio-tools/clean-voice-tool.tsx).
+ app({
+ id: "app-clean-up-voice",
+ name: "Clean up voice",
+ category: "Utility",
+ description: "Remove noise, echo and room sound from any voice",
+ icon: "AudioLines",
+ hue: 195,
+ badges: ["new"],
+ tool: "clean-voice",
+ inputs: [{ key: "audio", label: "Recording", hint: "Speech in any language, or a video with sound", accept: "audio", required: true }],
+ prompt: "Clean up the voice",
+ cloud: null,
+ open: { modelId: "oss-reuse-voice", op: "enhance-voice" },
+ parity: "Runs on open-source models only, on your GPU or CPU. RE-USE isn't hosted on fal or Replicate.",
+ }),
app({
name: "Object Remover",
category: "Utility",
diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.ts
index 320b694a..8527c6eb 100644
--- a/src/lib/catalog/canvas.ts
+++ b/src/lib/catalog/canvas.ts
@@ -54,6 +54,7 @@ export type CanvasNodeType =
| "bg-remove"
| "tts"
| "voice-change"
+ | "clean-voice"
| "clone-voice"
| "translate"
| "concat"
@@ -231,6 +232,8 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {
"bg-remove": { type: "bg-remove", label: "Remove background", group: "Utilities", icon: "Eraser", ops: ["bg-remove", "bg-remove-video"], variants: ["image", "video"], description: "Cut out the subject of an image or video" },
tts: { type: "tts", label: "Text to speech", group: "Utilities", icon: "Mic2", ops: ["tts"], description: "Speak a text, in a preset voice or a cloned one" },
"voice-change": { type: "voice-change", label: "Change voice", group: "Utilities", icon: "AudioWaveform", ops: ["voice-change"], description: "Say a recording again in another voice, keeping its timing" },
+ // NVIDIA RE-USE on the open engine only (nothing like it is hosted on fal or Replicate): hidden on a cloud-only install.
+ "clean-voice": { type: "clean-voice", label: "Clean up voice", group: "Utilities", icon: "AudioLines", ops: ["enhance-voice"], description: "Remove noise, echo and room sound from speech" },
"clone-voice": { type: "clone-voice", label: "Clone voice", group: "Inputs", icon: "UserRound", description: "A voice sample (or one of your saved voices) to speak with" },
translate: { type: "translate", label: "Translate", group: "Utilities", icon: "Languages", ops: ["translate", "dub"], variants: ["text", "video"], description: "Translate a text, or dub a video into another language" },
concat: { type: "concat", label: "Video concatenator", group: "Utilities", icon: "Film", ops: ["concat"], description: "Up to 50 clips in one film: trim and mute each, pick the frame" },
@@ -239,7 +242,7 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {
note: { type: "note", label: "Sticky note", group: "Output", icon: "StickyNote", description: "A note on the board (not run)" },
};
-export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "translate", "concat"]);
+export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "clean-voice", "translate", "concat"]);
export const isGenerator = (n: Pick<CanvasNode, "type">) => GENERATOR_TYPES.has(n.type);
/** Entries of the Add-node palette (several entries can make the same node type). */
@@ -273,6 +276,7 @@ export const PALETTE: PaletteItem[] = [
{ ...pick("bg-remove"), id: "bg-remove", data: { mediaKind: "image" }, keywords: "cutout matte transparent" },
{ ...pick("tts"), id: "tts", keywords: "voice speech narration clone" },
{ ...pick("voice-change"), id: "voice-change", keywords: "voice changer speech to speech revoice convert" },
+ { ...pick("clean-voice"), id: "clean-voice", keywords: "denoise enhance speech noise clean up voice echo reverb podcast" },
{ ...pick("clone-voice"), id: "clone-voice", keywords: "voice sample clone my voice speaker" },
{ ...pick("translate"), id: "translate", data: { mediaKind: "text" }, keywords: "language translate dub localize subtitles" },
{ ...pick("concat"), id: "concat", keywords: "concatenate join merge stitch edit trim mute film assemble" },
@@ -295,7 +299,8 @@ const paletteCache = new Map<string, PaletteItem[]>();
export function paletteItems(mode: "both" | "open" | "cloud" = "both"): PaletteItem[] {
const hit = paletteCache.get(mode);
if (hit) return hit;
- const items = PALETTE.filter((p) => p.id !== "model-text" || MODELS.some((m) => m.kind === "text" && !m.hidden)).map((p): PaletteItem => {
+ // Clean up voice has no cloud route: a cloud-only install doesn't offer it at all.
+ const items = PALETTE.filter((p) => (p.id !== "model-text" || MODELS.some((m) => m.kind === "text" && !m.hidden)) && !(mode === "cloud" && p.id === "clean-voice")).map((p): PaletteItem => {
if (mode === "both" || !isGenerator(p) || defaultModelForNode({ type: p.type, data: p.data ?? {} }, mode)) return p;
return { ...p, disabled: `No ${mode === "open" ? "open-source" : "cloud"} model for ${p.label.toLowerCase()} yet` };
});
@@ -339,6 +344,7 @@ const PREFERRED: Partial<Record<Operation, Partial<Record<Engine, string>>>> = {
lipsync: { cloud: "sync-lipsync-3" },
tts: { cloud: "elevenlabs-v4", open: "oss-chatterbox" },
"voice-change": { cloud: "elevenlabs-voice-changer", open: "oss-chatterbox-vc" },
+ "enhance-voice": { open: "oss-reuse-voice" },
dub: { cloud: "elevenlabs-dubbing" },
music: { cloud: "elevenlabs-music", open: "oss-ace-step" },
sfx: { cloud: "elevenlabs-sfx" },
@@ -499,6 +505,7 @@ const OP_PORTS: Partial<Record<Operation, InputPortId[]>> = {
mux: ["video", "audio"],
"image-to-3d": ["images"],
"separate-audio": ["audio", "video"],
+ "enhance-voice": ["audio", "video"],
translate: ["prompt"],
write: ["prompt"],
vectorize: ["images"],
diff --git a/src/lib/catalog/preset-recipe-routes.ts b/src/lib/catalog/preset-recipe-routes.ts
index f9a9dc54..4c692084 100644
--- a/src/lib/catalog/preset-recipe-routes.ts
+++ b/src/lib/catalog/preset-recipe-routes.ts
@@ -45,6 +45,7 @@ export type RecipeKind = "h3" | "orbit" | "turbo" | "specialist" | "words" | "ow
* - Recast, Video Face Swap: they carry a performance over from a clip.
* - 3D Rotation: its Rotate LoRA turns the subject into a solid object that spins in place.
* - Remove Background, Upscale, Vectorize, Video Background Remover, Image to 3D: tools, whose covers show the idea.
+ * - Clean up voice: a tool of its own (RE-USE), with nothing to recast.
*/
export const OWN_ROUTE_APPS: ReadonlySet<string> = new Set([
"app-fuobe-angles",
@@ -62,6 +63,7 @@ export const OWN_ROUTE_APPS: ReadonlySet<string> = new Set([
"app-vectorize",
"app-video-background-remover",
"app-image-to-3d",
+ "app-clean-up-voice",
]);
/** Presets whose clip was made on H3's 20-step graph (Quality: Best); the others on its 8-step Turbo graph (Fast). */
diff --git a/src/lib/command-search.ts b/src/lib/command-search.ts
index 2a25057d..1eea7025 100644
--- a/src/lib/command-search.ts
+++ b/src/lib/command-search.ts
@@ -156,6 +156,11 @@ export function rankPalette(entries: PaletteEntry[], query: string, limits: Reco
.map(({ kind, label, entries }) => ({ kind, label, entries }));
}
+/** Words people type for an app that its name doesn't say. */
+export const APP_KEYWORDS: Record<string, string> = {
+ "app-clean-up-voice": "clean up voice denoise noise removal remove echo reverb enhance speech podcast audio fix mic phone audio restore audio",
+};
+
/** The slim catalog the palette loads on first open (GET /api/search-index). */
export interface PaletteIndex {
apps: PalettePreset[];
@@ -193,7 +198,7 @@ export interface PaletteModel {
export function indexEntries(index: PaletteIndex, mode: "both" | "cloud" | "open", access?: AccessSummary): PaletteEntry[] {
const runs = (p: PalettePreset) => mode === "both" || p[mode];
const presets = (list: PalettePreset[], kind: "app" | "motion" | "effect", href: (id: string) => string) =>
- list.filter(runs).map((p): PaletteEntry => ({ key: `${kind}:${p.id}`, kind, label: p.name, hint: p.category, href: href(p.id) }));
+ list.filter(runs).map((p): PaletteEntry => ({ key: `${kind}:${p.id}`, kind, label: p.name, hint: p.category, href: href(p.id), ...(APP_KEYWORDS[p.id] && { keywords: APP_KEYWORDS[p.id] }) }));
return [
...presets(index.apps, "app", (id) => `/apps/${id}`),
...presets(index.motions, "motion", (id) => `/video?preset=${id}`),
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 22490cdf..893b40bc 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -424,6 +424,8 @@ export function blockerFor(s: {
/** Frames mode: the start frame to add, or a model that can't follow frames (framesBlocker in catalog/keyframes.ts). */
frames?: Blocker | null;
uploading: boolean;
+ /** A voice slot's "Clean up voice" is still running: the run waits for the clean file. */
+ cleaning?: boolean;
maskMissing?: boolean;
planError?: string | null;
promptMissing: boolean;
@@ -434,6 +436,7 @@ export function blockerFor(s: {
if (s.frames) return s.frames;
if (s.missing) return { message: missingMessage(s.missing), slot: s.missing.key };
if (s.uploading) return { message: "Uploading…", quiet: true };
+ if (s.cleaning) return { message: "Waiting for the clean voice", quiet: true };
if (s.maskMissing) return { message: "Paint the area to change", slot: "mask" };
// The planner says "Write a prompt first" too (an empty prompt on a model that needs one): as quiet as the composer's own.
if (s.planError) return s.planError === WRITE_PROMPT ? { message: WRITE_PROMPT, quiet: true } : { message: s.planError };
diff --git a/src/lib/hubs.ts b/src/lib/hubs.ts
index 52f19403..6e4247b5 100644
--- a/src/lib/hubs.ts
+++ b/src/lib/hubs.ts
@@ -19,6 +19,7 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {
{ id: "voice-change", label: "Voice change" },
{ id: "translate", label: "Translate" },
{ id: "transcribe", label: "Transcribe" },
+ { id: "clean", label: "Clean up voice" },
{ id: "split", label: "Split soundtrack" },
{ id: "sfx", label: "Sound effects" },
{ id: "music", label: "Music" },
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 381a860f..9680ec1c 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -10,6 +10,7 @@ import { cueText, type Cue } from "./cues";
import { downloadHref, downloadName, extensionOf } from "./library";
import { PRESETS as GRADE_PRESETS } from "./grade";
import { storedPath } from "./share";
+import { CLEAN_FEATURE } from "./av/clean-voice";
export type OutputActionId =
| "animate"
@@ -27,6 +28,7 @@ export type OutputActionId =
| "voice-change"
| "loop-audio"
| "split-soundtrack"
+ | "clean-voice"
| "copy-text"
| "view-3d"
| "download"
@@ -121,6 +123,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("upscale", "Upscale", `/upscale/video?video=${q(o.url)}`);
link("add-sound", "Add sound", `/audio/video?video=${q(o.url)}`);
link("split-soundtrack", "Split soundtrack", `/audio/split?video=${q(o.url)}`);
+ // Clean up voice on a video's soundtrack: results that carry sound, and uploads (a clip from a phone or a call).
+ if (g.feature === "upload" || (g.op && SOUNDED_VIDEO_OPS.has(g.op))) link("clean-voice", "Clean up voice", `/audio/clean?video=${q(o.url)}`);
// A Fuobe DoP colour-grade effect: the clip opens in Color grading with its grade picked (one click to export).
const dopGrade = gradeOf(o);
link("grade", dopGrade ? `Apply the ${dopGrade.name} grade` : "Color grade", `/color-grade?video=${q(o.url)}${dopGrade ? `&preset=${q(dopGrade.id)}` : ""}`);
@@ -133,6 +137,8 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("voice-change", "Change voice", `/audio/voice-change?audio=${q(o.url)}`);
link("loop-audio", "Loop / extend", `/audio/loop?audio=${q(o.url)}`);
link("split-soundtrack", "Split soundtrack", `/audio/split?audio=${q(o.url)}`);
+ // Not on music or sound effects (it keeps only a voice), nor on a voice it already cleaned.
+ if (g.op !== "music" && g.op !== "sfx" && g.feature !== CLEAN_FEATURE) link("clean-voice", "Clean up voice", `/audio/clean?audio=${q(o.url)}`);
break;
case "text":
out.push({ id: "copy-text", label: "Copy", placement: "primary" }, file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index 8fda4793..29923254 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -110,7 +110,7 @@ export const LIPSYNC_STUDIO: StudioConfig = {
slots: [
{ key: "image", label: "Portrait", accept: "image", hint: "For a talking avatar" },
{ key: "video", label: "Video", accept: "video", hint: "To re-sync an existing clip" },
- { key: "audio", label: "Voice", accept: "audio", required: true },
+ { key: "audio", label: "Voice", accept: "audio", required: true, cleanVoice: true },
],
anyOf: [["image", "video"]],
defaultModels: { cloud: "kling-avatar-2", open: "oss-infinitetalk" },
@@ -244,7 +244,7 @@ export const VOICE_CHANGE_STUDIO: StudioConfig = {
kind: "audio",
ops: ["voice-change"],
feed: { kind: "audio", features: ["audio"] },
- slots: [{ key: "audio", label: "Recording", accept: "audio", required: true }],
+ slots: [{ key: "audio", label: "Recording", accept: "audio", required: true, cleanVoice: true }],
defaultModels: { cloud: "elevenlabs-voice-changer", open: "oss-chatterbox-vc" },
promptOptional: true,
hidePrompt: true,
diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.ts
index 59956ad7..f2e7a791 100644
--- a/src/server/audio-tools.ts
+++ b/src/server/audio-tools.ts
@@ -2,11 +2,12 @@ import "server-only";
import { z } from "zod";
import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";
import { CLOUD_ONLY_PROBLEM, DBS_MODELS, dbsChannelsFor, hostPick, missingDbs, planRemux, planSplit, splitTime } from "@/lib/av/split";
+import { CLOUD_ONLY_CLEAN_PROBLEM, missingReuse, NO_REUSE_PACK, planClean, planTime, tooLongProblem } from "@/lib/av/clean-voice";
import type { Engine, Generation } from "@/lib/catalog/types";
import { lastGpuDevice } from "./account-gpu";
import { createPipeline } from "./chains";
import { ConnectComfyError, previewChained } from "./generations";
-import { comfyDbsModels, comfyDevice, ownGpu } from "./providers/comfyui";
+import { comfyDbsModels, comfyDevice, comfyReuseModels, ownGpu } from "./providers/comfyui";
import { engineMode } from "./settings";
import { storedMedia } from "./storage";
import { tenant, tenantAccount } from "./tenant";
@@ -56,6 +57,24 @@ export const AudioToolBody = z.discriminatedUnion("tool", [
channels: z.number().int().positive().max(64).optional(),
sourceDuration: z.number().positive().max(36_000).optional(),
}),
+ z.object({
+ tool: z.literal("clean"),
+ engine: Engine,
+ media: FileUrl,
+ kind: z.enum(["audio", "video"]),
+ name: z.string().max(200).optional(),
+ /** Voice only, or the laughter model. */
+ model: z.enum(["voice", "laughter"]).optional(),
+ quality: z.enum(["auto", "full", "fast"]).optional(),
+ strength: z.enum(["full", "natural", "light"]).optional(),
+ background: z.enum(["remove", "keep"]).optional(),
+ level: z.enum(["match", "voice"]).optional(),
+ /** A video: put the clean soundtrack back on the picture. */
+ remux: z.boolean().optional(),
+ stereo: z.boolean().optional(),
+ channels: z.number().int().positive().max(64).optional(),
+ sourceDuration: z.number().positive().max(36_000).optional(),
+ }),
z.object({
tool: z.literal("remux"),
engine: Engine,
@@ -111,6 +130,7 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine
const mode = engineMode();
// Split soundtrack runs on the open engine only: an install set to paid APIs only says why, whichever engine was asked for.
if (body.tool === "split" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_PROBLEM);
+ if (body.tool === "clean" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_CLEAN_PROBLEM);
if (mode !== "both" && body.engine !== mode) throw new AudioToolError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
try {
if (body.tool === "split") {
@@ -121,6 +141,12 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine
const channels = facts?.channels ?? body.channels;
return { engine: body.engine, ...planSplit({ ...body, seconds, channels }), split: { duration: seconds, channels }, headerChannels: facts?.channels };
}
+ if (body.tool === "clean") {
+ const facts = factsOf(body.media);
+ const seconds = facts?.duration ?? body.sourceDuration;
+ const channels = facts?.channels ?? body.channels;
+ return { engine: body.engine, ...planClean({ ...body, seconds, channels, silent: facts?.hasAudio === false }), split: { duration: seconds, channels }, headerChannels: facts?.channels };
+ }
if (body.tool === "remux") {
present(body.audio, "That mix is gone — export it again");
present(body.video, "That video is gone — add it again");
@@ -175,6 +201,35 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToo
Object.assign(out, { hostPick: pick, ...(device && { device }), ...(installed && { installed: installed.map((m) => (m === DBS_MODELS.best ? "best" : "fast")) }), ...(p.headerChannels && { channels: p.headerChannels }) });
if (seconds) out.estimate = splitTime({ seconds, quality, mode: dbsChannelsFor(body.stereo ? "each channel" : "mono", channels), channels, device });
}
+ if (body.tool === "clean") {
+ // As Split: the host's device and its RE-USE files (and DBS's, to keep music & effects), asked live for the owner;
+ // a visitor's price check never calls a GPU (an account's device is its last status check; the run checks the files).
+ const visitor = !!tenant() || !!ownGpu();
+ const account = tenantAccount();
+ const keep = (p.steps[0]?.request.params?.extra as { background?: string } | undefined)?.background === "keep";
+ const [device, installed, dbs] = demo
+ ? [undefined, undefined, undefined]
+ : visitor
+ ? [account ? lastGpuDevice(account) : undefined, undefined, undefined]
+ : await Promise.all([comfyDevice().catch(() => undefined), comfyReuseModels().catch(() => undefined), keep ? comfyDbsModels().catch(() => undefined) : undefined]);
+ if (installed === null) throw new AudioToolError(NO_REUSE_PACK);
+ const model = body.model ?? "voice";
+ if (installed && !installed.includes(model)) throw new AudioToolError(missingReuse(model, installed));
+ // No DBS file, or (the server answered for RE-USE) no DBS pack at all: refused here, not at the run's validation.
+ if (keep && (dbs ? !dbs.length : Array.isArray(installed))) throw new AudioToolError('"Keep music & effects" also needs DBS on your ComfyUI (models/dbs). Copy the install commands from Workflows → "Split a soundtrack", or pick Remove everything but the voice.');
+ const { duration: seconds, channels } = p.split ?? {};
+ const t = seconds ? planTime({ seconds, quality: body.quality, device, stereo: body.stereo, channels, background: keep ? "keep" : "remove" }) : undefined;
+ if (t && !demo) {
+ const problem = tooLongProblem(t, device);
+ if (problem) throw new AudioToolError(problem);
+ }
+ Object.assign(out, {
+ ...(device && { device }),
+ ...(p.headerChannels && { channels: p.headerChannels }),
+ reuse: { ...(installed && { installed }), rate: t?.rate ?? planTime({ seconds: 1, quality: body.quality, device }).rate, ...(seconds && { seconds }) },
+ ...(t && { estimate: { low: t.low, high: t.high } }),
+ });
+ }
return out;
}
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
index 0179dfee..a9dc3520 100644
--- a/src/server/canvas.ts
+++ b/src/server/canvas.ts
@@ -98,6 +98,7 @@ const NODE_TYPES = [
"bg-remove",
"tts",
"voice-change",
+ "clean-voice",
"clone-voice",
"translate",
"concat",
diff --git a/src/server/gpu/tools.ts b/src/server/gpu/tools.ts
index ff0dc643..5ea166e4 100644
--- a/src/server/gpu/tools.ts
+++ b/src/server/gpu/tools.ts
@@ -1,5 +1,6 @@
import "server-only";
import { SPLIT_MODEL } from "@/lib/av/split";
+import { CLEAN_MODEL } from "@/lib/av/clean-voice";
import { getModel, getPreset, MODELS, modelsFor, PRESETS } from "@/lib/catalog";
import { graphLoras } from "@/lib/catalog/character-swap";
import { PATH_MODELS } from "@/lib/catalog/cinema";
@@ -179,6 +180,8 @@ export const STUDIO_ROWS: StudioRowDef[] = [
{ href: "/audio/transcribe", label: "Transcribe", group: "Audio", config: S.TRANSCRIBE_STUDIO },
// DBS soundtrack separation (D1): dialogue, music and effects.
{ href: "/audio/split", label: "Split soundtrack", group: "Audio", steps: [{ modelId: SPLIT_MODEL, op: "separate-audio" }] },
+ // Clean up voice (NVIDIA RE-USE on ComfyUI-RE-USE).
+ { href: "/audio/clean", label: "Clean up voice", group: "Audio", steps: [{ modelId: CLEAN_MODEL, op: "enhance-voice" }] },
{ href: "/audio/sfx", label: "Sound effects", group: "Audio", config: S.SFX_STUDIO },
{ href: "/audio/music", label: "Music", group: "Audio", config: S.MUSIC_STUDIO },
{ href: "/audio/video", label: "Sound for video", group: "Audio", config: S.FOLEY_STUDIO },
diff --git a/tests/clean-voice.test.ts b/tests/clean-voice.test.ts
new file mode 100644
index 00000000..e6f61de6
--- /dev/null
+++ b/tests/clean-voice.test.ts
@@ -0,0 +1,316 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import {
+ CLEAN_MAX_SECONDS,
+ CLOUD_CLEAN_PROBLEM,
+ CLOUD_ONLY_CLEAN_PROBLEM,
+ cleanTime,
+ DEMO_PAIRS,
+ DEMO_READY,
+ installedReuse,
+ missingReuse,
+ planClean,
+ planTime,
+ rateFor,
+ reportLine,
+ reuseFileFor,
+ rtfAt,
+ scanHint,
+ tooLongProblem,
+ workRate,
+} from "@/lib/av/clean-voice";
+import { HUB_MODES, modeHref } from "@/lib/hubs";
+import { cleanedName } from "@/components/audio-tools/clean-voice-switch";
+import { outputActions } from "@/lib/output-actions";
+import { APPS, getModel } from "@/lib/catalog";
+import { blockerFor } from "@/lib/composer";
+import type { Generation } from "@/lib/catalog/types";
+import { defaultModelForNode, NODE_SPECS, nodeOps, paletteItems } from "@/lib/catalog/canvas";
+
+// Audio → Clean up voice (NVIDIA RE-USE): the planner, the rate and time rules, the Library action, the app, and the API
+// in demo mode.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-clean-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: the open model runs on the demo provider.
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+vi.mock("sonner", () => ({ toast: Object.assign(() => {}, { error: () => {} }) }));
+
+const { setSetting } = await import("@/server/settings");
+const { saveFile } = await import("@/server/storage");
+const gens = await import("@/server/generations");
+const route = await import("@/app/api/audio-tools/route");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+function upload(seconds: number, channels = 1, name = "voice.wav"): string {
+ const rate = 8000;
+ const n = Math.round(seconds * rate);
+ const buf = Buffer.alloc(44 + n * 2 * channels);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(36 + n * 2 * channels, 4);
+ buf.write("WAVEfmt ", 8);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(channels, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * 2 * channels, 28);
+ buf.writeUInt16LE(2 * channels, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36);
+ buf.writeUInt32LE(n * 2 * channels, 40);
+ return saveFile({ data: buf, contentType: "audio/wav", name, source: "upload" }).url;
+}
+
+const post = (body: unknown, preview = false) =>
+ route.POST(new Request(`http://x/api/audio-tools${preview ? "?preview=1" : ""}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));
+
+async function finished(id: string) {
+ const deadline = Date.now() + 15_000;
+ let g = gens.getGeneration(id)!;
+ while (g.status !== "succeeded" && g.status !== "failed" && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 200));
+ g = gens.getGeneration(id)!;
+ }
+ return g;
+}
+
+describe("the RE-USE files a host has", () => {
+ it("reads GET /models/reuse, Windows back slashes too", () => {
+ expect(installedReuse(["NemotronLabs-RE-USE.safetensors"])).toEqual(["voice"]);
+ expect(installedReuse(["x\\NemotronLabs-RE-USE-laughter.safetensors", "NemotronLabs-RE-USE.safetensors"])).toEqual(["voice", "laughter"]);
+ expect(installedReuse([])).toEqual([]);
+ expect(installedReuse(undefined)).toBeUndefined();
+ });
+
+ it("refuses a missing file in words, with what to do", () => {
+ expect(missingReuse("laughter", ["voice"])).toBe("Keep laughter isn't installed (models/reuse/NemotronLabs-RE-USE-laughter.safetensors, 39 MB); pick Voice only or install it from Workflows → Clean up voice.");
+ expect(missingReuse("voice", [])).toMatch(/^RE-USE isn't on your ComfyUI yet \(models\/reuse\/NemotronLabs-RE-USE\.safetensors, 39 MB\)\. Copy the install commands/);
+ expect(reuseFileFor("laughter", ["voice", "laughter"])).toBe("NemotronLabs-RE-USE-laughter.safetensors");
+ expect(reuseFileFor(undefined)).toBe("NemotronLabs-RE-USE.safetensors");
+ expect(() => reuseFileFor("laughter", ["voice"])).toThrow(/^Keep laughter isn't installed/);
+ });
+});
+
+describe("the rate a run gets", () => {
+ it("keeps the source's on a GPU, caps it on a CPU (16 kHz past 2 minutes), and runs Full band and Fast as named", () => {
+ expect(rateFor("auto", "cuda", 3600)).toBe("source");
+ expect(rateFor("auto", "cpu", 30)).toBe("source up to 24000");
+ expect(rateFor("auto", undefined, 120)).toBe("source up to 24000");
+ expect(rateFor("auto", "cpu", 121)).toBe("source up to 16000");
+ expect(rateFor("auto", "mps", 10)).toBe("source up to 24000");
+ for (const d of ["cuda", "cpu"]) {
+ expect(rateFor("full", d)).toBe("48000");
+ expect(rateFor("fast", d)).toBe("16000");
+ expect(rateFor("48000", d)).toBe("48000");
+ }
+ });
+
+ it("knows the rate the node will run at, for the estimate", () => {
+ expect(workRate("source", 44100)).toBe(44100);
+ expect(workRate("source", 96000)).toBe(48000);
+ expect(workRate("source", 6000)).toBe(8000);
+ expect(workRate("source up to 24000", 44100)).toBe(24000);
+ expect(workRate("source up to 24000", 16000)).toBe(16000);
+ expect(workRate("48000", 8000)).toBe(48000);
+ });
+});
+
+describe("time on the open engine", () => {
+ it("interpolates the measured work per second of audio by rate", () => {
+ expect(rtfAt("cuda", 16000)).toBe(0.26);
+ expect(rtfAt("cpu", 8000)).toBe(2);
+ expect(rtfAt("cpu", 20000)).toBeCloseTo(4.5);
+ expect(rtfAt("cpu", 96000)).toBe(15);
+ });
+
+ it("gives a range: GPU measurements were worst cases, a CPU's spread is DBS's, plus loading and DBS for the bed", () => {
+ expect(cleanTime({ seconds: 60, rate: 16000, device: "cuda" })).toEqual({ low: Math.round(3 + 60 * 0.26 * 0.3), high: Math.round(3 + 60 * 0.26 * 1.2) });
+ expect(cleanTime({ seconds: 60, rate: 16000, device: "cpu" })).toEqual({ low: Math.round(3 + 240 * 0.8), high: Math.round(3 + 240 * 1.6) });
+ expect(cleanTime({ seconds: 60, rate: 16000, device: "cuda", firstRun: true }).low).toBe(Math.round(23 + 60 * 0.26 * 0.3));
+ expect(cleanTime({ seconds: 60, rate: 16000, device: "cpu", bed: true }).low).toBeGreaterThan(cleanTime({ seconds: 60, rate: 16000, device: "cpu" }).low);
+ expect(cleanTime({ seconds: 10, rate: 16000, device: "cpu", passes: 2 }).high).toBe(Math.round(3 + 80 * 1.6));
+ });
+
+ it("refuses a plan over 2 hours, with what to change", () => {
+ const hour = planTime({ seconds: 3600, quality: "full", device: "cpu" });
+ expect(hour.rate).toBe(48000);
+ expect(hour.low).toBeGreaterThan(CLEAN_MAX_SECONDS);
+ expect(tooLongProblem(hour, "cpu")).toMatch(/^That's about \d+(\.\d)? h on a CPU\. Pick Fast 16 kHz, use a shorter file, or connect a GPU\.$/);
+ expect(tooLongProblem(planTime({ seconds: 600, device: "cpu" }), "cpu")).toBeNull();
+ expect(tooLongProblem(planTime({ seconds: 3600, device: "cuda" }), "cuda")).toBeNull();
+ });
+});
+
+describe("planClean", () => {
+ it("is one RE-USE job for a recording: Full strength, nothing kept but the voice", () => {
+ const p = planClean({ engine: "open", media: "/api/files/uploads/a.wav", kind: "audio", name: "Interview", seconds: 30 });
+ expect(p.steps).toHaveLength(1);
+ expect(p.steps[0].request).toMatchObject({
+ modelId: "oss-reuse-voice",
+ op: "enhance-voice",
+ feature: "voice-clean",
+ title: "Clean voice · Interview",
+ inputs: { audio: "/api/files/uploads/a.wav" },
+ params: { extra: { reuseModel: "voice", rate: "auto", strength: "full", level: "match input", channels: "mono" }, sourceDuration: 30 },
+ });
+ expect(p.steps[0].request.params?.extra).not.toHaveProperty("background");
+ // The speaker and gap notes show under Background and Strength, not again in the summary.
+ expect(p.notes).toEqual([]);
+ });
+
+ it("for a video removes everything but the voice at Natural strength and puts the clean soundtrack back on the picture", () => {
+ const d = planClean({ engine: "open", media: "/api/files/uploads/v.mp4", kind: "video", name: "Vlog" });
+ expect(d).toMatchObject({ strength: "natural", background: "remove", remux: true });
+ expect(d.steps[0].request.params?.extra).toMatchObject({ strength: "natural" });
+ expect(d.steps[0].request.params?.extra).not.toHaveProperty("background");
+ expect(d.summary).toMatch(/^Cleans the video's soundtrack with RE-USE, then puts it back on the picture/);
+ });
+
+ it("for a video keeps music & effects when asked (DBS first), and puts the clean soundtrack back on the picture", () => {
+ const p = planClean({ engine: "open", media: "/api/files/uploads/v.mp4", kind: "video", name: "Vlog", background: "keep" });
+ expect(p).toMatchObject({ strength: "natural", background: "keep", remux: true });
+ expect(p.steps.map((s) => s.key)).toEqual(["clean", "remux"]);
+ expect(p.steps[0].request).toMatchObject({ inputs: { video: "/api/files/uploads/v.mp4" }, params: { extra: { background: "keep", strength: "natural" } } });
+ expect(p.steps[1]).toMatchObject({ after: ["clean"], chain: [{ slot: "audio" }], request: { modelId: "oss-mux", op: "mux", feature: "voice-clean-remux", inputs: { video: "/api/files/uploads/v.mp4" } } });
+ expect(p.summary).toMatch(/^Splits the video's soundtrack with DBS, cleans the dialogue with RE-USE/);
+ });
+
+ it("leaves the video alone when asked, and cleans everything but the voice when asked", () => {
+ const p = planClean({ engine: "open", media: "/api/files/uploads/v.mp4", kind: "video", remux: false, background: "remove", strength: "full" });
+ expect(p.steps).toHaveLength(1);
+ expect(p.steps[0].request.params?.extra).toMatchObject({ strength: "full" });
+ expect(p.steps[0].request.params?.extra).not.toHaveProperty("background");
+ });
+
+ it("asks for Fast, the laughter model, voice-over level and stereo when picked; a surround file runs in mono", () => {
+ const p = planClean({ engine: "open", media: "/api/files/x.wav", kind: "audio", quality: "fast", model: "laughter", level: "voice", stereo: true, channels: 2 });
+ expect(p.steps[0].request.params?.extra).toMatchObject({ rate: "16000", reuseModel: "laughter", level: "-16 LUFS", channels: "each channel", sourceChannels: 2 });
+ const five = planClean({ engine: "open", media: "/api/files/x.wav", kind: "audio", stereo: true, channels: 6 });
+ expect(five.steps[0].request.params?.extra).toMatchObject({ channels: "mono", sourceChannels: 6 });
+ expect(five.notes.at(-1)).toBe("This file has 6 channels: it is cleaned in mono, as ComfyUI saves mono or stereo only.");
+ });
+
+ it("has no cloud route, and refuses a file with no sound", () => {
+ expect(() => planClean({ engine: "cloud", media: "/api/files/x.wav", kind: "audio" })).toThrow(CLOUD_CLEAN_PROBLEM);
+ expect(() => planClean({ engine: "open", media: "/api/files/x.mp4", kind: "video", silent: true })).toThrow("This video has no sound to clean");
+ expect(() => planClean({ engine: "open", media: "", kind: "audio" })).toThrow("Add the audio to clean");
+ });
+});
+
+describe("the report in words", () => {
+ it("says the device, rate, scan and speed, and when Triton is missing on a GPU", () => {
+ expect(reportLine('{"device":"cuda:0","scan":"triton","rate":48000,"times_real_time":1.9}')).toBe("GPU · 48 kHz · Triton · 1.9x real time");
+ expect(reportLine({ device: "cpu", scan: "numba", rate: 16000, times_real_time: 0.3 })).toBe("CPU · 16 kHz · numba · 0.3x real time");
+ expect(reportLine("not json")).toBeNull();
+ expect(scanHint({ device: "cuda:0", scan: "torch-loop" })).toBe("Install Triton for about 6x faster cleaning");
+ expect(scanHint({ device: "cpu", scan: "torch-loop" })).toBeNull();
+ });
+});
+
+describe("where Clean up voice opens", () => {
+ it("is an Audio mode right after Transcribe, and an app that renders the same tool", () => {
+ const ids = HUB_MODES.audio.map((m) => m.id);
+ expect(ids.indexOf("clean")).toBe(ids.indexOf("transcribe") + 1);
+ expect(modeHref("audio", "clean")).toBe("/audio/clean");
+ const app = APPS.find((a) => a.id === "app-clean-up-voice")!;
+ expect(app).toMatchObject({ tool: "clean-voice", category: "Utility", cloud: null, open: { modelId: "oss-reuse-voice", op: "enhance-voice" } });
+ expect(app.parity).toBe("Runs on open-source models only, on your GPU or CPU. RE-USE isn't hosted on fal or Replicate.");
+ expect(getModel("oss-reuse-voice")?.routes).toEqual([expect.objectContaining({ op: "enhance-voice", provider: "comfyui", endpoint: "voice-clean-reuse" })]);
+ });
+
+ it("offers a Clean up voice switch on every voice slot", () => {
+ const voiceApps = APPS.filter((a) => a.inputs.some((s) => s.key === "audio" && s.label === "Voice audio"));
+ expect(voiceApps.length).toBeGreaterThan(0);
+ expect(voiceApps.every((a) => a.inputs.find((s) => s.key === "audio")?.cleanVoice)).toBe(true);
+ });
+
+ it("names a cleaned file after the original, cutting only a real extension", () => {
+ expect(cleanedName("Take 2.wav")).toBe("Take 2 · cleaned");
+ expect(cleanedName("Take")).toBe("Take · cleaned");
+ expect(cleanedName("interview")).toBe("interview · cleaned");
+ expect(cleanedName(undefined)).toBe("Recording · cleaned");
+ });
+
+ it("makes Generate wait for a voice that is being cleaned", () => {
+ expect(blockerFor({ model: true, uploading: false, cleaning: true, promptMissing: false })).toEqual({ message: "Waiting for the clean voice", quiet: true });
+ });
+
+ it.runIf(DEMO_READY)("ships two demo pairs made from NVIDIA's sample, with the licence and notice beside them", () => {
+ const pub = path.resolve(__dirname, "..", "public");
+ for (const p of DEMO_PAIRS) for (const f of [p.before, p.after]) expect(fs.existsSync(path.join(pub, f))).toBe(true);
+ expect(fs.readFileSync(path.join(pub, "samples/clean-voice/LICENSE-OpenMDW-1.1.txt"), "utf8")).toMatch(/OpenMDW License Agreement, version 1\.1/);
+ expect(fs.readFileSync(path.join(pub, "samples/clean-voice/NOTICE.txt"), "utf8")).toMatch(/NVIDIA CORPORATION & AFFILIATES/);
+ });
+});
+
+describe("the Canvas node", () => {
+ it("cleans audio or a video's soundtrack on the open engine, and isn't offered on a cloud-only install", () => {
+ expect(NODE_SPECS["clean-voice"]).toMatchObject({ label: "Clean up voice", group: "Utilities", ops: ["enhance-voice"] });
+ expect(nodeOps({ type: "clean-voice", data: {} })).toEqual(["enhance-voice"]);
+ expect(defaultModelForNode({ type: "clean-voice", data: {} }, "open")?.id).toBe("oss-reuse-voice");
+ expect(defaultModelForNode({ type: "clean-voice", data: {} }, "cloud")).toBeUndefined();
+ expect(paletteItems("both").some((p) => p.id === "clean-voice")).toBe(true);
+ expect(paletteItems("open").find((p) => p.id === "clean-voice")?.disabled).toBeUndefined();
+ expect(paletteItems("cloud").some((p) => p.id === "clean-voice")).toBe(false);
+ });
+});
+
+describe("the Library's Clean up voice", () => {
+ const gen = (o: Partial<Generation>, kind: "audio" | "video"): Generation =>
+ ({ id: "g1", status: "succeeded", feature: "audio", op: "tts", outputs: [{ url: "/api/files/out/x", kind }], request: {}, createdAt: "", ...o }) as unknown as Generation;
+ const has = (g: Generation) => outputActions(g, 0).find((a) => a.id === "clean-voice");
+
+ it("is on speech and on videos with sound, and opens the tool with the file", () => {
+ expect(has(gen({ op: "tts" }, "audio"))?.href).toBe("/audio/clean?audio=%2Fapi%2Ffiles%2Fout%2Fx");
+ expect(has(gen({ op: "lipsync" }, "video"))).toMatchObject({ label: "Clean up voice", placement: "menu", href: "/audio/clean?video=%2Fapi%2Ffiles%2Fout%2Fx" });
+ expect(has(gen({ feature: "upload", op: undefined }, "video"))).toBeTruthy();
+ });
+
+ it("isn't on music, sound effects, a silent clip or a voice it already cleaned", () => {
+ expect(has(gen({ op: "music" }, "audio"))).toBeUndefined();
+ expect(has(gen({ op: "sfx" }, "audio"))).toBeUndefined();
+ expect(has(gen({ op: "enhance-voice", feature: "voice-clean" }, "audio"))).toBeUndefined();
+ expect(has(gen({ op: "t2v" }, "video"))).toBeUndefined();
+ });
+});
+
+describe("POST /api/audio-tools clean (demo mode)", () => {
+ it("prices a clean as free with an estimate, and runs it into a clean voice in the Library", async () => {
+ const media = upload(6);
+ const preview = await (await post({ tool: "clean", engine: "open", media, kind: "audio", name: "Take 1" }, true)).json();
+ expect(preview).toMatchObject({ steps: 1, costUsd: 0, demo: true, length: 6 });
+ expect(preview.summary).toBe("Cleans the recording with RE-USE.");
+ const res = await post({ tool: "clean", engine: "open", media, kind: "audio", name: "Take 1" });
+ expect(res.status).toBe(201);
+ const run = await res.json();
+ expect(run.result).toMatchObject({ feature: "voice-clean", modelId: "oss-reuse-voice", provider: "mock", op: "enhance-voice" });
+ const g = await finished(run.result.id);
+ expect(g.status).toBe("succeeded");
+ expect(g.outputs[0]).toMatchObject({ kind: "audio", meta: { stem: "voice" } });
+ expect(g.outputs[0].url.startsWith("/api/files/")).toBe(true);
+ });
+
+ it("says plainly that the cloud has no clean, and refuses on an install set to paid APIs only", async () => {
+ const media = upload(3);
+ const cloud = await post({ tool: "clean", engine: "cloud", media, kind: "audio" }, true);
+ expect(cloud.status).toBe(422);
+ expect((await cloud.json()).error).toBe(CLOUD_CLEAN_PROBLEM);
+ setSetting("engineMode", "cloud");
+ try {
+ expect((await (await post({ tool: "clean", engine: "open", media, kind: "audio" })).json()).error).toBe(CLOUD_ONLY_CLEAN_PROBLEM);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ expect((await (await post({ tool: "clean", engine: "open", media: "/etc/passwd", kind: "audio" })).json()).error).toBe("Add the audio or video to clean");
+ });
+
+ it("refuses a file with no sound before anything is queued", async () => {
+ const silent = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures", "shorts-silent.webm")), contentType: "video/webm", name: "silent.webm", source: "upload" }).url;
+ const res = await post({ tool: "clean", engine: "open", media: silent, kind: "video" }, true);
+ expect(res.status).toBe(422);
+ expect((await res.json()).error).toBe("This video has no sound to clean");
+ });
+});
diff --git a/tests/e2e/clean-voice.mjs b/tests/e2e/clean-voice.mjs
new file mode 100644
index 00000000..f8898d42
--- /dev/null
+++ b/tests/e2e/clean-voice.mjs
@@ -0,0 +1,277 @@
+// Browser check of Clean up voice (NVIDIA RE-USE): the Audio mode and the app.
+// Usage: node tests/e2e/clean-voice.mjs [appUrl] [outDir] [--guest guestAppUrl]
+// appUrl: the app in demo mode (no keys; COMFYUI_URL pointing at nothing or a fake ComfyUI), signed in as the owner.
+// --guest: the same build with public sign-up on, seen signed out.
+// Checks, at 1440 px and 390 px in light and dark: the empty tool with the demo player (it plays, the Before / After switch
+// and the B / A keys swap sides at the same moment, the divider moves), the cloud engine's "runs on your GPU" note, the
+// open engine's options and price, no sideways scroll; one audio run and one video run with "Put back on the video" (two
+// Library items); the app page; the Library's Clean up voice action; the Canvas node; the switch on Lipsync's voice slot;
+// and, with --guest, that a guest hears the demo and an upload asks to sign up. Screenshots go to outDir.
+// The demo player shows only once DEMO_READY is set (a person has listened to the pairs): until then the checks see that
+// it is absent. A page error (a hydration error included) fails the run.
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { DESKTOP, PHONE, launch, openRoute } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const guestAt = argv.indexOf("--guest");
+const guestApp = guestAt >= 0 ? argv[guestAt + 1] : null;
+const args = argv.filter((a, i) => !a.startsWith("--") && i !== guestAt + 1);
+const app = args[0] ?? "http://localhost:3000";
+const out = args[1] ?? fs.mkdtempSync("/tmp/fuobe-clean-voice-");
+fs.mkdirSync(out, { recursive: true });
+
+// A 6 s voice-like clip with hiss (bursts of a harmonic tone), and a 6 s video with it as its soundtrack.
+const wav = path.join(out, "clean-source.wav");
+const mp4 = path.join(out, "clean-source.mp4");
+const ff = (a) => {
+ const r = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...a]);
+ if (r.status !== 0) throw new Error(`ffmpeg failed: ${r.stderr}`);
+};
+ff(["-f", "lavfi", "-i", "aevalsrc=0.25*gt(sin(2*PI*1.5*t)\\,0)*(sin(2*PI*180*t)+0.4*sin(2*PI*360*t))+0.02*(random(0)-0.5):s=44100:d=6", wav]);
+ff(["-f", "lavfi", "-i", "testsrc2=s=320x180:r=24:d=6", "-i", wav, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", mp4]);
+
+// The demo shows once a person has listened to its pairs (src/lib/av/clean-voice.ts).
+const DEMO_READY = /export const DEMO_READY = true/.test(fs.readFileSync(new URL("../../src/lib/av/clean-voice.ts", import.meta.url), "utf8"));
+
+const failures = [];
+const check = (ok, what) => {
+ console.log(`${ok ? "✓" : "✗"} ${what}`);
+ if (!ok) failures.push(what);
+};
+const noSideScroll = async (page, label) => {
+ const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ check(over <= 0, `${label}: no horizontal scroll (${over}px)`);
+};
+/** Page errors (React's hydration errors among them) fail the check. */
+const watchErrors = (page, label) => page.on("pageerror", (e) => check(false, `${label}: no page error (${String(e.message).slice(0, 160)})`));
+async function setup(browser, device, theme, engine) {
+ const ctx = await browser.newContext({ ...device, colorScheme: theme });
+ ctx.on("page", (p) => watchErrors(p, `${engine} ${theme}`));
+ // (Init scripts run in every frame, about:blank too, where localStorage throws.)
+ await ctx.addInitScript(
+ ([e]) => {
+ try {
+ localStorage.setItem("fuobe.engine", e);
+ } catch {}
+ },
+ [engine],
+ );
+ // Nothing but the app: a stray request to a local ComfyUI (8188…) is refused here.
+ await ctx.route((u) => u.origin !== new URL(app).origin && (!guestApp || u.origin !== new URL(guestApp).origin) && /^https?:$/.test(u.protocol), (r) => r.abort());
+ return ctx;
+}
+const clockOf = async (page, scope) => (await scope.locator("span.font-mono", { hasText: "/" }).first().innerText()).trim();
+
+async function demoPlayer(page, label) {
+ if (!DEMO_READY) {
+ check((await page.getByText("Hear it first").count()) === 0, `${label}: no demo player until a person has listened to it`);
+ return;
+ }
+ const player = page.getByLabel(/Before and after player/).first();
+ await player.getByRole("button", { name: "Play" }).waitFor({ timeout: 20_000 });
+ await page.waitForFunction(() => !document.querySelector('[aria-label^="Before and after player"] button[disabled]'), null, { timeout: 20_000 });
+ check(await page.getByText("Sample and model: NVIDIA RE-USE (OpenMDW-1.1)", { exact: false }).isVisible(), `${label}: the demo credits NVIDIA RE-USE (OpenMDW-1.1)`);
+ await player.getByRole("button", { name: "Play" }).click();
+ await page.waitForTimeout(900);
+ const t1 = await clockOf(page, player);
+ check(!t1.startsWith("0:00 /"), `${label}: the demo plays (${t1})`);
+ // Switch to Before mid-play: the clock keeps running (one playhead), the divider shows the before whole.
+ await player.getByRole("radio", { name: /Before/ }).click();
+ await page.waitForTimeout(400);
+ const t2 = await clockOf(page, player);
+ check(t2 !== t1 && !t2.startsWith("0:00 /"), `${label}: Before keeps the same playhead (${t1} → ${t2})`);
+ check((await player.getByRole("slider", { name: "Divider between before and after" }).getAttribute("aria-valuenow")) === "100", `${label}: the divider shows the before whole`);
+ await player.focus();
+ await page.keyboard.press("a");
+ check((await player.getByRole("radio", { name: /After/ }).getAttribute("aria-checked")) === "true", `${label}: the A key switches to After`);
+ await player.getByRole("button", { name: "Pause" }).click();
+ const divider = player.getByRole("slider", { name: "Divider between before and after" });
+ await divider.focus();
+ await page.keyboard.press("ArrowRight");
+ check((await divider.getAttribute("aria-valuenow")) === "5", `${label}: the divider moves with the keys`);
+}
+
+async function waitDone(feature, ms = 45_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = (await (await fetch(`${app}/api/generations?features=${feature}&limit=1`)).json()).items?.[0];
+ if ((g && (g.status === "succeeded" || g.status === "failed")) || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 800));
+ }
+}
+
+const browser = await launch();
+try {
+ // ---- The empty tool and the options, at both widths and themes.
+ for (const [dname, device] of [
+ ["1440", DESKTOP],
+ ["390", PHONE],
+ ]) {
+ for (const theme of ["light", "dark"]) {
+ const label = `${dname} ${theme}`;
+ const ctx = await setup(browser, device, theme, "cloud");
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/audio/clean`);
+ check(await page.getByRole("heading", { name: "Clean up voice" }).first().isVisible(), `${label}: the empty tool says what it is`);
+ check(await page.getByText("Add a voice recording or a video to clean").isVisible(), `${label}: the drop zone`);
+ await demoPlayer(page, label);
+ await page.screenshot({ path: path.join(out, `clean-empty-${dname}-${theme}.png`), fullPage: true });
+ await noSideScroll(page, `${label} empty`);
+ await page.locator('input[type="file"]').setInputFiles(wav);
+ await page.getByText("Clean up voice runs on your GPU (open source).").waitFor({ timeout: 20_000 });
+ check(true, `${label}: the cloud engine says Clean up voice runs on your GPU`);
+ await page.screenshot({ path: path.join(out, `clean-cloud-${dname}-${theme}.png`), fullPage: true });
+ await page.getByRole("button", { name: "Use open source" }).click();
+ await page.getByText(/Free · runs on your ComfyUI|Demo · free/).waitFor({ timeout: 20_000 });
+ for (const g of ["Strength", "Model", "Quality", "Background", "Level"]) check(await page.getByRole("radiogroup", { name: g }).isVisible(), `${label}: the ${g} control`);
+ check((await page.getByRole("radio", { name: "Full", exact: true }).getAttribute("aria-checked")) === "true", `${label}: audio starts at Full strength`);
+ await page.screenshot({ path: path.join(out, `clean-open-${dname}-${theme}.png`), fullPage: true });
+ await noSideScroll(page, `${label} with a source`);
+ await ctx.close();
+ }
+ }
+
+ // ---- A run per source kind; a video goes back on the picture.
+ for (const [kind, file, device, dname, theme] of [
+ ["audio", wav, DESKTOP, "1440", "light"],
+ ["video", mp4, PHONE, "390", "dark"],
+ ]) {
+ const ctx = await setup(browser, device, theme, "open");
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/audio/clean`);
+ await page.locator('input[type="file"]').setInputFiles(file);
+ await page.getByText(/Free · runs on your ComfyUI|Demo · free/).waitFor({ timeout: 30_000 });
+ if (kind === "video") {
+ check((await page.getByRole("radio", { name: "Remove everything but the voice" }).getAttribute("aria-checked")) === "true", "video: Remove everything but the voice is the default");
+ check((await page.getByRole("radio", { name: "Natural", exact: true }).getAttribute("aria-checked")) === "true", "video: Natural strength is the default");
+ check(await page.getByRole("switch", { name: /Put back on the video/ }).isChecked(), "video: Put back on the video is on");
+ }
+ await page.getByRole("button", { name: "Clean up voice" }).last().click();
+ await page.getByText("Your before and after").waitFor({ timeout: 45_000 });
+ const result = page.getByLabel(/Before and after player/).last();
+ await result.getByRole("button", { name: "Play" }).waitFor({ timeout: 20_000 });
+ check(await page.getByRole("link", { name: "Use in Lipsync" }).isVisible(), `${kind}: Use in Lipsync`);
+ check(await page.getByRole("link", { name: "Download" }).isVisible(), `${kind}: Download`);
+ const g = await waitDone("voice-clean");
+ check(g?.status === "succeeded" && g.outputs?.[0]?.kind === "audio", `${kind}: the clean voice is in the Library (${g?.status})`);
+ if (kind === "video") {
+ const v = await waitDone("voice-clean-remux");
+ check(v?.status === "succeeded" && v.outputs?.[0]?.kind === "video", `video: the clean video is in the Library too (${v?.status}, ${v?.modelId})`);
+ }
+ await noSideScroll(page, `${kind} result (${dname})`);
+ await page.waitForTimeout(800);
+ await page.screenshot({ path: path.join(out, `clean-result-${kind}-${dname}.png`), fullPage: true });
+ await ctx.close();
+ }
+
+ // ---- The app page, the Library action, the Canvas node and Lipsync's voice slot.
+ {
+ const ctx = await setup(browser, DESKTOP, "light", "open");
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/apps/app-clean-up-voice`);
+ check(await page.getByRole("heading", { name: "Clean up voice" }).first().isVisible(), "app: the app page is the tool");
+ check(await page.getByRole("link", { name: "Apps" }).first().isVisible(), "app: an Apps breadcrumb");
+ await page.screenshot({ path: path.join(out, "clean-app-1440.png"), fullPage: true });
+ const g = await waitDone("voice-clean", 1000);
+ if (g) {
+ await openRoute(page, `${app}/library`);
+ await page.waitForTimeout(1500);
+ await page.screenshot({ path: path.join(out, "clean-library-1440.png") });
+ }
+ await openRoute(page, `${app}/lipsync`);
+ await page.waitForTimeout(1200);
+ const sw = page.getByRole("switch", { name: /Clean up voice/ });
+ check(await sw.first().isVisible(), "lipsync: the voice slot offers Clean up voice");
+ await page.screenshot({ path: path.join(out, "clean-lipsync-switch-1440.png") });
+ // Off: the voice lands as it is. On: the voice already in the slot is cleaned, Generate waits meanwhile, and the slot
+ // then holds the clean file.
+ check(!(await sw.first().isChecked()), "lipsync: the switch starts off");
+ await page.locator('[data-slot-key="audio"] input[type="file"]').setInputFiles(wav);
+ await page.waitForTimeout(2500);
+ check((await page.getByRole("status", { name: "Cleaning the voice" }).count()) === 0, "lipsync: with the switch off the voice isn't cleaned");
+ await sw.first().click();
+ // (Generate's "Waiting for the clean voice" ranks below a missing portrait: tests/clean-voice.test.ts covers it.)
+ const cleaning = await page
+ .getByRole("status", { name: "Cleaning the voice" })
+ .waitFor({ timeout: 15_000 })
+ .then(() => true)
+ .catch(() => false);
+ check(cleaning, "lipsync: turning the switch on cleans the voice already in the slot");
+ check(await page.getByText("Cleaning the voice… about 20 s").first().isVisible().catch(() => false), "lipsync: the switch says in words that it is cleaning");
+ const badge = page.getByRole("button", { name: "Clean voice: hear the original" });
+ check(await badge.waitFor({ timeout: 45_000 }).then(() => true).catch(() => false), "lipsync: the slot holds the clean voice, with the original to compare");
+ await badge.click();
+ check(await page.getByLabel(/Before and after player/).last().isVisible(), "lipsync: the badge plays the original against the clean voice");
+ await page.screenshot({ path: path.join(out, "clean-lipsync-cleaned-1440.png") });
+ await page.keyboard.press("Escape");
+ check(await page.getByRole("button", { name: /Clean voice · Hear original/ }).first().isVisible(), "lipsync: beside the switch, Clean voice · Hear original");
+ await page.screenshot({ path: path.join(out, "clean-lipsync-status-1440.png") });
+ // Off again: the slot goes back to the voice as it was added.
+ await sw.first().click();
+ const back = await badge
+ .waitFor({ state: "detached", timeout: 10_000 })
+ .then(() => true)
+ .catch(() => false);
+ check(back, "lipsync: turning the switch off puts the original back in the slot");
+ await ctx.close();
+ }
+ {
+ // Lipsync on a phone: the switch has its own line under the slot row, its label whole.
+ const ctx = await setup(browser, PHONE, "light", "open");
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/lipsync`);
+ await page.waitForTimeout(1200);
+ const label = page.locator("label", { hasText: "Clean up voice" }).filter({ visible: true }).first();
+ const box = await label.boundingBox();
+ const width = await page.evaluate(() => document.documentElement.clientWidth);
+ check(!!box && box.x >= 0 && box.x + box.width <= width, `lipsync 390: the switch label is whole on screen (${box ? Math.round(box.x + box.width) : "none"} of ${width} px)`);
+ await noSideScroll(page, "lipsync 390");
+ await page.screenshot({ path: path.join(out, "clean-lipsync-390.png") });
+ await ctx.close();
+ }
+ {
+ const ctx = await setup(browser, PHONE, "dark", "open");
+ const page = await ctx.newPage();
+ await openRoute(page, `${app}/apps/app-clean-up-voice`);
+ await page.getByRole("heading", { name: "Clean up voice" }).first().waitFor({ timeout: 20_000 });
+ await demoPlayer(page, "app 390");
+ await noSideScroll(page, "app 390");
+ await page.screenshot({ path: path.join(out, "clean-app-390-dark.png"), fullPage: true });
+ await ctx.close();
+ }
+} finally {
+ if (!guestApp) await browser.close();
+}
+
+// ---- A guest: the demo plays, an upload asks to sign up.
+if (guestApp) {
+ try {
+ for (const [dname, device] of [
+ ["1440", DESKTOP],
+ ["390", PHONE],
+ ]) {
+ const ctx = await browser.newContext({ ...device, colorScheme: "light" });
+ await ctx.route((u) => u.origin !== new URL(guestApp).origin && /^https?:$/.test(u.protocol), (r) => r.abort());
+ const page = await ctx.newPage();
+ watchErrors(page, `guest ${dname}`);
+ for (const route of ["/apps/app-clean-up-voice", "/audio/clean"]) await openRoute(page, `${guestApp}${route}`);
+ await page.waitForTimeout(1500);
+ await demoPlayer(page, `guest ${dname}`);
+ await page.getByRole("button", { name: "Upload" }).first().click();
+ const card = page.getByText(/Create a free account/).first();
+ check(await card.waitFor({ timeout: 10_000 }).then(() => true).catch(() => false), `guest ${dname}: Upload asks to create a free account`);
+ await page.screenshot({ path: path.join(out, `clean-guest-${dname}.png`), fullPage: true });
+ await ctx.close();
+ }
+ } finally {
+ await browser.close();
+ }
+}
+
+console.log(`\nScreenshots in ${out}`);
+if (failures.length) {
+ console.log(`${failures.length} failed`);
+ process.exitCode = 1;
+}
diff --git a/tests/preset-recipes.test.ts b/tests/preset-recipes.test.ts
index 7778b4b5..ce1b547f 100644
--- a/tests/preset-recipes.test.ts
+++ b/tests/preset-recipes.test.ts
@@ -72,7 +72,7 @@ describe("which presets get a recipe", () => {
const grades = [...MOTIONS, ...EFFECTS].filter((x) => x.grade && !x.prestep);
expect(grades).toHaveLength(15);
expect(new Set(none.map((x) => x.id))).toEqual(new Set([...steps.map((x) => x.id), ...grades.map((x) => x.id), ...OWN_ROUTE_APPS]));
- expect(none).toHaveLength(68);
+ expect(none).toHaveLength(69);
for (const x of none) for (const engine of ["open", "cloud"] as const) expect(presetRecipe(x, engine, inCatalog), x.id).toBeUndefined();
});
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index 8612767b..1f9425ad 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -1,7 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
/**
@@ -95,7 +95,7 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
it("lets guests and accounts open the tools' pages", () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
const cookie = auth.createSession(newAccount().id).value;
- for (const p of ["/audio/split", "/character-sheet", "/cinema", "/image", "/connect"]) {
+ for (const p of ["/audio/split", "/audio/clean", "/apps/app-clean-up-voice", "/samples/clean-voice/noisy-mic-after.m4a", "/character-sheet", "/cinema", "/image", "/connect"]) {
expect(passed(proxy(req(p))), `guest ${p}`).toBe(true);
expect(passed(proxy(req(p, { cookie }))), `account ${p}`).toBe(true);
}
@@ -230,6 +230,30 @@ describe("the routes: a visitor's price is its own GPU's, and the owner's charac
const owner = await audioTools.POST(call("/api/audio-tools?preview=1", body(owners), auth.createSession().value));
expect(await owner.json()).toMatchObject({ steps: 1, demo: true, channels: 2 });
});
+
+ it("prices a visitor's Clean up voice on its own GPU without asking any GPU, never a demo, and only of its own file", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const who = newAccount();
+ const cookie = auth.createSession(who.id).value;
+ const owners = wav();
+ const body = (media: string) => ({ tool: "clean", engine: "open", media, kind: "audio", name: "Take" });
+ for (const c of [undefined, cookie]) {
+ const r = await audioTools.POST(call("/api/audio-tools?preview=1", body(owners), c));
+ expect(r.status).toBe(422);
+ expect((await r.json()).error).toBe("That audio file is gone — add it again");
+ }
+ const asked = vi.spyOn(globalThis, "fetch");
+ try {
+ const account = await audioTools.POST(call("/api/audio-tools?preview=1", body(wav("mine.wav", who.id)), cookie));
+ const p = await account.json();
+ expect(p).toMatchObject({ steps: 1, costUsd: 0, demo: false, channels: 2 });
+ // No device known for it yet: a CPU's rate and estimate, and no files listed (the run checks them on its GPU).
+ expect(p.reuse).toEqual({ rate: 24000, seconds: expect.any(Number) });
+ expect(asked).not.toHaveBeenCalled();
+ } finally {
+ asked.mockRestore();
+ }
+ });
});
describe("the GPU pre-flight board lists PR #15's tools like main's studios", () => {
@@ -239,6 +263,7 @@ describe("the GPU pre-flight board lists PR #15's tools like main's studios", ()
it("has a row for Split soundtrack, the fly path and the turnaround, each on graphs the requirement index knows", () => {
const want: Record<string, { label: string; group: string; workflows: string[]; loras?: string[] }> = {
"/audio/split": { label: "Split soundtrack", group: "Audio", workflows: ["separate-soundtrack-dbs"] },
+ "/audio/clean": { label: "Clean up voice", group: "Audio", workflows: ["voice-clean-reuse"] },
"/cinema": { label: "Fly path", group: "Video", workflows: ["wan21-i2v-uni3c-path"] },
"/character-sheet": { label: "Turnaround", group: "Video", workflows: ["wan22-flf2v-14b", "qwen-image-edit-2511-multi"], loras: ["qwen-image-edit-2511-multiple-angles-lora.safetensors"] },
};
diff --git a/tests/split-soundtrack.test.ts b/tests/split-soundtrack.test.ts
index eafd4a22..c816ae08 100644
--- a/tests/split-soundtrack.test.ts
+++ b/tests/split-soundtrack.test.ts
@@ -418,9 +418,10 @@ describe("the mixer", () => {
});
describe("Split soundtrack in the Audio hub", () => {
- it("is a mode after Transcribe with its own path", () => {
+ it("is a mode after Transcribe and Clean up voice, with its own path", () => {
const ids = HUB_MODES.audio.map((m) => m.id);
- expect(ids.indexOf("split")).toBe(ids.indexOf("transcribe") + 1);
+ expect(ids.indexOf("split")).toBe(ids.indexOf("clean") + 1);
+ expect(ids.indexOf("clean")).toBe(ids.indexOf("transcribe") + 1);
expect(HUB_MODES.audio.find((m) => m.id === "split")?.label).toBe("Split soundtrack");
expect(modeHref("audio", "split")).toBe("/audio/split");
});