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
Audio: Loop / extend and Join tools on both engines
Claude9c2bdb07ce3c
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsnew file mode 100644index 00000000..3eee0776--- /dev/null+++ b/src/app/api/audio-tools/route.ts@@ -0,0 +1,27 @@+import { AudioToolBody, AudioToolError, previewAudioTool, runAudioTool } from "@/server/audio-tools";++/** Audio → Loop / extend and Join: start a run; `?preview=1` only plans and prices it. */+export async function POST(request: Request) {+ const parsed = AudioToolBody.safeParse(await request.json().catch(() => null));+ if (!parsed.success) {+ const path = parsed.error.issues[0]?.path.join(".") ?? "";+ const msg = path.startsWith("clips")+ ? "Add 2 to 10 audio clips to join"+ : path === "audio"+ ? "Add the audio to loop"+ : path === "duration"+ ? "Pick a length up to 10 minutes"+ : path === "crossfade"+ ? "Keep the crossfade between 0 and 10 seconds"+ : "Check the settings";+ return Response.json({ error: msg }, { status: 400 });+ }+ try {+ if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(await previewAudioTool(parsed.data));+ return Response.json(await runAudioTool(parsed.data), { status: 201 });+ } catch (e) {+ if (e instanceof AudioToolError) return Response.json({ error: e.message }, { status: 422 });+ console.error("[audio-tools]", e);+ return Response.json({ error: (e as Error).message || "Something went wrong" }, { status: 500 });+ }+}diff --git a/src/components/audio-tools/audio-tools.tsx b/src/components/audio-tools/audio-tools.tsxnew file mode 100644index 00000000..aab7e02f--- /dev/null+++ b/src/components/audio-tools/audio-tools.tsx@@ -0,0 +1,442 @@+"use client";++import { ArrowDown, ArrowUp, AudioLines, Library, Loader2, Merge, Plus, Repeat, Upload, X } from "lucide-react";+import { nanoid } from "nanoid";+import { useEffect, useId, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Slider } from "@/components/ui/slider";+import { Feed } from "@/components/studio/feed";+import { ACCEPT, fileToList, fileToSlot, kindOfFile, LibraryGrid, wrongKindMessage, type SlotValue } from "@/components/studio/media-slot";+import { Segmented } from "@/components/faceless/controls";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { useDraft } from "@/components/av/use-draft";+import { useEngine, useGenerations } from "@/lib/api";+import {+ clock,+ CROSSFADE_MAX,+ DEFAULT_JOIN_CROSSFADE,+ DEFAULT_LOOP_CROSSFADE,+ JOIN_FEATURE,+ JOIN_MAX_CLIPS,+ LOOP_FEATURE,+ LOOP_MAX_SECONDS,+ LOOP_PRESETS,+ type AudioToolPreview,+} from "@/lib/av/audio-tools";+import { cloudLoopLength, cloudLoopPasses } from "@/lib/av/crossfade";+import { parseCueTime } from "@/lib/av/cue-edit";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";+import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";++/**+ * Audio → Loop / extend and Audio → Join (r4/faceless-plus). A clip looped to a length, or clips joined in+ * order: crossfaded on the open engine (ComfyUI core audio nodes, CPU), whole plays and hard joins on the+ * cloud (fal merge-audios). The server plans and prices every change (src/lib/av/audio-tools.ts); results+ * land in the feed below and the Library.+ */++type Curve = "equal-power" | "linear";+type Clip = SlotValue & { duration?: number };++const money = (p: AudioToolPreview, engine: Engine) =>+ p.demo ? "Demo · free" : engine === "open" ? "Free · runs on your ComfyUI" : p.costUsd === null ? "Price unknown" : p.costUsd < 0.01 ? "Under $0.01" : `≈ $${p.costUsd.toFixed(2)}`;++const nameOf = (c: Clip) => (c.name ?? "Audio clip").replace(/\.[a-z0-9]{2,4}$/i, "");++/** A clip handed over in the address (/audio/loop?audio=/api/files/… from a result's "Loop / extend"), read once after hydration. */+function useHandoff(take: (clip: Clip) => void) {+ useEffect(() => {+ const url = new URLSearchParams(window.location.search).get("audio");+ if (url?.startsWith("/api/files/")) take({ ref: url, preview: url, kind: "audio", id: nanoid(8) });+ // Once, on arrival.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+}++/** The length the browser reads from a clip's header (fills in until the server reads it too). */+function AudioPlayer({ clip, onDuration, className }: { clip: Clip; onDuration: (s: number) => void; className?: string }) {+ return (+ <audio+ key={clip.preview}+ src={clip.preview}+ controls+ preload="metadata"+ onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && e.currentTarget.duration > 0 && onDuration(e.currentTarget.duration)}+ className={cn("h-9 w-full min-w-0", className)}+ aria-label={`Play ${nameOf(clip)}`}+ />+ );+}++/** Upload or pick audio from the library (a drop zone when empty, a button row otherwise). */+function AddAudio({ multiple, onFiles, onPick, compact, disabled }: { multiple?: boolean; onFiles: (files: File[]) => void; onPick: (v: SlotValue) => void; compact?: boolean; disabled?: boolean }) {+ const input = useRef<HTMLInputElement>(null);+ const [over, setOver] = useState(false);+ const [picking, setPicking] = useState(false);+ const take = (list: FileList | null | undefined) => {+ const files = [...(list ?? [])];+ const audio = files.filter((f) => kindOfFile(f) === "audio");+ if (files.length > audio.length) toast(wrongKindMessage("audio"));+ if (audio.length) onFiles(multiple ? audio : audio.slice(0, 1));+ };+ const buttons = (+ <div className="flex flex-wrap items-center justify-center gap-1.5">+ <Button size="sm" variant={compact ? "outline" : "default"} className="rounded-full" onClick={() => input.current?.click()} disabled={disabled}>+ {compact ? <Plus className="size-3.5" /> : <Upload className="size-3.5" />} {compact ? "Add a clip" : multiple ? "Upload audio clips" : "Upload audio"}+ </Button>+ <Popover open={picking} onOpenChange={setPicking}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="sm" className="rounded-full" disabled={disabled}>+ <Library className="size-3.5" /> 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"]}+ onPick={(v) => {+ onPick(v);+ setPicking(false);+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ <input+ ref={input}+ type="file"+ accept={ACCEPT.audio}+ multiple={multiple}+ hidden+ onChange={(e) => {+ take(e.target.files);+ e.target.value = "";+ }}+ />+ </div>+ );+ if (compact) return buttons;+ 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-10 text-center transition-colors sm:py-14",+ 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);+ }}+ >+ <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">{multiple ? "Add the clips to join" : "Add a clip to loop"}</p>+ <p className="mt-1 text-[13px] text-muted-foreground">WAV, MP3, FLAC, M4A or OGG up to 200 MB{multiple ? `, ${JOIN_MAX_CLIPS} clips at most` : ""}</p>+ </div>+ {buttons}+ </div>+ );+}++/** A length typed as m:ss (or seconds), committed on blur or Enter. */+function LengthField({ value, onCommit, max }: { value: number; onCommit: (s: number) => void; max: number }) {+ const id = useId();+ const [text, setText] = useDraft(clock(value));+ const commit = () => {+ const t = parseCueTime(text);+ if (t === null || t <= 0) return setText(clock(value));+ onCommit(Math.min(max, t));+ };+ return (+ <label htmlFor={id} className="flex items-center gap-1.5 text-[12px] text-muted-foreground">+ Length+ <input+ id={id}+ value={text}+ onChange={(e) => setText(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}+ inputMode="decimal"+ aria-describedby={`${id}-hint`}+ className="h-8 w-20 rounded-full border bg-background px-2.5 text-center font-mono text-[12px] text-foreground tabular-nums outline-none focus:border-primary focus:ring-2 focus:ring-brand-faint"+ />+ <span id={`${id}-hint`} className="sr-only">+ Minutes and seconds, up to {clock(max)}+ </span>+ </label>+ );+}++/** Crossfade length and fade shape (open engine), or why there is none (cloud). */+function CrossfadeControls({ engine, value, onChange, curve, onCurve, max }: { engine: Engine; value: number; onChange: (v: number) => void; curve: Curve; onCurve: (c: Curve) => void; max: number }) {+ if (engine === "cloud")+ return <p className="text-[13px] text-muted-foreground">The cloud joins the audio end to end, with no crossfade. Switch to the open engine (top right) for smooth crossfaded seams.</p>;+ const top = Math.max(0.5, Math.min(CROSSFADE_MAX, Math.floor(max * 2) / 2));+ return (+ <div className="space-y-3">+ <div className="flex items-center gap-3">+ <span className="w-24 shrink-0 text-[13px]">Crossfade</span>+ <Slider min={0.5} max={top} step={0.5} value={[Math.min(value, top)]} onValueChange={([v]) => onChange(v)} aria-label="Crossfade, seconds" className="min-w-0 flex-1" />+ <span className="w-12 shrink-0 text-right font-mono text-[12px] tabular-nums">{Math.min(value, top).toFixed(1)} s</span>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <span className="w-24 shrink-0 text-[13px]">Fade shape</span>+ <Segmented+ label="Fade shape"+ value={curve}+ onChange={onCurve}+ options={[+ { value: "equal-power", label: "Music and voices", hint: "Equal power: an even loudness through the seam" },+ { value: "linear", label: "Steady sound", hint: "Linear: no bump where near-identical sound overlaps (drones, ambience, room tone)" },+ ]}+ />+ </div>+ </div>+ );+}++/** The run bar: what will happen, what it costs, and the button. */+function RunBar({ label, icon: Icon, blocker, preview, engine, onRun, pending }: { label: string; icon: typeof Repeat; blocker: string | null; preview: ReturnType<typeof useAudioToolPreview>; engine: Engine; onRun: () => void; pending: boolean }) {+ const error = preview.error ? (preview.error as Error).message : null;+ const p = preview.data;+ const shown = blocker ?? error;+ return (+ <div className="space-y-2">+ {!shown && 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">+ {shown ??+ (p ? (+ <>+ {p.length !== null && <span className="font-mono text-foreground">{clock(p.length)}</span>}+ {p.length !== null && " · "}+ <span className="font-mono text-foreground">{money(p, engine)}</span>+ </>+ ) : (+ "Pricing…"+ ))}+ </p>+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={onRun} disabled={pending}>+ {pending ? <Loader2 className="size-4 animate-spin" /> : <Icon className="size-4" />} {label}+ </Button>+ </div>+ </div>+ );+}++/** The loop at a glance: each pass of the clip, the crossfaded seams (open) or where the asked length ends (cloud). */+function LoopBar({ clip, target, crossfade, engine }: { clip: number; target: number; crossfade: number; engine: Engine }) {+ const step = engine === "open" ? clip - crossfade : clip;+ if (!(step > 0) || target <= clip) return null;+ // The cloud plays whole copies, 2–5 a call: the same count the planner sends.+ const total = engine === "open" ? target : cloudLoopLength(clip, cloudLoopPasses(clip, target));+ const passes = Math.min(200, Math.ceil(total / step));+ return (+ <div className="mt-3" aria-hidden>+ <div className="relative flex h-6 overflow-hidden rounded-lg">+ {Array.from({ length: passes }, (_, i) => (+ <div key={i} className={cn("h-full border-r border-background last:border-r-0", i % 2 ? "bg-brand-faint" : "bg-primary/60")} style={{ width: `${(Math.min(step, total - i * step) / total) * 100}%` }} />+ ))}+ {engine === "cloud" && total > target && <div className="absolute inset-y-0 right-0 bg-background/70" style={{ width: `${((total - target) / total) * 100}%` }} />}+ </div>+ <div className="mt-1 flex justify-between font-mono text-[11px] text-subtle-foreground">+ <span>0:00</span>+ {engine === "cloud" && total > target ? <span>asked {clock(target)} · makes {clock(total)}</span> : <span>{clock(total)}</span>}+ </div>+ </div>+ );+}++function Results({ feature, title }: { feature: string; title: string }) {+ const results = useGenerations({ features: [feature], limit: 24 });+ // A cloud chain makes a result per call: show the finished ones (the last call carries the title).+ const items = (results.data ?? []).filter((g) => !!g.request.title);+ if (!items.length) return null;+ return (+ <section className="mt-10" aria-labelledby={`${feature}-results`}>+ <h3 id={`${feature}-results`} className="mb-3 font-heading text-[22px]">+ {title}+ </h3>+ <Feed items={items} />+ </section>+ );+}++/** Audio → Loop / extend. */+export function AudioLoopTool({ tabs }: { tabs?: React.ReactNode }) {+ const [engine] = useEngine();+ const run = useAudioToolRun();+ const [clip, setClip] = useState<Clip | null>(null);+ const [target, setTarget] = useState(120);+ const [crossfade, setCrossfade] = useState(DEFAULT_LOOP_CROSSFADE);+ const [curve, setCurve] = useState<Curve>("equal-power");+ useHandoff(setClip);+ const ready = clip && !clip.uploading && clip.ref ? clip : null;+ const body: AudioToolBody | null = useMemo(+ () => (ready ? { tool: "loop", engine, audio: ready.ref, name: nameOf(ready), duration: target, ...(ready.duration && { sourceDuration: ready.duration }), ...(engine === "open" && { crossfade, curve }) } : null),+ [ready, engine, target, crossfade, curve],+ );+ const preview = useAudioToolPreview(useSettled(body));+ const blocker = !clip ? "Add a clip to loop" : clip.uploading ? "Uploading…" : clip.duration && target <= clip.duration ? `The clip is already ${clock(clip.duration)} — pick a longer length` : null;+ const go = () => {+ if (blocker) return void toast(blocker);+ if (preview.error) return void toast.error((preview.error as Error).message);+ run.mutate(body!, { onSuccess: () => toast.success(engine === "open" ? "Looping on your ComfyUI" : "Looping"), onError: (e) => toast.error((e as Error).message) });+ };+ return (+ <ToolShell title="Audio" tabs={tabs}>+ {!clip && (+ <ToolHero+ title="Make it as long as you need"+ subtitle="Loop a music bed, ambience or a beat to any length up to 10 minutes. Smooth crossfaded seams on your ComfyUI (free, runs on CPU); whole repeats on the cloud, for under a cent."+ />+ )}+ <div className={cn("mx-auto max-w-[820px] space-y-3", clip ? "pt-4" : "mt-8")}>+ {!clip ? (+ <AddAudio onFiles={([f]) => void fileToSlot(f, (v) => setClip(v), "audio")} onPick={(v) => setClip(v)} />+ ) : (+ <Panel+ title={nameOf(clip)}+ aside={+ <>+ {clip.duration ? <span className="font-mono text-[12px] text-muted-foreground tabular-nums">{clock(clip.duration)}</span> : null}+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Remove the clip" onClick={() => setClip(null)}>+ <X className="size-4" />+ </Button>+ </>+ }+ >+ <AudioPlayer clip={clip} onDuration={(duration) => setClip((c) => (c ? { ...c, duration } : c))} />+ </Panel>+ )}+ {clip && (+ <Panel title="Length">+ <div className="flex flex-wrap items-center gap-2">+ <Segmented+ label="Length"+ value={LOOP_PRESETS.includes(target) ? target : -1}+ onChange={(v) => v > 0 && setTarget(v)}+ options={[...LOOP_PRESETS.map((s) => ({ value: s, label: `${s / 60} min` })), ...(LOOP_PRESETS.includes(target) ? [] : [{ value: -1, label: clock(target) }])]}+ />+ <LengthField value={target} onCommit={setTarget} max={LOOP_MAX_SECONDS} />+ </div>+ {clip.duration ? <LoopBar clip={clip.duration} target={target} crossfade={crossfade} engine={engine} /> : null}+ </Panel>+ )}+ {clip && (+ <Panel title="Seams">+ <CrossfadeControls engine={engine} value={crossfade} onChange={setCrossfade} curve={curve} onCurve={setCurve} max={clip.duration ? clip.duration / 2 - 0.1 : CROSSFADE_MAX} />+ </Panel>+ )}+ {clip && <RunBar label="Loop it" icon={Repeat} blocker={blocker} preview={preview} engine={engine} onRun={go} pending={run.isPending} />}+ </div>+ <Results feature={LOOP_FEATURE} title="Your loops" />+ </ToolShell>+ );+}++/** Audio → Join. */+export function AudioJoinTool({ tabs }: { tabs?: React.ReactNode }) {+ const [engine] = useEngine();+ const run = useAudioToolRun();+ const [clips, setClips] = useState<Clip[]>([]);+ const [crossfade, setCrossfade] = useState(DEFAULT_JOIN_CROSSFADE);+ const [curve, setCurve] = useState<Curve>("equal-power");+ useHandoff((c) => setClips([c]));+ const room = JOIN_MAX_CLIPS - clips.length;+ const add = (files: File[]) => {+ if (files.length > room) toast(`Join up to ${JOIN_MAX_CLIPS} clips — added the first ${room}`);+ for (const f of files.slice(0, Math.max(0, room))) fileToList(f, setClips, "audio");+ };+ const pick = (v: SlotValue) => (room > 0 ? setClips((xs) => [...xs, { ...v, id: nanoid(8) }]) : toast(`Join up to ${JOIN_MAX_CLIPS} clips`));+ const move = (i: number, by: -1 | 1) =>+ setClips((xs) => {+ const j = i + by;+ if (j < 0 || j >= xs.length) return xs;+ const next = [...xs];+ [next[i], next[j]] = [next[j], next[i]];+ return next;+ });+ const ready = clips.length >= 2 && clips.every((c) => !c.uploading && c.ref);+ const body: AudioToolBody | null = useMemo(+ () => (ready ? { tool: "join", engine, clips: clips.map((c) => ({ url: c.ref, name: nameOf(c), ...(c.duration && { duration: c.duration }) })), ...(engine === "open" && { crossfade, curve }) } : null),+ [ready, clips, engine, crossfade, curve],+ );+ const preview = useAudioToolPreview(useSettled(body));+ const blocker = clips.length < 2 ? "Add at least two clips" : clips.some((c) => c.uploading) ? "Uploading…" : null;+ const shortest = clips.reduce((m, c, i) => Math.min(m, (c.duration ?? Infinity) / (i === 0 || i === clips.length - 1 ? 1 : 2)), Infinity);+ const go = () => {+ if (blocker) return void toast(blocker);+ if (preview.error) return void toast.error((preview.error as Error).message);+ run.mutate(body!, { onSuccess: () => toast.success(engine === "open" ? "Joining on your ComfyUI" : "Joining"), onError: (e) => toast.error((e as Error).message) });+ };+ return (+ <ToolShell title="Audio" tabs={tabs}>+ {!clips.length && (+ <ToolHero+ title="Join clips into one track"+ subtitle={`Up to ${JOIN_MAX_CLIPS} clips, in the order you set. Crossfaded on your ComfyUI (free, runs on CPU); end to end on the cloud, for under a cent.`}+ />+ )}+ <div className={cn("mx-auto max-w-[820px] space-y-3", clips.length ? "pt-4" : "mt-8")}>+ {!clips.length ? (+ <AddAudio multiple onFiles={add} onPick={pick} />+ ) : (+ <Panel title={`Clips · ${clips.length} of ${JOIN_MAX_CLIPS}`} aside={<AddAudio compact multiple onFiles={add} onPick={pick} disabled={room <= 0} />}>+ <ol className="space-y-2" aria-label="Clips, in the order they play">+ {clips.map((c, i) => (+ <li key={c.id ?? c.ref} className="rounded-xl border p-2">+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="grid size-6 shrink-0 place-items-center rounded-full bg-brand-faint font-mono text-[11px] text-brand-text">{i + 1}</span>+ <p className="min-w-0 flex-1 truncate text-[13px] font-medium">{nameOf(c)}</p>+ {c.uploading ? (+ <Loader2 className="size-3.5 shrink-0 animate-spin text-muted-foreground" aria-label="Uploading" />+ ) : c.duration ? (+ <span className="shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums">{clock(c.duration)}</span>+ ) : null}+ <Button variant="ghost" size="icon-sm" className="shrink-0 rounded-full" aria-label={`Move clip ${i + 1} earlier`} disabled={i === 0} onClick={() => move(i, -1)}>+ <ArrowUp className="size-3.5" />+ </Button>+ <Button variant="ghost" size="icon-sm" className="shrink-0 rounded-full" aria-label={`Move clip ${i + 1} later`} disabled={i === clips.length - 1} onClick={() => move(i, 1)}>+ <ArrowDown className="size-3.5" />+ </Button>+ <Button variant="ghost" size="icon-sm" className="shrink-0 rounded-full" aria-label={`Remove clip ${i + 1}`} onClick={() => setClips((xs) => xs.filter((_, j) => j !== i))}>+ <X className="size-3.5" />+ </Button>+ </div>+ <AudioPlayer clip={c} className="mt-1.5" onDuration={(duration) => setClips((xs) => xs.map((x) => (x === c || (x.id && x.id === c.id) ? { ...x, duration } : x)))} />+ </li>+ ))}+ </ol>+ {clips.length === 1 && <p className="mt-2 text-[13px] text-muted-foreground">Add one more clip to join.</p>}+ </Panel>+ )}+ {clips.length > 0 && (+ <Panel title="Seams">+ <CrossfadeControls engine={engine} value={crossfade} onChange={setCrossfade} curve={curve} onCurve={setCurve} max={Number.isFinite(shortest) ? shortest - 0.1 : CROSSFADE_MAX} />+ </Panel>+ )}+ {clips.length > 0 && <RunBar label="Join them" icon={Merge} blocker={blocker} preview={preview} engine={engine} onRun={go} pending={run.isPending} />}+ </div>+ <Results feature={JOIN_FEATURE} title="Your joins" />+ </ToolShell>+ );+}diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.tsnew file mode 100644index 00000000..5feef462--- /dev/null+++ b/src/components/audio-tools/hooks.ts@@ -0,0 +1,46 @@+"use client";++import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { useEffect, useState } from "react";+import type { AudioToolPreview } from "@/lib/av/audio-tools";+import type { Engine, Generation } from "@/lib/catalog/types";++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" };++async function post<T>(url: string, body: AudioToolBody): Promise<T> {+ const res = await fetch(url, { 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 new Error(j.error ?? `Request failed (${res.status})`);+ return j;+}++/** The value once it has stopped changing for `ms` (sliders and typing don't price every step). */+export function useSettled<T>(value: T, ms = 300): T {+ const [v, setV] = useState(value);+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms);+ return () => clearTimeout(t);+ }, [value, ms]);+ return v;+}++/** What the settings would do and cost (null: nothing to price yet). */+export function useAudioToolPreview(body: AudioToolBody | null) {+ return useQuery({+ queryKey: ["audio-tool-preview", body],+ enabled: !!body,+ queryFn: () => post<AudioToolPreview>("/api/audio-tools?preview=1", body!),+ retry: false,+ staleTime: 30_000,+ });+}++export function useAudioToolRun() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (body: AudioToolBody) => post<{ batchId: string; result: Generation; items: Generation[] }>("/api/audio-tools", body),+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["generations"] }),+ });+}diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex a2e72a12..fe340b77 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -22,6 +22,7 @@ import { HUB_MODES, modeHref, type HubKind } from "@/lib/hubs";import { CaptionsStudio } from "@/components/captions/captions-studio";import { DubStudio } from "@/components/dub/dub-studio";import { TrimTool } from "@/components/av/trim-tool";+import { AudioJoinTool, AudioLoopTool } from "@/components/audio-tools/audio-tools";import { ModeStudio, ModeTabs } from "./mode-studio";import type { StudioConfig } from "./studio-context";@@ -45,9 +46,9 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {},};-/** Modes that are their own tool rather than a composer studio (Translate & dub, Captions, Trim). */+/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Captions, Trim). */const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {- audio: { translate: ({ tabs }) => <DubStudio tabs={tabs} /> },+ audio: { translate: ({ tabs }) => <DubStudio tabs={tabs} />, loop: ({ tabs }) => <AudioLoopTool tabs={tabs} />, join: ({ tabs }) => <AudioJoinTool tabs={tabs} /> },"video-tools": { captions: ({ tabs }) => <CaptionsStudio tabs={tabs} />, trim: ({ tabs }) => <TrimTool tabs={tabs} /> },};diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 47ae5bae..cc3b8d13 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -17,6 +17,7 @@ import {Layers2,Mic2,MoreHorizontal,+ Repeat,RotateCcw,SlidersHorizontal,Sparkles,@@ -70,6 +71,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {lipsync: Mic2,"add-sound": AudioLines,"voice-change": AudioLines,+ "loop-audio": Repeat,"copy-text": Copy,"view-3d": Box,download: Download,diff --git a/src/lib/av/audio-tools.ts b/src/lib/av/audio-tools.tsnew file mode 100644index 00000000..dcd22541--- /dev/null+++ b/src/lib/av/audio-tools.ts@@ -0,0 +1,213 @@+import type { ChainSlot, Engine, GenerationRequest } from "@/lib/catalog/types";+import { cloudLoopLength, cloudLoopPasses, crossfadeProblem, joinedLength, loopSeams, type CurveShape } from "./crossfade";++/**+ * The Audio hub's Loop / extend and Join tools (r4/faceless-plus): plain data and the planner shared by the+ * page and the server (src/server/audio-tools.ts), which turns a plan into one createPipeline batch.+ *+ * - Open engine (ComfyUI, CPU): one job each — audio-loop-crossfade extends a clip to any length up to+ * 10 minutes with a crossfade at every seam and a fade-out; audio-join-crossfade joins up to 10 clips with a+ * crossfade at every seam. The provider writes the fade curve.+ * - Cloud (fal merge-audios): whole plays and hard joins, 2–5 files a call, so longer loops and joins of+ * more clips run as a chain of calls. A loop comes out a whole number of plays long.+ */++export const LOOP_FEATURE = "audio-loop";+export const JOIN_FEATURE = "audio-join";++export const AUDIO_TOOL_MODELS: Record<Engine, { loop: string; join: string }> = {+ cloud: { loop: "join-audio", join: "join-audio" },+ open: { loop: "oss-audio-loop", join: "oss-audio-join" },+};++/** The longest loop: the open graph's limit, kept on the cloud too so both engines offer the same. */+export const LOOP_MAX_SECONDS = 600;+export const JOIN_MAX_CLIPS = 10;+/** fal merge-audios takes 2–5 files a call. */+export const CLOUD_PER_CALL = 5;+export const CROSSFADE_MAX = 10;+export const DEFAULT_LOOP_CROSSFADE = 2;+export const DEFAULT_JOIN_CROSSFADE = 1;+/** Lengths a loop offers at a click (seconds). */+export const LOOP_PRESETS = [60, 120, 180, 300, 600];++export interface ToolStep {+ key: string;+ request: GenerationRequest;+ after?: string[];+ chain?: ChainSlot[];+}++export interface ToolPlan {+ steps: ToolStep[];+ /** Seconds the result runs (null: a clip's length is unknown). */+ length: number | null;+ /** What it will do, in a sentence. */+ summary: string;+ /** Things to know (the cloud's whole plays, its hard joins). */+ notes: string[];+}++/** What the server answers for `?preview=1`: the plan in words and its price. */+export interface AudioToolPreview {+ summary: string;+ notes: string[];+ /** Seconds the result runs (null: a clip's length is unknown). */+ length: number | null;+ steps: number;+ costUsd: number | null;+ demo: boolean;+}++export interface LoopInput {+ engine: Engine;+ audio: string;+ name?: string;+ /** The clip's length (seconds). */+ sourceDuration: number;+ /** The length to make. */+ duration: number;+ crossfade?: number;+ curve?: CurveShape;+}++export interface JoinInput {+ engine: Engine;+ clips: { url: string; name?: string; duration?: number }[];+ crossfade?: number;+ curve?: CurveShape;+}++/** "2:05", "0:07.5" */+export function clock(seconds: number): string {+ const s = Math.max(0, seconds);+ const whole = Math.floor(s + 1e-6);+ const tenth = Math.round((s - whole) * 10);+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}${tenth && s < 60 ? `.${tenth}` : ""}`;+}++const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;+const fade = (x: number | undefined, fallback: number) => Math.min(CROSSFADE_MAX, Math.max(0.1, Math.round((x ?? fallback) * 10) / 10));++/** A clip extended to `duration`; throws what's in the way (in words the page shows). */+export function planLoop(i: LoopInput): ToolPlan {+ const L = i.sourceDuration;+ if (!(L > 0)) throw new Error("This clip's length can't be read — try a WAV, MP3, FLAC or M4A file");+ if (!(i.duration > L)) throw new Error(`The clip is already ${clock(L)} long — pick a longer length`);+ if (i.duration > LOOP_MAX_SECONDS) throw new Error(`Loops run up to ${LOOP_MAX_SECONDS / 60} minutes`);+ const duration = Math.round(i.duration * 10) / 10;+ const title = `Loop · ${i.name ? `${i.name} ` : ""}to ${clock(duration)}`;+ const base = { feature: LOOP_FEATURE, batchTitle: title } satisfies Partial<GenerationRequest>;+ const models = AUDIO_TOOL_MODELS[i.engine];+ if (i.engine === "open") {+ const x = fade(i.crossfade, DEFAULT_LOOP_CROSSFADE);+ const problem = crossfadeProblem([L], x, "loop");+ if (problem) throw new Error(problem);+ const seams = loopSeams(L, duration, x).length;+ return {+ steps: [+ {+ key: "loop",+ request: {+ ...base,+ modelId: models.loop,+ op: "audio-loop",+ inputs: { audio: i.audio },+ params: { duration, crossfade: x, sourceDuration: L, ...(i.curve === "linear" && { extra: { curve: "linear" } }) },+ title,+ },+ },+ ],+ length: duration,+ summary: `Loops it to ${clock(duration)} with ${plural(seams, "crossfaded seam")} (${x} s each), then fades out over the last ${x} s.`,+ notes: [],+ };+ }+ // The cloud repeats the whole clip: every call lists it 2–5 times, and each call's result is the next one's clip.+ const passes = cloudLoopPasses(L, duration, CLOUD_PER_CALL);+ const length = cloudLoopLength(L, passes);+ const plays = passes.reduce((a, b) => a * b, 1);+ // Each call's clip and length are rounded together (ms), so the route counts exactly `p` plays.+ let clip = Math.round(L * 1000) / 1000;+ const steps: ToolStep[] = passes.map((p, k) => {+ const made = Math.round(clip * p * 1000) / 1000;+ const step: ToolStep = {+ key: `loop-${k + 1}`,+ request: {+ ...base,+ modelId: models.loop,+ op: "audio-loop",+ ...(k === 0 && { inputs: { audio: i.audio } }),+ params: { duration: made, sourceDuration: clip },+ ...(k === passes.length - 1 && { title }),+ },+ ...(k > 0 && { after: [`loop-${k}`], chain: [{ slot: "audio" as const }] }),+ };+ clip = made;+ return step;+ });+ return {+ steps,+ length,+ summary: `Plays it ${plural(plays, "time")} back to back${passes.length > 1 ? ` (${passes.length} calls of up to ${CLOUD_PER_CALL})` : ""}: ${clock(length)}.`,+ notes: [+ ...(length - duration > 0.05 ? [`The cloud repeats the whole clip, so this comes out ${clock(length)}, not ${clock(duration)}.`] : []),+ "No crossfade on the cloud: switch to the open engine for smooth seams and an exact length.",+ ],+ };+}++/** Clips one after another; throws what's in the way. */+export function planJoin(i: JoinInput): ToolPlan {+ const clips = i.clips;+ if (clips.length < 2) throw new Error("Add at least two clips to join");+ if (clips.length > JOIN_MAX_CLIPS) throw new Error(`Join up to ${JOIN_MAX_CLIPS} clips at a time`);+ const lengths = clips.map((c) => c.duration);+ const known = lengths.every((l): l is number => typeof l === "number" && l > 0);+ const title = `Join · ${plural(clips.length, "clip")}`;+ const base = { feature: JOIN_FEATURE, batchTitle: title } satisfies Partial<GenerationRequest>;+ const models = AUDIO_TOOL_MODELS[i.engine];+ if (i.engine === "open") {+ const x = fade(i.crossfade, DEFAULT_JOIN_CROSSFADE);+ const problem = known ? crossfadeProblem(lengths as number[], x, "join") : null;+ if (problem) throw new Error(problem);+ return {+ steps: [+ {+ key: "join",+ request: {+ ...base,+ modelId: models.join,+ op: "audio-join",+ inputs: { audios: clips.map((c) => c.url) },+ params: { crossfade: x, ...(i.curve === "linear" && { extra: { curve: "linear" } }) },+ title,+ },+ },+ ],+ length: known ? joinedLength(lengths as number[], x) : null,+ summary: `Joins ${plural(clips.length, "clip")} in this order with a ${x} s crossfade at ${plural(clips.length - 1, "seam")}.`,+ notes: [],+ };+ }+ // The cloud joins end to end, up to 5 files a call: more clips continue from the last call's result.+ const steps: ToolStep[] = [];+ let at = 0;+ while (at < clips.length) {+ const k = steps.length + 1;+ const take = clips.slice(at, at + (k === 1 ? CLOUD_PER_CALL : CLOUD_PER_CALL - 1));+ at += take.length;+ const last = at >= clips.length;+ steps.push({+ key: `join-${k}`,+ request: { ...base, modelId: models.join, op: "audio-join", inputs: { audios: take.map((c) => c.url) }, ...(last && { title }) },+ ...(k > 1 && { after: [`join-${k - 1}`], chain: [{ slot: "audios" as const, position: "first" as const }] }),+ });+ }+ return {+ steps,+ length: known ? joinedLength(lengths as number[], 0) : null,+ summary: `Joins ${plural(clips.length, "clip")} end to end${steps.length > 1 ? ` (${steps.length} calls of up to ${CLOUD_PER_CALL})` : ""}.`,+ notes: ["No crossfade on the cloud: the clips meet with a hard cut. Switch to the open engine for crossfades."],+ };+}diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.tsindex 01072ec7..5d2d3a0f 100644--- a/src/lib/catalog/payload.ts+++ b/src/lib/catalog/payload.ts@@ -327,7 +327,8 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk}if (map.frames && images.length) out[map.frames.key] = images.map((url) => ({ [map.frames!.url]: url, [map.frames!.frames]: 1 }));if (map.loop && input.audio) {- const want = input.duration && input.sourceDuration ? Math.ceil(input.duration / input.sourceDuration) : map.loop.max;+ // A length that is a whole number of plays counts as that many (30.003 / 10.001 is a hair over 3 in floats).+ const want = input.duration && input.sourceDuration ? Math.ceil(input.duration / input.sourceDuration - 1e-6) : map.loop.max;out[map.loop.key] = Array.from({ length: Math.max(2, Math.min(map.loop.max, want)) }, () => input.audio);}if (map.model3d && input.model3d) out[map.model3d] = input.model3d;diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsindex d3da001a..13647754 100644--- a/src/lib/hubs.ts+++ b/src/lib/hubs.ts@@ -17,6 +17,8 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {{ id: "translate", label: "Translate" },{ id: "sfx", label: "Sound effects" },{ id: "music", label: "Music" },+ { id: "loop", label: "Loop / extend" },+ { id: "join", label: "Join" },{ id: "video", label: "Sound for video" },],"video-tools": [diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 56948458..c2b1960b 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -22,6 +22,7 @@ export type OutputActionId =| "lipsync"| "add-sound"| "voice-change"+ | "loop-audio"| "copy-text"| "view-3d"| "download"@@ -100,6 +101,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =link("lipsync", "Lipsync", `/lipsync?audio=${q(o.url)}`, "primary");out.push(file, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });link("voice-change", "Change voice", `/audio/voice-change?audio=${q(o.url)}`);+ link("loop-audio", "Loop / extend", `/audio/loop?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/server/audio-tools.ts b/src/server/audio-tools.tsnew file mode 100644index 00000000..bfd5161e--- /dev/null+++ b/src/server/audio-tools.ts@@ -0,0 +1,100 @@+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 type { Engine, Generation } from "@/lib/catalog/types";+import { probeMedia } from "@/lib/media-probe";+import { createPipeline } from "./chains";+import { previewChained } from "./generations";+import { engineMode } from "./settings";+import { readRef } from "./storage";++/**+ * The Audio hub's Loop / extend and Join tools on the server: each clip's length is read from its own header+ * (the browser's figure is the fallback for containers the probe doesn't read), the plan from+ * src/lib/av/audio-tools.ts is priced step by step, and a run is one createPipeline batch, so its result+ * lands in the Library like any generation.+ */++const FileUrl = z.string().startsWith("/api/files/").max(500);+const Engine = z.enum(["cloud", "open"]);+const Curve = z.enum(["equal-power", "linear"]).optional();+const Crossfade = z.number().min(0).max(CROSSFADE_MAX).optional();++export const AudioToolBody = z.discriminatedUnion("tool", [+ z.object({+ tool: z.literal("loop"),+ engine: Engine,+ audio: FileUrl,+ name: z.string().max(200).optional(),+ duration: z.number().positive().max(LOOP_MAX_SECONDS),+ /** What the browser measured, used when the server can't read the file's header. */+ sourceDuration: z.number().positive().max(36_000).optional(),+ crossfade: Crossfade,+ curve: Curve,+ }),+ z.object({+ tool: z.literal("join"),+ engine: Engine,+ clips: z.array(z.object({ url: FileUrl, name: z.string().max(200).optional(), duration: z.number().positive().max(36_000).optional() })).min(2).max(JOIN_MAX_CLIPS),+ crossfade: Crossfade,+ curve: Curve,+ }),+]);+export type AudioToolRequest = z.infer<typeof AudioToolBody>;++export class AudioToolError extends Error {}++/** A clip's length from its header (WAV, FLAC, MP3, M4A), else the browser's. */+async function lengthOf(url: string, given?: number): Promise<number | undefined> {+ try {+ const info = probeMedia((await readRef(url)).data);+ if (info?.duration && info.duration > 0) return Math.round(info.duration * 1000) / 1000;+ } catch {+ throw new AudioToolError("That audio file is gone — add it again");+ }+ return given;+}++async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine }> {+ const mode = engineMode();+ 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 === "loop") {+ const sourceDuration = await lengthOf(body.audio, body.sourceDuration);+ return { engine: body.engine, ...planLoop({ ...body, sourceDuration: sourceDuration ?? 0 }) };+ }+ const clips = await Promise.all(body.clips.map(async (c) => ({ ...c, duration: await lengthOf(c.url, c.duration) })));+ return { engine: body.engine, ...planJoin({ ...body, clips }) };+ } catch (e) {+ throw e instanceof AudioToolError ? e : new AudioToolError((e as Error).message);+ }+}++/** What a run would do and cost, without starting it. */+export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToolPreview> {+ const p = await plan(body);+ let cost: number | null = 0;+ let demo = false;+ for (const s of p.steps) {+ let r: ReturnType<typeof previewChained>;+ try {+ r = previewChained(s.chain ? { ...s.request, chain: s.chain } : s.request, s.after?.length ?? 0);+ } catch (e) {+ throw new AudioToolError((e as Error).message);+ }+ demo ||= r.demo;+ cost = cost === null || r.costUsd === null ? null : cost + r.costUsd;+ }+ return { summary: p.summary, notes: p.notes, length: p.length, steps: p.steps.length, costUsd: cost === null ? null : Math.round(cost * 1000) / 1000, demo };+}++/** Start a run: one batch; the last step's generation is the result. */+export async function runAudioTool(body: AudioToolRequest): Promise<{ batchId: string; result: Generation; items: Generation[] }> {+ const p = await plan(body);+ try {+ const run = createPipeline(p.steps.map((s) => ({ key: s.key, request: s.request, ...(s.after && { after: s.after }), ...(s.chain && { chain: s.chain }) })));+ return { batchId: run.batchId, result: run.byKey[p.steps[p.steps.length - 1].key], items: run.items };+ } catch (e) {+ throw new AudioToolError((e as Error).message);+ }+}diff --git a/tests/audio-tools.test.ts b/tests/audio-tools.test.tsnew file mode 100644index 00000000..903c218f--- /dev/null+++ b/tests/audio-tools.test.ts@@ -0,0 +1,166 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { clock, planJoin, planLoop } from "@/lib/av/audio-tools";+import { cloudLoopPasses } from "@/lib/av/crossfade";+import { getModel } from "@/lib/catalog";+import { buildPayload } from "@/lib/catalog/payload";+import type { Generation } from "@/lib/catalog/types";+import { HUB_MODES, modeHref } from "@/lib/hubs";+import { outputActions } from "@/lib/output-actions";++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-audio-tools-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: the open models run on the demo provider.+process.env.COMFYUI_URL = "http://127.0.0.1:9";++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 }));++/** A mono 16-bit WAV of a tone, saved as an upload. */+function upload(seconds: number, name = "clip.wav"): string {+ const rate = 8000;+ const n = Math.round(seconds * rate);+ const buf = Buffer.alloc(44 + n * 2);+ buf.write("RIFF", 0);+ buf.writeUInt32LE(36 + n * 2, 4);+ buf.write("WAVEfmt ", 8);+ buf.writeUInt32LE(16, 16);+ buf.writeUInt16LE(1, 20);+ buf.writeUInt16LE(1, 22);+ buf.writeUInt32LE(rate, 24);+ buf.writeUInt32LE(rate * 2, 28);+ buf.writeUInt16LE(2, 32);+ buf.writeUInt16LE(16, 34);+ buf.write("data", 36);+ buf.writeUInt32LE(n * 2, 40);+ for (let i = 0; i < n; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 220 * i) / rate) * 8000), 44 + i * 2);+ 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) }));++describe("Loop / extend and Join plans", () => {+ it("loops on the open engine in one job, crossfaded, to the exact length", () => {+ const p = planLoop({ engine: "open", audio: "/api/files/a.wav", name: "Bed", sourceDuration: 45, duration: 300, crossfade: 2 });+ expect(p.steps).toHaveLength(1);+ expect(p.steps[0].request).toMatchObject({ feature: "audio-loop", modelId: "oss-audio-loop", op: "audio-loop", inputs: { audio: "/api/files/a.wav" }, params: { duration: 300, crossfade: 2, sourceDuration: 45 }, title: "Loop · Bed to 5:00" });+ expect(p.length).toBe(300);+ expect(p.summary).toBe("Loops it to 5:00 with 6 crossfaded seams (2 s each), then fades out over the last 2 s.");+ expect(p.notes).toEqual([]);+ expect(planLoop({ engine: "open", audio: "a", sourceDuration: 30, duration: 60, curve: "linear" }).steps[0].request.params?.extra).toEqual({ curve: "linear" });+ });++ it("loops on the cloud by whole plays, in a chain of calls when one call's five aren't enough", () => {+ const one = planLoop({ engine: "cloud", audio: "/api/files/a.wav", sourceDuration: 30, duration: 100 });+ expect(one.steps.map((s) => [s.key, s.request.modelId, s.request.params?.duration, s.request.params?.sourceDuration])).toEqual([["loop-1", "join-audio", 120, 30]]);+ expect(one.length).toBe(120);+ expect(one.notes[0]).toBe("The cloud repeats the whole clip, so this comes out 2:00, not 1:40.");+ const chain = planLoop({ engine: "cloud", audio: "/api/files/a.wav", sourceDuration: 10, duration: 600 });+ expect(chain.steps.map((s) => s.request.params?.duration)).toEqual([50, 200, 600]);+ expect(chain.steps.map((s) => s.request.params?.sourceDuration)).toEqual([10, 50, 200]);+ expect(chain.steps[1]).toMatchObject({ after: ["loop-1"], chain: [{ slot: "audio" }] });+ expect(chain.steps[0].request.inputs?.audio).toBe("/api/files/a.wav");+ expect(chain.steps[2].request.inputs).toBeUndefined();+ expect(chain.steps.map((s) => !!s.request.title)).toEqual([false, false, true]);+ expect(chain.summary).toBe("Plays it 60 times back to back (3 calls of up to 5): 10:00.");+ expect(chain.notes).toEqual(["No crossfade on the cloud: switch to the open engine for smooth seams and an exact length."]);+ });++ it("sends each cloud call exactly its planned plays, whatever the clip's length in milliseconds", () => {+ const route = getModel("join-audio")!.routes.find((r) => r.op === "audio-loop")!;+ for (const L of [10.0004, 7.3337, 3.3333, 11.1119, 0.9999]) {+ const plan = planLoop({ engine: "cloud", audio: "/api/files/a.wav", sourceDuration: L, duration: 600 });+ const plays = plan.steps.map((s) => (buildPayload(route.map!, { audio: "a.wav", duration: s.request.params?.duration, sourceDuration: s.request.params?.sourceDuration }).audio_urls as string[]).length);+ expect(plays).toEqual(cloudLoopPasses(L, 600));+ // Each call's clip is the last call's result.+ plan.steps.slice(1).forEach((s, k) => expect(s.request.params?.sourceDuration).toBe(plan.steps[k].request.params?.duration));+ }+ });++ it("says what's in the way of a loop", () => {+ expect(() => planLoop({ engine: "open", audio: "a", sourceDuration: 90, duration: 60 })).toThrow("The clip is already 1:30 long — pick a longer length");+ expect(() => planLoop({ engine: "open", audio: "a", sourceDuration: 30, duration: 900 })).toThrow("Loops run up to 10 minutes");+ expect(() => planLoop({ engine: "open", audio: "a", sourceDuration: 3, duration: 60, crossfade: 2 })).toThrow(/needs a clip longer than 4 s/);+ expect(() => planLoop({ engine: "open", audio: "a", sourceDuration: 0, duration: 60 })).toThrow(/length can't be read/);+ });++ it("joins up to 10 clips: one crossfaded job on the open engine, chained five-file calls on the cloud", () => {+ const clips = Array.from({ length: 7 }, (_, i) => ({ url: `/api/files/${i}.wav`, duration: 10 }));+ const open = planJoin({ engine: "open", clips, crossfade: 1.5 });+ expect(open.steps).toHaveLength(1);+ expect(open.steps[0].request).toMatchObject({ feature: "audio-join", modelId: "oss-audio-join", op: "audio-join", inputs: { audios: clips.map((c) => c.url) }, params: { crossfade: 1.5 }, title: "Join · 7 clips" });+ expect(open.length).toBe(61);+ expect(open.summary).toBe("Joins 7 clips in this order with a 1.5 s crossfade at 6 seams.");+ const cloud = planJoin({ engine: "cloud", clips });+ expect(cloud.steps.map((s) => s.request.inputs?.audios?.length)).toEqual([5, 2]);+ expect(cloud.steps[1]).toMatchObject({ after: ["join-1"], chain: [{ slot: "audios", position: "first" }] });+ expect(cloud.length).toBe(70);+ expect(cloud.notes[0]).toMatch(/hard cut/);+ expect(() => planJoin({ engine: "open", clips: clips.slice(0, 1) })).toThrow("Add at least two clips to join");+ expect(() => planJoin({ engine: "open", clips: Array.from({ length: 11 }, () => clips[0]) })).toThrow("Join up to 10 clips at a time");+ expect(() => planJoin({ engine: "open", clips: [clips[0], { url: "b", duration: 2 }, clips[1]], crossfade: 1.5 })).toThrow(/^Clip 2 is 2 s, too short/);+ expect(planJoin({ engine: "open", clips: [{ url: "a" }, { url: "b" }] }).length).toBeNull();+ });++ it("are Audio hub modes with their own paths", () => {+ expect(HUB_MODES.audio.map((m) => m.id)).toEqual(expect.arrayContaining(["loop", "join"]));+ expect(modeHref("audio", "loop")).toBe("/audio/loop");+ // An audio result hands itself to Loop / extend.+ const g = { id: "a1", feature: "music", status: "succeeded", favorite: false, deletedAt: null, prompt: "", request: {}, outputs: [{ url: "/api/files/o/bed.flac", kind: "audio" }] } as unknown as Generation;+ expect(outputActions(g, 0).find((a) => a.id === "loop-audio")).toMatchObject({ label: "Loop / extend", placement: "menu", href: "/audio/loop?audio=%2Fapi%2Ffiles%2Fo%2Fbed.flac" });+ expect(clock(61.5)).toBe("1:01");+ expect(clock(7.5)).toBe("0:07.5");+ });+});++describe("POST /api/audio-tools (demo mode)", () => {+ it("prices a loop from the clip's own header, and runs it in the Library", async () => {+ const audio = upload(6);+ // The browser's figure is ignored when the header can be read.+ const preview = await (await post({ tool: "loop", engine: "open", audio, duration: 20, sourceDuration: 99, crossfade: 1 }, true)).json();+ expect(preview).toEqual({ summary: "Loops it to 0:20 with 3 crossfaded seams (1 s each), then fades out over the last 1 s.", notes: [], length: 20, steps: 1, costUsd: 0, demo: true });+ const cloud = await (await post({ tool: "loop", engine: "cloud", audio, duration: 20 }, true)).json();+ expect(cloud).toMatchObject({ length: 24, steps: 1, demo: true });+ const res = await post({ tool: "loop", engine: "open", audio, duration: 20, crossfade: 1 });+ expect(res.status).toBe(201);+ const run = await res.json();+ expect(run.result).toMatchObject({ feature: "audio-loop", modelId: "oss-audio-loop", provider: "mock", op: "audio-loop" });+ const deadline = Date.now() + 15_000;+ let g = gens.getGeneration(run.result.id)!;+ while (g.status !== "succeeded" && Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 200));+ g = gens.getGeneration(run.result.id)!;+ }+ expect(g.status).toBe("succeeded");+ expect(g.outputs[0].kind).toBe("audio");+ });++ it("joins clips, and answers what's wrong in words", async () => {+ const clips = [upload(4, "a.wav"), upload(3, "b.wav"), upload(5, "c.wav")].map((url) => ({ url }));+ const preview = await (await post({ tool: "join", engine: "open", clips, crossfade: 0.5 }, true)).json();+ expect(preview).toMatchObject({ length: 11, steps: 1, costUsd: 0, demo: true });+ const run = await (await post({ tool: "join", engine: "cloud", clips })).json();+ expect(run.items).toHaveLength(1);+ expect(run.result.request.inputs.audios).toHaveLength(3);++ const short = await post({ tool: "join", engine: "open", clips: [clips[0], { url: upload(0.8, "tiny.wav") }, clips[2]], crossfade: 0.5 }, true);+ expect(short.status).toBe(422);+ expect((await short.json()).error).toMatch(/^Clip 2 is 0.8 s, too short for a 0.5 s crossfade/);+ expect((await (await post({ tool: "join", engine: "open", clips: clips.slice(0, 1) })).json()).error).toBe("Add 2 to 10 audio clips to join");+ expect((await (await post({ tool: "loop", engine: "open", audio: "/etc/passwd", duration: 20 })).json()).error).toBe("Add the audio to loop");+ expect((await (await post({ tool: "loop", engine: "open", audio: "/api/files/uploads/nope.wav", duration: 20 }, true)).json()).error).toBe("That audio file is gone — add it again");+ setSetting("engineMode", "cloud");+ try {+ expect((await (await post({ tool: "join", engine: "open", clips }, true)).json()).error).toMatch(/cloud APIs only/);+ } finally {+ setSetting("engineMode", "both");+ }+ });+});