Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Remove dialogue: a Video tools mode that takes the talking out of a video, picture copied

Claudef9f3261c94ab
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.ts
index 1ebfafd1..051e304e 100644
--- a/src/app/api/audio-tools/route.ts
+++ b/src/app/api/audio-tools/route.ts
@@ -10,16 +10,26 @@ const MESSAGES: Record<string, string> = {
audio: "Add the audio to loop",
duration: "Pick a length up to 10 minutes",
crossfade: "Keep the crossfade between 0 and 10 seconds",
+ musicDb: "Lower the music by 0 to 30 dB",
};
-/** Audio → Loop / extend, Join and Split soundtrack (and a split's mix put back on its video): start a run; `?preview=1` only plans and prices it. */
+/**
+ * Audio → Loop / extend, Join and Split soundtrack (and a split's mix put back on its video), and Video tools → Remove
+ * dialogue: start a run; `?preview=1` only plans and prices it.
+ */
async function post(request: Request) {
const raw: unknown = await request.json().catch(() => null);
const parsed = AudioToolBody.safeParse(raw);
if (!parsed.success) {
const path = parsed.error.issues[0]?.path.join(".") ?? "";
- const remux = (raw as { tool?: unknown } | null)?.tool === "remux";
- const msg = path.startsWith("clips") ? "Add 2 to 10 audio clips to join" : remux && path === "audio" ? "Export the mix first" : (MESSAGES[path] ?? "Check the settings");
+ const tool = (raw as { tool?: unknown } | null)?.tool;
+ const msg = path.startsWith("clips")
+ ? "Add 2 to 10 audio clips to join"
+ : tool === "remux" && path === "audio"
+ ? "Export the mix first"
+ : tool === "remove-dialogue" && path === "video"
+ ? "Add the video to take the dialogue out of"
+ : (MESSAGES[path] ?? "Check the settings");
return Response.json({ error: msg }, { status: 400 });
}
const preview = new URL(request.url).searchParams.get("preview") === "1";
diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.ts
index 942aa127..56415914 100644
--- a/src/components/audio-tools/hooks.ts
+++ b/src/components/audio-tools/hooks.ts
@@ -10,7 +10,18 @@ export type AudioToolBody =
| { tool: "loop"; engine: Engine; audio: string; name?: string; duration: number; sourceDuration?: number; crossfade?: number; curve?: "equal-power" | "linear" }
| { tool: "join"; engine: Engine; clips: { url: string; name?: string; duration?: number }[]; crossfade?: number; curve?: "equal-power" | "linear" }
| { tool: "split"; engine: Engine; media: string; kind: "audio" | "video"; name?: string; quality?: "fast" | "best"; stereo?: boolean; channels?: number; sourceDuration?: number }
- | { tool: "remux"; engine: Engine; video: string; audio: string; name?: string };
+ | { tool: "remux"; engine: Engine; video: string; audio: string; name?: string }
+ | {
+ tool: "remove-dialogue";
+ engine: Engine;
+ video: string;
+ name?: string;
+ outcome?: "no-dialogue" | "dialogue-only" | "lower-music";
+ musicDb?: number;
+ quality?: "fast" | "best";
+ channels?: number;
+ sourceDuration?: number;
+ };
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/remove-dialogue-tool.tsx b/src/components/audio-tools/remove-dialogue-tool.tsx
new file mode 100644
index 00000000..c3b4a8fd
--- /dev/null
+++ b/src/components/audio-tools/remove-dialogue-tool.tsx
@@ -0,0 +1,778 @@
+"use client";
+
+import {
+ Cpu,
+ Download,
+ FileVideo,
+ Library,
+ Loader2,
+ MicOff,
+ Upload,
+ X,
+} from "lucide-react";
+import { nanoid } from "nanoid";
+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 { Feed } from "@/components/studio/feed";
+import {
+ ACCEPT,
+ fileToSlot,
+ kindOfFile,
+ LibraryGrid,
+} 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 { useAskBeforeUpload, useEngine, useGenerations } from "@/lib/api";
+import type { AudioToolPreview } from "@/lib/av/audio-tools";
+import {
+ CLOUD_ONLY_REMOVE_PROBLEM,
+ CLOUD_REMOVE_PROBLEM,
+ KEPT_STEM,
+ LOWER_DEFAULT_DB,
+ LOWER_MAX_DB,
+ LOWER_MIN_DB,
+ OUTCOMES,
+ REMOVE_DIALOGUE_FEATURE,
+ REMOVED_STEM,
+ type DialogueOutcome,
+} from "@/lib/av/remove-dialogue";
+import {
+ clock,
+ durationWords,
+ QUALITY_LABELS,
+ stemLabel,
+ type SplitQuality,
+ type StemId,
+} from "@/lib/av/split";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { downloadHref } from "@/lib/library";
+import { cn } from "@/lib/utils";
+import { toastError } from "@/lib/refusals";
+import {
+ useAudioToolPreview,
+ useAudioToolRun,
+ useSettled,
+ type AudioToolBody,
+} from "./hooks";
+
+/**
+ * Video tools → Remove dialogue (DBS D2). Drop or pick a video; choose No dialogue (music and effects), Dialogue only or
+ * Lower the music (−30…0 dB); DBS splits the soundtrack on your ComfyUI and the stream-copy mux puts the new sound on
+ * the picture without re-encoding it. Before / after players, and the stem taken out as a download. There's no hosted
+ * DBS (and SAM Audio in its place isn't the owner's choice), so the cloud engine says the tool runs on your GPU.
+ */
+
+type Source = {
+ ref: string;
+ preview: string;
+ id: string;
+ name?: string;
+ uploading?: boolean;
+ duration?: number;
+};
+
+const baseName = (s: { name?: string }) =>
+ (s.name ?? "Video").replace(/\.[a-z0-9]{2,4}$/i, "");
+
+const RUN_LABEL: Record<DialogueOutcome, string> = {
+ "no-dialogue": "Remove dialogue",
+ "dialogue-only": "Keep the dialogue",
+ "lower-music": "Lower the music",
+};
+
+const COPY =
+ "Takes the talking out and keeps the music and sound effects. The picture is not re-encoded.";
+
+/** ?video= from a result's "Remove dialogue", read once after hydration. */
+function useHandoff(take: (s: Source) => void) {
+ useEffect(() => {
+ const url = new URLSearchParams(window.location.search).get("video");
+ if (url?.startsWith("/api/files/"))
+ take({
+ ref: url,
+ preview: url,
+ id: nanoid(8),
+ name: decodeURIComponent(url.split("/").pop() ?? ""),
+ });
+ // Once, on arrival.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+}
+
+function AddVideo({
+ onPick,
+ onUpdate,
+}: {
+ onPick: (s: Source) => void;
+ onUpdate: (next: (cur: Source | null) => Source | null) => void;
+}) {
+ const input = useRef<HTMLInputElement>(null);
+ const [over, setOver] = useState(false);
+ const [picking, setPicking] = useState(false);
+ // A guest, or an account with neither its own GPU nor its own key, gets its card instead of the file chooser.
+ const askFirst = useAskBeforeUpload();
+ const take = (f: File | undefined) => {
+ if (!f || askFirst()) return;
+ if (kindOfFile(f) !== "video")
+ return void toast("Video only — drop a clip here (MP4, MOV or WebM)");
+ // Shown at once with its local preview, then given its address, or taken away when the upload is refused or fails
+ // (the answer counts only while it's still this upload).
+ const id = nanoid(8);
+ void fileToSlot(
+ f,
+ (v) => {
+ const s: Source | null = v && {
+ ref: v.ref,
+ preview: v.preview,
+ id,
+ name: f.name,
+ uploading: v.uploading,
+ };
+ if (s?.uploading) onPick(s);
+ else onUpdate((cur) => (cur?.id === id ? s : cur));
+ },
+ "video",
+ );
+ };
+ 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" /> : <MicOff className="size-5" />}
+ </span>
+ <div>
+ <p className="text-[15px] font-medium">
+ Add a video with talking in it
+ </p>
+ <p className="mt-1 text-[13px] text-muted-foreground">
+ MP4, MOV or WebM, up to 200 MB and 30 minutes
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-1.5">
+ <Button
+ size="sm"
+ className="rounded-full"
+ onClick={() => askFirst() || input.current?.click()}
+ >
+ <Upload className="size-3.5" /> Upload a 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={["video"]}
+ onPick={(v) => {
+ onPick({
+ ref: v.ref,
+ preview: v.preview,
+ id: v.id ?? nanoid(8),
+ name: v.name,
+ });
+ setPicking(false);
+ }}
+ />
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
+ <input
+ ref={input}
+ type="file"
+ accept={ACCEPT.video}
+ hidden
+ aria-label="Upload a video"
+ onChange={(e) => {
+ take(e.target.files?.[0]);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ );
+}
+
+const money = (p: AudioToolPreview) =>
+ p.demo ? "Placeholder · free" : "Free · runs on your ComfyUI";
+const onDevice = (device?: string) =>
+ device === "cuda" ? "on your GPU" : device ? "on your CPU" : "on a CPU";
+
+/** A stem of the split step, as a download. */
+function StemDownload({
+ split,
+ stem,
+ name,
+ label,
+}: {
+ split: Generation;
+ stem: StemId;
+ name: string;
+ label?: string;
+}) {
+ const o = split.outputs.find(
+ (x) => x.kind === "audio" && x.meta?.stem === stem,
+ );
+ if (!o) return null;
+ const file = `${name} · ${stemLabel(stem)}.flac`;
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ className="max-w-full rounded-full"
+ asChild
+ >
+ <a href={downloadHref(o.url, file)} download={file}>
+ <Download className="size-3.5 shrink-0" />{" "}
+ <span className="truncate">
+ {label ?? `${stemLabel(stem)} (taken out)`}
+ </span>
+ </a>
+ </Button>
+ );
+}
+
+function ResultPanel({
+ before,
+ result,
+ split,
+ outcome,
+ name,
+}: {
+ before: string;
+ result: Generation;
+ split?: Generation;
+ outcome: DialogueOutcome;
+ name: string;
+}) {
+ const video = result.outputs.find((o) => o.kind === "video");
+ if (!video) return null;
+ const file = `${name} · ${OUTCOMES.find((o) => o.id === outcome)?.label ?? "Remove dialogue"}.mp4`;
+ const removed = REMOVED_STEM[outcome];
+ return (
+ <Panel
+ title="Before and after"
+ aside={
+ <span className="text-[12px] text-muted-foreground">
+ Picture copied as it is
+ </span>
+ }
+ >
+ <div className="grid min-w-0 grid-cols-1 gap-3 md:grid-cols-2">
+ <figure className="min-w-0 space-y-1.5">
+ <video
+ src={before}
+ controls
+ playsInline
+ preload="metadata"
+ className="aspect-video w-full rounded-xl bg-media object-contain"
+ aria-label="The original video"
+ />
+ <figcaption className="text-[12px] text-muted-foreground">
+ Before
+ </figcaption>
+ </figure>
+ <figure className="min-w-0 space-y-1.5">
+ <video
+ src={video.url}
+ controls
+ playsInline
+ preload="metadata"
+ className="aspect-video w-full rounded-xl bg-media object-contain"
+ aria-label="The video with its new soundtrack"
+ />
+ <figcaption className="text-[12px] text-muted-foreground">
+ After · {OUTCOMES.find((o) => o.id === outcome)?.label}
+ </figcaption>
+ </figure>
+ </div>
+ <div className="mt-3 flex min-w-0 flex-wrap items-center gap-2">
+ <Button size="sm" className="max-w-full rounded-full" asChild>
+ <a href={downloadHref(video.url, file)} download={file}>
+ <Download className="size-3.5 shrink-0" />{" "}
+ <span className="truncate">Download the video</span>
+ </a>
+ </Button>
+ {split && removed && (
+ <StemDownload split={split} stem={removed} name={name} />
+ )}
+ {split && !removed && (
+ <>
+ <StemDownload
+ split={split}
+ stem="voice"
+ name={name}
+ label="Dialogue"
+ />
+ <StemDownload
+ split={split}
+ stem="background"
+ name={name}
+ label="Music & effects (full level)"
+ />
+ </>
+ )}
+ </div>
+ </Panel>
+ );
+}
+
+/** What a run of the tool was asked for, from its result's request (the mux step: its chain says which stems). */
+function outcomeOf(g: Generation): DialogueOutcome {
+ const chain = g.request.chain ?? [];
+ if (chain.some((c) => c.slot === "audio2")) return "lower-music";
+ return chain[0]?.stem === KEPT_STEM["dialogue-only"]
+ ? "dialogue-only"
+ : "no-dialogue";
+}
+
+export function RemoveDialogueTool({ tabs }: { tabs?: React.ReactNode }) {
+ const [engine, setEngine, mode] = useEngine();
+ const run = useAudioToolRun();
+ const [source, setSource] = useState<Source | null>(null);
+ const [outcome, setOutcome] = useState<DialogueOutcome>("no-dialogue");
+ const [musicDb, setMusicDb] = useState(LOWER_DEFAULT_DB);
+ const [quality, setQuality] = useState<SplitQuality | null>(null);
+ const [ran, setRan] = useState<{
+ result: string;
+ split?: string;
+ outcome: DialogueOutcome;
+ before: string;
+ name: string;
+ } | null>(null);
+ const result = useGeneration(ran?.result);
+ const split = useGeneration(ran?.split);
+ const sliderId = useId();
+ const take = useCallback((s: Source) => {
+ setSource(s);
+ setRan(null);
+ }, []);
+ useHandoff(take);
+ const ready = source && !source.uploading && source.ref ? source : null;
+ const body: AudioToolBody | null = useMemo(
+ () =>
+ ready
+ ? {
+ tool: "remove-dialogue",
+ engine,
+ video: ready.ref,
+ name: baseName(ready),
+ outcome,
+ ...(outcome === "lower-music" && { musicDb }),
+ ...(quality && { quality }),
+ ...(ready.duration && { sourceDuration: ready.duration }),
+ }
+ : null,
+ [ready, engine, outcome, musicDb, quality],
+ );
+ const preview = useAudioToolPreview(
+ useSettled(engine === "open" ? body : null),
+ );
+ const p = preview.data;
+ const picked: SplitQuality = quality ?? p?.hostPick ?? "fast";
+ const cloudProblem =
+ mode === "cloud" ? CLOUD_ONLY_REMOVE_PROBLEM : CLOUD_REMOVE_PROBLEM;
+ const blocker = !source
+ ? "Add a video"
+ : source.uploading
+ ? "Uploading…"
+ : engine === "cloud"
+ ? cloudProblem
+ : null;
+ const error = preview.error ? (preview.error as Error).message : null;
+ const g = result.data;
+ const busy =
+ run.isPending || g?.status === "queued" || g?.status === "running";
+ const go = () => {
+ if (blocker) return void toast(blocker);
+ if (error) return void toast.error(error);
+ run.mutate(body!, {
+ onSuccess: (r) => {
+ setRan({
+ result: r.result.id,
+ split: r.items.find((x) => x.op === "separate-audio")?.id,
+ outcome,
+ before: ready!.ref,
+ name: baseName(ready!),
+ });
+ toast.success("Taking the dialogue out on your ComfyUI");
+ },
+ onError: (e) => toastError(e),
+ });
+ };
+ const s = split.data;
+ const stage =
+ g?.status === "queued" && s && s.status !== "succeeded"
+ ? (s.message ?? "Splitting the soundtrack")
+ : (g?.message ?? "Working");
+ const progress =
+ g?.status === "running"
+ ? g.progress
+ : s?.status === "running"
+ ? s.progress
+ : null;
+
+ return (
+ <ToolShell title="Video tools" tabs={tabs}>
+ {!source && (
+ <ToolHero
+ title="Remove dialogue"
+ subtitle={`${COPY} 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 ? (
+ <AddVideo onPick={take} onUpdate={setSource} />
+ ) : (
+ <Panel
+ title={
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ <FileVideo 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 video"
+ onClick={() => {
+ setSource(null);
+ setRan(null);
+ }}
+ >
+ <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>
+ ) : (
+ <video
+ key={source.preview}
+ src={source.preview}
+ controls
+ playsInline
+ preload="metadata"
+ aria-label={`Play ${baseName(source)}`}
+ onLoadedMetadata={(e) => {
+ const d = e.currentTarget.duration;
+ if (Number.isFinite(d) && d > 0)
+ setSource((cur) => (cur ? { ...cur, duration: d } : cur));
+ }}
+ className="max-h-[36vh] w-full rounded-xl bg-media object-contain"
+ />
+ )}
+ </Panel>
+ )}
+ {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">
+ Remove dialogue runs on your GPU (open source).
+ </span>{" "}
+ {mode === "cloud"
+ ? "This install is set to paid cloud APIs only (Settings → Engine mode), and DBS isn't hosted on fal or Replicate."
+ : "DBS isn't hosted on fal or Replicate, so there's no cloud route that takes the dialogue out."}
+ </p>
+ {mode === "both" ? (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0 rounded-full"
+ onClick={() => setEngine("open" as Engine)}
+ >
+ <Cpu className="size-3.5" /> Use open source
+ </Button>
+ ) : null}
+ </div>
+ </Panel>
+ )}
+ {source && engine === "open" && (
+ <Panel title="What to keep">
+ <div className="space-y-3">
+ <Segmented
+ label="What to keep"
+ value={outcome}
+ onChange={setOutcome}
+ options={OUTCOMES.map((o) => ({
+ value: o.id,
+ label: o.label,
+ hint: o.hint,
+ }))}
+ />
+ <p className="text-[12px] text-muted-foreground">
+ {OUTCOMES.find((o) => o.id === outcome)?.hint}.
+ </p>
+ {outcome === "lower-music" && (
+ <div className="flex min-w-0 items-center gap-3">
+ <label htmlFor={sliderId} className="shrink-0 text-[13px]">
+ Music &amp; effects
+ </label>
+ <Slider
+ id={sliderId}
+ min={LOWER_MIN_DB}
+ max={LOWER_MAX_DB}
+ step={1}
+ value={[musicDb]}
+ onValueChange={([v]) => setMusicDb(v)}
+ aria-label="Music and effects level"
+ aria-valuetext={`${musicDb} dB`}
+ className="min-w-0 flex-1"
+ />
+ <span className="w-14 shrink-0 text-right font-mono text-[12px] tabular-nums">
+ {musicDb === 0 ? "0 dB" : `−${Math.abs(musicDb)} dB`}
+ </span>
+ </div>
+ )}
+ <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={(["fast", "best"] as const).map((q) => ({
+ value: q,
+ label: `${QUALITY_LABELS[q]}${p?.installed && !p.installed.includes(q) ? " · not installed" : ""}`,
+ }))}
+ />
+ {!quality && p?.hostPick && p.device && (
+ <span className="text-[12px] text-muted-foreground">
+ picked for your {p.device === "cuda" ? "GPU" : "CPU"}
+ </span>
+ )}
+ </div>
+ </div>
+ </Panel>
+ )}
+ {source && (
+ <div className="space-y-2">
+ {!blocker && !error && p && (
+ <div
+ className="space-y-1 text-[13px] text-muted-foreground"
+ aria-live="polite"
+ >
+ <p>{p.summary}</p>
+ {p.notes.map((n) => (
+ <p key={n} className="text-[12px]">
+ {n}
+ </p>
+ ))}
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-3">
+ <p
+ className={cn(
+ "min-w-0 flex-1 text-[13px]",
+ error && !blocker
+ ? "text-destructive"
+ : "text-muted-foreground",
+ )}
+ aria-live="polite"
+ >
+ {blocker && engine !== "cloud" ? (
+ blocker
+ ) : engine === "cloud" ? (
+ mode === "cloud" ? (
+ "Not available on this install: it is set to paid cloud APIs only"
+ ) : (
+ "Switch to the open engine to remove dialogue"
+ )
+ ) : error ? (
+ error
+ ) : p ? (
+ <>
+ <span className="font-mono text-foreground">
+ {money(p)}
+ </span>
+ {p.estimate && !p.demo
+ ? ` · ${durationWords(p.estimate)} ${onDevice(p.device)}`
+ : ""}
+ </>
+ ) : (
+ "Checking…"
+ )}
+ </p>
+ <Button
+ size="lg"
+ className={cn(
+ "rounded-full",
+ (blocker || error) &&
+ "bg-muted text-subtle-foreground hover:bg-muted",
+ )}
+ onClick={go}
+ disabled={busy}
+ >
+ {busy ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : (
+ <MicOff className="size-4" />
+ )}{" "}
+ {RUN_LABEL[outcome]}
+ </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" /> {stage}…
+ {progress ? ` ${Math.round(progress * 100)}%` : ""}
+ </p>
+ </Panel>
+ )}
+ {g?.status === "failed" && (
+ <p className="text-[13px] text-destructive" role="alert">
+ {g.error ?? "It didn't finish"}
+ </p>
+ )}
+ {ran && g?.status === "succeeded" && (
+ <ResultPanel
+ before={ran.before}
+ result={g}
+ split={s}
+ outcome={ran.outcome}
+ name={ran.name}
+ />
+ )}
+ </div>
+ <Results
+ open={ran?.result ?? null}
+ onOpen={(r, splitStep) => {
+ const video = r.request.inputs?.video;
+ if (!video) return;
+ const name = r.request.title?.replace(/^.* · /, "") || "Video";
+ setSource({ ref: video, preview: video, id: r.id, name });
+ setRan({
+ result: r.id,
+ split: splitStep?.id,
+ outcome: outcomeOf(r),
+ before: video,
+ name,
+ });
+ window.scrollTo({ top: 0, behavior: "smooth" });
+ }}
+ />
+ </ToolShell>
+ );
+}
+
+/** Earlier runs (both steps: the new video and its stems), and a way back to a finished one's before / after. */
+function Results({
+ onOpen,
+ open,
+}: {
+ onOpen: (g: Generation, split?: Generation) => void;
+ open: string | null;
+}) {
+ const runs = useGenerations({
+ features: [REMOVE_DIALOGUE_FEATURE],
+ limit: 24,
+ });
+ const items = runs.data ?? [];
+ const reopen = items
+ .filter((g) => g.op === "mux" && g.status === "succeeded" && g.id !== open)
+ .slice(0, 4);
+ if (!items.length) return null;
+ return (
+ <section
+ className="mx-auto mt-10 max-w-[1040px]"
+ aria-labelledby="remove-dialogue-results"
+ >
+ <h3
+ id="remove-dialogue-results"
+ className="mb-3 font-heading text-[22px]"
+ >
+ Your videos
+ </h3>
+ {reopen.length > 0 && (
+ <div className="mb-4 flex min-w-0 flex-wrap gap-2">
+ {reopen.map((g) => (
+ <Button
+ key={g.id}
+ variant="outline"
+ size="sm"
+ className="max-w-full rounded-full"
+ onClick={() =>
+ onOpen(
+ g,
+ items.find(
+ (x) =>
+ x.op === "separate-audio" &&
+ x.batchId &&
+ x.batchId === g.batchId,
+ ),
+ )
+ }
+ >
+ <MicOff className="size-3.5 shrink-0" />{" "}
+ <span className="truncate">
+ Compare {g.request.title ?? "result"}
+ </span>
+ </Button>
+ ))}
+ </div>
+ )}
+ <Feed items={items} />
+ </section>
+ );
+}
diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsx
index 98d3c0db..f394ae99 100644
--- a/src/components/studio/mode-switch-studio.tsx
+++ b/src/components/studio/mode-switch-studio.tsx
@@ -30,6 +30,7 @@ import { RemoveObjectTool } from "@/components/remove-object/remove-object-tool"
import { EvolutionTool } from "@/components/evolution/evolution-tool";
import { AudioJoinTool, AudioLoopTool } from "@/components/audio-tools/audio-tools";
import { SplitSoundtrackTool } from "@/components/audio-tools/split-tool";
+import { RemoveDialogueTool } from "@/components/audio-tools/remove-dialogue-tool";
import { ModeStudio, ModeTabs } from "./mode-studio";
import type { StudioConfig } from "./studio-context";
@@ -54,7 +55,7 @@ const CONFIGS: Record<HubKind, Record<string, StudioConfig>> = {
},
};
-/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Remove object, Evolution, Captions, Trim). */
+/** Modes that are their own tool rather than a composer studio (Translate & dub, Loop / extend, Join, Split soundtrack, Remove object, Remove dialogue, Evolution, Captions, Trim). */
const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode }) => React.ReactNode>>> = {
audio: {
translate: ({ tabs }) => <DubStudio tabs={tabs} />,
@@ -64,6 +65,7 @@ const TOOLS: Partial<Record<HubKind, Record<string, (p: { tabs: React.ReactNode
},
"video-tools": {
"remove-object": ({ tabs }) => <RemoveObjectTool tabs={tabs} />,
+ "remove-dialogue": ({ tabs }) => <RemoveDialogueTool tabs={tabs} />,
evolution: ({ tabs }) => <EvolutionTool tabs={tabs} />,
captions: ({ tabs }) => <CaptionsStudio tabs={tabs} />,
trim: ({ tabs }) => <TrimTool tabs={tabs} />,
diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsx
index 1d781fa4..71113139 100644
--- a/src/components/studio/result-actions.tsx
+++ b/src/components/studio/result-actions.tsx
@@ -20,6 +20,7 @@ import {
Layers2,
LayoutDashboard,
Mic2,
+ MicOff,
MoreHorizontal,
Pin,
Repeat,
@@ -91,6 +92,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {
"voice-change": AudioLines,
"loop-audio": Repeat,
"split-soundtrack": SlidersVertical,
+ "remove-dialogue": MicOff,
"copy-text": Copy,
"view-3d": Box,
download: Download,
diff --git a/src/lib/av/remove-dialogue.ts b/src/lib/av/remove-dialogue.ts
new file mode 100644
index 00000000..4939abec
--- /dev/null
+++ b/src/lib/av/remove-dialogue.ts
@@ -0,0 +1,240 @@
+import type { ChainSlot, Engine, GenerationRequest } from "@/lib/catalog/types";
+import type { ToolPlan, ToolStep } from "./audio-tools";
+import {
+ DBS_MODELS,
+ dbsChannelsFor,
+ splitTime,
+ SPLIT_MODEL,
+ type DbsChannels,
+ type SplitQuality,
+ type StemId,
+} from "./split";
+
+/**
+ * Video tools → Remove dialogue (DBS D2, docs/research/dbs-separation-7.md §4.4 and §9 D2): a video's dialogue taken
+ * out, kept alone, or kept with the music lowered under it, with the picture copied untouched. Pure: the page and the
+ * server (src/server/audio-tools.ts, tool "remove-dialogue") share it.
+ *
+ * - Open engine (ComfyUI + ComfyUI-DBS, CPU or GPU): two steps in one batch, no new graph. Graph A
+ * (separate-soundtrack-dbs on oss-dbs-separate) reads the video's soundtrack with LoadAudio and makes the stems; then
+ * the stream-copy mux (oss-mux): one stem for No dialogue (background) and Dialogue only (voice), which the provider
+ * runs as video-mux-audio-replace; the voice over the background at a lower level for Lower the music, which it runs
+ * as video-mux-audio. Concatenate Video with complete_audio copies the picture packet by packet.
+ * - Cloud: none. DBS is hosted nowhere, and SAM Audio in its place is the owner's call, not taken
+ * (docs/handoff/owner-decisions.json samAudioCloud: false): the cloud engine says the tool runs on your GPU.
+ */
+
+export const REMOVE_DIALOGUE_FEATURE = "remove-dialogue";
+export const REMOVE_DIALOGUE_MODELS = {
+ split: SPLIT_MODEL,
+ mux: "oss-mux",
+} as const;
+
+export type DialogueOutcome = "no-dialogue" | "dialogue-only" | "lower-music";
+
+export const OUTCOMES: { id: DialogueOutcome; label: string; hint: string }[] =
+ [
+ {
+ id: "no-dialogue",
+ label: "No dialogue",
+ hint: "Music and sound effects, no talking",
+ },
+ { id: "dialogue-only", label: "Dialogue only", hint: "Just the talking" },
+ {
+ id: "lower-music",
+ label: "Lower the music",
+ hint: "The talking, with the music and effects quieter under it",
+ },
+ ];
+export const outcomeLabel = (id: DialogueOutcome): string =>
+ OUTCOMES.find((o) => o.id === id)!.label;
+
+/** Lower the music: how far the music and effects go down (dB; the mux's backgroundVolumeDb is a whole number). */
+export const LOWER_MIN_DB = -30;
+export const LOWER_MAX_DB = 0;
+export const LOWER_DEFAULT_DB = -12;
+export const clampLowerDb = (db: number | undefined): number =>
+ Number.isFinite(db)
+ ? Math.min(LOWER_MAX_DB, Math.max(LOWER_MIN_DB, Math.round(db!)))
+ : LOWER_DEFAULT_DB;
+
+/** The longest video the tool takes (a CPU host takes about 4x its length to separate it; the stems are lossless FLAC). */
+export const REMOVE_DIALOGUE_MAX_SECONDS = 30 * 60;
+
+/** Why the cloud engine has no Remove dialogue (and what Engine mode "Paid APIs only" says). */
+export const CLOUD_REMOVE_PROBLEM =
+ "Remove dialogue runs on your GPU (open source): DBS isn't hosted on fal or Replicate, so the cloud engine can't take the dialogue out. Switch to the open engine.";
+export const CLOUD_ONLY_REMOVE_PROBLEM =
+ "Remove dialogue runs on your GPU (open source), but this install is set to paid cloud APIs only (Settings → Engine mode)";
+
+export const NO_SOUND_PROBLEM = "This clip has no sound";
+
+/** The stem the result keeps, and the one taken out (kept as a download beside the result). */
+export const KEPT_STEM: Record<DialogueOutcome, StemId | null> = {
+ "no-dialogue": "background",
+ "dialogue-only": "voice",
+ "lower-music": null,
+};
+export const REMOVED_STEM: Record<DialogueOutcome, StemId | null> = {
+ "no-dialogue": "voice",
+ "dialogue-only": "background",
+ "lower-music": null,
+};
+
+/** What's in the way of a run (in words the page shows), or null. */
+export function removeDialogueProblem(i: {
+ engine: Engine;
+ video?: string;
+ hasAudio?: boolean;
+ seconds?: number;
+}): string | null {
+ if (i.engine === "cloud") return CLOUD_REMOVE_PROBLEM;
+ if (!i.video) return "Add the video to take the dialogue out of";
+ if (i.hasAudio === false) return NO_SOUND_PROBLEM;
+ if (i.seconds && i.seconds > REMOVE_DIALOGUE_MAX_SECONDS)
+ return `Videos run up to ${REMOVE_DIALOGUE_MAX_SECONDS / 60} minutes here — trim it first (Video tools → Trim)`;
+ return null;
+}
+
+export interface RemoveDialogueInput {
+ engine: Engine;
+ /** The video (/api/files/…). */
+ video: string;
+ name?: string;
+ outcome?: DialogueOutcome;
+ /** Lower the music: the music and effects' level (dB, LOWER_MIN_DB…LOWER_MAX_DB). */
+ musicDb?: number;
+ /** Fast (DBS-BSRNN) or Best (DBS-TIGER); unset = the host's pick. */
+ quality?: SplitQuality;
+ /** The soundtrack's channel count (its header, else what the browser decoded). */
+ channels?: number;
+ /** Seconds the video runs, when known. */
+ seconds?: number;
+ /** False when the video's header says it has no sound. */
+ hasAudio?: boolean;
+}
+
+export interface RemoveDialoguePlan extends ToolPlan {
+ outcome: DialogueOutcome;
+ mode: DbsChannels;
+ /** Lower the music: the level the music and effects go to. */
+ musicDb: number | null;
+}
+
+/** The mux step's chain: which stem goes where (both come from the one split step). */
+export function muxChain(outcome: DialogueOutcome): ChainSlot[] {
+ if (outcome === "lower-music")
+ return [
+ { slot: "audio", stem: "voice" },
+ { slot: "audio2", stem: "background" },
+ ];
+ return [{ slot: "audio", stem: KEPT_STEM[outcome]! }];
+}
+
+const MUX_LABEL: Record<DialogueOutcome, string> = {
+ "no-dialogue": "Music and effects back on the video · picture copied",
+ "dialogue-only": "Dialogue back on the video · picture copied",
+ "lower-music": "Dialogue over the lowered music · picture copied",
+};
+
+/** Two steps on the open engine (split, then the stream-copy mux); throws what's in the way (in words the page shows). */
+export function planRemoveDialogue(i: RemoveDialogueInput): RemoveDialoguePlan {
+ const problem = removeDialogueProblem(i);
+ if (problem) throw new Error(problem);
+ const outcome = i.outcome ?? "no-dialogue";
+ const lower = outcome === "lower-music";
+ const musicDb = lower ? clampLowerDb(i.musicDb) : null;
+ // Mono: the background is the original minus the speech, so it keeps the original's stereo image at one pass's cost
+ // (§2.1's "fast stereo" bed). A file with more channels than ComfyUI can save is split in mono too, its bed made from
+ // the music and effects stems (dbsSurroundBed), so that rule needs nothing here.
+ const mode = dbsChannelsFor("mono", i.channels);
+ const name = i.name?.trim() || "video";
+ const title = `${outcomeLabel(outcome)}${musicDb !== null ? ` (${musicDb} dB)` : ""} · ${name}`;
+ const base = {
+ feature: REMOVE_DIALOGUE_FEATURE,
+ batchTitle: title,
+ } satisfies Partial<GenerationRequest>;
+ 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 seconds =
+ i.seconds && i.seconds > 0
+ ? Math.round(i.seconds * 1000) / 1000
+ : undefined;
+ const steps: ToolStep[] = [
+ {
+ key: "split",
+ request: {
+ ...base,
+ modelId: REMOVE_DIALOGUE_MODELS.split,
+ op: "separate-audio",
+ title: `Stems · ${name}`,
+ inputs: { video: i.video },
+ params: { extra, ...(seconds && { sourceDuration: seconds }) },
+ step: { label: "Dialogue, music, effects", index: 0, of: 2 },
+ },
+ },
+ {
+ key: "video",
+ // Both stems of Lower the music come from the one split (createPipeline takes a step twice for two stems).
+ after: lower ? ["split", "split"] : ["split"],
+ chain: muxChain(outcome),
+ request: {
+ ...base,
+ modelId: REMOVE_DIALOGUE_MODELS.mux,
+ op: "mux",
+ title,
+ inputs: { video: i.video },
+ ...(lower && { params: { extra: { backgroundVolumeDb: musicDb } } }),
+ step: { label: MUX_LABEL[outcome], index: 1, of: 2 },
+ },
+ },
+ ];
+ return {
+ steps,
+ length: seconds ?? null,
+ outcome,
+ mode,
+ musicDb,
+ summary:
+ outcome === "no-dialogue"
+ ? "Takes the talking out and keeps the music and sound effects. The picture is not re-encoded."
+ : outcome === "dialogue-only"
+ ? "Keeps only the talking: the music and sound effects go. The picture is not re-encoded."
+ : `Keeps the talking and lowers the music and sound effects by ${Math.abs(musicDb!)} dB under it. The picture is not re-encoded.`,
+ notes: [
+ outcome === "dialogue-only"
+ ? "Music or effects the model takes for speech (singing, a shout in a crowd) stay with the dialogue."
+ : "Speech the model misses (singing, a voice deep in the mix) stays in the music and effects: nothing is invented, sound is only moved between stems.",
+ lower
+ ? "The dialogue and the music & effects come back as downloads too."
+ : `The ${outcome === "no-dialogue" ? "dialogue" : "music & effects"} it takes out is kept as a download beside the result.`,
+ ...(i.channels && i.channels > 2
+ ? [
+ `This file has ${i.channels} channels: its new soundtrack comes out in mono, as ComfyUI saves mono or stereo only.`,
+ ]
+ : []),
+ ],
+ };
+}
+
+/** Writing the new soundtrack (AAC) and copying the picture's packets: seconds, beside the split (measured on the CPU host). */
+const MUX_OVERHEAD_SECONDS = 2;
+const MUX_SPEED = 40;
+
+/** About how long a run takes on the open engine: the split, then the mux (a range in seconds). */
+export function removeDialogueTime(o: {
+ seconds: number;
+ quality: SplitQuality;
+ mode: DbsChannels;
+ channels?: number | null;
+ device?: string | null;
+}): { low: number; high: number } {
+ const split = splitTime(o);
+ const mux = MUX_OVERHEAD_SECONDS + Math.max(0, o.seconds) / MUX_SPEED;
+ return {
+ low: Math.round(split.low + mux),
+ high: Math.round(split.high + mux * 2),
+ };
+}
diff --git a/src/lib/hubs.ts b/src/lib/hubs.ts
index 52f19403..94e96448 100644
--- a/src/lib/hubs.ts
+++ b/src/lib/hubs.ts
@@ -29,6 +29,7 @@ export const HUB_MODES: Record<HubKind, { id: string; label: string }[]> = {
"video-tools": [
{ id: "matte", label: "Remove background" },
{ id: "remove-object", label: "Remove object" },
+ { id: "remove-dialogue", label: "Remove dialogue" },
{ id: "evolution", label: "Evolution" },
{ id: "relight", label: "Relight" },
{ id: "depth", label: "Depth map" },
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 90fc17c6..d118ff47 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -29,6 +29,7 @@ export type OutputActionId =
| "voice-change"
| "loop-audio"
| "split-soundtrack"
+ | "remove-dialogue"
| "copy-text"
| "view-3d"
| "download"
@@ -125,6 +126,7 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =
link("upscale", "Upscale", `/upscale/video?video=${q(o.url)}`);
link("add-sound", "Add sound", `/audio/video?video=${q(o.url)}`);
link("split-soundtrack", "Split soundtrack", `/audio/split?video=${q(o.url)}`);
+ link("remove-dialogue", "Remove dialogue", `/video-tools/remove-dialogue?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)}` : ""}`);
@@ -175,7 +177,7 @@ const NEXT_STEPS: Partial<Record<OutputFile["kind"], OutputActionId[]>> = {
video: ["extend", "upscale", "add-sound"],
audio: ["lipsync", "voice-change", "split-soundtrack"],
};
-/** Clips made with their sound (or keeping the source's): Split soundtrack instead of Add sound. */
+/** Clips made with their sound (or keeping the source's): Remove dialogue and Split soundtrack instead of Upscale and Add sound. */
const SOUNDED_VIDEO_OPS = new Set<Generation["op"]>(["v2a", "mux", "lipsync", "trim", "captions"]);
/**
@@ -187,7 +189,7 @@ 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 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 video: OutputActionId[] | undefined = o.kind === "video" && g.op && SOUNDED_VIDEO_OPS.has(g.op) ? ["extend", "remove-dialogue", "split-soundtrack"] : 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))
diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.ts
index 59956ad7..70aab0e4 100644
--- a/src/server/audio-tools.ts
+++ b/src/server/audio-tools.ts
@@ -2,6 +2,7 @@ import "server-only";
import { z } from "zod";
import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";
import { CLOUD_ONLY_PROBLEM, DBS_MODELS, dbsChannelsFor, hostPick, missingDbs, planRemux, planSplit, splitTime } from "@/lib/av/split";
+import { CLOUD_ONLY_REMOVE_PROBLEM, LOWER_MAX_DB, LOWER_MIN_DB, NO_SOUND_PROBLEM, planRemoveDialogue, removeDialogueTime } from "@/lib/av/remove-dialogue";
import type { Engine, Generation } from "@/lib/catalog/types";
import { lastGpuDevice } from "./account-gpu";
import { createPipeline } from "./chains";
@@ -12,11 +13,12 @@ import { storedMedia } from "./storage";
import { tenant, tenantAccount } from "./tenant";
/**
- * 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.
+ * The Audio hub's Loop / extend, Join and Split soundtrack tools, and Video tools → Remove dialogue, 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, src/lib/av/split.ts or src/lib/av/remove-dialogue.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 and
+ * Remove dialogue run on the open engine only (DBS isn't hosted); a split's mix goes back on the video with a "remux" run
+ * on either engine.
*/
const FileUrl = z.string().startsWith("/api/files/").max(500);
@@ -56,6 +58,18 @@ export const AudioToolBody = z.discriminatedUnion("tool", [
channels: z.number().int().positive().max(64).optional(),
sourceDuration: z.number().positive().max(36_000).optional(),
}),
+ z.object({
+ tool: z.literal("remove-dialogue"),
+ engine: Engine,
+ video: FileUrl,
+ name: z.string().max(200).optional(),
+ outcome: z.enum(["no-dialogue", "dialogue-only", "lower-music"]).optional(),
+ /** Lower the music: the music and effects' level in dB. */
+ musicDb: z.number().min(LOWER_MIN_DB).max(LOWER_MAX_DB).optional(),
+ quality: z.enum(["fast", "best"]).optional(),
+ channels: z.number().int().positive().max(64).optional(),
+ sourceDuration: z.number().positive().max(36_000).optional(),
+ }),
z.object({
tool: z.literal("remux"),
engine: Engine,
@@ -98,9 +112,9 @@ function present(url: string, gone: string): void {
* storedMedia: only the asker's own files, header only, cached; a WebM or AVI header too: screen and browser recordings
* are WebM), or null when no reader knows the file.
*/
-function factsOf(url: string): ClipFacts | null {
+function factsOf(url: string, gone = "That audio file is gone — add it again"): ClipFacts | null {
const found = storedMedia(url, { allContainers: true });
- if (!found) throw new AudioToolError("That audio file is gone — add it again");
+ if (!found) throw new AudioToolError(gone);
const info = found.info;
if (!info) return null;
const duration = info.duration && info.duration > 0 ? Math.round(info.duration * 1000) / 1000 : undefined;
@@ -109,8 +123,10 @@ function factsOf(url: string): ClipFacts | null {
async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine; split?: ClipFacts; headerChannels?: number }> {
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.
+ // Split soundtrack and Remove dialogue run on the open engine only: an install set to paid APIs only says why, whichever
+ // engine was asked for.
if (body.tool === "split" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_PROBLEM);
+ if (body.tool === "remove-dialogue" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_REMOVE_PROBLEM);
if (mode !== "both" && body.engine !== mode) throw new AudioToolError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
try {
if (body.tool === "split") {
@@ -121,6 +137,14 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine
const channels = facts?.channels ?? body.channels;
return { engine: body.engine, ...planSplit({ ...body, seconds, channels }), split: { duration: seconds, channels }, headerChannels: facts?.channels };
}
+ if (body.tool === "remove-dialogue") {
+ const facts = factsOf(body.video, "That video is gone — add it again");
+ // A clip made without sound (a silent text-to-video take): nothing to take out, said before anything is queued.
+ if (facts?.hasAudio === false) throw new AudioToolError(NO_SOUND_PROBLEM);
+ const seconds = facts?.duration ?? body.sourceDuration;
+ const channels = facts?.channels ?? body.channels;
+ return { engine: body.engine, ...planRemoveDialogue({ ...body, seconds, channels, hasAudio: facts?.hasAudio }), split: { duration: seconds, channels }, headerChannels: facts?.channels };
+ }
if (body.tool === "remux") {
present(body.audio, "That mix is gone — export it again");
present(body.video, "That video is gone — add it again");
@@ -154,7 +178,7 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToo
cost = cost === null || r.costUsd === null ? null : cost + r.costUsd;
}
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") {
+ if (body.tool === "split" || body.tool === "remove-dialogue") {
// How long it takes on this host: its device (asked once a minute), the model it would use (one it has on disk) and
// how many passes. A model the host doesn't have is refused here, before the run, with how to install it.
// A visitor's price check (a guest's, or an account's on its own GPU) never calls a GPU, as main's price checks
@@ -173,7 +197,8 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToo
if (installed && !installed.includes(DBS_MODELS[quality])) throw new AudioToolError(missingDbs(DBS_MODELS[quality], installed));
const { duration: seconds, channels } = p.split ?? {};
Object.assign(out, { hostPick: pick, ...(device && { device }), ...(installed && { installed: installed.map((m) => (m === DBS_MODELS.best ? "best" : "fast")) }), ...(p.headerChannels && { channels: p.headerChannels }) });
- if (seconds) out.estimate = splitTime({ seconds, quality, mode: dbsChannelsFor(body.stereo ? "each channel" : "mono", channels), channels, device });
+ const mode = dbsChannelsFor(body.tool === "split" && body.stereo ? "each channel" : "mono", channels);
+ if (seconds) out.estimate = (body.tool === "split" ? splitTime : removeDialogueTime)({ seconds, quality, mode, channels, device });
}
return out;
}
diff --git a/src/server/chains.ts b/src/server/chains.ts
index a3e3bc13..7f14b6ec 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -660,8 +660,12 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}
if (a === s.key) throw new Error(`Step “${s.key}” can't wait for itself`);
if (!keys.has(a) && !Object.hasOwn(existing, a)) throw new Error(`Step “${s.key}” waits for “${a}”, which isn't in the pipeline`);
}
- if (new Set(after).size !== after.length) throw new Error(`Step “${s.key}” lists the same step twice`);
const chain = s.chain ?? s.request.chain;
+ // A step listed twice is two stems of one split (Remove dialogue's voice over its background): each slot it fills
+ // names a stem of its own. Anything else listed twice is a mistake.
+ const stemsFrom = (a: string) => after.flatMap((x, i) => (x === a ? [chain?.[i]?.stem?.toLowerCase()] : []));
+ const twice = after.filter((a, i) => after.indexOf(a) !== i);
+ if (twice.some((a) => stemsFrom(a).some((st) => !st) || new Set(stemsFrom(a)).size !== stemsFrom(a).length)) throw new Error(`Step “${s.key}” lists the same step twice`);
if (chain && chain.length !== after.length) throw new Error(`Step “${s.key}” has ${chain.length} chain slot${chain.length === 1 ? "" : "s"} for ${after.length} earlier step${after.length === 1 ? "" : "s"}`);
const stray = chain?.find((c) => c.stem && !AUDIO_SLOTS.has(c.slot));
if (stray) throw new Error(`Step “${s.key}”: a stem (“${stray.stem}”) only goes into an audio slot, not “${stray.slot}”`);
diff --git a/src/server/gpu/tools.ts b/src/server/gpu/tools.ts
index ff0dc643..ed5e4fd9 100644
--- a/src/server/gpu/tools.ts
+++ b/src/server/gpu/tools.ts
@@ -1,5 +1,6 @@
import "server-only";
import { SPLIT_MODEL } from "@/lib/av/split";
+import { REMOVE_DIALOGUE_MODELS } from "@/lib/av/remove-dialogue";
import { getModel, getPreset, MODELS, modelsFor, PRESETS } from "@/lib/catalog";
import { graphLoras } from "@/lib/catalog/character-swap";
import { PATH_MODELS } from "@/lib/catalog/cinema";
@@ -187,6 +188,16 @@ export const STUDIO_ROWS: StudioRowDef[] = [
{ href: "/upscale/hdr", label: "SDR to HDR", group: "Video tools", config: S.SDR_TO_HDR_STUDIO },
{ href: "/upscale/export", label: "Export", group: "Video tools", config: S.VIDEO_EXPORT_STUDIO },
{ href: "/video-tools", label: "Remove background", group: "Video tools", config: S.VIDEO_MATTE_STUDIO },
+ // DBS D2: the split, then the stream-copy mux (one stem in place of the sound, or the voice over the lowered bed).
+ {
+ href: "/video-tools/remove-dialogue",
+ label: "Remove dialogue",
+ group: "Video tools",
+ steps: [
+ { modelId: REMOVE_DIALOGUE_MODELS.split, op: "separate-audio" },
+ { modelId: REMOVE_DIALOGUE_MODELS.mux, op: "mux" },
+ ],
+ },
{ href: "/video-tools/relight", label: "Relight", group: "Video tools", config: S.VIDEO_RELIGHT_STUDIO },
{ href: "/video-tools/depth", label: "Depth map", group: "Video tools", config: S.VIDEO_DEPTH_STUDIO },
{ href: "/video-tools/join", label: "Join clips", group: "Video tools", config: S.JOIN_CLIPS_STUDIO },
diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.ts
index 5d158840..ce4b8dfc 100644
--- a/tests/library-pure.test.ts
+++ b/tests/library-pure.test.ts
@@ -112,6 +112,7 @@ describe("outputActions", () => {
"menu:upscale",
"menu:add-sound",
"menu:split-soundtrack",
+ "menu:remove-dialogue",
"menu:grade",
"menu:genjutsu",
"menu:finalize",
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index 8612767b..c90e631b 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -95,7 +95,7 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
it("lets guests and accounts open the tools' pages", () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
const cookie = auth.createSession(newAccount().id).value;
- for (const p of ["/audio/split", "/character-sheet", "/cinema", "/image", "/connect"]) {
+ for (const p of ["/audio/split", "/video-tools/remove-dialogue", "/character-sheet", "/cinema", "/image", "/connect"]) {
expect(passed(proxy(req(p))), `guest ${p}`).toBe(true);
expect(passed(proxy(req(p, { cookie }))), `account ${p}`).toBe(true);
}
@@ -232,6 +232,29 @@ describe("the routes: a visitor's price is its own GPU's, and the owner's charac
});
});
+describe("Remove dialogue (DBS D2) on /api/audio-tools", () => {
+ it("prices a visitor's run on its own GPU, never a demo, and only of its own video; the run is own-gpu-tool at the proxy", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const who = newAccount();
+ const cookie = auth.createSession(who.id).value;
+ const clip = (accountId?: string) => saveFile({ data: Buffer.from("a clip the header reader doesn't know"), contentType: "video/mp4", name: "talk.mp4", source: "upload", ...(accountId && { accountId }) }).url;
+ const owners = clip();
+ const body = (video: string) => ({ tool: "remove-dialogue", engine: "open", video, name: "Talk", sourceDuration: 12 });
+ for (const c of [undefined, cookie]) {
+ const r = await audioTools.POST(call("/api/audio-tools?preview=1", body(owners), c));
+ expect(r.status).toBe(422);
+ expect((await r.json()).error).toBe("That video is gone — add it again");
+ }
+ const account = await audioTools.POST(call("/api/audio-tools?preview=1", body(clip(who.id)), cookie));
+ expect(await account.json()).toMatchObject({ steps: 2, costUsd: 0, demo: false, length: 12 });
+ const owner = await audioTools.POST(call("/api/audio-tools?preview=1", body(owners), auth.createSession().value));
+ expect(await owner.json()).toMatchObject({ steps: 2, demo: true });
+ const run = proxy(req("/api/audio-tools", { method: "POST", cookie }));
+ expect(run.status).toBe(403);
+ expect((await run.json()).code).toBe("own-gpu-tool");
+ });
+});
+
describe("the GPU pre-flight board lists PR #15's tools like main's studios", () => {
const idx = loadIndex();
const row = (href: string) => STUDIO_ROWS.find((r) => r.href === href)!;
@@ -239,6 +262,7 @@ describe("the GPU pre-flight board lists PR #15's tools like main's studios", ()
it("has a row for Split soundtrack, the fly path and the turnaround, each on graphs the requirement index knows", () => {
const want: Record<string, { label: string; group: string; workflows: string[]; loras?: string[] }> = {
"/audio/split": { label: "Split soundtrack", group: "Audio", workflows: ["separate-soundtrack-dbs"] },
+ "/video-tools/remove-dialogue": { label: "Remove dialogue", group: "Video tools", workflows: ["separate-soundtrack-dbs", "video-mux-audio"] },
"/cinema": { label: "Fly path", group: "Video", workflows: ["wan21-i2v-uni3c-path"] },
"/character-sheet": { label: "Turnaround", group: "Video", workflows: ["wan22-flf2v-14b", "qwen-image-edit-2511-multi"], loras: ["qwen-image-edit-2511-multiple-angles-lora.safetensors"] },
};
diff --git a/tests/remove-dialogue.test.ts b/tests/remove-dialogue.test.ts
new file mode 100644
index 00000000..77886bfa
--- /dev/null
+++ b/tests/remove-dialogue.test.ts
@@ -0,0 +1,682 @@
+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_REMOVE_PROBLEM,
+ CLOUD_REMOVE_PROBLEM,
+ clampLowerDb,
+ KEPT_STEM,
+ LOWER_DEFAULT_DB,
+ muxChain,
+ NO_SOUND_PROBLEM,
+ OUTCOMES,
+ planRemoveDialogue,
+ REMOVE_DIALOGUE_FEATURE,
+ REMOVE_DIALOGUE_MAX_SECONDS,
+ REMOVED_STEM,
+ removeDialogueProblem,
+ removeDialogueTime,
+} from "@/lib/av/remove-dialogue";
+import { splitTime } from "@/lib/av/split";
+import { resolveWorkflowId } from "@/lib/comfy-variants";
+import { HUB_MODES, modeHref } from "@/lib/hubs";
+import type { Generation, GenInput } from "@/lib/catalog/types";
+
+// Video tools → Remove dialogue (DBS D2): the planner, the two-step chain on the open engine (graph A, then the
+// stream-copy mux), the graph the mux runs, the provider's bindings and the API in demo mode.
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-remove-dialogue-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: the open models run on the demo provider.
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { saveFile } = await import("@/server/storage");
+const gens = await import("@/server/generations");
+const { createPipeline } = await import("@/server/chains");
+const { prepareWorkflow } = await import("@/server/providers/comfyui");
+const route = await import("@/app/api/audio-tools/route");
+const { nextSteps, outputActions } = await import("@/lib/output-actions");
+const { STUDIO_ROWS, studioTool } = await import("@/server/gpu/tools");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const VIDEO = "/api/files/uploads/2026-11-01/interview.mp4";
+
+/** A small MP4: a video track and, unless `channels` is null, an AAC sound track with that many channels (2 s each). */
+function mp4Sound(channels: number | null): Buffer {
+ const u32 = (...v: number[]) =>
+ Buffer.concat(
+ v.map((n) =>
+ Buffer.from([n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]),
+ ),
+ );
+ const box = (type: string, ...parts: Buffer[]) => {
+ const body = Buffer.concat(parts);
+ return Buffer.concat([u32(8 + body.length), Buffer.from(type), body]);
+ };
+ const trak = (handler: string, ...stbl: Buffer[]) =>
+ box(
+ "trak",
+ box(
+ "mdia",
+ box("mdhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(4)),
+ box("hdlr", u32(0, 0), Buffer.from(handler), Buffer.alloc(12)),
+ box("minf", box("stbl", ...stbl)),
+ ),
+ );
+ const entry = Buffer.alloc(28);
+ entry.writeUInt16BE(1, 6);
+ entry.writeUInt16BE(channels ?? 2, 16);
+ entry.writeUInt16BE(16, 18);
+ const sound =
+ channels === null
+ ? []
+ : [trak("soun", box("stsd", u32(0, 1), box("mp4a", entry)))];
+ return Buffer.concat([
+ box("ftyp", Buffer.from("isom"), u32(0)),
+ box(
+ "moov",
+ box("mvhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(80)),
+ trak("vide", box("stts", u32(0, 1, 50, 40))),
+ ...sound,
+ ),
+ ]);
+}
+const video = (channels: number | null = 2, name = "interview.mp4") =>
+ saveFile({
+ data: mp4Sound(channels),
+ contentType: "video/mp4",
+ 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 plan per outcome (open engine)", () => {
+ it("No dialogue: graph A on the video, then the background stem in place of its sound", () => {
+ const p = planRemoveDialogue({
+ engine: "open",
+ video: VIDEO,
+ name: "Interview",
+ });
+ expect(p.outcome).toBe("no-dialogue");
+ expect(p.steps.map((s) => s.key)).toEqual(["split", "video"]);
+ const [split, mux] = p.steps;
+ expect(split.request).toMatchObject({
+ modelId: "oss-dbs-separate",
+ op: "separate-audio",
+ feature: REMOVE_DIALOGUE_FEATURE,
+ inputs: { video: VIDEO },
+ params: { extra: { channels: "mono" } },
+ step: { index: 0, of: 2 },
+ });
+ expect(split.after).toBeUndefined();
+ expect(mux.request).toMatchObject({
+ modelId: "oss-mux",
+ op: "mux",
+ inputs: { video: VIDEO },
+ title: "No dialogue · Interview",
+ batchTitle: "No dialogue · Interview",
+ step: { index: 1, of: 2 },
+ });
+ expect(mux.after).toEqual(["split"]);
+ expect(mux.chain).toEqual([{ slot: "audio", stem: "background" }]);
+ expect(mux.request.params).toBeUndefined();
+ expect(p.summary).toBe(
+ "Takes the talking out and keeps the music and sound effects. The picture is not re-encoded.",
+ );
+ expect(p.notes[0]).toMatch(
+ /^Speech the model misses .* stays in the music and effects/,
+ );
+ expect(p.notes[1]).toBe(
+ "The dialogue it takes out is kept as a download beside the result.",
+ );
+ });
+
+ it("Dialogue only: the voice stem in place of the sound", () => {
+ const p = planRemoveDialogue({
+ engine: "open",
+ video: VIDEO,
+ outcome: "dialogue-only",
+ });
+ expect(p.steps[1].chain).toEqual([{ slot: "audio", stem: "voice" }]);
+ expect(p.steps[1].after).toEqual(["split"]);
+ expect(p.steps[1].request.title).toBe("Dialogue only · video");
+ expect(p.notes[1]).toBe(
+ "The music & effects it takes out is kept as a download beside the result.",
+ );
+ });
+
+ it("Lower the music: the voice over the background at the slider's level, both from the one split", () => {
+ const p = planRemoveDialogue({
+ engine: "open",
+ video: VIDEO,
+ outcome: "lower-music",
+ musicDb: -18,
+ });
+ const mux = p.steps[1];
+ expect(mux.after).toEqual(["split", "split"]);
+ expect(mux.chain).toEqual([
+ { slot: "audio", stem: "voice" },
+ { slot: "audio2", stem: "background" },
+ ]);
+ expect(mux.request.params).toEqual({ extra: { backgroundVolumeDb: -18 } });
+ expect(p.musicDb).toBe(-18);
+ expect(p.summary).toBe(
+ "Keeps the talking and lowers the music and sound effects by 18 dB under it. The picture is not re-encoded.",
+ );
+ // The default and the slider's ends.
+ expect(
+ planRemoveDialogue({
+ engine: "open",
+ video: VIDEO,
+ outcome: "lower-music",
+ }).musicDb,
+ ).toBe(LOWER_DEFAULT_DB);
+ expect([
+ clampLowerDb(-40),
+ clampLowerDb(3),
+ clampLowerDb(-12.4),
+ clampLowerDb(undefined),
+ ]).toEqual([-30, 0, -12, -12]);
+ });
+
+ it("keeps one stem and lists the other as the one taken out", () => {
+ expect(OUTCOMES.map((o) => o.id)).toEqual([
+ "no-dialogue",
+ "dialogue-only",
+ "lower-music",
+ ]);
+ expect(KEPT_STEM).toEqual({
+ "no-dialogue": "background",
+ "dialogue-only": "voice",
+ "lower-music": null,
+ });
+ expect(REMOVED_STEM).toEqual({
+ "no-dialogue": "voice",
+ "dialogue-only": "background",
+ "lower-music": null,
+ });
+ for (const o of OUTCOMES)
+ expect(
+ muxChain(o.id).every(
+ (c) => c.stem === "voice" || c.stem === "background",
+ ),
+ ).toBe(true);
+ });
+
+ it("passes the model asked for and the channel count; a surround file is split in mono", () => {
+ const best = planRemoveDialogue({
+ engine: "open",
+ video: VIDEO,
+ quality: "best",
+ channels: 2,
+ seconds: 20,
+ });
+ expect(best.steps[0].request.params).toEqual({
+ extra: {
+ channels: "mono",
+ separationModel: "DBS-TIGER-DnR",
+ sourceChannels: 2,
+ },
+ sourceDuration: 20,
+ });
+ expect(best.length).toBe(20);
+ const five = planRemoveDialogue({
+ engine: "open",
+ video: VIDEO,
+ channels: 6,
+ });
+ expect(five.mode).toBe("mono");
+ expect(five.steps[0].request.params?.extra).toEqual({
+ channels: "mono",
+ sourceChannels: 6,
+ });
+ expect(five.notes.at(-1)).toBe(
+ "This file has 6 channels: its new soundtrack comes out in mono, as ComfyUI saves mono or stereo only.",
+ );
+ });
+});
+
+describe("what's in the way", () => {
+ it("names the cloud, a missing video, a clip with no sound and one over 30 minutes", () => {
+ expect(removeDialogueProblem({ engine: "cloud", video: VIDEO })).toBe(
+ CLOUD_REMOVE_PROBLEM,
+ );
+ expect(CLOUD_REMOVE_PROBLEM).toMatch(
+ /^Remove dialogue runs on your GPU \(open source\)/,
+ );
+ expect(removeDialogueProblem({ engine: "open" })).toBe(
+ "Add the video to take the dialogue out of",
+ );
+ expect(
+ removeDialogueProblem({ engine: "open", video: VIDEO, hasAudio: false }),
+ ).toBe(NO_SOUND_PROBLEM);
+ expect(NO_SOUND_PROBLEM).toBe("This clip has no sound");
+ expect(
+ removeDialogueProblem({
+ engine: "open",
+ video: VIDEO,
+ seconds: REMOVE_DIALOGUE_MAX_SECONDS,
+ }),
+ ).toBeNull();
+ expect(
+ removeDialogueProblem({
+ engine: "open",
+ video: VIDEO,
+ seconds: REMOVE_DIALOGUE_MAX_SECONDS + 1,
+ }),
+ ).toBe(
+ "Videos run up to 30 minutes here — trim it first (Video tools → Trim)",
+ );
+ expect(() => planRemoveDialogue({ engine: "cloud", video: VIDEO })).toThrow(
+ CLOUD_REMOVE_PROBLEM,
+ );
+ });
+});
+
+describe("time on the open engine", () => {
+ it("is the split's time plus the mux's", () => {
+ const o = {
+ seconds: 20,
+ quality: "fast" as const,
+ mode: "mono" as const,
+ channels: 2,
+ };
+ const t = removeDialogueTime(o);
+ const s = splitTime(o);
+ expect(t.low).toBeGreaterThan(s.low);
+ expect(t.high).toBeGreaterThan(s.high);
+ expect(t.low).toBeLessThan(t.high);
+ expect(removeDialogueTime({ ...o, device: "cuda" }).high).toBeLessThan(
+ t.low,
+ );
+ });
+});
+
+describe("the mux graph the provider picks", () => {
+ const has = (id: string) =>
+ ["video-mux-audio", "video-mux-audio-replace"].includes(id);
+ const graphFor = (outcome: "no-dialogue" | "dialogue-only" | "lower-music") =>
+ resolveWorkflowId("video-mux-audio", {
+ op: "mux",
+ clips: 0,
+ images: 0,
+ audio2: muxChain(outcome).some((c) => c.slot === "audio2"),
+ extra: {},
+ has,
+ });
+
+ it("replaces the sound with one stem, and mixes two for Lower the music", () => {
+ expect(graphFor("no-dialogue")).toBe("video-mux-audio-replace");
+ expect(graphFor("dialogue-only")).toBe("video-mux-audio-replace");
+ expect(graphFor("lower-music")).toBe("video-mux-audio");
+ });
+});
+
+describe("the provider's bindings for the two steps", () => {
+ const ctx = (op: string) => ({
+ generationId: "gen1",
+ op,
+ upload: async (_d: unknown, _t: unknown, name: string) => `up_${name}`,
+ media: () => undefined,
+ device: async () => "cpu",
+ dbsModels: async () => undefined,
+ });
+
+ it("binds the video to LoadAudio for the oss-dbs-separate step (its soundtrack, no frames decoded)", async () => {
+ const p = planRemoveDialogue({ engine: "open", video: VIDEO });
+ const req = p.steps[0].request;
+ const input: GenInput = {
+ seed: 1,
+ video: "interview.mp4",
+ extra: req.params?.extra as Record<string, unknown>,
+ };
+ const { workflow } = await prepareWorkflow(
+ "separate-soundtrack-dbs",
+ input,
+ ctx("separate-audio"),
+ );
+ expect(workflow["1"]).toMatchObject({
+ class_type: "LoadAudio",
+ inputs: { audio: "interview.mp4" },
+ });
+ expect(
+ Object.values(workflow).some(
+ (n) =>
+ n.class_type === "LoadVideo" || n.class_type === "GetVideoComponents",
+ ),
+ ).toBe(false);
+ expect(workflow["3"].inputs.channels).toBe("mono");
+ });
+
+ it("puts a stem on the picture with the stream-copy graph, and the voice over the lowered bed", async () => {
+ const one = await prepareWorkflow(
+ "video-mux-audio",
+ { seed: 1, video: "interview.mp4", audio: "bg.flac", extra: {} },
+ ctx("mux"),
+ );
+ expect(one.manifest.id).toBe("video-mux-audio-replace");
+ expect(one.workflow["3"].inputs.audio).toBe("bg.flac");
+ expect(
+ Object.values(one.workflow).find(
+ (n) => n.class_type === "ConcatenateVideo",
+ )?.inputs.complete_audio,
+ ).toBeDefined();
+ const lower = await prepareWorkflow(
+ "video-mux-audio",
+ {
+ seed: 1,
+ video: "interview.mp4",
+ audio: "voice.flac",
+ audio2: "bg.flac",
+ extra: { backgroundVolumeDb: -12 },
+ } as GenInput,
+ ctx("mux"),
+ );
+ expect(lower.manifest.id).toBe("video-mux-audio");
+ expect([
+ lower.workflow["3"].inputs.audio,
+ lower.workflow["4"].inputs.audio,
+ lower.workflow["5"].inputs.volume,
+ ]).toEqual(["voice.flac", "bg.flac", -12]);
+ });
+});
+
+describe("createPipeline takes one step twice for two of its stems", () => {
+ it("allows two different stems of one split, and refuses anything else listed twice", () => {
+ const split = {
+ key: "split",
+ request: {
+ feature: "test",
+ modelId: "oss-dbs-separate",
+ op: "separate-audio" as const,
+ inputs: { audio: "/api/files/x.wav" },
+ },
+ };
+ const mux = (chain: { slot: "audio" | "audio2"; stem?: string }[]) => ({
+ key: "mux",
+ after: ["split", "split"],
+ chain,
+ request: {
+ feature: "test",
+ modelId: "oss-mux",
+ op: "mux" as const,
+ inputs: { video: "/api/files/x.mp4" },
+ },
+ });
+ expect(() =>
+ createPipeline([split, mux([{ slot: "audio" }, { slot: "audio2" }])]),
+ ).toThrow("Step “mux” lists the same step twice");
+ expect(() =>
+ createPipeline([
+ split,
+ mux([
+ { slot: "audio", stem: "voice" },
+ { slot: "audio2", stem: "voice" },
+ ]),
+ ]),
+ ).toThrow("Step “mux” lists the same step twice");
+ const run = createPipeline([
+ split,
+ mux([
+ { slot: "audio", stem: "voice" },
+ { slot: "audio2", stem: "background" },
+ ]),
+ ]);
+ expect(run.items).toHaveLength(2);
+ });
+});
+
+describe("Remove dialogue in Video tools", () => {
+ it("is a mode after Remove object with its own path", () => {
+ const ids = HUB_MODES["video-tools"].map((m) => m.id);
+ expect(ids.indexOf("remove-dialogue")).toBe(
+ ids.indexOf("remove-object") + 1,
+ );
+ expect(
+ HUB_MODES["video-tools"].find((m) => m.id === "remove-dialogue")?.label,
+ ).toBe("Remove dialogue");
+ expect(modeHref("video-tools", "remove-dialogue")).toBe(
+ "/video-tools/remove-dialogue",
+ );
+ });
+
+ it("is a hand-off from any video, and a next step under a clip that has its sound", () => {
+ const gen = (op: Generation["op"]): Generation =>
+ ({
+ id: "g1",
+ status: "succeeded",
+ kind: "video",
+ op,
+ feature: "video",
+ outputs: [{ kind: "video", url: "/api/files/clip.mp4" }],
+ request: { modelId: "x" },
+ createdAt: 1,
+ }) as unknown as Generation;
+ const link = outputActions(gen("t2v"), 0).find(
+ (a) => a.id === "remove-dialogue",
+ );
+ expect(link).toMatchObject({
+ label: "Remove dialogue",
+ placement: "menu",
+ href: "/video-tools/remove-dialogue?video=%2Fapi%2Ffiles%2Fclip.mp4",
+ });
+ expect(nextSteps(gen("lipsync"), 0).map((a) => a.id)).toEqual([
+ "extend",
+ "remove-dialogue",
+ "split-soundtrack",
+ ]);
+ expect(nextSteps(gen("t2v"), 0).map((a) => a.id)).toEqual([
+ "extend",
+ "upscale",
+ "add-sound",
+ ]);
+ });
+
+ it("has a row on the GPU pre-flight board: the split's graph and the mux's", () => {
+ const row = STUDIO_ROWS.find(
+ (r) => r.href === "/video-tools/remove-dialogue",
+ )!;
+ expect(row).toMatchObject({
+ label: "Remove dialogue",
+ group: "Video tools",
+ });
+ const t = studioTool(row)!;
+ expect(t.ref).toBe("studio:/video-tools/remove-dialogue");
+ expect(t.workflows).toEqual(
+ expect.arrayContaining(["separate-soundtrack-dbs", "video-mux-audio"]),
+ );
+ });
+});
+
+describe("POST /api/audio-tools remove-dialogue (demo mode)", () => {
+ it("prices it as free with a time estimate, and runs both steps into the Library", async () => {
+ const media = video(2);
+ const preview = await (
+ await post(
+ {
+ tool: "remove-dialogue",
+ engine: "open",
+ video: media,
+ name: "Interview",
+ },
+ true,
+ )
+ ).json();
+ expect(preview).toMatchObject({
+ steps: 2,
+ costUsd: 0,
+ demo: true,
+ length: 2,
+ channels: 2,
+ hostPick: "fast",
+ });
+ expect(preview.summary).toBe(
+ "Takes the talking out and keeps the music and sound effects. The picture is not re-encoded.",
+ );
+ expect(preview.estimate).toEqual(
+ removeDialogueTime({
+ seconds: 2,
+ quality: "fast",
+ mode: "mono",
+ channels: 2,
+ }),
+ );
+
+ const res = await post({
+ tool: "remove-dialogue",
+ engine: "open",
+ video: media,
+ name: "Interview",
+ outcome: "lower-music",
+ musicDb: -15,
+ });
+ expect(res.status).toBe(201);
+ const run = await res.json();
+ expect(run.items.map((g: Generation) => [g.modelId, g.op])).toEqual([
+ ["oss-dbs-separate", "separate-audio"],
+ ["oss-mux", "mux"],
+ ]);
+ expect(run.result).toMatchObject({
+ feature: REMOVE_DIALOGUE_FEATURE,
+ modelId: "oss-mux",
+ op: "mux",
+ provider: "mock",
+ });
+ expect(run.result.request.params.extra).toEqual({
+ backgroundVolumeDb: -15,
+ });
+ const g = await finished(run.result.id);
+ expect(g.status).toBe("succeeded");
+ expect(g.outputs[0].kind).toBe("video");
+ // The removed stems stay in the Library beside it.
+ const split = gens.getGeneration(run.items[0].id)!;
+ expect(
+ split.outputs.filter((o) => o.kind === "audio").map((o) => o.meta?.stem),
+ ).toEqual(["voice", "music", "effects", "background"]);
+ }, 30_000);
+
+ it("refuses a clip with no sound, the cloud, and an install set to paid APIs only, before anything is queued", async () => {
+ const silent = video(null, "t2v.mp4");
+ for (const preview of [true, false]) {
+ const res = await post(
+ { tool: "remove-dialogue", engine: "open", video: silent },
+ preview,
+ );
+ expect(res.status).toBe(422);
+ expect((await res.json()).error).toBe(NO_SOUND_PROBLEM);
+ }
+ const media = video(2, "b.mp4");
+ expect(
+ (
+ await (
+ await post(
+ { tool: "remove-dialogue", engine: "cloud", video: media },
+ true,
+ )
+ ).json()
+ ).error,
+ ).toBe(CLOUD_REMOVE_PROBLEM);
+ setSetting("engineMode", "cloud");
+ try {
+ expect(
+ (
+ await (
+ await post({
+ tool: "remove-dialogue",
+ engine: "open",
+ video: media,
+ })
+ ).json()
+ ).error,
+ ).toBe(CLOUD_ONLY_REMOVE_PROBLEM);
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ expect(
+ (
+ await (
+ await post({
+ tool: "remove-dialogue",
+ engine: "open",
+ video: "/etc/passwd",
+ })
+ ).json()
+ ).error,
+ ).toBe("Add the video to take the dialogue out of");
+ expect(
+ (
+ await (
+ await post(
+ {
+ tool: "remove-dialogue",
+ engine: "open",
+ video: "/api/files/uploads/gone.mp4",
+ },
+ true,
+ )
+ ).json()
+ ).error,
+ ).toBe("That video is gone — add it again");
+ expect(
+ (
+ await (
+ await post(
+ {
+ tool: "remove-dialogue",
+ engine: "open",
+ video: media,
+ musicDb: -40,
+ },
+ true,
+ )
+ ).json()
+ ).error,
+ ).toBe("Lower the music by 0 to 30 dB");
+ });
+
+ it("refuses a video over 30 minutes by the browser's length when the header can't say", async () => {
+ const odd = saveFile({
+ data: Buffer.from("not really a video"),
+ contentType: "video/mp4",
+ name: "long.mp4",
+ source: "upload",
+ }).url;
+ const res = await post(
+ {
+ tool: "remove-dialogue",
+ engine: "open",
+ video: odd,
+ sourceDuration: 1801,
+ },
+ true,
+ );
+ expect((await res.json()).error).toBe(
+ "Videos run up to 30 minutes here — trim it first (Video tools → Trim)",
+ );
+ });
+});
diff --git a/tests/ux-flows.test.ts b/tests/ux-flows.test.ts
index d10b9a3f..61d017f0 100644
--- a/tests/ux-flows.test.ts
+++ b/tests/ux-flows.test.ts
@@ -61,11 +61,12 @@ describe("next steps under a fresh result", () => {
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", "split-soundtrack"]);
- // A clip that has its sound (Sound for video, a soundtrack mux) offers Split soundtrack in place of Add sound.
+ // A clip that has its sound (Sound for video, a soundtrack mux) offers Remove dialogue and Split soundtrack in place
+ // of Upscale and 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"],
+ ["Remove dialogue", "/video-tools/remove-dialogue?video=%2Fapi%2Ffiles%2Fclip.mp4"],
["Split soundtrack", "/audio/split?video=%2Fapi%2Ffiles%2Fclip.mp4"],
]);
});