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: the demo holds up on phones and laptops
Adarsh336d09e8f482
diff --git a/src/components/audio-tools/clean-voice-demo.tsx b/src/components/audio-tools/clean-voice-demo.tsxindex cbd737dc..7fa03684 100644--- a/src/components/audio-tools/clean-voice-demo.tsx+++ b/src/components/audio-tools/clean-voice-demo.tsx@@ -1,8 +1,19 @@"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 { Pause, Play } from "lucide-react";+import { useCallback, useEffect, useId, useReducer, useRef, useState } from "react";+import {+ createDemoAudio,+ DEMO_MEDIA,+ DEMO_START,+ demoReducer,+ FLASH_MS,+ isRunning,+ playLabel,+ switchDue,+ type DemoAudio,+ type DemoState,+} from "@/lib/av/clean-voice-demo";import { cn } from "@/lib/utils";/**@@ -15,17 +26,10 @@ import { cn } from "@/lib/utils";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));+/** A clip that hasn't arrived by then counts as not loaded (the button offers to try again). */+const FETCH_TIMEOUT_MS = 15_000;-/** 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 {}- }-}+const decode = (ctx: AudioContext, bytes: ArrayBuffer) => new Promise<AudioBuffer>((ok, no) => ctx.decodeAudioData(bytes, ok, no));/** iPhone: play like a video does, with the ringer switch on silent too (asked before the sound starts). */function playThroughSilentSwitch() {@@ -36,24 +40,31 @@ function playThroughSilentSwitch() {}async function fetchBytes(url: string): Promise<ArrayBuffer> {- const r = await fetch(url);+ const signal = typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(FETCH_TIMEOUT_MS) : undefined;+ const r = await fetch(url, { signal });if (!r.ok) throw new Error(`${url}: ${r.status}`);return r.arrayBuffer();}-export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?: string; className?: string }) {+export function CleanVoiceDemo({+ name = "Clean up voice",+ ready = true,+ className,+}: {+ name?: string;+ /** False while the page doesn't yet know whether to show the demo: it keeps its place, unseen, and fetches nothing. */+ ready?: boolean;+ 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 headingId = useId();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 audioRef = useRef<DemoAudio | null>(null);const barRef = useRef<HTMLElement>(null);useEffect(() => {@@ -69,10 +80,10 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:return bytesRef.current;}, []);- // Fetch the clips straight away, so the first tap plays at once.+ // Fetch the clips as soon as the demo shows, so the first tap plays at once.useEffect(() => {- bytes().catch(() => {});- }, [bytes]);+ if (ready) bytes().catch(() => {});+ }, [ready, bytes]);/** The AudioContext, made and resumed inside the tap (a phone only lets a tap start sound). */const context = () => {@@ -80,7 +91,17 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:const AC = window.AudioContext ?? (window as Win).webkitAudioContext;if (!AC) return null;playThroughSilentSwitch();- ctxRef.current = new AC();+ let ctx: AudioContext;+ try {+ ctx = new AC();+ } catch {+ return null;+ }+ // A call, the lock screen or another app can stop the sound: show it as paused, so one tap resumes it.+ ctx.onstatechange = () => {+ if (ctx.state !== "running") dispatch({ type: "interrupted" });+ };+ ctxRef.current = ctx;}ctxRef.current.resume().catch(() => {});return ctxRef.current;@@ -88,39 +109,21 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:// A new run: both clips from the top, at the gains of the mode it starts in.useEffect(() => {- if (!state.run) return;+ // Only a start asks for one (the page coming back into view runs this again with nothing to start).+ if (!state.run || stateRef.current.phase !== "loading") return;let cancelled = false;(async () => {const ctx = ctxRef.current;- if (!ctx) throw new Error("No Web Audio");- if (!buffersRef.current) {+ if (!ctx) throw new Error("No sound");+ if (!audioRef.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));+ const buffers = await Promise.all(raw.map((b) => decode(ctx, b.slice(0))));+ if (cancelled || ctxRef.current !== ctx) return;+ audioRef.current = createDemoAudio(ctx, buffers);}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;+ audioRef.current.start(stateRef.current.clean, () => dispatch({ type: "ended" }));dispatch({ type: "started" });})().catch(() => {if (!cancelled) dispatch({ type: "failed" });@@ -132,32 +135,22 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:// 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));- });+ audioRef.current?.switchTo(state.clean, state.ramp);}, [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%";+ if (barRef.current && state.phase !== "paused") barRef.current.style.width = state.phase === "done" ? "100%" : "0%";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 });+ const audio = audioRef.current;+ if (!audio) return;+ const t = audio.elapsed();+ if (barRef.current) barRef.current.style.width = `${Math.min(100, (t / audio.length) * 100)}%`;+ if (switchDue(stateRef.current, t)) dispatch({ type: "time", t });raf = requestAnimationFrame(step);};raf = requestAnimationFrame(step);@@ -172,13 +165,30 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:return () => clearTimeout(t);}, [state.flash]);- // Leaving the page stops the sound.+ // A hidden tab pauses the demo (a phone would otherwise keep playing it in the background).+ useEffect(() => {+ const onHide = () => {+ if (!document.hidden || stateRef.current.phase !== "playing") return;+ ctxRef.current?.suspend().catch(() => {});+ dispatch({ type: "interrupted" });+ };+ document.addEventListener("visibilitychange", onHide);+ return () => document.removeEventListener("visibilitychange", onHide);+ }, []);++ // Leaving the page (or the page being kept aside for a quick way back) stops the sound and starts the demo over.useEffect(() => () => {- stopAll(sourcesRef.current);- sourcesRef.current = [];- ctxRef.current?.close().catch(() => {});+ audioRef.current?.stop();+ audioRef.current = null;+ const ctx = ctxRef.current;ctxRef.current = null;+ if (ctx) {+ ctx.onstatechange = null;+ ctx.close().catch(() => {});+ }+ setShown(stateRef.current.flash);+ dispatch({ type: "reset" });},[],);@@ -186,13 +196,16 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?: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" });+ const ctx = ctxRef.current;+ // Stopped from outside while it looked like it was playing: this tap brings the sound back.+ if (s.phase === "playing" && ctx && ctx.state !== "running") return void ctx.resume().catch(() => {});+ if (s.phase === "playing") ctx?.suspend().catch(() => {});+ else if (s.phase === "paused") ctx?.resume().catch(() => {});+ else if (!context()) return void dispatch({ type: "failed", unsupported: true });dispatch({ type: "tap" });};const choose = (clean: boolean) => {- if (!isRunning(stateRef.current) && !context()) return void dispatch({ type: "failed" });+ if (!isRunning(stateRef.current) && !context()) return void dispatch({ type: "failed", unsupported: true });dispatch({ type: "choose", clean });};@@ -201,10 +214,13 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:const buttonShown = !playing;return (- <section className={cn("mx-auto grid w-full max-w-[760px] gap-[18px]", className)} aria-labelledby="clean-voice-demo">+ <section+ className={cn("mx-auto grid w-full max-w-[760px] gap-[18px] transition-opacity duration-300 motion-reduce:transition-none", !ready && "invisible opacity-0", className)}+ aria-labelledby={headingId}+ ><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">+ <h2 id={headingId} 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">@@ -216,7 +232,7 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?: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]"+ className="relative isolate aspect-[4/3] w-full max-w-full cursor-pointer touch-manipulation overflow-hidden rounded-xl bg-media [-webkit-tap-highlight-color:transparent]"><divclassName={cn(@@ -264,19 +280,19 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?:Noise removed</span>+ {/* Hidden while it plays, but still reachable from the keyboard: focused, it shows as Pause. */}<buttontype="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",+ "absolute inset-x-0 bottom-[22px] z-[3] mx-auto inline-flex min-h-[52px] w-fit cursor-pointer touch-manipulation items-center gap-2.5 rounded-full border-0 bg-white/92 pr-[22px] pl-4 text-[15px] leading-none font-semibold whitespace-nowrap 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 focus-visible:pointer-events-auto focus-visible:translate-y-0 focus-visible:opacity-100",)}>- <Play className="size-[22px] fill-current" aria-hidden="true" />+ {playing ? <Pause className="size-[22px] fill-current" aria-hidden="true" /> : <Play className="size-[22px] fill-current" aria-hidden="true" />}<span>{playLabel(state)}</span></button>@@ -297,7 +313,7 @@ export function CleanVoiceDemo({ name = "Clean up voice", className }: { name?: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",+ "min-h-11 cursor-pointer touch-manipulation 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",)}>diff --git a/src/components/audio-tools/clean-voice-tool.tsx b/src/components/audio-tools/clean-voice-tool.tsxindex 7682175d..47796be2 100644--- a/src/components/audio-tools/clean-voice-tool.tsx+++ b/src/components/audio-tools/clean-voice-tool.tsx@@ -14,7 +14,7 @@ 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 { useAskBeforeUpload, useEngine, useGenerations, useHydrated, useViewer } from "@/lib/api";import type { AudioToolPreview } from "@/lib/av/audio-tools";import {BACKGROUND_LABELS,@@ -57,7 +57,7 @@ import { uploadSource } from "./split-tool";*/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.";+ "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.";type Source = SlotValue & { kind: "audio" | "video"; duration?: number; channels?: number };@@ -220,9 +220,14 @@ export function CleanVoiceTool({ tabs, app }: { tabs?: React.ReactNode; app?: {setBackground(keep ? "keep" : null);}, []);useHandoff(take);- // 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");+ // Someone who has cleaned a file of their own sees their results, not the demo. Until that's known the demo keeps its+ // place unseen (a guest has none, so no need to wait): neither an account with cleans nor a guest sees the page jump.+ // Both wait for hydration, so the first render matches the server's HTML even when the answers came in before it.+ const hydrated = useHydrated();+ const viewer = useViewer().data;+ const own = useGenerations({ features: [CLEAN_FEATURE], statuses: ["succeeded"], limit: 1 });+ const known = hydrated && (viewer?.signedIn === false || own.isFetched || own.isError);+ const demo = !source && !(hydrated && own.data?.length);const kind = source?.kind ?? "audio";const d = cleanDefaults(kind);@@ -301,11 +306,13 @@ export function CleanVoiceTool({ tabs, app }: { tabs?: React.ReactNode; app?: {}>{!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")}>+ {/* The demo's photo narrows on a short screen, so its play button and Noise on / off stay above the fold. */}+ <div className={cn("mx-auto space-y-3", demo ? "max-w-[min(760px,max(480px,calc((100svh_-_356px)*4/3)))] pt-6" : "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>+ <CleanVoiceDemo name={app?.name ?? "Clean up voice"} ready={known} />+ {/* The tool's one line leads into the upload box under the demo. */}+ <p className="pt-8 text-[13px] text-pretty text-muted-foreground">{TOOL_SUBTITLE}</p></>)}{!source ? (diff --git a/src/lib/av/clean-voice-demo.ts b/src/lib/av/clean-voice-demo.tsindex 91ebf86c..b8270795 100644--- a/src/lib/av/clean-voice-demo.ts+++ b/src/lib/av/clean-voice-demo.ts@@ -2,8 +2,8 @@* 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.+ * "Noise on" / "Noise off" switch both at the same moment in her speech and stop the automatic switch. demoReducer+ * decides what happens when; createDemoAudio plays the two clips on the context the component makes inside the tap.*/export const DEMO_DIR = "/samples/clean-voice";@@ -50,7 +50,12 @@ export type DemoEvent =/** The clips' clock, in seconds since they started (the automatic switch is due at AUTO_AT). */| { type: "time"; t: number }| { type: "ended" }- | { type: "failed" };+ /** The sound stopped from outside the page (a call, the lock screen, the tab hidden): shown as paused. */+ | { type: "interrupted" }+ /** The page was put away (its sound closed): back to the start, ready to play again. */+ | { type: "reset" }+ /** The clips didn't load, or (`unsupported`) the browser can't play them this way. */+ | { type: "failed"; unsupported?: boolean };export const HINTS = {ready: "Sound on. The noise goes by itself after a few seconds.",@@ -60,6 +65,7 @@ export const HINTS = {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.",+ unsupported: "This browser can't play the demo's sound.",} as const;export const DEMO_START: DemoState = { phase: "idle", clean: false, auto: true, ramp: 0, run: 0, flash: 0, hint: HINTS.ready };@@ -90,19 +96,24 @@ export function demoReducer(s: DemoState, e: DemoEvent): DemoState {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;+ if (!switchDue(s, e.t)) 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 "interrupted":+ return s.phase === "playing" ? { ...s, phase: "paused" } : s;+ case "reset":+ return { ...DEMO_START, run: s.run, flash: s.flash };case "failed":- return { ...s, phase: "failed", auto: false, hint: HINTS.failed };+ return { ...s, phase: "failed", auto: false, hint: e.unsupported ? HINTS.unsupported : HINTS.failed };}}/** The play button's words. */export function playLabel(s: DemoState): string {if (s.phase === "loading") return "Loading…";+ if (s.phase === "playing") return "Pause";if (s.phase === "paused") return "Resume";if (s.phase === "done") return "Play again";if (s.phase === "failed") return "Tap to try again";@@ -111,3 +122,78 @@ export function playLabel(s: DemoState): string {/** Target gains for the room and the voice. */export const gainsFor = (clean: boolean): [number, number] => (clean ? [0, 1] : [1, 0]);++/** The automatic switch is due: worth telling the reducer (it changes nothing before then). */+export const switchDue = (s: DemoState, t: number) => s.phase === "playing" && s.auto && !s.clean && t >= AUTO_AT;++/** How far ahead both clips are scheduled, so they start on the same sample. */+const LEAD = 0.05;++/** The parts of an AudioContext the demo's sound uses. */+export type DemoAudioContext = Pick<BaseAudioContext, "currentTime" | "destination" | "createGain" | "createBufferSource">;++export interface DemoAudio {+ /** The shorter clip's length, in seconds. */+ readonly length: number;+ /** Both clips from the top at the same moment, at the gains of this mode; `onEnd` once they have played through. */+ start(clean: boolean, onEnd: () => void): void;+ /** Both gains ramp to this mode together, over `ramp` seconds: the voice carries on where it was. */+ switchTo(clean: boolean, ramp: number): void;+ /** Seconds since the clips started, on the context's clock (it stands still while the context is suspended). */+ elapsed(): number;+ /** Stops both clips quietly (a stop isn't the end of the demo) and lets go of their nodes. */+ stop(): void;+}++/** The demo's sound: the room as recorded and her voice alone (`buffers`, in that order), each through its own gain. */+export function createDemoAudio(ctx: DemoAudioContext, buffers: AudioBuffer[]): DemoAudio {+ let gains: GainNode[] = [];+ let sources: AudioBufferSourceNode[] = [];+ let t0 = 0;+ const stop = () => {+ for (const s of sources) {+ s.onended = null;+ try {+ s.stop();+ } catch {}+ s.disconnect();+ }+ for (const g of gains) g.disconnect();+ sources = [];+ gains = [];+ };+ return {+ length: Math.min(...buffers.map((b) => b.duration)),+ start(clean, onEnd) {+ stop();+ const target = gainsFor(clean);+ gains = buffers.map((_, i) => {+ const g = ctx.createGain();+ g.gain.value = target[i];+ g.connect(ctx.destination);+ return g;+ });+ t0 = ctx.currentTime + LEAD;+ sources = buffers.map((b, i) => {+ const s = ctx.createBufferSource();+ s.buffer = b;+ s.connect(gains[i]);+ s.start(t0);+ return s;+ });+ sources[0].onended = onEnd;+ },+ switchTo(clean, ramp) {+ const now = ctx.currentTime;+ gainsFor(clean).forEach((v, i) => {+ const g = gains[i]?.gain;+ if (!g) return;+ g.cancelScheduledValues(now);+ g.setValueAtTime(g.value, now);+ g.linearRampToValueAtTime(v, now + Math.max(ramp, 0.01));+ });+ },+ elapsed: () => Math.max(0, ctx.currentTime - t0),+ stop,+ };+}diff --git a/tests/clean-voice-demo.test.ts b/tests/clean-voice-demo.test.tsindex de7f88da..a29a49f1 100644--- a/tests/clean-voice-demo.test.ts+++ b/tests/clean-voice-demo.test.ts@@ -8,6 +8,7 @@ import { CleanVoiceDemo } from "@/components/audio-tools/clean-voice-demo";import {AUTO_AT,AUTO_FADE,+ createDemoAudio,DEMO_MEDIA,DEMO_START,demoReducer,@@ -16,6 +17,8 @@ import {isRunning,playLabel,SWITCH_RAMP,+ switchDue,+ type DemoAudioContext,type DemoEvent,type DemoState,} from "@/lib/av/clean-voice-demo";@@ -94,6 +97,139 @@ describe("the demo's story", () => {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 });+ expect(demoReducer(loading, { type: "failed", unsupported: true })).toMatchObject({ phase: "failed", hint: HINTS.unsupported });+ });++ it("shows Pause on the button while it plays", () => {+ expect(playLabel(run(tap, started))).toBe("Pause");+ expect(playLabel(DEMO_START)).toBe("Tap to listen");+ });++ it("shows a stop from outside the page as paused, so one tap resumes it", () => {+ const stopped = run(tap, started, { type: "interrupted" });+ expect(stopped).toMatchObject({ phase: "paused", clean: false, auto: true });+ expect(demoReducer(stopped, tap).phase).toBe("playing");+ for (const s of [DEMO_START, run(tap), stopped, run(tap, started, { type: "ended" })]) expect(demoReducer(s, { type: "interrupted" })).toBe(s);+ });++ it("starts over, ready to play, when the page is put away and comes back", () => {+ const playing = run(tap, started, at(AUTO_AT));+ for (const s of [playing, demoReducer(playing, tap), demoReducer(playing, { type: "ended" }), run(tap)]) {+ const back = demoReducer(s, { type: "reset" });+ expect(back).toMatchObject({ phase: "idle", clean: false, auto: true, hint: HINTS.ready, run: s.run, flash: s.flash });+ expect(playLabel(back)).toBe("Tap to listen");+ expect(demoReducer(back, tap)).toMatchObject({ phase: "loading", auto: true, run: s.run + 1 });+ }+ });++ it("asks for the automatic switch only when it is due", () => {+ const playing = run(tap, started);+ expect(switchDue(playing, AUTO_AT - 0.01)).toBe(false);+ expect(switchDue(playing, AUTO_AT)).toBe(true);+ expect(switchDue(demoReducer(playing, tap), AUTO_AT)).toBe(false);+ expect(switchDue(run(tap, started, at(AUTO_AT)), AUTO_AT + 1)).toBe(false);+ expect(switchDue(run(tap, started, { type: "choose", clean: false }), AUTO_AT + 1)).toBe(false);+ });+});++/** A stand-in for an AudioContext that records what the demo asks of it. */+function fakeContext() {+ const log: string[] = [];+ const node = (name: string) => ({+ connect: (to: { name?: string }) => void log.push(`${name} -> ${to.name ?? "?"}`),+ disconnect: () => void log.push(`${name} disconnected`),+ });+ const gains: { name: string; gain: { value: number; ramps: [number, number][] } }[] = [];+ const sources: { name: string; buffer: unknown; when?: number; stopped: boolean; onended: (() => void) | null }[] = [];+ const ctx = {+ currentTime: 10,+ destination: { name: "out" },+ createGain() {+ const name = `gain${gains.length}`;+ const g = {+ ...node(name),+ name,+ gain: {+ value: 1,+ ramps: [] as [number, number][],+ cancelScheduledValues() {},+ setValueAtTime() {},+ linearRampToValueAtTime(v: number, t: number) {+ this.ramps.push([v, t]);+ },+ },+ };+ gains.push(g);+ return g;+ },+ createBufferSource() {+ const name = `source${sources.length}`;+ const s = {+ ...node(name),+ name,+ buffer: null as unknown,+ when: undefined as number | undefined,+ stopped: false,+ onended: null as (() => void) | null,+ start(when: number) {+ this.when = when;+ },+ stop() {+ this.stopped = true;+ },+ };+ sources.push(s);+ return s;+ },+ };+ return { ctx: ctx as unknown as DemoAudioContext, raw: ctx, log, gains, sources };+}+const clip = (duration: number) => ({ duration }) as AudioBuffer;++describe("the demo's sound", () => {+ it("starts both clips at the same moment, each through its own gain, at the mode's gains", () => {+ const f = fakeContext();+ const audio = createDemoAudio(f.ctx, [clip(8), clip(8.02)]);+ expect(audio.length).toBe(8);+ audio.start(false, () => {});+ expect(f.sources.map((s) => s.when)).toEqual([f.sources[0].when, f.sources[0].when]);+ expect(f.sources[0].when).toBeGreaterThan(10);+ expect(f.gains.map((g) => g.gain.value)).toEqual(gainsFor(false));+ expect(f.log).toEqual(expect.arrayContaining(["gain0 -> out", "gain1 -> out", "source0 -> gain0", "source1 -> gain1"]));+ });++ it("ramps both gains together on a switch", () => {+ const f = fakeContext();+ const audio = createDemoAudio(f.ctx, [clip(8), clip(8)]);+ audio.start(false, () => {});+ audio.switchTo(true, AUTO_FADE);+ expect(f.gains.map((g) => g.gain.ramps)).toEqual([[[0, 10 + AUTO_FADE]], [[1, 10 + AUTO_FADE]]]);+ });++ it("counts time from the start on the context's clock, and calls the end once the room's clip ends", () => {+ const f = fakeContext();+ const audio = createDemoAudio(f.ctx, [clip(8), clip(8)]);+ let ended = 0;+ audio.start(false, () => ended++);+ expect(audio.elapsed()).toBe(0);+ f.raw.currentTime = f.sources[0].when! + 3.5;+ expect(audio.elapsed()).toBeCloseTo(3.5);+ f.sources[0].onended?.();+ expect(ended).toBe(1);+ });++ it("stops the old clips quietly and lets go of their nodes when it starts again or stops", () => {+ const f = fakeContext();+ const audio = createDemoAudio(f.ctx, [clip(8), clip(8)]);+ audio.start(true, () => {});+ const first = [...f.sources];+ audio.start(false, () => {});+ expect(first.every((s) => s.stopped && s.onended === null)).toBe(true);+ expect(f.log).toEqual(expect.arrayContaining(["source0 disconnected", "source1 disconnected", "gain0 disconnected", "gain1 disconnected"]));+ expect(f.gains.slice(2).map((g) => g.gain.value)).toEqual(gainsFor(false));+ audio.stop();+ expect(f.sources.slice(2).every((s) => s.stopped)).toBe(true);+ expect(f.log).toEqual(expect.arrayContaining(["gain2 disconnected", "gain3 disconnected"]));});});@@ -110,6 +246,12 @@ describe("the demo page", () => {expect(html).toContain(HINTS.ready);expect(html).toContain("min-h-11");expect(html).toContain("motion-reduce:transition-none");+ expect(html).not.toContain("invisible");+ });++ it("keeps its place unseen until the page knows whether to show it", () => {+ const html = renderToStaticMarkup(createElement(CleanVoiceDemo, { ready: false }));+ expect(html).toMatch(/<section[^>]*class="[^"]*\binvisible\b/);});it("ships its pictures and two 8 s clips of the same length", () => {diff --git a/tests/comfy-reuse.test.ts b/tests/comfy-reuse.test.tsindex a9a04cf4..525bff84 100644--- a/tests/comfy-reuse.test.ts+++ b/tests/comfy-reuse.test.ts@@ -223,5 +223,6 @@ describe("licences, as information", () => {expect(pack?.licence).toMatchObject({ name: "MIT", class: "commercial" });expect(pack?.repo).toBe(`https://github.com/workingprototype/Fuobe/tree/${requirements.packs["ComfyUI-RE-USE"].commit}/comfy-nodes/ComfyUI-RE-USE`);expect(pack?.licence.note).toMatch(/not NVIDIA's code path/);- expect(ATTRIBUTIONS.find((a) => a.for === "RE-USE (clean up voice)")).toMatchObject({ licence: "OpenMDW-1.1", note: expect.stringMatching(/non-commercial \(NSCLv1\)/) }); });+ expect(ATTRIBUTIONS.find((a) => a.for === "RE-USE (clean up voice)")).toMatchObject({ licence: "OpenMDW-1.1", note: expect.stringMatching(/non-commercial \(NSCLv1\)/) });+ });});diff --git a/tests/e2e/clean-voice.mjs b/tests/e2e/clean-voice.mjsindex a750a669..d667e07c 100644--- a/tests/e2e/clean-voice.mjs+++ b/tests/e2e/clean-voice.mjs@@ -62,8 +62,8 @@ async function setup(browser, device, theme, engine) {/** 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");+ const items = (await (await fetch(`${base}/api/generations?features=voice-clean&statuses=succeeded&limit=1`)).json()).items ?? [];+ return items.length > 0;} catch {return false;}