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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Clean up voice: hear her, not the room
Adarsh67a4a4cb8e96
diff --git a/src/app/globals.css b/src/app/globals.cssindex 9a9129ea..4867fe18 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -219,6 +219,8 @@/* Home: the composer's ring brightens once when a Try chip fills it; Audio's waveform ripples on hover. */--animate-ring-flash: ring-flash 260ms ease-out both;--animate-wave-bar: wave-bar 900ms ease-in-out infinite;+ /* Clean up voice's demo: the "Busy brasserie" dot pulses while the room plays. */+ --animate-live-dot: live-dot 1.1s ease-out infinite;@keyframes shimmer-text {from { mask-position: 100% 0; }@@ -253,6 +255,10 @@0%, 100% { transform: scaleY(1); }50% { transform: scaleY(0.35); }}+ @keyframes live-dot {+ from { box-shadow: 0 0 0 0 rgb(255 179 71 / 60%); }+ to { box-shadow: 0 0 0 8px rgb(255 179 71 / 0%); }+ }}@layer base {diff --git a/src/components/audio-tools/clean-voice-demo.tsx b/src/components/audio-tools/clean-voice-demo.tsxnew file mode 100644index 00000000..cbd737dc--- /dev/null+++ b/src/components/audio-tools/clean-voice-demo.tsx@@ -0,0 +1,318 @@+"use client";++import { Play } from "lucide-react";+import { useCallback, useEffect, useReducer, useRef, useState } from "react";+import { DEMO_MEDIA, DEMO_START, demoReducer, FLASH_MS, gainsFor, isRunning, playLabel, type DemoState } from "@/lib/av/clean-voice-demo";+import { cn } from "@/lib/utils";++/**+ * Clean up voice's demo, for anyone who hasn't cleaned a file of their own yet: a photo of a woman talking in a busy+ * brasserie, and one tap to hear her. Both takes (the room as recorded, her voice alone) start together through Web Audio,+ * one AudioContext with a gain each, so a switch happens at the same moment in her speech; the picture softens with the+ * sound. What happens when is decided in src/lib/av/clean-voice-demo.ts.+ */++type Win = Window & { webkitAudioContext?: typeof AudioContext };+type Nav = Navigator & { audioSession?: { type: string } };++const decode = (ctx: AudioContext, bytes: ArrayBuffer) => new Promise<AudioBuffer>((ok, no) => ctx.decodeAudioData(bytes, ok, no));++/** Stops clips quietly: a stopped clip doesn't count as the end of the demo. */+function stopAll(sources: AudioBufferSourceNode[]) {+ for (const s of sources) {+ s.onended = null;+ try {+ s.stop();+ } catch {}+ }+}++/** iPhone: play like a video does, with the ringer switch on silent too (asked before the sound starts). */+function playThroughSilentSwitch() {+ try {+ const session = (navigator as Nav).audioSession;+ if (session) session.type = "playback";+ } catch {}+}++async function fetchBytes(url: string): Promise<ArrayBuffer> {+ const r = await fetch(url);+ if (!r.ok) throw new Error(`${url}: ${r.status}`);+ return r.arrayBuffer();+}++export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?: string; className?: string }) {+ const [state, dispatch] = useReducer(demoReducer, DEMO_START);+ // The last automatic switch whose "Noise removed" has gone again.+ const [shown, setShown] = useState(0);+ const toast = state.flash > shown;+ const stateRef = useRef<DemoState>(state);+ const ctxRef = useRef<AudioContext | null>(null);+ const bytesRef = useRef<Promise<ArrayBuffer[]> | null>(null);+ const buffersRef = useRef<AudioBuffer[] | null>(null);+ const gainsRef = useRef<GainNode[] | null>(null);+ const sourcesRef = useRef<AudioBufferSourceNode[]>([]);+ const t0Ref = useRef(0);+ const lengthRef = useRef(8);+ const barRef = useRef<HTMLElement>(null);++ useEffect(() => {+ stateRef.current = state;+ }, [state]);++ /** Both clips' bytes, fetched once (again after a failure). */+ const bytes = useCallback(() => {+ bytesRef.current ??= Promise.all([fetchBytes(DEMO_MEDIA.noisy), fetchBytes(DEMO_MEDIA.clean)]).catch((e) => {+ bytesRef.current = null;+ throw e;+ });+ return bytesRef.current;+ }, []);++ // Fetch the clips straight away, so the first tap plays at once.+ useEffect(() => {+ bytes().catch(() => {});+ }, [bytes]);++ /** The AudioContext, made and resumed inside the tap (a phone only lets a tap start sound). */+ const context = () => {+ if (!ctxRef.current) {+ const AC = window.AudioContext ?? (window as Win).webkitAudioContext;+ if (!AC) return null;+ playThroughSilentSwitch();+ ctxRef.current = new AC();+ }+ ctxRef.current.resume().catch(() => {});+ return ctxRef.current;+ };++ // A new run: both clips from the top, at the gains of the mode it starts in.+ useEffect(() => {+ if (!state.run) return;+ let cancelled = false;+ (async () => {+ const ctx = ctxRef.current;+ if (!ctx) throw new Error("No Web Audio");+ if (!buffersRef.current) {+ const raw = await bytes();+ // decodeAudioData takes its buffer over: decode copies, so a later decode still has the bytes.+ buffersRef.current = await Promise.all(raw.map((b) => decode(ctx, b.slice(0))));+ lengthRef.current = Math.min(...buffersRef.current.map((b) => b.duration));+ }+ if (cancelled) return;+ stopAll(sourcesRef.current);+ sourcesRef.current = [];+ const target = gainsFor(stateRef.current.clean);+ const gains = buffersRef.current.map((_, i) => {+ const g = ctx.createGain();+ g.gain.value = target[i];+ g.connect(ctx.destination);+ return g;+ });+ const t0 = ctx.currentTime + 0.05;+ const sources = buffersRef.current.map((b, i) => {+ const s = ctx.createBufferSource();+ s.buffer = b;+ s.connect(gains[i]);+ s.start(t0);+ return s;+ });+ sources[0].onended = () => dispatch({ type: "ended" });+ gainsRef.current = gains;+ sourcesRef.current = sources;+ t0Ref.current = t0;+ dispatch({ type: "started" });+ })().catch(() => {+ if (!cancelled) dispatch({ type: "failed" });+ });+ return () => {+ cancelled = true;+ };+ }, [state.run, bytes]);++ // A switch: both gains ramp at once, so the voice carries on where it was.+ useEffect(() => {+ const ctx = ctxRef.current;+ const gains = gainsRef.current;+ if (!ctx || !gains) return;+ const now = ctx.currentTime;+ gainsFor(state.clean).forEach((v, i) => {+ const g = gains[i].gain;+ g.cancelScheduledValues(now);+ g.setValueAtTime(g.value, now);+ g.linearRampToValueAtTime(v, now + Math.max(state.ramp, 0.01));+ });+ }, [state.clean, state.ramp]);++ // The progress line and the automatic switch follow the clips' own clock (it stops while paused).+ useEffect(() => {+ if (state.phase !== "playing") {+ if (state.phase === "done" && barRef.current) barRef.current.style.width = "100%";+ return;+ }+ let raf = 0;+ const step = () => {+ const ctx = ctxRef.current;+ if (!ctx) return;+ const t = Math.max(0, ctx.currentTime - t0Ref.current);+ if (barRef.current) barRef.current.style.width = `${Math.min(100, (t / lengthRef.current) * 100)}%`;+ const s = stateRef.current;+ if (s.auto && !s.clean) dispatch({ type: "time", t });+ raf = requestAnimationFrame(step);+ };+ raf = requestAnimationFrame(step);+ return () => cancelAnimationFrame(raf);+ }, [state.phase]);++ // "Noise removed", for a moment, when the noise goes by itself.+ useEffect(() => {+ if (!state.flash) return;+ const flash = state.flash;+ const t = setTimeout(() => setShown(flash), FLASH_MS);+ return () => clearTimeout(t);+ }, [state.flash]);++ // Leaving the page stops the sound.+ useEffect(+ () => () => {+ stopAll(sourcesRef.current);+ sourcesRef.current = [];+ ctxRef.current?.close().catch(() => {});+ ctxRef.current = null;+ },+ [],+ );++ const tap = () => {+ const s = stateRef.current;+ if (s.phase === "loading") return;+ if (s.phase === "playing") ctxRef.current?.suspend().catch(() => {});+ else if (s.phase === "paused") ctxRef.current?.resume().catch(() => {});+ else if (!context()) return void dispatch({ type: "failed" });+ dispatch({ type: "tap" });+ };+ const choose = (clean: boolean) => {+ if (!isRunning(stateRef.current) && !context()) return void dispatch({ type: "failed" });+ dispatch({ type: "choose", clean });+ };++ const playing = state.phase === "playing";+ const moving = isRunning(state) || state.phase === "done";+ const buttonShown = !playing;++ return (+ <section className={cn("mx-auto grid w-full max-w-[760px] gap-[18px]", className)} aria-labelledby="clean-voice-demo">+ <header className="grid gap-1.5">+ <span className="text-[12px] font-medium tracking-[.06em] text-muted-foreground uppercase">{name}</span>+ <h2 id="clean-voice-demo" className="font-heading text-[clamp(34px,7vw,48px)] leading-[1.05] tracking-[-.01em] text-balance">+ Hear her, not the room.+ </h2>+ <p className="max-w-[52ch] text-[15px] leading-[1.55] text-muted-foreground">+ A phone recording from a packed brasserie: music, clatter and every other table. Tap play and the room falls away while she keeps talking.+ </p>+ </header>++ <div+ role="group"+ aria-label="Demo: a woman talking in a busy brasserie"+ onClick={tap}+ className="relative isolate aspect-[4/3] w-full max-w-full cursor-pointer overflow-hidden rounded-xl bg-media [-webkit-tap-highlight-color:transparent]"+ >+ <div+ className={cn(+ "absolute inset-0 origin-[50%_38%] transition-transform duration-[9s] ease-[cubic-bezier(.2,.6,.3,1)] motion-reduce:scale-100 motion-reduce:transition-none",+ moving && "scale-[1.045]",+ )}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={DEMO_MEDIA.room}+ alt="A woman talking at a marble table in a packed Paris brasserie, waiters and diners behind her"+ width={1280}+ height={960}+ fetchPriority="high"+ draggable={false}+ className="absolute inset-0 block size-full object-cover select-none"+ />+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={DEMO_MEDIA.quiet}+ alt=""+ width={1280}+ height={960}+ draggable={false}+ data-demo-quiet+ className={cn("absolute inset-0 block size-full object-cover transition-opacity duration-1000 ease-in-out select-none motion-reduce:transition-none", state.clean ? "opacity-100" : "opacity-0")}+ />+ </div>++ <span+ className="absolute top-3 left-3 z-[2] inline-flex items-center gap-2 rounded-full bg-[rgb(10_8_6/.55)] py-1.5 pr-3 pl-2.5 text-[13px] font-medium text-white backdrop-blur-[10px]"+ aria-live="polite"+ >+ <span className={cn("size-2 rounded-full motion-reduce:animate-none", state.clean ? "bg-[#7ee2b8]" : "bg-[#ffb347]", playing && !state.clean && "animate-live-dot")} />+ <span data-demo-state>{state.clean ? "Voice only" : "Busy brasserie"}</span>+ </span>++ <span+ aria-hidden="true"+ className={cn(+ "pointer-events-none absolute top-1/2 left-1/2 z-[2] -translate-x-1/2 rounded-full bg-[rgb(10_8_6/.6)] px-[18px] py-2.5 font-heading text-[26px] leading-[1.1] tracking-[.01em] whitespace-nowrap text-white backdrop-blur-[10px] transition-[opacity,translate] duration-600 ease-in-out motion-reduce:transition-none",+ toast ? "-translate-y-1/2 opacity-100" : "-translate-y-[40%] opacity-0",+ )}+ >+ Noise removed+ </span>++ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ tap();+ }}+ tabIndex={buttonShown ? 0 : -1}+ className={cn(+ "absolute bottom-[22px] left-1/2 z-[3] inline-flex min-h-[52px] -translate-x-1/2 cursor-pointer items-center gap-2.5 rounded-full border-0 bg-white/92 pr-[22px] pl-4 text-[15px] leading-none font-semibold text-[#141210] shadow-[0_10px_30px_rgb(0_0_0/.35)] transition-[opacity,translate] duration-350 ease-in-out outline-none focus-visible:outline-3 focus-visible:outline-offset-3 focus-visible:outline-ring motion-reduce:transition-none",+ buttonShown ? "opacity-100" : "pointer-events-none translate-y-1.5 opacity-0",+ )}+ >+ <Play className="size-[22px] fill-current" aria-hidden="true" />+ <span>{playLabel(state)}</span>+ </button>++ <div className="absolute inset-x-0 bottom-0 z-[2] h-[3px] bg-white/18" aria-hidden="true">+ <i ref={barRef} className="block h-full w-0 bg-white" />+ </div>+ </div>++ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="inline-flex gap-1 rounded-full bg-muted p-1" role="group" aria-label="Noise">+ {[+ { clean: false, label: "Noise on" },+ { clean: true, label: "Noise off" },+ ].map((o) => (+ <button+ key={o.label}+ type="button"+ aria-pressed={state.clean === o.clean}+ onClick={() => choose(o.clean)}+ className={cn(+ "min-h-11 cursor-pointer rounded-full px-[18px] text-[14px] leading-none font-medium transition-[background-color,color] duration-250 outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",+ state.clean === o.clean ? "bg-background text-foreground shadow-[0_1px_3px_rgb(0_0_0/.12)]" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {o.label}+ </button>+ ))}+ </div>+ <p className="m-0 text-[13px] text-muted-foreground" data-demo-hint>+ {state.hint}+ </p>+ </div>++ <p className="max-w-[60ch] border-t pt-3.5 text-[13px] text-muted-foreground">+ Same 8 seconds, same moment in her sentence: switching only changes what you hear around her voice.+ </p>+ </section>+ );+}diff --git a/src/components/audio-tools/clean-voice-tool.tsx b/src/components/audio-tools/clean-voice-tool.tsxindex 6572540f..7682175d 100644--- a/src/components/audio-tools/clean-voice-tool.tsx+++ b/src/components/audio-tools/clean-voice-tool.tsx@@ -24,9 +24,6 @@ import {CLOUD_ONLY_CLEAN_PROBLEM,CLOUD_CLEAN_PROBLEM,cleanDefaults,- DEMO_CREDIT,- DEMO_PAIRS,- DEMO_READY,durationWords,khz,LEVEL_LABELS,@@ -48,16 +45,20 @@ import { downloadHref } from "@/lib/library";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { BeforeAfterAudio } from "./before-after-audio";+import { CleanVoiceDemo } from "./clean-voice-demo";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.+ * before and after from one playhead. Until someone has cleaned a file of their own, the page opens on the demo+ * (CleanVoiceDemo), so everyone (guests too) hears what it does at once. There's no hosted RE-USE, so the cloud engine says so.*/+const TOOL_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.";+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, "");@@ -77,41 +78,6 @@ function useHandoff(take: (s: Source, keep?: boolean) => void) {}, []);}-/** 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);@@ -254,16 +220,9 @@ export function CleanVoiceTool({ tabs, app }: { tabs?: React.ReactNode; app?: {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");- }- };+ // Someone who has cleaned a file of their own sees their results, not the demo (the same query as Results').+ const cleans = useGenerations({ features: [CLEAN_FEATURE], limit: 12 });+ const demo = !source && !cleans.data?.some((g) => g.status === "succeeded");const kind = source?.kind ?? "audio";const d = cleanDefaults(kind);@@ -341,14 +300,14 @@ export function CleanVoiceTool({ tabs, app }: { tabs?: React.ReactNode; app?: {) : 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 && !demo && <ToolHero title={app?.name ?? "Clean up voice"} subtitle={TOOL_SUBTITLE} />}+ <div className={cn("mx-auto space-y-3", demo ? "max-w-[760px] pt-6 sm:pt-10" : "max-w-[860px]", source ? "pt-4" : !demo && "mt-6")}>+ {demo && (+ <>+ <CleanVoiceDemo name={app?.name ?? "Clean up voice"} />+ <p className="pt-7 text-[13px] text-pretty text-muted-foreground">{TOOL_SUBTITLE}</p>+ </>+ )}{!source ? (<AddMedia onPick={take} onUpdate={setSource} />) : (diff --git a/src/lib/av/clean-voice-demo.ts b/src/lib/av/clean-voice-demo.tsnew file mode 100644index 00000000..91ebf86c--- /dev/null+++ b/src/lib/av/clean-voice-demo.ts@@ -0,0 +1,113 @@+/**+ * Clean up voice's demo (src/components/audio-tools/clean-voice-demo.tsx): a woman talking in a busy brasserie. One tap+ * plays two 8 s takes of the same moment at once, the room as recorded and her voice alone, each through its own gain.+ * The room plays first; at 3 s the noise fades out over 1 s while she keeps talking, and the photo softens to match.+ * "Noise on" / "Noise off" switch both at the same moment in her speech and stop the automatic switch. Pure: the+ * component runs the audio, this decides what happens.+ */++export const DEMO_DIR = "/samples/clean-voice";+export const DEMO_MEDIA = {+ /** The room as recorded, and her voice alone: 8 s, 48 kHz mono AAC, the same moment, at the same gain. */+ noisy: `${DEMO_DIR}/noisy.m4a`,+ clean: `${DEMO_DIR}/clean.m4a`,+ /** The brasserie, and the same photo with the room softened and dimmed around her (1280x960). */+ room: `${DEMO_DIR}/room.webp`,+ quiet: `${DEMO_DIR}/quiet.webp`,+} as const;++/** When the noise goes by itself (seconds into the clip), how long it fades, and how fast a choice switches. */+export const AUTO_AT = 3;+export const AUTO_FADE = 1;+export const SWITCH_RAMP = 0.35;+/** How long "Noise removed" shows. */+export const FLASH_MS = 1600;++export type DemoPhase = "idle" | "loading" | "playing" | "paused" | "done" | "failed";++export interface DemoState {+ phase: DemoPhase;+ /** Hearing her voice only (the noise off). */+ clean: boolean;+ /** The automatic switch at AUTO_AT is still to come (a play of the whole story, with no choice made yet). */+ auto: boolean;+ /** Seconds the last change of `clean` ramps over. */+ ramp: number;+ /** Counts each start: a new value starts both clips from the top. */+ run: number;+ /** Counts each automatic switch: a new value shows "Noise removed". */+ flash: number;+ hint: string;+}++export type DemoEvent =+ /** The play button or the photo. */+ | { type: "tap" }+ /** "Noise on" (false) or "Noise off" (true). */+ | { type: "choose"; clean: boolean }+ /** Both clips are decoded and started. */+ | { type: "started" }+ /** The clips' clock, in seconds since they started (the automatic switch is due at AUTO_AT). */+ | { type: "time"; t: number }+ | { type: "ended" }+ | { type: "failed" };++export const HINTS = {+ ready: "Sound on. The noise goes by itself after a few seconds.",+ story: "Listen to the room.",+ voice: "Voice only.",+ room: "The room as recorded.",+ auto: "Only her voice is left. Switch back and forth any time.",+ done: "Play again to hear the room go quiet.",+ failed: "The sound didn't load. Check your connection and tap again.",+} as const;++export const DEMO_START: DemoState = { phase: "idle", clean: false, auto: true, ramp: 0, run: 0, flash: 0, hint: HINTS.ready };++/** Playing or paused: both clips exist and keep their place. */+export const isRunning = (s: DemoState) => s.phase === "playing" || s.phase === "paused";++const modeHint = (clean: boolean) => (clean ? HINTS.voice : HINTS.room);++/** Starts both clips from the top: the whole story (auto) or one mode chosen before playing. */+function start(s: DemoState, clean: boolean, story: boolean): DemoState {+ return { ...s, phase: "loading", clean, auto: story, ramp: 0, run: s.run + 1 };+}++export function demoReducer(s: DemoState, e: DemoEvent): DemoState {+ switch (e.type) {+ case "tap":+ if (s.phase === "playing") return { ...s, phase: "paused" };+ if (s.phase === "paused") return { ...s, phase: "playing" };+ if (s.phase === "loading") return s;+ return start(s, false, true);+ case "choose":+ if (isRunning(s)) return { ...s, clean: e.clean, auto: false, ramp: SWITCH_RAMP, hint: modeHint(e.clean) };+ // Still loading: the clips start in this mode.+ if (s.phase === "loading") return { ...s, clean: e.clean, auto: false, ramp: 0, hint: modeHint(e.clean) };+ return { ...start(s, e.clean, false), hint: modeHint(e.clean) };+ case "started":+ if (s.phase !== "loading") return s;+ return { ...s, phase: "playing", hint: s.auto ? HINTS.story : modeHint(s.clean) };+ case "time":+ if (s.phase !== "playing" || !s.auto || s.clean || e.t < AUTO_AT) return s;+ return { ...s, clean: true, auto: false, ramp: AUTO_FADE, flash: s.flash + 1, hint: HINTS.auto };+ case "ended":+ if (!isRunning(s)) return s;+ return { ...s, phase: "done", auto: false, hint: HINTS.done };+ case "failed":+ return { ...s, phase: "failed", auto: false, hint: HINTS.failed };+ }+}++/** The play button's words. */+export function playLabel(s: DemoState): string {+ if (s.phase === "loading") return "Loading…";+ if (s.phase === "paused") return "Resume";+ if (s.phase === "done") return "Play again";+ if (s.phase === "failed") return "Tap to try again";+ return "Tap to listen";+}++/** Target gains for the room and the voice. */+export const gainsFor = (clean: boolean): [number, number] => (clean ? [0, 1] : [1, 0]);diff --git a/src/lib/av/clean-voice.ts b/src/lib/av/clean-voice.tsindex 6f07f091..775d2bc0 100644--- a/src/lib/av/clean-voice.ts+++ b/src/lib/av/clean-voice.ts@@ -321,26 +321,3 @@ function safeJson(s: string): unknown {return null;}}--// ----------------------------------------------------------------------------// The guest demo: NVIDIA's own sample, cleaned (static files, no run)--export interface DemoPair {- id: string;- label: string;- hint: string;- before: string;- after: string;-}--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", 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/tests/clean-voice-demo.test.ts b/tests/clean-voice-demo.test.tsnew file mode 100644index 00000000..de7f88da--- /dev/null+++ b/tests/clean-voice-demo.test.ts@@ -0,0 +1,131 @@+import { execFileSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { CleanVoiceDemo } from "@/components/audio-tools/clean-voice-demo";+import {+ AUTO_AT,+ AUTO_FADE,+ DEMO_MEDIA,+ DEMO_START,+ demoReducer,+ gainsFor,+ HINTS,+ isRunning,+ playLabel,+ SWITCH_RAMP,+ type DemoEvent,+ type DemoState,+} from "@/lib/av/clean-voice-demo";++/*+ * Clean up voice's demo (src/lib/av/clean-voice-demo.ts, src/components/audio-tools/clean-voice-demo.tsx): the room plays+ * first and goes by itself at 3 s; a choice switches at once and stops the automatic switch; Play again tells it all again.+ */++const run = (...events: DemoEvent[]) => events.reduce<DemoState>(demoReducer, DEMO_START);+const tap: DemoEvent = { type: "tap" };+const started: DemoEvent = { type: "started" };+const at = (t: number): DemoEvent => ({ type: "time", t });++describe("the demo's story", () => {+ it("starts on the room, with the automatic switch to come", () => {+ const s = run(tap);+ expect(s).toMatchObject({ phase: "loading", clean: false, auto: true, run: 1 });+ expect(playLabel(s)).toBe("Loading…");+ expect(run(tap, started)).toMatchObject({ phase: "playing", clean: false, hint: HINTS.story });+ expect(gainsFor(false)).toEqual([1, 0]);+ });++ it("takes the noise away by itself at 3 s, fading over 1 s, and shows Noise removed once", () => {+ expect(run(tap, started, at(AUTO_AT - 0.01))).toMatchObject({ clean: false, flash: 0 });+ const s = run(tap, started, at(AUTO_AT));+ expect(s).toMatchObject({ clean: true, auto: false, ramp: AUTO_FADE, flash: 1, hint: HINTS.auto });+ expect(gainsFor(true)).toEqual([0, 1]);+ // Later ticks change nothing (the same state, so nothing renders again).+ expect(demoReducer(s, at(AUTO_AT + 1))).toBe(s);+ });++ it("doesn't switch while paused, and switches after resuming", () => {+ const paused = run(tap, started, tap);+ expect(paused.phase).toBe("paused");+ expect(playLabel(paused)).toBe("Resume");+ expect(demoReducer(paused, at(AUTO_AT + 0.5)).clean).toBe(false);+ expect(run(tap, started, tap, tap, at(AUTO_AT)).clean).toBe(true);+ });++ it("cancels the automatic switch when a choice is made", () => {+ const s = run(tap, started, { type: "choose", clean: false });+ expect(s).toMatchObject({ clean: false, auto: false, ramp: SWITCH_RAMP, hint: HINTS.room });+ expect(demoReducer(s, at(AUTO_AT + 1))).toBe(s);+ expect(run(tap, started, { type: "choose", clean: true })).toMatchObject({ clean: true, auto: false, ramp: SWITCH_RAMP, flash: 0, hint: HINTS.voice });+ // After the automatic switch, Noise on puts the room back in a quick ramp.+ expect(run(tap, started, at(AUTO_AT), { type: "choose", clean: false })).toMatchObject({ clean: false, ramp: SWITCH_RAMP });+ });++ it("starts in the mode chosen before playing, with no automatic switch", () => {+ const off = run({ type: "choose", clean: true });+ expect(off).toMatchObject({ phase: "loading", clean: true, auto: false, run: 1 });+ expect(demoReducer(off, started)).toMatchObject({ phase: "playing", hint: HINTS.voice });+ const on = run({ type: "choose", clean: false }, started, at(AUTO_AT + 2));+ expect(on).toMatchObject({ phase: "playing", clean: false, flash: 0, hint: HINTS.room });+ // A choice while the clips load sets the mode they start in.+ expect(run(tap, { type: "choose", clean: true }, started, at(AUTO_AT))).toMatchObject({ clean: true, auto: false, run: 1, flash: 0 });+ });++ it("ends on Play again, which tells the whole story again", () => {+ const done = run(tap, started, at(AUTO_AT), { type: "ended" });+ expect(done).toMatchObject({ phase: "done", hint: HINTS.done });+ expect(playLabel(done)).toBe("Play again");+ expect(isRunning(done)).toBe(false);+ const again = demoReducer(done, tap);+ expect(again).toMatchObject({ phase: "loading", clean: false, auto: true, run: 2 });+ expect(run(tap, started, at(AUTO_AT), { type: "ended" }, tap, started, at(AUTO_AT))).toMatchObject({ clean: true, flash: 2 });+ // A choice after the end plays again in that mode.+ expect(demoReducer(done, { type: "choose", clean: false })).toMatchObject({ phase: "loading", clean: false, auto: false, run: 2 });+ });++ it("ignores taps while loading, and offers to try again when the sound doesn't load", () => {+ const loading = run(tap);+ expect(demoReducer(loading, tap)).toBe(loading);+ const failed = demoReducer(loading, { type: "failed" });+ expect(failed).toMatchObject({ phase: "failed", hint: HINTS.failed });+ expect(playLabel(failed)).toBe("Tap to try again");+ expect(demoReducer(failed, tap)).toMatchObject({ phase: "loading", run: 2 });+ });+});++describe("the demo page", () => {+ it("renders the stage before anything plays: the room, Tap to listen, Noise on pressed", () => {+ const html = renderToStaticMarkup(createElement(CleanVoiceDemo));+ expect(html).toContain("Hear her, not the room.");+ expect(html).toContain(`src="${DEMO_MEDIA.room}"`);+ expect(html).toContain(`src="${DEMO_MEDIA.quiet}"`);+ expect(html).toContain("Tap to listen");+ expect(html).toContain("Busy brasserie");+ expect(html).toMatch(/aria-pressed="true"[^>]*>Noise on</);+ expect(html).toMatch(/aria-pressed="false"[^>]*>Noise off</);+ expect(html).toContain(HINTS.ready);+ expect(html).toContain("min-h-11");+ expect(html).toContain("motion-reduce:transition-none");+ });++ it("ships its pictures and two 8 s clips of the same length", () => {+ const pub = path.resolve(__dirname, "..", "public");+ for (const f of Object.values(DEMO_MEDIA)) expect(fs.existsSync(path.join(pub, f)), f).toBe(true);+ for (const f of [DEMO_MEDIA.noisy, DEMO_MEDIA.clean]) {+ const file = path.join(pub, f);+ expect(fs.statSync(file).size).toBeLessThan(200_000);+ let probe: string;+ try {+ probe = execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_name,sample_rate,channels:format=duration", "-of", "compact=p=0", file], { encoding: "utf8" });+ } catch {+ continue; // no ffprobe on this machine+ }+ expect(probe).toMatch(/codec_name=aac\|sample_rate=48000\|channels=1/);+ expect(Number(/duration=([\d.]+)/.exec(probe)?.[1])).toBeCloseTo(8, 1);+ }+ });+});diff --git a/tests/clean-voice.test.ts b/tests/clean-voice.test.tsindex e6f61de6..8bc3a568 100644--- a/tests/clean-voice.test.ts+++ b/tests/clean-voice.test.ts@@ -7,8 +7,6 @@ import {CLOUD_CLEAN_PROBLEM,CLOUD_ONLY_CLEAN_PROBLEM,cleanTime,- DEMO_PAIRS,- DEMO_READY,installedReuse,missingReuse,planClean,@@ -238,12 +236,6 @@ describe("where Clean up voice opens", () => {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", () => {diff --git a/tests/e2e/clean-voice.mjs b/tests/e2e/clean-voice.mjsindex f8898d42..a750a669 100644--- a/tests/e2e/clean-voice.mjs+++ b/tests/e2e/clean-voice.mjs@@ -2,13 +2,13 @@// 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+// Checks, at 1440 px and 390 px in light and dark: the empty tool with the demo (one tap plays it, the noise goes by itself+// and the photo softens, Noise on brings the room back), 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.+// The demo shows until the install has a clean of its own; after that the page opens on the tool, and the checks see that.+// 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";@@ -32,9 +32,6 @@ const ff = (a) => {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}`);@@ -62,35 +59,38 @@ async function setup(browser, device, theme, engine) {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();+/** Whether the install (as `base` sees it; a guest sees none of its runs) has a clean of its own: then there's no demo. */+async function hasCleaned(base) {+ try {+ const items = (await (await fetch(`${base}/api/generations?features=voice-clean&limit=12`)).json()).items ?? [];+ return items.some((g) => g.status === "succeeded");+ } catch {+ return false;+ }+}-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`);+async function demoPlayer(page, label, base = app) {+ const stage = page.getByRole("group", { name: "Demo: a woman talking in a busy brasserie" });+ if (await hasCleaned(base)) {+ check((await stage.count()) === 0, `${label}: after a clean of your own, the page opens on the tool, not the demo`);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`);+ await stage.waitFor({ timeout: 20_000 });+ check(await page.getByRole("heading", { name: "Hear her, not the room." }).isVisible(), `${label}: the demo says what it shows`);+ const chip = page.locator("[data-demo-state]");+ check((await chip.innerText()) === "Busy brasserie", `${label}: the demo starts on the busy room`);+ await page.getByRole("button", { name: "Tap to listen" }).click();+ const quiet = await page+ .waitForFunction(() => document.querySelector("[data-demo-state]")?.textContent === "Voice only", null, { timeout: 15_000 })+ .then(() => true)+ .catch(() => false);+ check(quiet, `${label}: one tap plays it, and the noise goes by itself`);+ await page.waitForTimeout(1200);+ const shown = Number(await page.locator("[data-demo-quiet]").evaluate((el) => getComputedStyle(el).opacity));+ check(shown > 0.95, `${label}: the photo softens with the sound (${shown})`);+ await page.getByRole("button", { name: "Noise on" }).click();+ check((await page.getByRole("button", { name: "Noise on" }).getAttribute("aria-pressed")) === "true", `${label}: Noise on is pressed`);+ check((await chip.innerText()) === "Busy brasserie", `${label}: Noise on brings the room back`);}async function waitDone(feature, ms = 45_000) {@@ -114,7 +114,7 @@ try {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.getByRole("heading", { name: /^(Clean up voice|Hear her, not the room\.)$/ }).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 });@@ -171,7 +171,7 @@ try {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("heading", { name: /^(Clean up voice|Hear her, not the room\.)$/ }).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);@@ -235,7 +235,7 @@ try {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 page.getByRole("heading", { name: /^(Clean up voice|Hear her, not the room\.)$/ }).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 });@@ -258,7 +258,7 @@ if (guestApp) {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 demoPlayer(page, `guest ${dname}`, guestApp);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`);