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
DBS D1: Split soundtrack in the Audio hub, on the open engine
Claude1c4ce9b22483
diff --git a/docs/research/dbs-separation-7.md b/docs/research/dbs-separation-7.mdindex 524ccb9b..bf68caa8 100644--- a/docs/research/dbs-separation-7.md+++ b/docs/research/dbs-separation-7.md@@ -90,7 +90,19 @@ Measured by the pack's author (`docs/VERIFICATION.md` L96–108; Windows 11, RTX| DBS-BSRNN | CPU, 24 threads | 60 s, mono | 32.8 s | 1.83x | – |- **On a CPU, use DBS-BSRNN.** It has 4x the MACs of DBS-TIGER but runs 3.7x faster there.-- **Fuobe's ComfyUI host** (4 logical CPUs, 14.3 GB RAM, torch 2.14.1+cpu, started with `--cpu`; `/system_stats`, `nproc`) was not measured, because the research rules forbid running the pack. Guess, scaling from 24 threads to 4: DBS-BSRNN at 0.3–0.6x real time, so a 1-minute clip takes 2–3 minutes; DBS-TIGER about 4x slower than that.+- **Fuobe's ComfyUI host** (4 logical CPUs, 14.3 GB RAM, torch 2.14.1+cpu, started with `--cpu`; `/system_stats`, `nproc`) was not measured during the research, because the research rules forbid running the pack. The guess then, scaling from 24 threads to 4: DBS-BSRNN at 0.3–0.6x real time, so a 1-minute clip takes 2–3 minutes; DBS-TIGER about 4x slower than that.+- **Measured on this host (package D1, 2026-10-29).** ComfyUI-DBS at `f656e53` on an isolated CPU worker (a copy of the same ComfyUI `fc04da91`, Python 3.13, torch 2.14.1+cpu, `--cpu`), the four weight files of §3.1 at their pinned revisions (`sha256sum -c` OK), graph `separate-soundtrack-dbs` with `output_sample_rate` `input`, synthetic 44.1 kHz test mixes (speech, a chord bed, noise bursts). The host was shared with other jobs (load average 3.4–6 on 4 CPUs), so these are a busy host's numbers. "Seconds" is the pack's own report (separation only); a run adds about 1–2 s to load and save.++ | Model | Input | Channels | Seconds | Real time (per channel) |+ |---|---|---|---|---|+ | DBS-BSRNN | 20 s stereo WAV | mono | 73.7 | 0.27x |+ | DBS-BSRNN | 20 s MP4 (H.264 + AAC, read by `LoadAudio`) | mono | 61.1 | 0.33x |+ | DBS-TIGER | 20 s stereo WAV | mono | 220.7 | 0.09x |+ | DBS-BSRNN | 20 s stereo WAV | each channel (2 passes) | 232.4 | 0.17x |+ | DBS-TIGER | 10 s stereo WAV | each channel (2 passes) | 247.0 | 0.08x |+ | DBS-BSRNN | 10 s 5.1 WAV | each channel (6 passes) | 193.4 | 0.31x |++ So DBS-BSRNN runs at about 0.27x real time here (a minute of audio in about 4 minutes, 3–6 on a busy host) and DBS-TIGER at about 0.09x (about 11 minutes a minute): 3x slower, not 4x. Stereo stems cost one pass per channel. On the 20 s test mix, against its known parts (a sanity check, not a benchmark): the dialogue stem scored 14.6 dB SI-SDR with DBS-BSRNN and 18.5 dB with DBS-TIGER (the mix itself scores −1.0 dB as "dialogue"); the music-and-effects bed 15.6 and 19.4 dB. Music + effects + speech matched the channel mean of the input to 3e-5 (16-bit FLAC). Split soundtrack's time estimate uses 0.27x / 0.09x per pass (`src/lib/av/split.ts` `DBS_SPEED`).- **Threads.** The upstream demo runs DBS-TIGER on a CPU with one thread and NNPACK off and says that is faster and identical (`demo/README.md` L74–75; `demo/backend.py` L134–155). The pack measured that mode as 3.3x slower and not bit-identical (71.5 s against 21.4 s for 10 s of audio; VERIFICATION.md L112–114). Which wins on a 4-core host is unknown.- **Memory.** The stems of the whole input stay in memory until the end: 12 bytes per input sample at 44.1 kHz, about 0.3 GB per 10 minutes (VERIFICATION.md L107–108). An hour of audio would need about 1.9 GB on top of the decoded input (my arithmetic).diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex 6f8315de..befb95a8 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -2405,7 +2405,8 @@ export const SPEC = [license: 'DBS weights Apache-2.0 (JusperLee; trained on DnR v2, CC BY 4.0); ComfyUI-DBS code MIT; vendored DBS code Apache-2.0 with MIT notices (BS-RoFormer, MSST, TIGER)',notes:'CPU OK, about 1.7 GiB on CUDA. audio = an audio file or a video (LoadAudio reads a video\'s soundtrack without decoding frames). ' +- 'DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 4x slower on a CPU, the CUDA default); device auto. ' ++ 'DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 3x slower on a CPU, the CUDA default); device auto. ' ++ 'Measured on a 4-CPU host (torch 2.14.1+cpu, 10-20 s clips): DBS-BSRNN 0.17-0.33x real time per channel, DBS-TIGER 0.08-0.09x. ' +'DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (every channel separated on its own: 2x the time for stereo, 6x for 5.1; ' +'the provider forces it for inputs with more than 2 channels, where the subtract below would also take speech out of the LFE and surrounds); output_sample_rate input. ' +'Outputs in order: voice (speech), music, effects (sfx), background = original minus speech (AudioMerge subtract: with mono it keeps the original stereo image at mono cost; ' +diff --git a/src/app/(studio)/settings/about/page.tsx b/src/app/(studio)/settings/about/page.tsxindex d8284f9f..5c1bd816 100644--- a/src/app/(studio)/settings/about/page.tsx+++ b/src/app/(studio)/settings/about/page.tsx@@ -8,7 +8,7 @@ import { PageHeader, PageShell } from "@/components/page-shell";import { MODELS } from "@/lib/catalog";import type { Manifest } from "@/lib/comfy";import { FUOBE_REPO } from "@/lib/connections";-import { buildLicenceList } from "@/lib/licences";+import { ATTRIBUTIONS, buildLicenceList } from "@/lib/licences";export const metadata: Metadata = { title: "About & licences" };@@ -96,6 +96,32 @@ export default async function Page() {</section>)}+ <section aria-labelledby="credits" className="mt-8">+ <h2 id="credits" className="text-[15px] font-semibold">+ Credits+ </h2>+ <p className="mt-1 text-[13px] text-muted-foreground">Attributions the licences of the data and code behind Fuobe's open models ask for.</p>+ <ul className="mt-3 grid gap-2 sm:grid-cols-2">+ {ATTRIBUTIONS.map((a) => (+ <li key={a.text} className="min-w-0 rounded-xl border px-4 py-3">+ <p className="text-[13px] [overflow-wrap:anywhere]">+ {a.url ? (+ <a href={a.url} target="_blank" rel="noreferrer" className="underline underline-offset-2 hover:text-brand-text">+ {a.text}+ <span className="sr-only"> (opens in a new tab)</span>+ </a>+ ) : (+ a.text+ )}+ </p>+ <p className="mt-0.5 text-[12px] text-muted-foreground [overflow-wrap:anywhere]">+ {a.licence} · for {a.for}+ </p>+ </li>+ ))}+ </ul>+ </section>+<section aria-labelledby="licences" className="mt-10"><h2 id="licences" className="font-heading text-[24px] leading-tight">Open model licencesdiff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsindex 3eee0776..37eb1a09 100644--- a/src/app/api/audio-tools/route.ts+++ b/src/app/api/audio-tools/route.ts@@ -1,19 +1,22 @@import { AudioToolBody, AudioToolError, previewAudioTool, runAudioTool } from "@/server/audio-tools";-/** Audio → Loop / extend and Join: start a run; `?preview=1` only plans and prices it. */+/** What a field that doesn't check out means, in words the page shows. */+const MESSAGES: Record<string, string> = {+ media: "Add the audio or video to split",+ video: "Add the video to put the mix on",+ audio: "Add the audio to loop",+ duration: "Pick a length up to 10 minutes",+ crossfade: "Keep the crossfade between 0 and 10 seconds",+};++/** Audio → Loop / extend, Join and Split soundtrack (and a split's mix put back on its video): start a run; `?preview=1` only plans and prices it. */export async function POST(request: Request) {- const parsed = AudioToolBody.safeParse(await request.json().catch(() => null));+ const raw: unknown = await request.json().catch(() => null);+ const parsed = AudioToolBody.safeParse(raw);if (!parsed.success) {const path = parsed.error.issues[0]?.path.join(".") ?? "";- const 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";+ const remux = (raw as { tool?: unknown } | null)?.tool === "remux";+ const msg = path.startsWith("clips") ? "Add 2 to 10 audio clips to join" : remux && path === "audio" ? "Export the mix first" : (MESSAGES[path] ?? "Check the settings");return Response.json({ error: msg }, { status: 400 });}try {diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.tsindex 5feef462..6786c7a2 100644--- a/src/components/audio-tools/hooks.ts+++ b/src/components/audio-tools/hooks.ts@@ -7,7 +7,9 @@ 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" };+ | { tool: "join"; engine: Engine; clips: { url: string; name?: string; duration?: number }[]; crossfade?: number; curve?: "equal-power" | "linear" }+ | { tool: "split"; engine: Engine; media: string; kind: "audio" | "video"; name?: string; quality?: "fast" | "best"; stereo?: boolean; channels?: number; sourceDuration?: number }+ | { tool: "remux"; engine: Engine; video: string; audio: string; name?: string };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) });diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsxnew file mode 100644index 00000000..470e989a--- /dev/null+++ b/src/components/audio-tools/split-tool.tsx@@ -0,0 +1,749 @@+"use client";++import { AudioLines, Clapperboard, Cpu, Download, FileVideo, Headphones, Library, Loader2, Pause, Play, Save, SlidersVertical, Upload, Volume2, VolumeX, X } from "lucide-react";+import { nanoid } from "nanoid";+import { useRouter } from "next/navigation";+import { useCallback, 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 { Switch } from "@/components/ui/switch";+import { Feed } from "@/components/studio/feed";+import { ACCEPT, fileToSlot, kindOfFile, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";+import { Segmented } from "@/components/faceless/controls";+import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";+import { useGeneration } from "@/components/av/use-generation";+import { useEngine, useGenerations } from "@/lib/api";+import type { AudioToolPreview } from "@/lib/av/audio-tools";+import {+ clock,+ CLOUD_SPLIT_PROBLEM,+ dbLabel,+ durationWords,+ encodeWav,+ headroomGain,+ LEVEL_MAX,+ LEVEL_MIN,+ mixName,+ ORIGINAL_MIX,+ presetOf,+ PRESETS,+ QUALITY_LABELS,+ REMUX_FEATURE,+ setLevel,+ setMute,+ setSolo,+ SPLIT_FEATURE,+ STEMS,+ stemGains,+ type Mix,+ type SplitQuality,+ type StemId,+} from "@/lib/av/split";+import type { Engine, OutputFile } from "@/lib/catalog/types";+import { downloadHref } from "@/lib/library";+import { cn } from "@/lib/utils";+import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";++/**+ * Audio → Split soundtrack (DBS D1). Drop a song, podcast, film clip or video; DBS splits it into Dialogue, Music,+ * Effects and Music & effects on your ComfyUI (free, CPU or GPU). The stems are Library outputs; the mixer below plays+ * them live in the browser (WebAudio: solo, mute, level, presets), exports the mix as a WAV into the Library and, for a+ * video, puts it back on the picture (stream-copied on the open engine). There's no hosted DBS, so the cloud engine+ * says so instead of running something else.+ */++type Source = SlotValue & { kind: "audio" | "video"; duration?: number; channels?: number };+type Stem = { id: StemId; url: string; name: string };++const baseName = (s: { name?: string }) => (s.name ?? "Soundtrack").replace(/\.[a-z0-9]{2,4}$/i, "");++/** ?audio= / ?video= from a result's "Split soundtrack", read once after hydration. */+function useHandoff(take: (s: Source) => void) {+ useEffect(() => {+ const q = new URLSearchParams(window.location.search);+ for (const kind of ["video", "audio"] as const) {+ const url = q.get(kind);+ if (url?.startsWith("/api/files/")) return take({ ref: url, preview: url, kind, id: nanoid(8), name: decodeURIComponent(url.split("/").pop() ?? "") });+ }+ // Once, on arrival.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+}++/** The channel count the browser decodes (the server reads WAV / FLAC / MP3 headers itself; this covers MP4 and the rest). */+async function decodedChannels(url: string): Promise<number | undefined> {+ try {+ const data = await (await fetch(url)).arrayBuffer();+ const ctx = new OfflineAudioContext(1, 1, 44100);+ return (await ctx.decodeAudioData(data)).numberOfChannels;+ } catch {+ return undefined;+ }+}++// ---------------------------------------------------------------------------+// Input++function AddMedia({ onPick }: { onPick: (s: Source) => void }) {+ const input = useRef<HTMLInputElement>(null);+ const [over, setOver] = useState(false);+ const [picking, setPicking] = useState(false);+ const take = (f: File | undefined) => {+ if (!f) return;+ const kind = kindOfFile(f);+ if (kind !== "audio" && kind !== "video") return void toast("Audio or video only — drop a sound file or a clip here");+ void fileToSlot(f, (v) => v && onPick({ ...v, kind: v.kind === "video" ? "video" : "audio", name: f.name }), kind);+ };+ 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?.[0]);+ }}+ >+ <span className="grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">{over ? <Upload className="size-5" /> : <SlidersVertical className="size-5" />}</span>+ <div>+ <p className="text-[15px] font-medium">Add a soundtrack to split</p>+ <p className="mt-1 text-[13px] text-muted-foreground">A song, podcast, film clip or video, up to 200 MB</p>+ </div>+ <div className="flex flex-wrap items-center justify-center gap-1.5">+ <Button size="sm" className="rounded-full" onClick={() => input.current?.click()}>+ <Upload className="size-3.5" /> Upload audio or video+ </Button>+ <Popover open={picking} onOpenChange={setPicking}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="sm" className="rounded-full">+ <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", "video"]}+ onPick={(v) => {+ onPick({ ...v, kind: v.kind === "video" ? "video" : "audio" });+ setPicking(false);+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ </div>+ <input+ ref={input}+ type="file"+ accept={`${ACCEPT.audio},${ACCEPT.video}`}+ hidden+ onChange={(e) => {+ take(e.target.files?.[0]);+ e.target.value = "";+ }}+ />+ </div>+ );+}++function SourcePanel({ source, onDuration, onRemove }: { source: Source; onDuration: (s: number) => void; onRemove: () => void }) {+ const meta = (e: React.SyntheticEvent<HTMLMediaElement>) => Number.isFinite(e.currentTarget.duration) && e.currentTarget.duration > 0 && onDuration(e.currentTarget.duration);+ return (+ <Panel+ title={+ <span className="inline-flex min-w-0 items-center gap-1.5">+ {source.kind === "video" ? <FileVideo className="size-3.5 shrink-0" /> : <AudioLines className="size-3.5 shrink-0" />}+ <span className="truncate">{baseName(source)}</span>+ </span>+ }+ aside={+ <>+ {source.duration ? <span className="font-mono text-[12px] text-muted-foreground tabular-nums">{clock(source.duration)}</span> : null}+ <Button variant="ghost" size="icon-sm" className="rounded-full" aria-label="Remove the soundtrack" onClick={onRemove}>+ <X className="size-4" />+ </Button>+ </>+ }+ >+ {source.uploading ? (+ <p className="inline-flex items-center gap-2 text-[13px] text-muted-foreground" role="status">+ <Loader2 className="size-3.5 animate-spin" /> Uploading…+ </p>+ ) : source.kind === "video" ? (+ <video key={source.preview} src={source.preview} controls playsInline preload="metadata" onLoadedMetadata={meta} className="max-h-[36vh] w-full rounded-xl bg-media object-contain" />+ ) : (+ <audio key={source.preview} src={source.preview} controls preload="metadata" onLoadedMetadata={meta} className="h-9 w-full min-w-0" aria-label={`Play ${baseName(source)}`} />+ )}+ </Panel>+ );+}++// ---------------------------------------------------------------------------+// The live mixer (WebAudio): every stem decoded once, one gain per stem, sources restarted on play and seek.++const BARS = 96;++/** Loudest sample per bar, across channels (0…1), for the waveform. */+function peaksOf(buf: AudioBuffer, bars = BARS): number[] {+ const step = Math.max(1, Math.floor(buf.length / bars));+ const chans = Array.from({ length: buf.numberOfChannels }, (_, c) => buf.getChannelData(c));+ return Array.from({ length: bars }, (_, b) => {+ let m = 0;+ for (const d of chans) for (let i = b * step, end = Math.min(d.length, i + step); i < end; i += 16) m = Math.max(m, Math.abs(d[i]));+ return Math.min(1, m);+ });+}++function useStemPlayer(stems: Stem[]) {+ const ctx = useRef<AudioContext | null>(null);+ const gains = useRef<Partial<Record<StemId, GainNode>>>({});+ const sources = useRef<AudioBufferSourceNode[]>([]);+ const started = useRef<{ at: number; offset: number } | null>(null);+ const [buffers, setBuffers] = useState<Partial<Record<StemId, AudioBuffer>>>({});+ const [failed, setFailed] = useState<string | null>(null);+ const [playing, setPlaying] = useState<false | "mix" | StemId>(false);+ const [position, setPosition] = useState(0);+ const key = stems.map((s) => s.url).join("|");++ // Decode every stem when they arrive (the mixer is keyed by its result, so a new split starts a new player).+ useEffect(() => {+ let live = true;+ if (!stems.length) return;+ const ac = (ctx.current ??= new AudioContext());+ for (const s of stems) {+ if (!gains.current[s.id]) {+ const g = ac.createGain();+ g.connect(ac.destination);+ gains.current[s.id] = g;+ }+ void fetch(s.url)+ .then((r) => {+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ return r.arrayBuffer();+ })+ .then((data) => ac.decodeAudioData(data))+ .then((buf) => live && setBuffers((b) => ({ ...b, [s.id]: buf })))+ .catch(() => live && setFailed(`Couldn't load the ${s.name.toLowerCase()} stem in the browser — download it instead`));+ }+ return () => {+ live = false;+ };+ // The stems' addresses say when they changed.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);++ const length = useMemo(() => Math.max(0, ...Object.values(buffers).map((b) => b!.duration)), [buffers]);+ const ready = stems.length > 0 && stems.every((s) => buffers[s.id]);++ const stop = useCallback((keepPosition = true) => {+ for (const s of sources.current) {+ s.onended = null;+ try {+ s.stop();+ } catch {}+ }+ sources.current = [];+ if (keepPosition && started.current && ctx.current) setPosition(Math.min(length, started.current.offset + ctx.current.currentTime - started.current.at));+ started.current = null;+ setPlaying(false);+ }, [length]);++ const play = useCallback(+ (what: "mix" | StemId, from?: number) => {+ const ac = ctx.current;+ if (!ac || !ready) return;+ stop(false);+ void ac.resume();+ const offset = Math.max(0, Math.min(from ?? position, length - 0.05));+ const playingNow = what === "mix" ? stems : stems.filter((s) => s.id === what);+ sources.current = playingNow.map((s) => {+ const src = ac.createBufferSource();+ src.buffer = buffers[s.id]!;+ src.connect(gains.current[s.id]!);+ src.start(0, Math.min(offset, src.buffer.duration));+ return src;+ });+ const longest = sources.current.reduce((a, b) => ((b.buffer?.duration ?? 0) > (a?.buffer?.duration ?? 0) ? b : a), sources.current[0]);+ if (longest)+ longest.onended = () => {+ started.current = null;+ sources.current = [];+ setPlaying(false);+ setPosition(0);+ };+ started.current = { at: ac.currentTime, offset };+ setPosition(offset);+ setPlaying(what);+ },+ [buffers, length, position, ready, stems, stop],+ );++ // The playhead, about 10 times a second while playing.+ useEffect(() => {+ if (!playing) return;+ const t = setInterval(() => {+ if (started.current && ctx.current) setPosition(Math.min(length, started.current.offset + ctx.current.currentTime - started.current.at));+ }, 100);+ return () => clearInterval(t);+ }, [playing, length]);++ // Close the audio context with the page.+ useEffect(+ () => () => {+ for (const s of sources.current) {+ try {+ s.stop();+ } catch {}+ }+ void ctx.current?.close();+ },+ [],+ );++ /** Live gains: the mix, or one stem alone at its level while its own Play is on. */+ const apply = useCallback(+ (mix: Mix) => {+ const ac = ctx.current;+ if (!ac) return;+ const g = stemGains(mix);+ for (const s of STEMS) {+ const alone = playing && playing !== "mix" ? (playing === s.id ? 10 ** (mix[s.id].db / 20) : 0) : g[s.id];+ gains.current[s.id]?.gain.setTargetAtTime(alone, ac.currentTime, 0.015);+ }+ },+ [playing],+ );++ return { buffers, ready, failed, playing, position, length, play, stop, seek: (t: number) => (playing ? play(playing, t) : setPosition(t)), apply };+}++function Waveform({ buffer, position, length, muted }: { buffer?: AudioBuffer; position: number; length: number; muted: boolean }) {+ const peaks = useMemo(() => (buffer ? peaksOf(buffer) : null), [buffer]);+ const at = length ? position / length : 0;+ return (+ <svg viewBox={`0 0 ${BARS} 40`} preserveAspectRatio="none" className={cn("h-10 w-full", muted ? "text-muted-foreground/40" : "text-primary")} aria-hidden>+ {peaks+ ? peaks.map((p, i) => <rect key={i} x={i + 0.15} width={0.7} y={20 - Math.max(0.6, p * 19)} height={Math.max(1.2, p * 38)} rx={0.3} fill="currentColor" opacity={i / BARS <= at ? 1 : 0.55} />)+ : Array.from({ length: BARS }, (_, i) => <rect key={i} x={i + 0.15} width={0.7} y={19} height={2} className="fill-muted" />)}+ </svg>+ );+}++function StemTile({+ stem,+ mix,+ onMix,+ player,+}: {+ stem: Stem;+ mix: Mix;+ onMix: (m: Mix) => void;+ player: ReturnType<typeof useStemPlayer>;+}) {+ const id = useId();+ const s = mix[stem.id];+ const info = STEMS.find((x) => x.id === stem.id)!;+ const audible = stemGains(mix)[stem.id] > 0;+ const alone = player.playing === stem.id;+ return (+ <li className={cn("min-w-0 rounded-2xl border bg-background p-3 shadow-soft transition-opacity", !audible && "opacity-80")}>+ <div className="flex min-w-0 items-center gap-1.5">+ <Button+ variant={alone ? "default" : "outline"}+ size="icon-sm"+ className="shrink-0 rounded-full"+ disabled={!player.ready}+ aria-label={alone ? `Stop ${stem.name}` : `Play ${stem.name} alone`}+ onClick={() => (alone ? player.stop() : player.play(stem.id))}+ >+ {alone ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}+ </Button>+ <div className="min-w-0 flex-1">+ <p className="truncate text-[13px] font-semibold">{stem.name}</p>+ <p className="truncate text-[11px] text-muted-foreground">{info.hint}</p>+ </div>+ <Button+ variant={s.solo ? "default" : "ghost"}+ size="sm"+ className="h-7 shrink-0 rounded-full px-2.5 text-[12px]"+ aria-pressed={s.solo}+ aria-label={`Solo ${stem.name}`}+ onClick={() => onMix(setSolo(mix, stem.id, !s.solo))}+ >+ Solo+ </Button>+ <Button variant="ghost" size="icon-sm" className="shrink-0 rounded-full" aria-pressed={s.mute} aria-label={s.mute ? `Unmute ${stem.name}` : `Mute ${stem.name}`} onClick={() => onMix(setMute(mix, stem.id, !s.mute))}>+ {s.mute ? <VolumeX className="size-4" /> : <Volume2 className="size-4" />}+ </Button>+ <Button variant="ghost" size="icon-sm" className="shrink-0 rounded-full" asChild>+ <a href={downloadHref(stem.url, `${stem.name}.flac`)} download aria-label={`Download ${stem.name}`}>+ <Download className="size-4" />+ </a>+ </Button>+ </div>+ <div className="mt-2">+ <Waveform buffer={player.buffers[stem.id]} position={player.position} length={player.length} muted={!audible} />+ </div>+ <div className="mt-2 flex items-center gap-3">+ <label htmlFor={id} className="w-10 shrink-0 text-[12px] text-muted-foreground">+ Level+ </label>+ <Slider id={id} min={LEVEL_MIN} max={LEVEL_MAX} step={0.5} value={[s.db]} onValueChange={([v]) => onMix(setLevel(mix, stem.id, v))} aria-label={`${stem.name} level`} className="min-w-0 flex-1" />+ <span className="w-14 shrink-0 text-right font-mono text-[12px] tabular-nums">{s.mute ? "Muted" : dbLabel(s.db)}</span>+ </div>+ </li>+ );+}++/** Render the mix offline, exactly as it plays (gains, solo, mute), kept under full scale: 16-bit WAV bytes. */+async function renderMix(stems: Stem[], buffers: Partial<Record<StemId, AudioBuffer>>, mix: Mix): Promise<{ wav: Uint8Array; lowered: boolean }> {+ const bufs = stems.map((s) => buffers[s.id]!).filter(Boolean);+ const rate = bufs[0].sampleRate;+ const channels = Math.max(...bufs.map((b) => b.numberOfChannels));+ const length = Math.max(...bufs.map((b) => b.length));+ const oc = new OfflineAudioContext(channels, length, rate);+ const g = stemGains(mix);+ for (const s of stems) {+ if (!g[s.id] || !buffers[s.id]) continue;+ const src = oc.createBufferSource();+ src.buffer = buffers[s.id]!;+ const gain = oc.createGain();+ gain.gain.value = g[s.id];+ src.connect(gain).connect(oc.destination);+ src.start();+ }+ const out = await oc.startRendering();+ const data = Array.from({ length: out.numberOfChannels }, (_, c) => out.getChannelData(c));+ let peak = 0;+ for (const d of data) for (let i = 0; i < d.length; i++) peak = Math.max(peak, Math.abs(d[i]));+ const k = headroomGain(peak);+ if (k < 1) for (const d of data) for (let i = 0; i < d.length; i++) d[i] *= k;+ return { wav: encodeWav(data, rate), lowered: k < 1 };+}++async function uploadWav(wav: Uint8Array, name: string): Promise<string> {+ const form = new FormData();+ form.append("file", new File([wav as BlobPart], name, { type: "audio/wav" }));+ const res = await fetch("/api/uploads", { method: "POST", body: form });+ const body = (await res.json().catch(() => ({}))) as { url?: string; error?: string };+ if (!res.ok || !body.url) throw new Error(body.error ?? `Upload failed (${res.status})`);+ return body.url;+}++function Mixer({ stems, source, engine }: { stems: Stem[]; source: Source; engine: Engine }) {+ const player = useStemPlayer(stems);+ const [mix, setMixState] = useState<Mix>(ORIGINAL_MIX);+ const [busy, setBusy] = useState<null | "export" | "remux">(null);+ const exported = useRef<{ key: string; url: string } | null>(null);+ const remux = useAudioToolRun();+ const router = useRouter();+ const { apply } = player;+ useEffect(() => apply(mix), [apply, mix]);+ const preset = presetOf(mix);+ const mixKey = JSON.stringify(mix);+ const name = baseName(source);+ // The price of putting a mix back (any stored audio prices it: the cloud merge bills by compute, not by the mix).+ const background = stems.find((s) => s.id === "background")?.url ?? stems[0]?.url;+ const remuxPrice = useAudioToolPreview(source.kind === "video" && background ? { tool: "remux", engine, video: source.ref, audio: background, name } : null);++ const exportMix = async (): Promise<string> => {+ if (exported.current?.key === mixKey) return exported.current.url;+ const { wav, lowered } = await renderMix(stems, player.buffers, mix);+ const url = await uploadWav(wav, `${name} · ${mixName(mix)}.wav`);+ exported.current = { key: mixKey, url };+ if (lowered) toast("The mix peaked over full scale, so it was lowered as a whole to stay clean");+ return url;+ };+ const onExport = async () => {+ setBusy("export");+ try {+ await exportMix();+ toast.success("Mix saved to your Library", { action: { label: "Open Library", onClick: () => router.push("/library") } });+ } catch (e) {+ toast.error((e as Error).message || "Couldn't export the mix");+ } finally {+ setBusy(null);+ }+ };+ const onRemux = async () => {+ setBusy("remux");+ try {+ const audio = await exportMix();+ await remux.mutateAsync({ tool: "remux", engine, video: source.ref, audio, name });+ toast.success(engine === "open" ? "Putting the mix on your video (picture copied as it is)" : "Putting the mix on your video");+ } catch (e) {+ toast.error((e as Error).message || "Couldn't put the mix on the video");+ } finally {+ setBusy(null);+ }+ };+ const remuxCost = remuxPrice.data ? (remuxPrice.data.demo ? "Demo · free" : engine === "open" ? "Free" : remuxPrice.data.costUsd !== null && remuxPrice.data.costUsd < 0.01 ? "under $0.01" : `≈ $${remuxPrice.data.costUsd?.toFixed(2)}`) : null;++ return (+ <section aria-labelledby="mixer" className="space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ <h3 id="mixer" className="font-heading text-[22px] leading-tight">+ Stems and mixer+ </h3>+ <span className="rounded-full bg-success/15 px-2 py-0.5 text-[12px] font-medium text-success">Free · plays in your browser</span>+ </div>+ <p className="text-[13px] text-muted-foreground">Dialogue comes out clean; music and effects can bleed into each other. Every stem is already in your Library.</p>+ {player.failed && (+ <p className="text-[13px] text-destructive" role="alert">+ {player.failed}+ </p>+ )}+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <Button className="rounded-full" disabled={!player.ready} onClick={() => (player.playing === "mix" ? player.stop() : player.play("mix"))}>+ {!player.ready ? <Loader2 className="size-4 animate-spin" /> : player.playing === "mix" ? <Pause className="size-4" /> : <Headphones className="size-4" />}+ {!player.ready ? "Loading stems…" : player.playing === "mix" ? "Pause" : "Play the mix"}+ </Button>+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">+ {clock(player.position)} / {clock(player.length)}+ </span>+ <Slider+ min={0}+ max={Math.max(0.1, player.length)}+ step={0.1}+ value={[Math.min(player.position, player.length)]}+ onValueChange={([v]) => player.seek(v)}+ disabled={!player.ready}+ aria-label="Position"+ className="min-w-[8rem] flex-1 basis-40"+ />+ </div>+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <span className="text-[13px]">Presets</span>+ <Segmented label="Presets" value={preset ?? "custom"} onChange={(id) => id !== "custom" && setMixState(PRESETS.find((p) => p.id === id)!.mix)} options={[...PRESETS.map((p) => ({ value: p.id, label: p.label })), ...(preset ? [] : [{ value: "custom", label: "Custom" }])]} />+ </div>+ <ul className="grid grid-cols-1 gap-3 md:grid-cols-2" aria-label="Stems">+ {stems.map((s) => (+ <StemTile key={s.id} stem={s} mix={mix} onMix={setMixState} player={player} />+ ))}+ </ul>+ <div className="flex flex-wrap items-center gap-2 pt-1">+ <Button variant="outline" className="rounded-full" disabled={!player.ready || busy !== null} onClick={() => void onExport()}>+ {busy === "export" ? <Loader2 className="size-4 animate-spin" /> : <Save className="size-4" />} Export mix+ </Button>+ {source.kind === "video" && (+ <Button className="rounded-full" disabled={!player.ready || busy !== null} onClick={() => void onRemux()}>+ {busy === "remux" ? <Loader2 className="size-4 animate-spin" /> : <Clapperboard className="size-4" />} Put back on the video{remuxCost ? ` · ${remuxCost}` : ""}+ </Button>+ )}+ <span className="text-[12px] text-muted-foreground">{mixName(mix)}</span>+ </div>+ </section>+ );+}++// ---------------------------------------------------------------------------+// The tool++const money = (p: AudioToolPreview) => (p.demo ? "Demo · free" : "Free · runs on your ComfyUI");++function stemsOf(outputs: OutputFile[]): Stem[] {+ return STEMS.flatMap((s) => {+ const o = outputs.find((x) => x.kind === "audio" && x.meta?.stem === s.id);+ return o ? [{ id: s.id, url: o.url, name: s.label }] : [];+ });+}++export function SplitSoundtrackTool({ tabs }: { tabs?: React.ReactNode }) {+ const [engine, setEngine, mode] = useEngine();+ const run = useAudioToolRun();+ const [source, setSource] = useState<Source | null>(null);+ const [quality, setQuality] = useState<SplitQuality | null>(null);+ const [stereo, setStereo] = useState(false);+ const [resultId, setResultId] = useState<string | null>(null);+ const result = useGeneration(resultId);+ const stereoId = useId();+ const take = useCallback((s: Source) => {+ setSource(s);+ setResultId(null);+ }, []);+ useHandoff(take);+ const ready = source && !source.uploading && source.ref ? source : null;+ // MP4 and the like: the browser says how many channels there are (the server reads WAV / FLAC / MP3 itself).+ const readyRef = ready?.ref;+ useEffect(() => {+ if (!readyRef || source?.channels) return;+ let live = true;+ void decodedChannels(readyRef).then((n) => live && n && setSource((s) => (s && s.ref === readyRef ? { ...s, channels: n } : s)));+ return () => {+ live = false;+ };+ }, [readyRef, source?.channels]);+ const body: AudioToolBody | null = useMemo(+ () =>+ ready+ ? {+ tool: "split",+ engine,+ media: ready.ref,+ kind: ready.kind,+ name: baseName(ready),+ ...(quality && { quality }),+ ...(stereo && { stereo }),+ ...(ready.channels && { channels: ready.channels }),+ ...(ready.duration && { sourceDuration: ready.duration }),+ }+ : null,+ [ready, engine, quality, stereo],+ );+ const preview = useAudioToolPreview(useSettled(engine === "open" ? body : null));+ const p = preview.data;+ const picked: SplitQuality = quality ?? p?.hostPick ?? "fast";+ const blocker = !source ? "Add a soundtrack to split" : source.uploading ? "Uploading…" : engine === "cloud" ? CLOUD_SPLIT_PROBLEM : null;+ const error = preview.error ? (preview.error as Error).message : null;+ const go = () => {+ if (blocker) return void toast(blocker);+ if (error) return void toast.error(error);+ run.mutate(body!, {+ onSuccess: (r) => {+ setResultId(r.result.id);+ toast.success("Splitting on your ComfyUI");+ },+ onError: (e) => toast.error((e as Error).message),+ });+ };+ const g = result.data;+ const stems = useMemo(() => (g?.status === "succeeded" ? stemsOf(g.outputs) : []), [g]);++ return (+ <ToolShell title="Audio" tabs={tabs}>+ {!source && (+ <ToolHero+ title="Split any soundtrack"+ subtitle="Dialogue, music and effects from a song, podcast, film clip or video, with a free live mixer. Runs on your ComfyUI with DBS (open source, 23 MB, CPU or GPU): free."+ />+ )}+ <div className={cn("mx-auto max-w-[860px] space-y-3", source ? "pt-4" : "mt-8")}>+ {!source ? (+ <AddMedia onPick={take} />+ ) : (+ <SourcePanel+ source={source}+ onDuration={(duration) => setSource((s) => (s ? { ...s, duration } : s))}+ onRemove={() => {+ setSource(null);+ setResultId(null);+ }}+ />+ )}+ {source && engine === "cloud" && (+ <Panel>+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">+ <p className="min-w-0 flex-1 text-[13px] text-muted-foreground">+ <span className="font-medium text-foreground">Split soundtrack runs on your GPU (open source).</span> DBS isn't hosted on fal or Replicate, so there's no cloud route for dialogue, music and effects.+ </p>+ {mode === "both" ? (+ <Button variant="outline" size="sm" className="shrink-0 rounded-full" onClick={() => setEngine("open")}>+ <Cpu className="size-3.5" /> Use open source+ </Button>+ ) : null}+ </div>+ </Panel>+ )}+ {source && engine === "open" && (+ <Panel title="Options">+ <div className="space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ <span className="w-16 shrink-0 text-[13px]">Model</span>+ <Segmented+ label="Model"+ value={picked}+ onChange={(v) => setQuality(v)}+ options={[+ { value: "fast", label: QUALITY_LABELS.fast, hint: "18.9 MB, about 3x faster on a CPU" },+ { value: "best", label: QUALITY_LABELS.best, hint: "4.1 MB, cleaner music and effects; the pick on an NVIDIA GPU" },+ ]}+ />+ {!quality && p?.hostPick && <span className="text-[12px] text-muted-foreground">picked for your {p.device === "cuda" ? "GPU" : "CPU"}</span>}+ </div>+ <div className="flex items-center gap-2">+ <Switch id={stereoId} checked={stereo} onCheckedChange={setStereo} />+ <label htmlFor={stereoId} className="text-[13px]">+ Stereo stems <span className="text-muted-foreground">(takes about twice as long)</span>+ </label>+ </div>+ </div>+ </Panel>+ )}+ {source && (+ <div className="space-y-2">+ {!blocker && !error && p && (+ <div className="space-y-1 text-[13px] text-muted-foreground" aria-live="polite">+ <p>{p.summary}</p>+ {p.notes.map((n) => (+ <p key={n} className="text-[12px]">+ {n}+ </p>+ ))}+ </div>+ )}+ <div className="flex flex-wrap items-center gap-3">+ <p className={cn("min-w-0 flex-1 text-[13px]", error && !blocker ? "text-destructive" : "text-muted-foreground")} aria-live="polite">+ {blocker && engine !== "cloud" ? (+ blocker+ ) : engine === "cloud" ? (+ "Switch to the open engine to split"+ ) : error ? (+ error+ ) : p ? (+ <>+ <span className="font-mono text-foreground">{money(p)}</span>+ {p.estimate && !p.demo ? ` · ${durationWords(p.estimate)} on your ${p.device === "cuda" ? "GPU" : "CPU"}` : ""}+ </>+ ) : (+ "Checking…"+ )}+ </p>+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={go} disabled={run.isPending || g?.status === "queued" || g?.status === "running"}>+ {run.isPending || g?.status === "queued" || g?.status === "running" ? <Loader2 className="size-4 animate-spin" /> : <SlidersVertical className="size-4" />} Split it+ </Button>+ </div>+ </div>+ )}+ {g && (g.status === "queued" || g.status === "running") && (+ <Panel>+ <p className="inline-flex items-center gap-2 text-[13px] text-muted-foreground" role="status">+ <Loader2 className="size-3.5 animate-spin" /> {g.message ?? "Splitting"}…{g.progress ? ` ${Math.round(g.progress * 100)}%` : ""}+ </p>+ </Panel>+ )}+ {g?.status === "failed" && (+ <p className="text-[13px] text-destructive" role="alert">+ {g.error ?? "The split failed"}+ </p>+ )}+ {source && stems.length > 0 && <Mixer key={g!.id} stems={stems} source={source} engine={engine} />}+ </div>+ <Results />+ </ToolShell>+ );+}++function Results() {+ const splits = useGenerations({ features: [SPLIT_FEATURE], limit: 12 });+ const remuxes = useGenerations({ features: [REMUX_FEATURE], limit: 12 });+ const items = [...(remuxes.data ?? []), ...(splits.data ?? [])].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));+ if (!items.length) return null;+ return (+ <section className="mx-auto mt-10 max-w-[1040px]" aria-labelledby="split-results">+ <h3 id="split-results" className="mb-3 font-heading text-[22px]">+ Your splits+ </h3>+ <Feed items={items} />+ </section>+ );+}diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsxindex 8ffbef80..98d3c0db 100644--- a/src/components/studio/mode-switch-studio.tsx+++ b/src/components/studio/mode-switch-studio.tsx@@ -29,6 +29,7 @@ import { TrimTool } from "@/components/av/trim-tool";import { RemoveObjectTool } from "@/components/remove-object/remove-object-tool";import { EvolutionTool } from "@/components/evolution/evolution-tool";import { AudioJoinTool, AudioLoopTool } from "@/components/audio-tools/audio-tools";+import { SplitSoundtrackTool } from "@/components/audio-tools/split-tool";import { ModeStudio, ModeTabs } from "./mode-studio";import type { StudioConfig } from "./studio-context";@@ -53,12 +54,13 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {},};-/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Remove object, Evolution, Captions, Trim). */+/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Remove object, Evolution, Captions, Trim). */const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {audio: {translate: ({ tabs }) => <DubStudio tabs={tabs} />,loop: ({ tabs }) => <AudioLoopTool tabs={tabs} />,join: ({ tabs }) => <AudioJoinTool tabs={tabs} />,+ split: ({ tabs }) => <SplitSoundtrackTool tabs={tabs} />,},"video-tools": {"remove-object": ({ tabs }) => <RemoveObjectTool tabs={tabs} />,diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 97c6d145..c3f19d8e 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -24,6 +24,7 @@ import {RotateCcw,Share2,SlidersHorizontal,+ SlidersVertical,Sparkles,Trash2,UserRoundPlus,@@ -84,6 +85,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {genjutsu: WandSparkles,"voice-change": AudioLines,"loop-audio": Repeat,+ "split-soundtrack": SlidersVertical,"copy-text": Copy,"view-3d": Box,download: Download,diff --git a/src/lib/av/audio-tools.ts b/src/lib/av/audio-tools.tsindex 54dfab2c..74620303 100644--- a/src/lib/av/audio-tools.ts+++ b/src/lib/av/audio-tools.ts@@ -57,6 +57,11 @@ export interface AudioToolPreview {steps: number;costUsd: number | null;demo: boolean;+ /** Split soundtrack: about how long the open engine takes (seconds, a range), and the DBS model the host would pick. */+ estimate?: { low: number; high: number };+ hostPick?: "fast" | "best";+ /** The ComfyUI host's device type ("cpu", "cuda"…), when it said. */+ device?: string;}export interface LoopInput {diff --git a/src/lib/av/split.ts b/src/lib/av/split.tsnew file mode 100644index 00000000..87399622--- /dev/null+++ b/src/lib/av/split.ts@@ -0,0 +1,373 @@+import type { Engine, GenerationRequest } from "@/lib/catalog/types";+import { clock, type ToolPlan } from "./audio-tools";++/**+ * Audio → Split soundtrack (DBS D1, docs/research/dbs-separation-7.md): any audio or video split into Dialogue,+ * Music, Effects and Music & effects stems, a free live mixer over them, and the mix exported or put back on the video.+ * Pure: the page and the server (src/server/audio-tools.ts) share it, and the ComfyUI provider takes its model and+ * channel rules.+ *+ * - Open engine (ComfyUI + ComfyUI-DBS, CPU or GPU): one job on oss-dbs-separate (graph separate-soundtrack-dbs).+ * - Cloud: none. DBS is hosted nowhere, and a different model in its place (fal's SAM Audio) is the owner's call, not+ * taken: the cloud engine says the tool runs on your GPU. A result's mix still goes back on a video on either engine+ * (oss-mux / fal merge-audio-video).+ */++export const SPLIT_FEATURE = "audio-split";+export const SPLIT_MODEL = "oss-dbs-separate";+/** Putting a mix back on its video: the open stream-copy mux, or fal's merge on the cloud. */+export const REMUX_FEATURE = "audio-split-remux";+export const REMUX_MODELS: Record<Engine, string> = {+ open: "oss-mux",+ cloud: "merge-audio-video",+};++/** Why the cloud engine has no Split soundtrack (and what Engine mode "Paid APIs only" says). */+export const CLOUD_SPLIT_PROBLEM =+ "Split soundtrack runs on your GPU (open source): DBS isn't hosted on fal or Replicate, so the cloud engine can't split dialogue, music and effects. Switch to the open engine.";+export const CLOUD_ONLY_PROBLEM = "Split soundtrack runs on your GPU (open source), but this install is set to paid cloud APIs only (Settings → Engine mode)";++// ---------------------------------------------------------------------------+// The DBS models and how a host picks one++export type SplitQuality = "fast" | "best";+export type DbsModel = "DBS-BSRNN-DnR" | "DBS-TIGER-DnR";+export const DBS_MODELS: Record<SplitQuality, DbsModel> = {+ fast: "DBS-BSRNN-DnR",+ best: "DBS-TIGER-DnR",+};+export const QUALITY_LABELS: Record<SplitQuality, string> = {+ fast: "Fast (DBS-BSRNN)",+ best: "Best (DBS-TIGER)",+};+export type DbsChannels = "mono" | "each channel";++/**+ * The model a host does best with: DBS-TIGER (10.13 dB) on a CUDA GPU, where both run well over 10x real time+ * (ROCm reports "cuda" too); DBS-BSRNN (9.07 dB) on a CPU, where it runs about 4x faster than DBS-TIGER.+ */+export function hostPick(deviceType?: string | null): SplitQuality {+ return deviceType === "cuda" ? "best" : "fast";+}++/** The DBSLoader model a run gets: the one asked for ("fast" / "best" or the model's name), else the host's pick. */+export function dbsModelFor(asked: unknown, deviceType?: string | null): DbsModel {+ if (asked === "DBS-BSRNN-DnR" || asked === "DBS-TIGER-DnR") return asked;+ if (asked === "fast" || asked === "best") return DBS_MODELS[asked];+ return DBS_MODELS[hostPick(deviceType)];+}++/**+ * DBSSeparate's channel mode: "mono" (the mean of the channels, the official usage) unless stereo stems are asked+ * for; always "each channel" for more than 2 channels, where the background (original minus the mono speech) would+ * also take speech out of the LFE and surround channels.+ */+export function dbsChannelsFor(asked: unknown, channels?: number | null): DbsChannels {+ if (typeof channels === "number" && channels > 2) return "each channel";+ return asked === "each channel" || asked === "stereo" || asked === true ? "each channel" : "mono";+}++/** How many times the model runs over the clip: once in mono, once per channel otherwise. */+export function separationPasses(mode: DbsChannels, channels?: number | null): number {+ return mode === "mono" ? 1 : Math.max(2, Math.round(channels ?? 2));+}++// ---------------------------------------------------------------------------+// Time on the open engine++/**+ * Times real time (seconds of audio per second of work, one pass), as measured. CPU: real runs on a 4-CPU host+ * (torch 2.14.1+cpu, ComfyUI-DBS f656e53, 10–20 s clips, other jobs sharing the CPU; docs/research/dbs-separation-7.md+ * §2.4): DBS-BSRNN 0.17–0.33x, typically 0.27x; DBS-TIGER 0.08–0.09x. GPU: the pack author's RTX 5090 (the same+ * section); a smaller GPU is slower, so the estimate is a range.+ */+export const DBS_SPEED: Record<"cpu" | "cuda", Record<SplitQuality, number>> = {+ cpu: { fast: 0.27, best: 0.09 },+ cuda: { fast: 22.4, best: 15.9 },+};+/** Loading the model and the audio, saving four FLAC stems (seconds, measured on the CPU host). */+const OVERHEAD_SECONDS = 3;++/** About how long a split takes, as a range in seconds (a busy or slower host takes longer). */+export function splitTime(o: { seconds: number; quality: SplitQuality; mode: DbsChannels; channels?: number | null; device?: string | null }): { low: number; high: number } {+ const speed = DBS_SPEED[o.device === "cuda" ? "cuda" : "cpu"][o.quality];+ const work = (Math.max(0, o.seconds) * separationPasses(o.mode, o.channels)) / speed;+ // CPU: from a bit faster than measured to the slowest run measured on a busy host; a GPU smaller than the+ // reference card can be several times slower.+ const [lo, hi] = o.device === "cuda" ? [1, 4] : [0.8, 1.6];+ return {+ low: Math.round(OVERHEAD_SECONDS + work * lo),+ high: Math.round(OVERHEAD_SECONDS + work * hi),+ };+}++/** "about 1–2 min", "under a minute" */+export function durationWords(r: { low: number; high: number }): string {+ if (r.high < 60) return "under a minute";+ const lo = Math.max(1, Math.round(r.low / 60));+ const hi = Math.max(lo, Math.round(r.high / 60));+ if (hi >= 90) return `about ${Math.round((r.low / 3600) * 10) / 10}–${Math.round((r.high / 3600) * 10) / 10} h`;+ return lo === hi ? `about ${lo} min` : `about ${lo}–${hi} min`;+}++// ---------------------------------------------------------------------------+// The plan++export interface SplitInput {+ engine: Engine;+ /** The audio or video file (/api/files/…). */+ media: string;+ kind: "audio" | "video";+ name?: string;+ quality?: SplitQuality;+ /** Stereo stems: every channel separated on its own (about twice as long for stereo). */+ stereo?: boolean;+ /** The source's channel count (its header, else what the browser decoded). */+ channels?: number;+ /** Seconds the soundtrack runs, when known. */+ seconds?: number;+}++export interface SplitPlan extends ToolPlan {+ quality: SplitQuality | null;+ mode: DbsChannels;+}++const STEP_LABEL: Record<DbsChannels, string> = {+ mono: "Dialogue, music, effects",+ "each channel": "Dialogue, music, effects · every channel",+};++/** One DBS job on the open engine; throws what's in the way (in words the page shows). */+export function planSplit(i: SplitInput): SplitPlan {+ if (i.engine === "cloud") throw new Error(CLOUD_SPLIT_PROBLEM);+ if (!i.media) throw new Error(`Add the ${i.kind === "video" ? "video" : "audio"} to split`);+ const mode = dbsChannelsFor(i.stereo ? "each channel" : "mono", i.channels);+ const name = i.name?.trim();+ const title = `Split · ${name || (i.kind === "video" ? "video soundtrack" : "soundtrack")}`;+ const extra: Record<string, unknown> = { channels: mode };+ if (i.quality) extra.separationModel = DBS_MODELS[i.quality];+ if (i.channels && i.channels > 0) extra.sourceChannels = Math.round(i.channels);+ const request: GenerationRequest = {+ modelId: SPLIT_MODEL,+ op: "separate-audio",+ feature: SPLIT_FEATURE,+ batchTitle: title,+ title,+ inputs: i.kind === "video" ? { video: i.media } : { audio: i.media },+ params: {+ extra,+ ...(i.seconds &&+ i.seconds > 0 && {+ sourceDuration: Math.round(i.seconds * 1000) / 1000,+ }),+ },+ step: { label: STEP_LABEL[mode], index: 0, of: 1 },+ };+ const forced = mode === "each channel" && !i.stereo;+ const passes = separationPasses(mode, i.channels);+ return {+ steps: [{ key: "split", request }],+ length: i.seconds && i.seconds > 0 ? i.seconds : null,+ quality: i.quality ?? null,+ mode,+ summary: `Splits ${i.kind === "video" ? "the video's soundtrack" : "it"} into dialogue, music, effects and music & effects${mode === "each channel" ? `, every channel on its own (${passes} passes)` : ""}.`,+ notes: [+ ...(forced ? [`This file has ${i.channels} channels, so each is split on its own: about ${passes}x the time.`] : []),+ "Dialogue comes out clean; music and effects can bleed into each other.",+ ],+ };+}++/** The mix put back on its video (the picture copied untouched on the open engine). */+export function planRemux(i: { engine: Engine; video: string; audio: string; name?: string }): ToolPlan {+ const title = `Remix · ${i.name?.trim() || "video"}`;+ return {+ steps: [+ {+ key: "remux",+ request: {+ modelId: REMUX_MODELS[i.engine],+ op: "mux",+ feature: REMUX_FEATURE,+ batchTitle: title,+ title,+ inputs: { video: i.video, audio: i.audio },+ step: {+ label: i.engine === "open" ? "New soundtrack · picture copied" : "New soundtrack",+ index: 0,+ of: 1,+ },+ },+ },+ ],+ length: null,+ summary: "Puts your mix on the video in place of its sound.",+ notes: i.engine === "open" ? ["The picture is copied as it is, not re-encoded."] : [],+ };+}++// ---------------------------------------------------------------------------+// Stems and the mixer (the browser's WebAudio graph and its export use these numbers)++export type StemId = "voice" | "music" | "effects" | "background";+export const STEMS: { id: StemId; label: string; hint: string }[] = [+ { id: "voice", label: "Dialogue", hint: "Speech, clean" },+ { id: "music", label: "Music", hint: "Score and songs (singing lands here)" },+ { id: "effects", label: "Effects", hint: "Sound effects and ambience" },+ {+ id: "background",+ label: "Music & effects",+ hint: "Everything but the dialogue",+ },+];+export const stemLabel = (id: string): string => STEMS.find((s) => s.id === id)?.label ?? id;++export const LEVEL_MIN = -24;+export const LEVEL_MAX = 6;++export interface StemMix {+ /** Level in dB, LEVEL_MIN…LEVEL_MAX. */+ db: number;+ mute: boolean;+ solo: boolean;+}+export type Mix = Record<StemId, StemMix>;++const on = (db = 0): StemMix => ({ db, mute: false, solo: false });+const off = (db = 0): StemMix => ({ db, mute: true, solo: false });++/**+ * The original back: dialogue plus music & effects (they sum to the source exactly). The separate music and effects+ * stems start muted, so nothing plays twice.+ */+export const ORIGINAL_MIX: Mix = {+ voice: on(),+ music: off(),+ effects: off(),+ background: on(),+};++export const PRESETS: { id: string; label: string; mix: Mix }[] = [+ { id: "original", label: "Original", mix: ORIGINAL_MIX },+ {+ id: "no-dialogue",+ label: "No dialogue",+ mix: { voice: off(), music: off(), effects: off(), background: on() },+ },+ {+ id: "dialogue-only",+ label: "Dialogue only",+ mix: { voice: on(), music: off(), effects: off(), background: off() },+ },+ {+ id: "music-only",+ label: "Music only",+ mix: { voice: off(), music: on(), effects: off(), background: off() },+ },+ {+ id: "music-under",+ label: "Music under dialogue (−12 dB)",+ mix: { voice: on(), music: off(), effects: off(), background: on(-12) },+ },+];++/** The preset a mix is, if any (levels within 0.5 dB, solo off). */+export function presetOf(mix: Mix): string | null {+ const same = (a: StemMix, b: StemMix) => a.mute === b.mute && a.solo === b.solo && (a.mute || Math.abs(a.db - b.db) < 0.5);+ return PRESETS.find((p) => STEMS.every((s) => same(mix[s.id], p.mix[s.id])))?.id ?? null;+}++export const clampDb = (db: number): number => Math.min(LEVEL_MAX, Math.max(LEVEL_MIN, Math.round(db * 2) / 2));++/** A level in dB as a gain (0 dB = 1, −6 dB ≈ 0.5, +6 dB ≈ 2). */+export function dbToGain(db: number): number {+ return Number.isFinite(db) ? 10 ** (db / 20) : 0;+}++/** "+3 dB", "−12 dB", "0 dB" */+export function dbLabel(db: number): string {+ const v = Math.round(db * 2) / 2;+ return v === 0 ? "0 dB" : `${v > 0 ? "+" : "−"}${Math.abs(v)} dB`;+}++/** What each stem plays at: muted = 0; while any stem is soloed, only the soloed ones play. */+export function stemGains(mix: Mix): Record<StemId, number> {+ const solo = STEMS.some((s) => mix[s.id].solo);+ return Object.fromEntries(STEMS.map((s) => [s.id, mix[s.id].mute || (solo && !mix[s.id].solo) ? 0 : dbToGain(clampDb(mix[s.id].db))])) as Record<StemId, number>;+}++/**+ * Mute or unmute a stem. Music & effects is the music and effects stems together, so turning it on turns those two+ * off, and turning either of them on turns it off: nothing plays twice.+ */+export function setMute(mix: Mix, id: StemId, mute: boolean): Mix {+ const next: Mix = { ...mix, [id]: { ...mix[id], mute } };+ if (!mute && id === "background") {+ next.music = { ...next.music, mute: true };+ next.effects = { ...next.effects, mute: true };+ }+ if (!mute && (id === "music" || id === "effects")) next.background = { ...next.background, mute: true };+ return next;+}++export function setSolo(mix: Mix, id: StemId, solo: boolean): Mix {+ return { ...mix, [id]: { ...mix[id], solo } };+}++/** A level change unmutes the stem (moving a fader means you want to hear it). */+export function setLevel(mix: Mix, id: StemId, db: number): Mix {+ const next = mix[id].mute ? setMute(mix, id, false) : mix;+ return { ...next, [id]: { ...next[id], db: clampDb(db) } };+}++/** "Dialogue + Music & effects −12 dB" — the mix in words, for its title in the Library. */+export function mixName(mix: Mix): string {+ const preset = presetOf(mix);+ if (preset && preset !== "original") return PRESETS.find((p) => p.id === preset)!.label;+ const g = stemGains(mix);+ const parts = STEMS.filter((s) => g[s.id] > 0).map((s) => `${s.label}${Math.abs(mix[s.id].db) >= 0.5 ? ` ${dbLabel(mix[s.id].db)}` : ""}`);+ return parts.length ? parts.join(" + ") : "Silence";+}++// ---------------------------------------------------------------------------+// Export: the rendered mix as a WAV file++/**+ * The gain that keeps a mix from clipping: 1 when its peak is at or under full scale, else just enough to bring the+ * peak to −0.1 dBFS (the whole mix, so the balance stays as set).+ */+export function headroomGain(peak: number): number {+ const ceiling = dbToGain(-0.1);+ return peak > ceiling ? ceiling / peak : 1;+}++/** 16-bit PCM WAV from planar float channels (−1…1, clipped), as the export uploads it. */+export function encodeWav(channels: Float32Array[], sampleRate: number): Uint8Array {+ const n = channels.length ? channels[0].length : 0;+ const ch = Math.max(1, channels.length);+ const bytes = new Uint8Array(44 + n * ch * 2);+ const d = new DataView(bytes.buffer);+ const text = (o: number, s: string) => [...s].forEach((c, k) => d.setUint8(o + k, c.charCodeAt(0)));+ text(0, "RIFF");+ d.setUint32(4, 36 + n * ch * 2, true);+ text(8, "WAVE");+ text(12, "fmt ");+ d.setUint32(16, 16, true);+ d.setUint16(20, 1, true);+ d.setUint16(22, ch, true);+ d.setUint32(24, sampleRate, true);+ d.setUint32(28, sampleRate * ch * 2, true);+ d.setUint16(32, ch * 2, true);+ d.setUint16(34, 16, true);+ text(36, "data");+ d.setUint32(40, n * ch * 2, true);+ for (let i = 0, o = 44; i < n; i++)+ for (let c = 0; c < ch; c++, o += 2) {+ const v = Math.max(-1, Math.min(1, channels[c]?.[i] ?? 0));+ d.setInt16(o, Math.round(v < 0 ? v * 0x8000 : v * 0x7fff), true);+ }+ return bytes;+}++export { clock };diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex d063c252..041679b0 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1136,6 +1136,27 @@ const open: ModelDef[] = [routes: [comfy("separate-audio", "dub-prepare-separate-transcribe", "voice stem, background stem, timed cues, transcript")],options: {},}),+ // DBS (docs/research/dbs-separation-7.md): dialogue, music and effects from any soundtrack, small enough for a CPU. The+ // provider picks the model by the host (DBS-TIGER on CUDA, DBS-BSRNN otherwise) unless one is asked for, and separates+ // every channel on its own for inputs with more than 2 channels. Split soundtrack (src/lib/av/split.ts) runs on it.+ o({+ id: "oss-dbs-separate",+ name: "DBS (dialogue, music, effects)",+ vendor: "Open source",+ family: "dbs",+ kind: "audio",+ tagline: "Splits a soundtrack into dialogue, music and effects · 23 MB · CPU or GPU · Apache-2.0",+ badges: ["new"],+ routes: [comfy("separate-audio", "separate-soundtrack-dbs", "voice, music, effects and music & effects (FLAC) + a speed report; ComfyUI-DBS")],+ options: {+ promptless: true,+ controls: [+ // No default: the host decides (DBS-TIGER on a CUDA GPU, DBS-BSRNN on a CPU, where it runs about 3x faster).+ { param: "separationModel", label: "Model", values: ["DBS-BSRNN-DnR", "DBS-TIGER-DnR"], labels: { "DBS-BSRNN-DnR": "Fast (DBS-BSRNN)", "DBS-TIGER-DnR": "Best (DBS-TIGER)" } },+ { param: "channels", label: "Stems", values: ["mono", "each channel"], default: "mono", labels: { mono: "Mono", "each channel": "Stereo stems (about twice as long)" } },+ ],+ },+ }),o({id: "oss-qwen3-asr",name: "Qwen3-ASR",diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.tsindex 94eba0a8..14c6f8f8 100644--- a/src/lib/catalog/payload.ts+++ b/src/lib/catalog/payload.ts@@ -827,7 +827,8 @@ function hdrOutputs(response: unknown): ExtractedOutput[] {return preview ? [{ url: preview.url, kind: "video", contentType: preview.contentType, meta: { preview: "sdr", artifacts: { exr: exr.url } } }] : [];}-const STEM_ORDER = ["vocals", "voice", "speech", "target", "drums", "bass", "guitar", "piano", "other", "residual", "accompaniment", "instrumental"];+// Voice first, then DBS's music and effects, then Demucs's instruments and the backgrounds.+const STEM_ORDER = ["vocals", "voice", "speech", "target", "music", "sfx", "effects", "drums", "bass", "guitar", "piano", "other", "residual", "accompaniment", "instrumental"];/** Demucs: {vocals, drums, bass, other, guitar, piano} files; SAM Audio: {target, residual}. Voice first. */function stemOutputs(response: unknown): ExtractedOutput[] {diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 41384943..7cfa639b 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -56,7 +56,7 @@ export type Operation =| "captions" // video → the same video with burned-in captions| "mux" // video + audio → the video with that soundtrack| "image-to-3d" // image → a 3D model (.glb), optionally a turntable video- | "separate-audio" // audio or video → voice and background stems+ | "separate-audio" // audio or video → stems (meta.stem): voice and background; DBS also music and effects| "translate" // text → the same text in params.targetLanguage (LLM)| "write" // brief → text (LLM: scripts, ad copy, shot lists)| "vectorize" // image → the same picture as an SVG@@ -928,8 +928,9 @@ export interface ChainSlot {position?: "first" | "last";/*** Audio slots: take the dependency's output whose `meta.stem` is this (separate-audio makes- * "voice" and "background"; "voice" also matches vocals/speech/target, "background" also- * accompaniment/instrumental/residual/no_vocals). Without it, the first output of the slot's kind.+ * "voice" and "background", DBS also "music" and "effects"; "voice" also matches vocals/speech/target,+ * "background" also accompaniment/instrumental/residual/no_vocals, "effects" also sfx). Without it, the first+ * output of the slot's kind.*/stem?: string;/**diff --git a/src/lib/comfy.ts b/src/lib/comfy.tsindex db2fef51..b6e21177 100644--- a/src/lib/comfy.ts+++ b/src/lib/comfy.ts@@ -57,15 +57,15 @@ export interface ManifestModel {export interface ManifestOutput {node: string;kind: MediaKind;- /** Audio stems of a voice/background separation. */- stem?: "voice" | "background";+ /** Audio stems of a separation: voice / background, and DBS's music and effects. */+ stem?: "voice" | "background" | "music" | "effects";/*** What a text, image or 3D output is: timed caption cues, a plain transcript, the detected language, layers, a grid's sheet or tiles…* Round 4: OCR "lines" (JSON, boxes 0–1000) and the "frame" the model saw, an EXR sequence's "frames", a whole-"scene" GLB and its* "depth" map, a Gaussian "splat", a reference video's style "brief"; a painted eraser's last tracked "mask" (handed to the next* window), and a matte graph's "cutout" (transparent video) and "matte" (black and white) videos. A "preview" is the clip shown* for an EXR export (the frames ride along zipped). A "master" is a lossless copy a later job continues from (Character Swap- * Studio's segment, 16-bit FFV1).+ * Studio's segment, 16-bit FFV1). A "report" is a node's own account of the run (DBS: model, device, windows, seconds).*/role?:| "cues"@@ -87,7 +87,8 @@ export interface ManifestOutput {| "cutout"| "matte"| "preview"- | "master";+ | "master"+ | "report";}export interface ManifestWorkflow {diff --git a/src/lib/hubs.ts b/src/lib/hubs.tsindex e983a067..d6e0b1a5 100644--- a/src/lib/hubs.ts+++ b/src/lib/hubs.ts@@ -19,6 +19,7 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {{ id: "voice-change", label: "Voice change" },{ id: "translate", label: "Translate" },{ id: "transcribe", label: "Transcribe" },+ { id: "split", label: "Split soundtrack" },{ id: "sfx", label: "Sound effects" },{ id: "music", label: "Music" },{ id: "loop", label: "Loop / extend" },diff --git a/src/lib/licences.ts b/src/lib/licences.tsindex f1690323..4ce9d933 100644--- a/src/lib/licences.ts+++ b/src/lib/licences.ts@@ -431,10 +431,42 @@ export const NODE_PACKS: NodePack[] = [...GPL,note: "H3 Relay 2.0 (Sendy Software LLC and contributors); GPL-3.0 code, vendored Context Loop and Spectrum GPL-3.0. Opt-in (H3_RELAY=1): it registers HTTP routes when it loads",}),+ // DBS soundtrack separation (docs/research/dbs-separation-7.md §3.2), pinned in install-comfyui.sh.+ pack("ComfyUI-DBS", "https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/f656e53434b5485c148a2866fbd6ddc6b6152ed6", {+ name: "MIT",+ class: "commercial",+ url: SPDX("MIT"),+ note: "Dialogue / music / effects separation; MIT code, vendored DBS code Apache-2.0 with MIT notices; the DBS weights are Apache-2.0, trained on DnR v2 (CC BY 4.0)",+ }),];export const nodePack = (name: string): NodePack | undefined => NODE_PACKS.find((p) => p.name === name);+/**+ * Credits About & licences shows: attributions a licence asks for (CC BY) and the notices that ship with code Fuobe+ * installs (the MIT notices kept in DBS's THIRD_PARTY.md). Information, like everything here.+ */+export interface Attribution {+ /** What it is for, as the list names it. */+ for: string;+ /** The credit, as it should read. */+ text: string;+ licence: string;+ url?: string;+}++export const ATTRIBUTIONS: Attribution[] = [+ {+ for: "DBS (dialogue, music, effects)",+ text: "Trained on the Divide and Remaster (DnR) v2 dataset by Darius Petermann, Gordon Wichern, Zhong-Qiu Wang and Jonathan Le Roux",+ licence: "CC BY 4.0",+ url: "https://zenodo.org/records/6949108",+ },+ { for: "DBS (vendored code)", text: "BS-RoFormer, copyright (c) 2023 Phil Wang", licence: "MIT", url: "https://github.com/lucidrains/BS-RoFormer" },+ { for: "DBS (vendored code)", text: "Music-Source-Separation-Training, copyright (c) 2024 Roman Solovyev (ZFTurbo)", licence: "MIT", url: "https://github.com/ZFTurbo/Music-Source-Separation-Training" },+ { for: "DBS (vendored code)", text: "TIGER / Look2Hear, copyright (c) 2026 Kai Li", licence: "MIT", url: "https://github.com/JusperLee/TIGER" },+];+/** The parts of a LoRA's licence snapshot the class needs (src/lib/catalog/types.ts LoraLicence). */interface LoraLicenceLike {commercial: boolean;diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.tsindex ae542713..d9ab6c1f 100644--- a/src/lib/media-probe.ts+++ b/src/lib/media-probe.ts@@ -20,6 +20,8 @@ export interface MediaInfo {frames?: number;hasVideo: boolean;hasAudio: boolean;+ /** Audio channels, where the header says (WAV, FLAC, MP3); unset for MP4 and the rest. */+ channels?: number;}const fourcc = (b: Uint8Array, o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);@@ -201,13 +203,17 @@ function probeIsoBmff(data: Uint8Array): MediaInfo | null {function probeWav(data: Uint8Array): MediaInfo | null {const d = new DataView(data.buffer, data.byteOffset, data.byteLength);let byteRate = 0;+ let channels = 0;for (let o = 12; o + 8 <= data.length; ) {const id = fourcc(data, o);let size = d.getUint32(o + 4, true);- if (id === "fmt ") byteRate = d.getUint32(o + 16, true);+ if (id === "fmt ") {+ channels = d.getUint16(o + 10, true);+ byteRate = d.getUint32(o + 16, true);+ }if (id === "data") {if (!size || size === 0xffffffff || o + 8 + size > data.length) size = data.length - o - 8; // streamed header- return byteRate ? { container: "wav", duration: size / byteRate, hasVideo: false, hasAudio: true } : null;+ return byteRate ? { container: "wav", duration: size / byteRate, hasVideo: false, hasAudio: true, ...(channels > 0 && { channels }) } : null;}o += 8 + size + (size % 2);}@@ -215,12 +221,13 @@ function probeWav(data: Uint8Array): MediaInfo | null {}function probeFlac(data: Uint8Array): MediaInfo | null {- // STREAMINFO is always the first metadata block: 20-bit sample rate, 36-bit total samples.+ // STREAMINFO is always the first metadata block: 20-bit sample rate, 3-bit channels - 1, 36-bit total samples.const o = 8 + 10;const rate = (data[o] << 12) | (data[o + 1] << 4) | (data[o + 2] >> 4);+ const channels = ((data[o + 2] >> 1) & 0x07) + 1;const total = (data[o + 3] & 0x0f) * 2 ** 32 + ((data[o + 4] << 24) >>> 0) + (data[o + 5] << 16) + (data[o + 6] << 8) + data[o + 7];if (!rate) return null;- return { container: "flac", ...(total ? { duration: total / rate } : {}), hasVideo: false, hasAudio: true };+ return { container: "flac", ...(total ? { duration: total / rate } : {}), hasVideo: false, hasAudio: true, channels };}const MP3_BITRATES: Record<string, number[]> = {@@ -248,8 +255,8 @@ function probeMp3(data: Uint8Array): MediaInfo | null {const tag = fourcc(data, x);if ((tag === "Xing" || tag === "Info") && data[x + 7] & 1) {const frames = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(x + 8);- return { container: "mp3", duration: (frames * samplesPerFrame) / rate, hasVideo: false, hasAudio: true };+ return { container: "mp3", duration: (frames * samplesPerFrame) / rate, hasVideo: false, hasAudio: true, channels: mono ? 1 : 2 };}if (!bitrate) return null;- return { container: "mp3", duration: ((data.length - o) * 8) / bitrate, hasVideo: false, hasAudio: true };+ return { container: "mp3", duration: ((data.length - o) * 8) / bitrate, hasVideo: false, hasAudio: true, channels: mono ? 1 : 2 };}diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 71eeeeb1..552bb13e 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -26,6 +26,7 @@ export type OutputActionId =| "genjutsu"| "voice-change"| "loop-audio"+ | "split-soundtrack"| "copy-text"| "view-3d"| "download"@@ -118,6 +119,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =link("lipsync", "Lipsync", `/lipsync?video=${q(o.url)}`);link("upscale", "Upscale", `/upscale/video?video=${q(o.url)}`);link("add-sound", "Add sound", `/audio/video?video=${q(o.url)}`);+ link("split-soundtrack", "Split soundtrack", `/audio/split?video=${q(o.url)}`);// A Fuobe DoP colour-grade effect: the clip opens in Color grading with its grade picked (one click to export).const dopGrade = gradeOf(o);link("grade", dopGrade ? `Apply the ${dopGrade.name} grade` : "Color grade", `/color-grade?video=${q(o.url)}${dopGrade ? `&preset=${q(dopGrade.id)}` : ""}`);@@ -129,6 +131,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =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)}`);+ link("split-soundtrack", "Split soundtrack", `/audio/split?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" });@@ -163,8 +166,10 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =const NEXT_STEPS: Partial<Record<OutputFile["kind"], OutputActionId[]>> = {image: ["animate", "upscale", "edit"],video: ["extend", "upscale", "add-sound"],- audio: ["lipsync", "voice-change"],+ audio: ["lipsync", "voice-change", "split-soundtrack"],};+/** Clips made with their sound (or keeping the source's): Split soundtrack instead of Add sound. */+const SOUNDED_VIDEO_OPS = new Set<Generation["op"]>(["v2a", "mux", "lipsync", "trim", "captions"]);/*** Up to `max` next steps for output `index` (Animate, Upscale, Edit for a picture), taken from@@ -175,7 +180,8 @@ export function nextSteps(g: Generation, index: number, max = 3): OutputAction[]if (!o || g.status !== "succeeded") return [];const all = outputActions(g, index);// A clip with a grade still to apply (a Fuobe DoP colour-grade effect) offers it first.- const order: OutputActionId[] = o.kind === "video" && gradeOf(o) ? ["grade", ...(NEXT_STEPS.video ?? [])] : (NEXT_STEPS[o.kind] ?? []);+ const video = o.kind === "video" && g.op && SOUNDED_VIDEO_OPS.has(g.op) ? (NEXT_STEPS.video ?? []).map((id) => (id === "add-sound" ? "split-soundtrack" : id)) : NEXT_STEPS.video;+ const order: OutputActionId[] = o.kind === "video" ? [...(gradeOf(o) ? (["grade"] as const) : []), ...(video ?? [])] : (NEXT_STEPS[o.kind] ?? []);return order.map((id) => all.find((a) => a.id === id && a.href)).filter((a): a is OutputAction => !!a)diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.tsindex d719ad61..c5d44c63 100644--- a/src/server/audio-tools.ts+++ b/src/server/audio-tools.ts@@ -2,18 +2,21 @@ import "server-only";import fs from "node:fs/promises";import { z } from "zod";import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";+import { CLOUD_ONLY_PROBLEM, dbsChannelsFor, hostPick, planRemux, planSplit, splitTime } from "@/lib/av/split";import type { Engine, Generation } from "@/lib/catalog/types";import { probeMedia } from "@/lib/media-probe";import { createPipeline } from "./chains";import { previewChained } from "./generations";+import { comfyDevice } from "./providers/comfyui";import { engineMode } from "./settings";import { absolutePath } 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.+ * The Audio hub's Loop / extend, Join and Split soundtrack 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 or src/lib/av/split.ts is priced step by step, and a run is one createPipeline batch, so its+ * results land in the Library like any generation. Split soundtrack runs on the open engine only (DBS isn't hosted);+ * its mix goes back on the video with a "remux" run on either engine.*/const FileUrl = z.string().startsWith("/api/files/").max(500);@@ -40,23 +43,63 @@ export const AudioToolBody = z.discriminatedUnion("tool", [crossfade: Crossfade,curve: Curve,}),+ z.object({+ tool: z.literal("split"),+ engine: Engine,+ media: FileUrl,+ kind: z.enum(["audio", "video"]),+ name: z.string().max(200).optional(),+ /** Fast (DBS-BSRNN) or Best (DBS-TIGER); unset = the host's pick. */+ quality: z.enum(["fast", "best"]).optional(),+ stereo: z.boolean().optional(),+ /** What the browser decoded (the server reads WAV / FLAC / MP3 headers itself). */+ channels: z.number().int().positive().max(64).optional(),+ sourceDuration: z.number().positive().max(36_000).optional(),+ }),+ z.object({+ tool: z.literal("remux"),+ engine: Engine,+ video: FileUrl,+ audio: FileUrl,+ name: z.string().max(200).optional(),+ }),]);export type AudioToolRequest = z.infer<typeof AudioToolBody>;export class AudioToolError extends Error {}+/** What a clip's header says. */+interface ClipFacts {+ duration?: number;+ channels?: number;+}+declare global {- var __fuobeAudioLengths: Map<string, number | null> | undefined;+ var __fuobeAudioFacts: Map<string, ClipFacts | null> | undefined;}/*** Lengths already read, by file and version (path, size, modified time): the page asks for a price after* every settled change, and a Join of big WAVs would read every file again each time.*/-const lengths = (globalThis.__fuobeAudioLengths ??= new Map<string, number | null>());+const lengths = (globalThis.__fuobeAudioFacts ??= new Map<string, ClipFacts | null>());const LENGTHS_KEPT = 500;/** A clip's length from its header (WAV, FLAC, MP3, M4A), else the browser's. Read without blocking the server. */async function lengthOf(url: string, given?: number): Promise<number | undefined> {+ return (await factsOf(url))?.duration ?? given;+}++/** Throws `gone` unless the file is still in storage. */+async function present(url: string, gone: string): Promise<void> {+ try {+ if (!(await fs.stat(absolutePath(decodeURIComponent(url.slice("/api/files/".length))))).isFile()) throw new Error("not a file");+ } catch {+ throw new AudioToolError(gone);+ }+}++/** A clip's length and channel count from its header (cached by file version), or null when the header says neither. */+async function factsOf(url: string): Promise<ClipFacts | null> {let file: string;let key: string;try {@@ -76,15 +119,29 @@ async function lengthOf(url: string, given?: number): Promise<number | undefined}const info = probeMedia(data);if (lengths.size >= LENGTHS_KEPT) lengths.delete(lengths.keys().next().value!);- lengths.set(key, info?.duration && info.duration > 0 ? Math.round(info.duration * 1000) / 1000 : null);+ const duration = info?.duration && info.duration > 0 ? Math.round(info.duration * 1000) / 1000 : undefined;+ lengths.set(key, duration || info?.channels ? { ...(duration && { duration }), ...(info?.channels && { channels: info.channels }) } : null);}- return lengths.get(key) ?? given;+ return lengths.get(key) ?? null;}-async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine }> {+async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine; split?: ClipFacts }> {const mode = engineMode();+ // Split soundtrack runs on the open engine only: an install set to paid APIs only says why, whichever engine was asked for.+ if (body.tool === "split" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_PROBLEM);if (mode !== "both" && body.engine !== mode) throw new AudioToolError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");try {+ if (body.tool === "split") {+ const facts = await factsOf(body.media);+ const seconds = facts?.duration ?? body.sourceDuration;+ const channels = facts?.channels ?? body.channels;+ return { engine: body.engine, ...planSplit({ ...body, seconds, channels }), split: { duration: seconds, channels } };+ }+ if (body.tool === "remux") {+ await present(body.audio, "That mix is gone — export it again");+ await present(body.video, "That video is gone — add it again");+ return { engine: body.engine, ...planRemux(body) };+ }if (body.tool === "loop") {const sourceDuration = await lengthOf(body.audio, body.sourceDuration);return { engine: body.engine, ...planLoop({ ...body, sourceDuration: sourceDuration ?? 0 }) };@@ -111,7 +168,16 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToodemo ||= 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 };+ const out: AudioToolPreview = { summary: p.summary, notes: p.notes, length: p.length, steps: p.steps.length, costUsd: cost === null ? null : Math.round(cost * 1000) / 1000, demo };+ if (body.tool === "split") {+ // How long it takes on this host: its device (asked once a minute), the model it would use and how many passes.+ const device = demo ? undefined : await comfyDevice().catch(() => undefined);+ const quality = body.quality ?? hostPick(device);+ const { duration: seconds, channels } = p.split ?? {};+ Object.assign(out, { hostPick: hostPick(device), ...(device && { device }) });+ if (seconds) out.estimate = splitTime({ seconds, quality, mode: dbsChannelsFor(body.stereo ? "each channel" : "mono", channels), channels, device });+ }+ return out;}/** Start a run: one batch; the last step's generation is the result. */diff --git a/src/server/generations.ts b/src/server/generations.tsindex 0f339ba1..6bca38a8 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -801,10 +801,12 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {prompt: "text",};-/** Names providers give the same stem (ComfyUI: voice/background; Demucs: vocals…; SAM Audio: target/residual). */+/** Names providers give the same stem (ComfyUI: voice/background, DBS also music/effects; Demucs: vocals…; SAM Audio: target/residual). */const STEM_ALIASES: Record<string, string[]> = {voice: ["voice", "vocals", "speech", "target"],background: ["background", "accompaniment", "instrumental", "residual", "no_vocals"],+ music: ["music"],+ effects: ["effects", "sfx"],};/**diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex b3d4a3a9..c095c887 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -36,6 +36,7 @@ import {} from "@/lib/comfy";import { fpsPlan } from "@/lib/av/fps";import { crossfadeProblem, fadeCurveWav } from "@/lib/av/crossfade";+import { dbsChannelsFor, dbsModelFor } from "@/lib/av/split";import { expandAudioJoinWorkflow, expandVideoJoinWorkflow } from "@/lib/av/joins";import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";import { exportValues, exrWorkflow, framesPerPass, hdrColorSpace, upscaleShortSide, wholeClipProblem, wholeClipTool } from "@/lib/av/video-finish";@@ -449,6 +450,27 @@ export async function probeComfy(force = false): Promise<boolean> {return sharedCheck("comfy", url, () => checkComfy(url));}+declare global {+ /** The torch device each ComfyUI address reported last (GET /system_stats devices[0].type), and when. */+ var __fuobeComfyDevice: Map<string, { type?: string; at: number }> | undefined;+}++/**+ * The connected ComfyUI's first torch device type ("cuda" for NVIDIA and ROCm, "cpu", "mps"…), from GET /system_stats+ * (devices[0], as Settings' test reads it), kept for a minute; undefined when the server doesn't say or can't be reached.+ */+export async function comfyDevice(worker: ComfyWorker = "main"): Promise<string | undefined> {+ const url = baseUrl(worker);+ if (!url) return undefined;+ const cache = (globalThis.__fuobeComfyDevice ??= new Map());+ const hit = cache.get(url);+ if (hit && Date.now() - hit.at < 60_000) return hit.type;+ const s = await comfyJson<{ devices?: { type?: unknown }[] }>("/system_stats", worker).catch(() => undefined);+ const type = typeof s?.devices?.[0]?.type === "string" ? (s.devices[0].type as string) : undefined;+ if (s) cache.set(url, { type, at: Date.now() });+ return type;+}+/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */export function comfyRam(): number | undefined {const cur = globalThis.__fuobeComfyReach;@@ -595,6 +617,8 @@ export interface PrepareContext {media?: (name: string) => MediaInfo | undefined;/** The ComfyUI server's RAM in bytes, for graphs that hold a whole clip in memory. */serverRam?: () => Promise<number | undefined>;+ /** The server's first torch device type ("cuda", "cpu", "mps"…; GET /system_stats devices[0].type): DBS picks its model by it. */+ device?: () => Promise<string | undefined>;/*** The route puts the run's one LoRA in the graph's own LoRA slot (ModelRoute.loraSlot: Fuobe Speak's FusioniX on kijai's* InfiniteTalk graph, with the settings it goes with). Without it a graph with no model loader refuses a LoRA.@@ -1083,6 +1107,11 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,// A Video concatenator clip muted in the canvas (video-fit-clip): its sound becomes silence below.const muted = manifest.id === "video-fit-clip" && extra.mute === true;delete extra.mute;+ // DBS (separate-soundtrack-dbs): the model asked for, else the host's pick (DBS-TIGER on a CUDA GPU, DBS-BSRNN on a+ // CPU); "each channel" for stereo stems, and always for more than 2 channels (the header's count, else the browser's).+ if (b.separationModel) values.separationModel = dbsModelFor(extra.separationModel, extra.separationModel ? undefined : await ctx.device?.().catch(() => undefined));+ if (b.channels) values.channels = dbsChannelsFor(extra.channels, ctx.media?.(String(values.audio ?? ""))?.channels ?? (Number(extra.sourceChannels) || undefined));+ for (const k of ["separationModel", "channels", "sourceChannels"]) delete extra[k];for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;if (audio2 && ctx.op !== "dialogue" && ctx.op !== "voice-change") values.audio2 = audio2;// Soundtrack mix: a silent bed as long as the video, so neither track cuts the other short.@@ -1361,6 +1390,7 @@ export const comfyProvider: ProviderAdapter = {upload: (data, contentType, name) => uploadTo(worker, data, contentType, name),media: mediaInfoFor,serverRam: async () => (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats", worker).catch(() => undefined))?.system?.ram_total,+ device: () => comfyDevice(worker),});const { clientId } = ensureSocket(worker);const res = await comfyFetch(diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.tsindex 4b401f9b..ac9fc5d3 100644--- a/src/server/providers/mock.ts+++ b/src/server/providers/mock.ts@@ -285,10 +285,11 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,case "write":return [demoWrite(brief)];case "separate-audio": {- const stems: DemoOutput[] = [- { url: toDataUri(demoWav(3, [220, 330], 3), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: "voice", demo: true } },- { url: toDataUri(demoWav(3, [110, 165]), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: "background", demo: true } },- ];+ const stem = (name: string, wav: Buffer): DemoOutput => ({ url: toDataUri(wav, "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: name, demo: true } });+ // A dialogue / music / effects split (DBS) returns those three and the music-and-effects bed, voice first.+ const stems: DemoOutput[] = meta.threeStems+ ? [stem("voice", demoWav(3, [220, 330], 3)), stem("music", demoWav(3, [262, 392])), stem("effects", demoWav(3, [90, 140], 7)), stem("background", demoWav(3, [110, 165]))]+ : [stem("voice", demoWav(3, [220, 330], 3)), stem("background", demoWav(3, [110, 165]))];// Workflows that also time the voice stem (the open dub's first step) return its cues too.if (meta.transcript) {const cues = demoCues("");@@ -412,6 +413,8 @@ export const mockProvider: ProviderAdapter = {master: route.provider === "comfyui" && route.endpoint === "video-character-swap-h3-segment",// A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).transcript: route.op === "separate-audio" && route.provider === "comfyui" && route.endpoint.includes("transcribe"),+ // A dialogue / music / effects split (ComfyUI's separate-soundtrack-dbs): four stems.+ threeStems: route.op === "separate-audio" && route.endpoint === "separate-soundtrack-dbs",},payload: { demo: true, ...input },};diff --git a/tests/chain-soundtrack.test.ts b/tests/chain-soundtrack.test.tsindex 5a2d0872..267a44a4 100644--- a/tests/chain-soundtrack.test.ts+++ b/tests/chain-soundtrack.test.ts@@ -28,6 +28,18 @@ describe("pickOutput: which output of an earlier step a chained slot takes", ()expect(pickOutput([voice, bed], { slot: "audio2", stem: "voice" })).toBe(voice);});+ it("DBS's music and effects stems answer by name, effects also as sfx; background never takes either", () => {+ const stem = (s: string): OutputFile => ({ url: `/api/files/${s}.flac`, kind: "audio", contentType: "audio/flac", meta: { stem: s } });+ const [speech, music, sfx, effects, background] = ["speech", "music", "sfx", "effects", "background"].map(stem);+ expect(pickOutput([speech, music, sfx], { slot: "audio", stem: "music" })).toBe(music);+ expect(pickOutput([speech, music, sfx], { slot: "audio", stem: "effects" })).toBe(sfx);+ expect(pickOutput([speech, music, effects, background], { slot: "audio", stem: "Effects" })).toBe(effects);+ expect(pickOutput([speech, music, sfx], { slot: "audio2", stem: "background" })).toBeUndefined();+ expect(pickOutput([speech, music, sfx, background], { slot: "audio2", stem: "background" })).toBe(background);+ // Without a stem the first audio output: DBS puts the dialogue first.+ expect(pickOutput([speech, music, sfx, background], { slot: "audio" })).toBe(speech);+ });+it("other slots are unchanged: a video slot takes a video, an image slot an image, never a stand-in", () => {expect(pickOutput([still, clip], { slot: "video" })).toBe(clip);expect(pickOutput([voice], { slot: "video" })).toBeUndefined();diff --git a/tests/comfy-dbs.test.ts b/tests/comfy-dbs.test.tsnew file mode 100644index 00000000..5ebf875d--- /dev/null+++ b/tests/comfy-dbs.test.ts@@ -0,0 +1,218 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { GenInput } from "@/lib/catalog/types";+import type { ComfyWorkflow, Manifest, ManifestWorkflow } from "@/lib/comfy";+import { installScript, nodeInstall } from "@/lib/comfy-install";+import { ATTRIBUTIONS, licenceInfo, nodePack, workflowLicence } from "@/lib/licences";+import type { MediaInfo } from "@/lib/media-probe";++// DBS D1's ground on the open engine: the pinned pack and weights, graph A (separate-soundtrack-dbs) in the manifest,+// the folder models, the licence rows, and how the provider fills the model and channel bindings.+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-comfy-dbs-"));+process.env.FUOBE_DATA_DIR = tmp;+process.env.COMFYUI_URL = "http://comfy.test:8188";+const { collectOutputs, prepareWorkflow } = await import("@/server/providers/comfyui");+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));++const root = path.resolve(__dirname, "..");+const manifest = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/manifest.json"), "utf8")) as Manifest;+const entry = manifest.workflows.find((w) => w.id === "separate-soundtrack-dbs") as ManifestWorkflow;+const graph = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/separate-soundtrack-dbs.json"), "utf8")) as ComfyWorkflow;+const install = fs.readFileSync(path.join(root, "scripts/comfy/install-comfyui.sh"), "utf8");++const PACK = "f656e53434b5485c148a2866fbd6ddc6b6152ed6";+const BSRNN = "5af343f57f106fbb95efe8a60f1a3999eeb0aef8";+const TIGER = "22da7d4cd3ea63f9365181008bff1c0d2ab6fb2b";++describe("separate-soundtrack-dbs in the manifest", () => {+ it("binds the audio, the DBS model and the channel mode, with BSRNN and mono as defaults", () => {+ expect(entry).toMatchObject({ capability: "separate-audio", vramGb: 0, validated: true });+ expect(entry.bindings.audio).toEqual([{ node: "1", input: "audio" }]);+ expect(entry.bindings.separationModel).toEqual([{ node: "2", input: "model" }]);+ expect(entry.bindings.channels).toEqual([{ node: "3", input: "channels" }]);+ expect(entry.defaults).toEqual({ separationModel: "DBS-BSRNN-DnR", channels: "mono" });+ expect(entry.notes).toMatch(/^CPU OK, about 1\.7 GiB on CUDA\./);+ expect(entry.license).toBe("DBS weights Apache-2.0 (JusperLee; trained on DnR v2, CC BY 4.0); ComfyUI-DBS code MIT; vendored DBS code Apache-2.0 with MIT notices (BS-RoFormer, MSST, TIGER)");+ });++ it("outputs voice, music, effects, background and the report, in that order", () => {+ expect(entry.outputs).toEqual([+ { node: "5", kind: "audio", stem: "voice" },+ { node: "6", kind: "audio", stem: "music" },+ { node: "7", kind: "audio", stem: "effects" },+ { node: "8", kind: "audio", stem: "background" },+ { node: "9", kind: "text", role: "report" },+ ]);+ });++ it("is graph A: speech, music and sfx at the input's rate, the background as the original minus the speech, FLAC stems", () => {+ expect(Object.fromEntries(Object.entries(graph).map(([id, n]) => [id, n.class_type]))).toEqual({+ "1": "LoadAudio",+ "2": "DBSLoader",+ "3": "DBSSeparate",+ "4": "AudioMerge",+ "5": "SaveAudioAdvanced",+ "6": "SaveAudioAdvanced",+ "7": "SaveAudioAdvanced",+ "8": "SaveAudioAdvanced",+ "9": "PreviewAny",+ });+ expect(graph["2"].inputs).toEqual({ model: "DBS-BSRNN-DnR", device: "auto" });+ expect(graph["3"].inputs).toEqual({ model: ["2", 0], audio: ["1", 0], channels: "mono", output_sample_rate: "input" });+ expect(graph["4"].inputs).toEqual({ audio1: ["1", 0], audio2: ["3", 2], merge_method: "subtract" });+ // DBSSeparate's outputs: 0 music, 1 sfx, 2 speech, 3 report.+ expect(["5", "6", "7", "8"].map((id) => graph[id].inputs.audio)).toEqual([["3", 2], ["3", 0], ["3", 1], ["4", 0]]);+ expect(["5", "6", "7", "8"].every((id) => graph[id].inputs.format === "flac")).toBe(true);+ expect(graph["9"].inputs.source).toEqual(["3", 3]);+ });++ it("lists the BSRNN pair as required and the TIGER pair as optional, under models/dbs, at pinned revisions", () => {+ expect(entry.models).toEqual([+ { file: "DBS-BSRNN-DnR/model.safetensors", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/model.safetensors`, sizeGb: 0.019 },+ { file: "DBS-BSRNN-DnR/config.json", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/config.json`, sizeGb: 0 },+ { file: "DBS-TIGER-DnR/model.safetensors", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/model.safetensors`, sizeGb: 0.004, optional: true },+ { file: "DBS-TIGER-DnR/config.json", folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/config.json`, sizeGb: 0, optional: true },+ ]);+ expect(entry.customNodes).toEqual([{ name: "ComfyUI-DBS", repo: `https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/${PACK}` }]);+ });++ it("copies install commands that clone the pack at its pin and make each model's folder first", () => {+ const script = installScript({ ...entry, models: entry.models.map((m) => ({ ...m, present: false })) });+ expect(script).toContain(nodeInstall({ name: "ComfyUI-DBS", repo: `https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/${PACK}` }));+ expect(script).toContain(`git -C "$COMFYUI/custom_nodes/ComfyUI-DBS" checkout -q ${PACK}`);+ expect(script).toContain(`mkdir -p "$COMFYUI/models/dbs/DBS-BSRNN-DnR" && wget -c -O "$COMFYUI/models/dbs/DBS-BSRNN-DnR/model.safetensors" "https://huggingface.co/JusperLee/DBS-BSRNN-DnR/resolve/${BSRNN}/model.safetensors"`);+ expect(script).toContain('"$COMFYUI/models/dbs/DBS-BSRNN-DnR/config.json"');+ // TIGER is optional: named on the card, not installed by default.+ expect(script).not.toContain("DBS-TIGER-DnR");+ });+});++describe("install-comfyui.sh", () => {+ it("pins ComfyUI-DBS and records the Registry flag", () => {+ expect(install).toContain(`[ComfyUI-DBS]="https://github.com/hiroki-abe-58/ComfyUI-DBS ${PACK}"`);+ expect(install).toMatch(/Comfy Registry flags its only version \(0\.1\.0/);+ });++ it("fetches the four weight files at their revisions into models/dbs/<model>/ and checks their SHA-256 (DBS_WEIGHTS=0 skips it)", () => {+ const block = install.slice(install.indexOf("# --- DBS weights"), install.indexOf("# --- end DBS weights"));+ expect(block).toContain('if [ "${DBS_WEIGHTS:-1}" = "1" ]; then');+ expect(block).toContain(`"DBS-BSRNN-DnR ${BSRNN}"`);+ expect(block).toContain(`"DBS-TIGER-DnR ${TIGER}"`);+ expect(block).toContain("https://huggingface.co/JusperLee/$name/resolve/$rev/$f");+ expect(block).toContain("sha256sum -c");+ for (const line of [+ "26290f93e7b501113325e922e7b0c18edca944634e6b9be39856a55204628405 DBS-BSRNN-DnR/model.safetensors",+ "57055e2b71913d98a4e1ed426b71617f0dfc372901cc5a8a3bc4a5c69415043e DBS-BSRNN-DnR/config.json",+ "3d8205743f2a6f5a6704f5d4104d7cf5bf7bf02dab2fd728da31f4c69225cadb DBS-TIGER-DnR/model.safetensors",+ "c7f7893323e78f9b99747a13090558a13c4f4b77383a38acb9979709fd04d1d8 DBS-TIGER-DnR/config.json",+ ])+ expect(block).toContain(line);+ });+});++describe("the library spec", async () => {+ const spec = await import("../scripts/comfy/library.spec.mjs");+ const build = await import("../scripts/comfy/build-library.mjs");++ it("knows the pack's classes and repository, the folder models and the new binding keys", () => {+ expect(spec.PACK_CLASSES["ComfyUI-DBS"].test("DBSLoader")).toBe(true);+ expect(spec.PACK_CLASSES["ComfyUI-DBS"].test("DBSSeparate")).toBe(true);+ expect(spec.PACK_CLASSES["ComfyUI-DBS"].test("DBSLoaderX")).toBe(false);+ expect(spec.CUSTOM_NODE_REPOS["ComfyUI-DBS"]).toBe(`https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/${PACK}`);+ expect(spec.KNOWN_MODELS["DBS-TIGER-DnR/model.safetensors"]).toEqual({ folder: "dbs", url: `https://huggingface.co/JusperLee/DBS-TIGER-DnR/resolve/${TIGER}/model.safetensors` });+ const e = spec.SPEC.find((s: { id: string }) => s.id === "separate-soundtrack-dbs");+ expect(e).toMatchObject({ packs: ["ComfyUI-DBS"], requiredModels: ["DBS-BSRNN-DnR/model.safetensors", "DBS-BSRNN-DnR/config.json"], optionalModels: ["DBS-TIGER-DnR/model.safetensors", "DBS-TIGER-DnR/config.json"] });+ expect(build.BINDING_KEYS.has("separationModel")).toBe(true);+ expect(build.BINDING_KEYS.has("channels")).toBe(true);+ });+});++describe("the provider fills the DBS bindings", () => {+ async function prepare(input: GenInput, opts: { device?: string; media?: Record<string, MediaInfo> } = {}) {+ let asked = 0;+ const res = await prepareWorkflow("separate-soundtrack-dbs", { seed: 1, ...input }, {+ generationId: "gen1",+ op: "separate-audio",+ upload: async (_d, _t, name) => `up_${name}`,+ media: (name) => opts.media?.[name],+ device: async () => {+ asked++;+ return opts.device;+ },+ });+ return { wf: res.workflow, asked };+ }++ it("uses DBS-BSRNN on a CPU host and DBS-TIGER on a CUDA one, unless the run picks a model", async () => {+ expect((await prepare({ audio: "film.wav" }, { device: "cpu" })).wf["2"].inputs.model).toBe("DBS-BSRNN-DnR");+ expect((await prepare({ audio: "film.wav" }, { device: "cuda" })).wf["2"].inputs.model).toBe("DBS-TIGER-DnR");+ expect((await prepare({ audio: "film.wav" })).wf["2"].inputs.model).toBe("DBS-BSRNN-DnR");+ const picked = await prepare({ audio: "film.wav", extra: { separationModel: "DBS-BSRNN-DnR" } }, { device: "cuda" });+ expect(picked.wf["2"].inputs.model).toBe("DBS-BSRNN-DnR");+ // The host isn't asked when the run says which model.+ expect(picked.asked).toBe(0);+ expect((await prepare({ audio: "film.wav", extra: { separationModel: "best" } }, { device: "cpu" })).wf["2"].inputs.model).toBe("DBS-TIGER-DnR");+ });++ it("separates the mono mix unless stereo stems are asked for, and each channel of a file with more than 2", async () => {+ expect((await prepare({ audio: "film.wav" })).wf["3"].inputs.channels).toBe("mono");+ expect((await prepare({ audio: "film.wav", extra: { channels: "each channel" } })).wf["3"].inputs.channels).toBe("each channel");+ const surround: MediaInfo = { container: "wav", duration: 10, hasVideo: false, hasAudio: true, channels: 6 };+ expect((await prepare({ audio: "film.wav", extra: { channels: "mono" } }, { media: { "film.wav": surround } })).wf["3"].inputs.channels).toBe("each channel");+ // An MP4 the header doesn't count: the channels the browser decoded.+ expect((await prepare({ video: "clip.mp4", extra: { sourceChannels: 6 } })).wf["3"].inputs.channels).toBe("each channel");+ expect((await prepare({ video: "clip.mp4", extra: { sourceChannels: 2 } })).wf["3"].inputs.channels).toBe("mono");+ });++ it("reads a video's soundtrack with LoadAudio and keeps the rest of the graph as built", async () => {+ const { wf } = await prepare({ video: "clip.mp4" });+ expect(wf["1"].inputs.audio).toBe("clip.mp4");+ expect(wf["3"].inputs.output_sample_rate).toBe("input");+ expect(["5", "6", "7", "8"].map((id) => wf[id].inputs.filename_prefix)).toEqual(Array(4).fill("fuobe/gen1"));+ // Nothing of the page's own keys reaches the graph.+ expect(JSON.stringify(wf)).not.toContain("sourceChannels");+ });+});++describe("a finished DBS job's outputs", () => {+ it("are the four FLAC stems, tagged and voice first, then the pack's report as text", () => {+ const flac = (n: string) => ({ audio: [{ filename: `gen1_${n}.flac`, subfolder: "fuobe", type: "output" }] });+ const report = JSON.stringify({ model: "DBS-BSRNN-DnR", device: "cpu", audio_seconds: 20, seconds: 73.7, times_real_time: 0.27 });+ const outs = collectOutputs({ outputs: { "8": flac("8"), "6": flac("6"), "5": flac("5"), "7": flac("7"), "9": { text: [report] } } } as never, entry, "http://comfy.test:8188");+ expect(outs.map((o) => [o.kind, o.meta?.stem ?? o.meta?.role])).toEqual([+ ["audio", "voice"],+ ["audio", "music"],+ ["audio", "effects"],+ ["audio", "background"],+ ["text", "report"],+ ]);+ expect(outs[4].text).toBe(report);+ });+});++describe("licences, as information", () => {+ it("records the ComfyUI-DBS pack (MIT) and gives the workflow's model row from its licence text", () => {+ expect(nodePack("ComfyUI-DBS")).toMatchObject({+ repo: `https://github.com/hiroki-abe-58/ComfyUI-DBS/tree/${PACK}`,+ licence: {+ name: "MIT",+ class: "commercial",+ note: "Dialogue / music / effects separation; MIT code, vendored DBS code Apache-2.0 with MIT notices; the DBS weights are Apache-2.0, trained on DnR v2 (CC BY 4.0)",+ },+ });+ expect(licenceInfo(workflowLicence(entry))).toMatchObject({ name: "Apache-2.0", class: "commercial" });+ });++ it("credits DnR v2 (CC BY 4.0) and the three MIT notices of the vendored code", () => {+ expect(ATTRIBUTIONS.find((a) => a.licence === "CC BY 4.0")?.text).toBe(+ "Trained on the Divide and Remaster (DnR) v2 dataset by Darius Petermann, Gordon Wichern, Zhong-Qiu Wang and Jonathan Le Roux",+ );+ expect(ATTRIBUTIONS.filter((a) => a.licence === "MIT").map((a) => a.text)).toEqual([+ "BS-RoFormer, copyright (c) 2023 Phil Wang",+ "Music-Source-Separation-Training, copyright (c) 2024 Roman Solovyev (ZFTurbo)",+ "TIGER / Look2Hear, copyright (c) 2026 Kai Li",+ ]);+ });+});diff --git a/tests/comfy-library-4.test.ts b/tests/comfy-library-4.test.tsindex 201bcf75..edc294ec 100644--- a/tests/comfy-library-4.test.ts+++ b/tests/comfy-library-4.test.ts@@ -60,6 +60,8 @@ const ROLES: NonNullable<ManifestOutput["role"]>[] = ["mask", "cutout", "matte",// Character Swap Studio: a segment's lossless master, which the next segment continues from."master",+ // DBS soundtrack separation: the pack's own report of the run (model, device, windows, seconds).+ "report",];describe("round-4 ComfyUI workflows", () => {diff --git a/tests/media-probe.test.ts b/tests/media-probe.test.tsindex be84a331..41686006 100644--- a/tests/media-probe.test.ts+++ b/tests/media-probe.test.ts@@ -62,8 +62,10 @@ describe("media probe", () => {});it("reads WAV, FLAC and MP3 lengths", () => {- expect(probeMedia(wav(2.5))).toEqual({ container: "wav", duration: 2.5, hasVideo: false, hasAudio: true });- expect(probeMedia(wav(1, 48000, 2))?.duration).toBe(1);+ expect(probeMedia(wav(2.5))).toEqual({ container: "wav", duration: 2.5, hasVideo: false, hasAudio: true, channels: 1 });+ expect(probeMedia(wav(1, 48000, 2))).toMatchObject({ duration: 1, channels: 2 });+ // Split soundtrack separates every channel of a 5.1 file on its own: the header says how many there are.+ expect(probeMedia(wav(1, 48000, 6))?.channels).toBe(6);// FLAC STREAMINFO: 44.1 kHz, 132300 samples = 3 sconst flac = Buffer.alloc(42);flac.write("fLaC", 0);@@ -75,7 +77,7 @@ describe("media probe", () => {flac[20] = ((rate & 0xf) << 4) | (1 << 1);flac[21] = 0xf0 | Math.floor(total / 2 ** 32);flac.writeUInt32BE(total >>> 0, 22);- expect(probeMedia(flac)).toEqual({ container: "flac", duration: 3, hasVideo: false, hasAudio: true });+ expect(probeMedia(flac)).toEqual({ container: "flac", duration: 3, hasVideo: false, hasAudio: true, channels: 2 });// MP3 with a Xing header: MPEG-1 Layer III, 44.1 kHz stereo, 100 frames × 1152 samplesconst mp3 = Buffer.alloc(417 * 3);mp3.set([0xff, 0xfb, 0x90, 0x00], 0);@@ -83,6 +85,7 @@ describe("media probe", () => {mp3.writeUInt32BE(1, 4 + 32 + 4);mp3.writeUInt32BE(100, 4 + 32 + 8);expect(probeMedia(mp3)?.duration).toBeCloseTo((100 * 1152) / 44100, 6);+ expect(probeMedia(mp3)?.channels).toBe(2);// CBR without a header: 128 kbps → bytes × 8 / bitrateconst cbr = Buffer.alloc(16000);cbr.set([0xff, 0xfb, 0x90, 0x00], 0);diff --git a/tests/outputs.test.ts b/tests/outputs.test.tsindex da40cba5..fff654fa 100644--- a/tests/outputs.test.ts+++ b/tests/outputs.test.ts@@ -211,6 +211,18 @@ describe("3D models, stems and other extras", () => {]);});+ it("stems sort voice first, then music and effects (DBS names), then instruments and the backgrounds", () => {+ const res = {+ residual: file("https://v3.fal.media/files/rest.wav", "audio/wav"),+ effects: file("https://v3.fal.media/files/fx.wav", "audio/wav"),+ drums: file("https://v3.fal.media/files/drums.wav", "audio/wav"),+ music: file("https://v3.fal.media/files/music.wav", "audio/wav"),+ sfx: file("https://v3.fal.media/files/sfx.wav", "audio/wav"),+ speech: file("https://v3.fal.media/files/speech.wav", "audio/wav"),+ };+ expect(extractOutputs(res, "separate-audio").map((o) => o.meta?.stem)).toEqual(["speech", "music", "sfx", "effects", "drums", "residual"]);+ });+it("keeps Recraft's new style id and puts Bria's matte on the cut-out", () => {expect(extractOutputs({ images: [file("https://v3.fal.media/files/a.png", "image/png")], style_id: "style-9" }, "t2i")[0].meta).toEqual({ styleId: "style-9" });const cut = extractOutputs({ image: file("https://v3.fal.media/files/cut.png", "image/png"), mask: file("https://v3.fal.media/files/mask.png", "image/png") }, "edit");diff --git a/tests/split-soundtrack.test.ts b/tests/split-soundtrack.test.tsnew file mode 100644index 00000000..a8ea34f2--- /dev/null+++ b/tests/split-soundtrack.test.ts@@ -0,0 +1,340 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import {+ CLOUD_ONLY_PROBLEM,+ CLOUD_SPLIT_PROBLEM,+ clampDb,+ dbLabel,+ dbsChannelsFor,+ dbsModelFor,+ dbToGain,+ DBS_SPEED,+ durationWords,+ encodeWav,+ headroomGain,+ hostPick,+ mixName,+ ORIGINAL_MIX,+ planRemux,+ planSplit,+ presetOf,+ PRESETS,+ setLevel,+ setMute,+ setSolo,+ splitTime,+ STEMS,+ stemGains,+ type Mix,+} from "@/lib/av/split";+import { getModel } from "@/lib/catalog";+import { HUB_MODES, modeHref } from "@/lib/hubs";++// Audio → Split soundtrack (DBS D1): the planner, the mixer maths and the API in demo mode.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-split-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: the open model runs on the demo provider.+process.env.COMFYUI_URL = "http://127.0.0.1:9";++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 16-bit WAV of a tone with `channels` channels, saved as an upload. */+function upload(seconds: number, channels = 2, name = "film.wav"): string {+ const rate = 8000;+ const n = Math.round(seconds * rate);+ const buf = Buffer.alloc(44 + n * 2 * channels);+ buf.write("RIFF", 0);+ buf.writeUInt32LE(36 + n * 2 * channels, 4);+ buf.write("WAVEfmt ", 8);+ buf.writeUInt32LE(16, 16);+ buf.writeUInt16LE(1, 20);+ buf.writeUInt16LE(channels, 22);+ buf.writeUInt32LE(rate, 24);+ buf.writeUInt32LE(rate * 2 * channels, 28);+ buf.writeUInt16LE(2 * channels, 32);+ buf.writeUInt16LE(16, 34);+ buf.write("data", 36);+ buf.writeUInt32LE(n * 2 * channels, 40);+ return saveFile({ data: buf, contentType: "audio/wav", name, source: "upload" }).url;+}++const post = (body: unknown, preview = false) =>+ route.POST(new Request(`http://x/api/audio-tools${preview ? "?preview=1" : ""}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));++async function finished(id: string) {+ const deadline = Date.now() + 15_000;+ let g = gens.getGeneration(id)!;+ while (g.status !== "succeeded" && g.status !== "failed" && Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 200));+ g = gens.getGeneration(id)!;+ }+ return g;+}++describe("the DBS model and channels a run gets", () => {+ it("picks DBS-TIGER on a CUDA host and DBS-BSRNN otherwise, unless one is asked for", () => {+ expect(hostPick("cuda")).toBe("best");+ expect(hostPick("cpu")).toBe("fast");+ expect(hostPick("mps")).toBe("fast");+ expect(hostPick(undefined)).toBe("fast");+ expect(dbsModelFor(undefined, "cuda")).toBe("DBS-TIGER-DnR");+ expect(dbsModelFor(undefined, "cpu")).toBe("DBS-BSRNN-DnR");+ expect(dbsModelFor("fast", "cuda")).toBe("DBS-BSRNN-DnR");+ expect(dbsModelFor("best", "cpu")).toBe("DBS-TIGER-DnR");+ expect(dbsModelFor("DBS-TIGER-DnR", "cpu")).toBe("DBS-TIGER-DnR");+ expect(dbsModelFor("something else", "cpu")).toBe("DBS-BSRNN-DnR");+ });++ it("separates the mono mix unless stereo stems are asked for, and every channel of anything over two", () => {+ expect(dbsChannelsFor(undefined, 2)).toBe("mono");+ expect(dbsChannelsFor("mono", 1)).toBe("mono");+ expect(dbsChannelsFor("each channel", 2)).toBe("each channel");+ expect(dbsChannelsFor("stereo")).toBe("each channel");+ // 5.1: the background (original minus mono speech) would take speech out of the LFE and surrounds too.+ expect(dbsChannelsFor("mono", 6)).toBe("each channel");+ expect(dbsChannelsFor(undefined, 3)).toBe("each channel");+ });+});++describe("planSplit", () => {+ it("is one DBS job on the open engine, the host's model unless one is picked", () => {+ const p = planSplit({ engine: "open", media: "/api/files/u/film.wav", kind: "audio", name: "Film", channels: 2, seconds: 20 });+ expect(p.steps).toHaveLength(1);+ expect(p.steps[0].key).toBe("split");+ expect(p.steps[0].request).toEqual({+ modelId: "oss-dbs-separate",+ op: "separate-audio",+ feature: "audio-split",+ batchTitle: "Split · Film",+ title: "Split · Film",+ inputs: { audio: "/api/files/u/film.wav" },+ params: { extra: { channels: "mono", sourceChannels: 2 }, sourceDuration: 20 },+ step: { label: "Dialogue, music, effects", index: 0, of: 1 },+ });+ expect(p).toMatchObject({ length: 20, quality: null, mode: "mono" });+ expect(p.summary).toBe("Splits it into dialogue, music, effects and music & effects.");+ expect(p.notes).toEqual(["Dialogue comes out clean; music and effects can bleed into each other."]);+ // The model the page picked goes as the DBSLoader name.+ expect(planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", quality: "best" }).steps[0].request.params?.extra).toEqual({ channels: "mono", separationModel: "DBS-TIGER-DnR" });+ expect(planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", quality: "fast" }).steps[0].request.params?.extra?.separationModel).toBe("DBS-BSRNN-DnR");+ });++ it("takes a video's soundtrack (LoadAudio reads it) and does stereo stems on request", () => {+ const p = planSplit({ engine: "open", media: "/api/files/u/clip.mp4", kind: "video", stereo: true });+ expect(p.steps[0].request.inputs).toEqual({ video: "/api/files/u/clip.mp4" });+ expect(p.steps[0].request.title).toBe("Split · video soundtrack");+ expect(p.steps[0].request.params?.extra).toEqual({ channels: "each channel" });+ expect(p.steps[0].request.step?.label).toBe("Dialogue, music, effects · every channel");+ expect(p.mode).toBe("each channel");+ expect(p.summary).toBe("Splits the video's soundtrack into dialogue, music, effects and music & effects, every channel on its own (2 passes).");+ expect(p.length).toBeNull();+ });++ it("splits every channel of a 5.1 file on its own, and says why it takes longer", () => {+ const p = planSplit({ engine: "open", media: "/api/files/a.wav", kind: "audio", channels: 6 });+ expect(p.mode).toBe("each channel");+ expect(p.steps[0].request.params?.extra).toEqual({ channels: "each channel", sourceChannels: 6 });+ expect(p.notes[0]).toBe("This file has 6 channels, so each is split on its own: about 6x the time.");+ });++ it("has no cloud route: DBS isn't hosted, and no other model stands in for it", () => {+ expect(() => planSplit({ engine: "cloud", media: "/api/files/a.wav", kind: "audio" })).toThrow(CLOUD_SPLIT_PROBLEM);+ expect(CLOUD_SPLIT_PROBLEM).toMatch(/runs on your GPU \(open source\)/);+ expect(() => planSplit({ engine: "open", media: "", kind: "video" })).toThrow("Add the video to split");+ });++ it("puts a mix back on its video: the stream-copy mux on the open engine, fal's merge on the cloud", () => {+ const open = planRemux({ engine: "open", video: "/api/files/v.mp4", audio: "/api/files/mix.wav", name: "Trailer" });+ expect(open.steps[0].request).toMatchObject({ modelId: "oss-mux", op: "mux", feature: "audio-split-remux", inputs: { video: "/api/files/v.mp4", audio: "/api/files/mix.wav" }, title: "Remix · Trailer" });+ expect(open.notes).toEqual(["The picture is copied as it is, not re-encoded."]);+ const cloud = planRemux({ engine: "cloud", video: "/api/files/v.mp4", audio: "/api/files/mix.wav" });+ expect(cloud.steps[0].request).toMatchObject({ modelId: "merge-audio-video", op: "mux", title: "Remix · video" });+ // Both models exist and do the mux.+ for (const id of ["oss-mux", "merge-audio-video", "oss-dbs-separate"]) expect(getModel(id)).toBeTruthy();+ expect(getModel("oss-dbs-separate")!.routes[0]).toMatchObject({ op: "separate-audio", provider: "comfyui", endpoint: "separate-soundtrack-dbs" });+ });+});++describe("time on the open engine", () => {+ it("uses the measured CPU speeds (0.27x / 0.09x per pass) and the reference GPU's", () => {+ expect(DBS_SPEED.cpu).toEqual({ fast: 0.27, best: 0.09 });+ // 60 s on a CPU with DBS-BSRNN: about 222 s of work, 3 s to load and save.+ expect(splitTime({ seconds: 60, quality: "fast", mode: "mono", device: "cpu" })).toEqual({ low: 181, high: 359 });+ // Stereo stems: one pass per channel.+ const stereo = splitTime({ seconds: 60, quality: "fast", mode: "each channel", channels: 2, device: "cpu" });+ expect(stereo.high).toBe(Math.round(3 + ((60 * 2) / 0.27) * 1.6));+ expect(splitTime({ seconds: 60, quality: "best", mode: "mono" }).low).toBe(Math.round(3 + (60 / 0.09) * 0.8));+ // A 5.1 file: six passes.+ expect(splitTime({ seconds: 10, quality: "fast", mode: "each channel", channels: 6, device: "cpu" }).low).toBe(Math.round(3 + (60 / 0.27) * 0.8));+ // CUDA: well over real time, a range up to 4x slower than the reference card.+ expect(splitTime({ seconds: 600, quality: "best", mode: "mono", device: "cuda" })).toEqual({ low: 41, high: 154 });+ });++ it("says it in words", () => {+ expect(durationWords({ low: 20, high: 50 })).toBe("under a minute");+ expect(durationWords({ low: 181, high: 359 })).toBe("about 3–6 min");+ expect(durationWords({ low: 120, high: 130 })).toBe("about 2 min");+ expect(durationWords({ low: 7200, high: 10800 })).toBe("about 2–3 h");+ });+});++describe("the mixer", () => {+ it("turns levels into gains: −24…+6 dB in half-dB steps", () => {+ expect(dbToGain(0)).toBe(1);+ expect(dbToGain(-6)).toBeCloseTo(0.501, 3);+ expect(dbToGain(6)).toBeCloseTo(1.995, 3);+ expect(dbToGain(-12)).toBeCloseTo(0.251, 3);+ expect(dbToGain(-Infinity)).toBe(0);+ expect(clampDb(-40)).toBe(-24);+ expect(clampDb(9)).toBe(6);+ expect(clampDb(-3.3)).toBe(-3.5);+ expect([dbLabel(0), dbLabel(3), dbLabel(-12), dbLabel(-0.2)]).toEqual(["0 dB", "+3 dB", "−12 dB", "0 dB"]);+ });++ it("starts as the original: dialogue plus music & effects, the separate stems muted so nothing plays twice", () => {+ expect(stemGains(ORIGINAL_MIX)).toEqual({ voice: 1, music: 0, effects: 0, background: 1 });+ expect(presetOf(ORIGINAL_MIX)).toBe("original");+ expect(STEMS.map((s) => [s.id, s.label])).toEqual([+ ["voice", "Dialogue"],+ ["music", "Music"],+ ["effects", "Effects"],+ ["background", "Music & effects"],+ ]);+ });++ it("has the presets: no dialogue, dialogue only, music only, music under dialogue at −12 dB", () => {+ const gains = Object.fromEntries(PRESETS.map((p) => [p.id, stemGains(p.mix)]));+ expect(gains["no-dialogue"]).toEqual({ voice: 0, music: 0, effects: 0, background: 1 });+ expect(gains["dialogue-only"]).toEqual({ voice: 1, music: 0, effects: 0, background: 0 });+ expect(gains["music-only"]).toEqual({ voice: 0, music: 1, effects: 0, background: 0 });+ expect(gains["music-under"].voice).toBe(1);+ expect(gains["music-under"].background).toBeCloseTo(0.251, 3);+ expect(PRESETS.map((p) => p.label)).toEqual(["Original", "No dialogue", "Dialogue only", "Music only", "Music under dialogue (−12 dB)"]);+ for (const p of PRESETS) expect(presetOf(p.mix)).toBe(p.id);+ });++ it("never plays music or effects twice: the bed and its two stems take turns", () => {+ let m: Mix = setMute(ORIGINAL_MIX, "music", false);+ expect(stemGains(m)).toEqual({ voice: 1, music: 1, effects: 0, background: 0 });+ m = setMute(m, "effects", false);+ expect(stemGains(m)).toEqual({ voice: 1, music: 1, effects: 1, background: 0 });+ m = setMute(m, "background", false);+ expect(stemGains(m)).toEqual({ voice: 1, music: 0, effects: 0, background: 1 });+ // Moving a muted stem's level unmutes it (and the same rule applies).+ m = setLevel(m, "music", -6);+ expect(m.music).toEqual({ db: -6, mute: false, solo: false });+ expect(m.background.mute).toBe(true);+ expect(presetOf(m)).toBeNull();+ expect(setLevel(ORIGINAL_MIX, "voice", 40).voice.db).toBe(6);+ });++ it("solo plays only the soloed stems; a muted one stays silent", () => {+ let m = setSolo(ORIGINAL_MIX, "voice", true);+ expect(stemGains(m)).toEqual({ voice: 1, music: 0, effects: 0, background: 0 });+ m = setSolo(m, "background", true);+ expect(stemGains(m)).toEqual({ voice: 1, music: 0, effects: 0, background: 1 });+ m = setMute(m, "voice", true);+ expect(stemGains(m).voice).toBe(0);+ });++ it("names a mix for the Library", () => {+ expect(mixName(ORIGINAL_MIX)).toBe("Dialogue + Music & effects");+ expect(mixName(PRESETS.find((p) => p.id === "music-under")!.mix)).toBe("Music under dialogue (−12 dB)");+ expect(mixName(setLevel(PRESETS.find((p) => p.id === "dialogue-only")!.mix, "voice", 3))).toBe("Dialogue +3 dB");+ expect(mixName({ ...ORIGINAL_MIX, voice: { db: 0, mute: true, solo: false }, background: { db: 0, mute: true, solo: false } })).toBe("Silence");+ });++ it("exports a 16-bit WAV kept under full scale", () => {+ expect(headroomGain(0.5)).toBe(1);+ expect(headroomGain(2) * 2).toBeCloseTo(dbToGain(-0.1), 6);+ const wav = encodeWav([Float32Array.from([0, 0.5, -1, 2]), Float32Array.from([1, -0.5, 0, 0])], 44100);+ const d = new DataView(wav.buffer);+ expect(String.fromCharCode(...wav.slice(0, 4))).toBe("RIFF");+ expect(String.fromCharCode(...wav.slice(8, 12))).toBe("WAVE");+ expect([d.getUint16(22, true), d.getUint32(24, true), d.getUint16(34, true), d.getUint32(40, true)]).toEqual([2, 44100, 16, 4 * 2 * 2]);+ // Interleaved L/R, clipped at full scale.+ expect(Array.from({ length: 8 }, (_, i) => d.getInt16(44 + i * 2, true))).toEqual([0, 32767, 16384, -16384, -32768, 0, 32767, 0]);+ });+});++describe("Split soundtrack in the Audio hub", () => {+ it("is a mode after Transcribe with its own path", () => {+ const ids = HUB_MODES.audio.map((m) => m.id);+ expect(ids.indexOf("split")).toBe(ids.indexOf("transcribe") + 1);+ expect(HUB_MODES.audio.find((m) => m.id === "split")?.label).toBe("Split soundtrack");+ expect(modeHref("audio", "split")).toBe("/audio/split");+ });+});++describe("POST /api/audio-tools split and remux (demo mode)", () => {+ it("prices a split as free with a time estimate, and runs it into four Library stems", async () => {+ const media = upload(6, 2);+ const preview = await (await post({ tool: "split", engine: "open", media, kind: "audio", name: "Film" }, true)).json();+ expect(preview).toMatchObject({ steps: 1, costUsd: 0, demo: true, length: 6, hostPick: "fast" });+ expect(preview.summary).toBe("Splits it into dialogue, music, effects and music & effects.");+ // The header's length beats the browser's; the estimate is the CPU's (no device in demo mode).+ expect(preview.estimate).toEqual(splitTime({ seconds: 6, quality: "fast", mode: "mono", channels: 2 }));+ const best = await (await post({ tool: "split", engine: "open", media, kind: "audio", quality: "best", stereo: true, sourceDuration: 99 }, true)).json();+ expect(best.estimate).toEqual(splitTime({ seconds: 6, quality: "best", mode: "each channel", channels: 2 }));++ const res = await post({ tool: "split", engine: "open", media, kind: "audio", name: "Film" });+ expect(res.status).toBe(201);+ const run = await res.json();+ expect(run.result).toMatchObject({ feature: "audio-split", modelId: "oss-dbs-separate", provider: "mock", op: "separate-audio" });+ const g = await finished(run.result.id);+ expect(g.status).toBe("succeeded");+ expect(g.outputs.map((o) => [o.kind, o.meta?.stem])).toEqual([+ ["audio", "voice"],+ ["audio", "music"],+ ["audio", "effects"],+ ["audio", "background"],+ ]);+ expect(g.outputs.every((o) => o.url.startsWith("/api/files/"))).toBe(true);+ });++ it("reads a 5.1 file's channels from its header and splits each one", async () => {+ const media = upload(4, 6, "surround.wav");+ const preview = await (await post({ tool: "split", engine: "open", media, kind: "audio" }, true)).json();+ expect(preview.notes[0]).toBe("This file has 6 channels, so each is split on its own: about 6x the time.");+ const run = await (await post({ tool: "split", engine: "open", media, kind: "audio" })).json();+ expect(run.result.request.params.extra).toEqual({ channels: "each channel", sourceChannels: 6 });+ });++ it("says plainly that the cloud has no split, and refuses on an install set to paid APIs only", async () => {+ const media = upload(3, 2, "a.wav");+ const cloud = await post({ tool: "split", engine: "cloud", media, kind: "audio" }, true);+ expect(cloud.status).toBe(422);+ expect((await cloud.json()).error).toBe(CLOUD_SPLIT_PROBLEM);+ setSetting("engineMode", "cloud");+ try {+ expect((await (await post({ tool: "split", engine: "cloud", media, kind: "audio" }, true)).json()).error).toBe(CLOUD_ONLY_PROBLEM);+ expect((await (await post({ tool: "split", engine: "open", media, kind: "audio" })).json()).error).toBe(CLOUD_ONLY_PROBLEM);+ } finally {+ setSetting("engineMode", "both");+ }+ expect((await (await post({ tool: "split", engine: "open", media: "/etc/passwd", kind: "audio" })).json()).error).toBe("Add the audio or video to split");+ expect((await (await post({ tool: "split", engine: "open", media: "/api/files/uploads/gone.wav", kind: "audio" }, true)).json()).error).toBe("That audio file is gone — add it again");+ });++ it("puts a mix back on the video: free on the open engine, priced on the cloud", async () => {+ const audio = upload(3, 2, "mix.wav");+ const video = saveFile({ data: Buffer.from("not really a video"), contentType: "video/mp4", name: "clip.mp4", source: "upload" }).url;+ const open = await (await post({ tool: "remux", engine: "open", video, audio, name: "Clip" }, true)).json();+ expect(open).toMatchObject({ steps: 1, costUsd: 0, summary: "Puts your mix on the video in place of its sound." });+ const cloud = await (await post({ tool: "remux", engine: "cloud", video, audio }, true)).json();+ expect(cloud.steps).toBe(1);+ const run = await (await post({ tool: "remux", engine: "open", video, audio, name: "Clip" })).json();+ expect(run.result).toMatchObject({ feature: "audio-split-remux", modelId: "oss-mux", op: "mux" });+ expect(run.result.request.inputs).toEqual({ video, audio });+ expect((await (await post({ tool: "remux", engine: "open", video, audio: "/api/files/uploads/gone.wav" }, true)).json()).error).toBe("That mix is gone — export it again");+ expect((await (await post({ tool: "remux", engine: "open", video })).json()).error).toBe("Export the mix first");+ });+});diff --git a/tests/ux-flows.test.ts b/tests/ux-flows.test.tsindex 5992a96d..d10b9a3f 100644--- a/tests/ux-flows.test.ts+++ b/tests/ux-flows.test.ts@@ -60,7 +60,14 @@ describe("next steps under a fresh result", () => {expect(img[0].href).toBe(`/video?image=${encodeURIComponent("/api/files/out-0.png")}`);const vid = nextSteps(gen([{ kind: "video", url: "/api/files/clip.mp4" }], { kind: "video", op: "t2v" }), 0);expect(vid.map((a) => a.label)).toEqual(["Extend", "Upscale", "Add sound"]);- expect(nextSteps(gen([{ kind: "audio", url: "/api/files/a.mp3" }], { kind: "audio", op: "tts" }), 0).map((a) => a.id)).toEqual(["lipsync", "voice-change"]);+ expect(nextSteps(gen([{ kind: "audio", url: "/api/files/a.mp3" }], { kind: "audio", op: "tts" }), 0).map((a) => a.id)).toEqual(["lipsync", "voice-change", "split-soundtrack"]);+ // A clip that has its sound (Sound for video, a soundtrack mux) offers Split soundtrack in place of Add sound.+ const sounded = nextSteps(gen([{ kind: "video", url: "/api/files/clip.mp4" }], { kind: "video", op: "v2a" }), 0);+ expect(sounded.map((a) => [a.label, a.href])).toEqual([+ ["Extend", "/extend?video=%2Fapi%2Ffiles%2Fclip.mp4"],+ ["Upscale", "/upscale/video?video=%2Fapi%2Ffiles%2Fclip.mp4"],+ ["Split soundtrack", "/audio/split?video=%2Fapi%2Ffiles%2Fclip.mp4"],+ ]);});it("has none for what doesn't hand off (text, vectors) or isn't done", () => {diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex 2c104e20..6b7891af 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -1,6 +1,6 @@{"version": 1,- "generatedAt": "2026-10-29T17:59:35.567Z",+ "generatedAt": "2026-10-29T18:20:35.522Z","comfyuiCommit": "fc04da91b2ab12f99e4716371a7e4f98ac982597","comfyuiVersion": "0.41.0","workflowTemplatesVersion": "0.11.86",@@ -10975,7 +10975,7 @@"vramGb": 0,"license": "DBS weights Apache-2.0 (JusperLee; trained on DnR v2, CC BY 4.0); ComfyUI-DBS code MIT; vendored DBS code Apache-2.0 with MIT notices (BS-RoFormer, MSST, TIGER)","validated": true,- "notes": "CPU OK, about 1.7 GiB on CUDA. audio = an audio file or a video (LoadAudio reads a video's soundtrack without decoding frames). DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 4x slower on a CPU, the CUDA default); device auto. DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (every channel separated on its own: 2x the time for stereo, 6x for 5.1; the provider forces it for inputs with more than 2 channels, where the subtract below would also take speech out of the LFE and surrounds); output_sample_rate input. Outputs in order: voice (speech), music, effects (sfx), background = original minus speech (AudioMerge subtract: with mono it keeps the original stereo image at mono cost; AudioMerge scales the whole result down when it peaks over 1.0), and the pack's JSON report (model, device, rates, windows, seconds, times real time). Stems are FLAC, so they still add up to the source. Voice is first, so a chain without a stem takes the dialogue. Trained on synthetic English mixes (DnR v2): dialogue separates well (15-16 dB), music against effects less so (5.7-7.8 dB)."+ "notes": "CPU OK, about 1.7 GiB on CUDA. audio = an audio file or a video (LoadAudio reads a video's soundtrack without decoding frames). DBSLoader model DBS-BSRNN-DnR (fast: 18.9 MB, 9.07 dB SI-SDR on DnR v2, the CPU default) or DBS-TIGER-DnR (best: 4.1 MB, 10.13 dB, about 3x slower on a CPU, the CUDA default); device auto. Measured on a 4-CPU host (torch 2.14.1+cpu, 10-20 s clips): DBS-BSRNN 0.17-0.33x real time per channel, DBS-TIGER 0.08-0.09x. DBSSeparate channels mono (the mean of the channels, the official usage) or each channel (every channel separated on its own: 2x the time for stereo, 6x for 5.1; the provider forces it for inputs with more than 2 channels, where the subtract below would also take speech out of the LFE and surrounds); output_sample_rate input. Outputs in order: voice (speech), music, effects (sfx), background = original minus speech (AudioMerge subtract: with mono it keeps the original stereo image at mono cost; AudioMerge scales the whole result down when it peaks over 1.0), and the pack's JSON report (model, device, rates, windows, seconds, times real time). Stems are FLAC, so they still add up to the source. Voice is first, so a chain without a stem takes the dialogue. Trained on synthetic English mixes (DnR v2): dialogue separates well (15-16 dB), music against effects less so (5.7-7.8 dB)."},{"id": "captions-qwen3-asr",