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
Sound tools: split and remix from Assist, a Canvas split node, Clean the voice first and Original sound
Adarsh41bc70902237
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsindex 94053480..9fe5a30c 100644--- a/src/app/api/auth/me/route.ts+++ b/src/app/api/auth/me/route.ts@@ -4,6 +4,7 @@ import { z } from "zod";import { AccountError, accountGpu, authEnabled, createSession, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, setAccountPassword, validToken, verifyAccount } from "@/server/auth";import { runnerFacts } from "@/server/computer/tasks";import { getSetting } from "@/server/settings";+import { soundLive } from "@/server/sound-live";import { removeAccount } from "@/server/account-sweep";import { hit } from "@/server/rate";@@ -18,6 +19,8 @@ export async function GET(request: Request) {const computer = account ? accountGpu(account.id)?.mode === "computer" : owner && !validToken(request.headers.get("authorization")) && getSetting("comfyWhere") === "computer";// Where that computer's tab last found ComfyUI (another browser of theirs starts looking there).const comfyPort = computer ? runnerFacts(account ? `acct:${account.id}` : "owner")?.port : undefined;+ // The sound features that have passed a real run (src/server/sound-live.ts): their switches start on and show to everyone.+ const live = Object.entries(soundLive()).flatMap(([k, v]) => (v ? [k] : []));return Response.json({signedIn: owner || !!account,@@ -25,6 +28,7 @@ export async function GET(request: Request) {publicSignup: open,...(account && { account: { email: account.email } }),...(computer && { computer: true, ...(comfyPort && { comfyPort }) }),+ ...(live.length && { soundLive: live }),},{ headers: { "Cache-Control": "no-store" } },);diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 31b9c8d7..2054c6ff 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -11,6 +11,8 @@ import { OPERATION_LABELS } from "@/lib/catalog/types";import { ANY_ANGLE } from "@/lib/catalog/any-angle";import { directRunFeatures } from "@/lib/catalog/genjutsu";import { genjutsuLive } from "@/server/genjutsu-live";+import { soundLive } from "@/server/sound-live";+import { wantsVoiceFirst } from "@/lib/av/voice-first";import { relightRunTitle } from "@/lib/relight/engine";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { accountInputProblem } from "@/server/account-inputs";@@ -97,6 +99,8 @@ export async function POST(request: Request) {// Genjutsu's new makers open one by one (src/server/genjutsu-live.ts): sent here directly, a maker that hasn't opened// runs for the owner only, as on the Genjutsu page.if (viewer.kind !== "owner") {+ // "Clean the voice first" opens to visitors once it has passed a real run (src/server/sound-live.ts).+ if (wantsVoiceFirst(asked) && !soundLive()["clean-voice-first"]) return refuse(403, OWN_GPU_TOOL_MESSAGE, { code: "own-gpu-tool" });const extra = asked.params?.extra?.openjutsu;const needs = directRunFeatures(asked.modelId, extra && typeof extra === "object" ? (extra as Record<string, unknown>) : {});if (needs) {diff --git a/src/app/api/swap-studio/projects/[id]/assemble/route.ts b/src/app/api/swap-studio/projects/[id]/assemble/route.tsindex 1d36b80c..6ed6628b 100644--- a/src/app/api/swap-studio/projects/[id]/assemble/route.ts+++ b/src/app/api/swap-studio/projects/[id]/assemble/route.ts@@ -1,13 +1,16 @@+import { ORIGINAL_SOUND_IDS } from "@/lib/av/original-sound";import { z } from "zod";import { body, handle } from "@/server/shorts-schemas";import { assemble } from "@/server/swap-studio";-const Assemble = z.object({ clipId: z.string().min(1).max(80) });+/** originalSound: what of the clip's sound goes back (src/lib/av/original-sound.ts). */+const Assemble = z.object({ clipId: z.string().min(1).max(80), originalSound: z.enum(ORIGINAL_SOUND_IDS).optional() });/** Assemble a clip: its chosen takes over the original timeline, with the clip's own sound. */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/assemble">) {return handle(async () => {const { id } = await ctx.params;- return Response.json(assemble(id, (await body(request, Assemble, "Pick a clip")).clipId), { status: 201 });+ const b = await body(request, Assemble, "Pick a clip");+ return Response.json(assemble(id, b.clipId, { originalSound: b.originalSound }), { status: 201 });}, request);}diff --git a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts b/src/app/api/swap-studio/projects/[id]/transcribe/route.tsindex 01681252..b20ed0a5 100644--- a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts+++ b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts@@ -2,12 +2,14 @@ import { z } from "zod";import { body, handle } from "@/server/shorts-schemas";import { transcribe } from "@/server/swap-studio";-const Transcribe = z.object({ clipId: z.string().min(1).max(80) });+/** cleanVoiceFirst: the speech apart from the music and effects before it's read (src/lib/av/voice-first.ts). */+const Transcribe = z.object({ clipId: z.string().min(1).max(80), cleanVoiceFirst: z.boolean().optional() });/** The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU). */export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) {return handle(async () => {const { id } = await ctx.params;- return Response.json(transcribe(id, (await body(request, Transcribe, "Pick a clip")).clipId));+ const b = await body(request, Transcribe, "Pick a clip");+ return Response.json(transcribe(id, b.clipId, { cleanVoiceFirst: b.cleanVoiceFirst }));}, request);}diff --git a/src/components/audio-tools/voice-first-switch.tsx b/src/components/audio-tools/voice-first-switch.tsxnew file mode 100644index 00000000..07a2f8b1--- /dev/null+++ b/src/components/audio-tools/voice-first-switch.tsx@@ -0,0 +1,44 @@+"use client";++import { useId } from "react";+import { Switch } from "@/components/ui/switch";+import { useIsAccount, useIsGuest, useSoundLive } from "@/lib/api";+import { VOICE_FIRST_BED, VOICE_FIRST_FEATURE, VOICE_FIRST_HINT, VOICE_FIRST_LABEL, voiceFirstCost } from "@/lib/av/voice-first";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";++/**+ * "Clean the voice first" beside a transcript or a lip sync (src/lib/av/voice-first.ts): the switch, what it does on+ * this engine and what it adds (time on your GPU, a price in the cloud). Until it has passed a real run it shows for the+ * studio's owner only and starts off (the server refuses it to visitors); once it has, it shows for everyone.+ */+export function useVoiceFirstLive(): boolean {+ return useSoundLive(VOICE_FIRST_FEATURE);+}++export function useVoiceFirstShown(): boolean {+ const guest = useIsGuest();+ const account = useIsAccount();+ const live = useVoiceFirstLive();+ return live || (!guest && !account);+}++export function VoiceFirstSwitch({ engine, on, onChange, seconds, lip, className }: { engine: Engine; on: boolean; onChange: (on: boolean) => void; seconds?: number; lip?: boolean; className?: string }) {+ const id = useId();+ const cost = voiceFirstCost(engine, seconds);+ return (+ <div className={cn("flex min-w-0 items-start gap-2", className)}>+ <Switch id={id} checked={on} onCheckedChange={onChange} className="mt-0.5 shrink-0" />+ <div className="min-w-0">+ <label htmlFor={id} className="text-[13px] font-medium">+ {VOICE_FIRST_LABEL}+ {on && cost ? <span className="font-normal text-muted-foreground"> · {cost}</span> : null}+ </label>+ <p className="text-[12px] text-pretty text-muted-foreground">+ {VOICE_FIRST_HINT[engine]}+ {lip ? ` ${VOICE_FIRST_BED[engine]}` : ""}+ </p>+ </div>+ </div>+ );+}diff --git a/src/components/av/original-sound-picker.tsx b/src/components/av/original-sound-picker.tsxnew file mode 100644index 00000000..ce04cfc8--- /dev/null+++ b/src/components/av/original-sound-picker.tsx@@ -0,0 +1,39 @@+"use client";++import { useId } from "react";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { CLOUD_ORIGINAL_SOUND, ORIGINAL_SOUNDS, type OriginalSound } from "@/lib/av/original-sound";+import type { Engine } from "@/lib/catalog/types";+import { cn } from "@/lib/utils";++/**+ * "Original sound" (src/lib/av/original-sound.ts): what of the clip's sound goes back under its new picture. On your GPU+ * all four choices; in the cloud Everything, with a line saying where the others run.+ */+export function OriginalSoundPicker({ engine, value, onChange, className, label = "Original sound" }: { engine: Engine; value: OriginalSound; onChange: (v: OriginalSound) => void; className?: string; label?: string }) {+ const id = useId();+ const cloud = engine === "cloud";+ const current = cloud ? "everything" : value;+ return (+ <div className={cn("min-w-0 space-y-1.5", className)}>+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <label htmlFor={id} className="text-[13px] font-medium">+ {label}+ </label>+ <Select value={current} onValueChange={(v) => onChange(v as OriginalSound)} disabled={cloud}>+ <SelectTrigger id={id} className="h-8 w-auto min-w-[11rem] rounded-full text-[13px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {ORIGINAL_SOUNDS.map((o) => (+ <SelectItem key={o.id} value={o.id}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <p className="text-[12px] text-pretty text-muted-foreground">{cloud ? CLOUD_ORIGINAL_SOUND : ORIGINAL_SOUNDS.find((o) => o.id === current)!.hint}</p>+ </div>+ );+}diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsxindex 772b2614..3f9b6b1f 100644--- a/src/components/canvas/nodes.tsx+++ b/src/components/canvas/nodes.tsx@@ -95,12 +95,14 @@ import {nodeOps,OPEN_DUB_HINT,OUT,+ outputLabel,TABLE_LIMITS,tableRows,outputType,PORT_TYPE_LABEL,PREVIEW_IN,promptPlaceholder,+ SPLIT_OUTPUTS,sanitizeParams,type CanvasEdge,type CanvasGraph,@@ -182,6 +184,32 @@ function OutPort({ type }: { type: PortType }) {);}+/**+ * Split soundtrack's four outputs, one row each, every one carrying its stem on. A hidden OUT sits on Dialogue: an edge+ * saved before the node had four outputs (or made by "Connect output to…") draws from there and carries the dialogue.+ */+function StemOutPorts() {+ return (+ <div className="border-t py-1" role="group" aria-label="Outputs">+ {SPLIT_OUTPUTS.map((o, k) => (+ <div key={o.id} className="relative flex h-6 items-center justify-end gap-1.5 pr-3.5 pl-3 text-[11px] text-muted-foreground">+ <span className="font-medium">{o.label}</span>+ <Handle+ type="source"+ position={Position.Right}+ id={o.id}+ className="canvas-handle canvas-handle-out"+ style={{ "--port": PORT_COLOR.audio } as React.CSSProperties}+ aria-label={`${o.label} output (Audio)`}+ title={`${o.label} out — drag to connect`}+ />+ {k === 0 && <Handle type="source" position={Position.Right} id={OUT} isConnectable={false} className="canvas-handle pointer-events-none opacity-0" aria-hidden tabIndex={-1} />}+ </div>+ ))}+ </div>+ );+}+// ---------------------------------------------------------------------------// Menus: the ⋯ button and right-click show the same items (keyboard users get Rename, Connect and Disconnect)@@ -260,7 +288,8 @@ function DisconnectItems({ id, kit }: { id: string; kit: MenuKit }) {{edges.map((e) => {const incoming = e.target === id;const other = byId.get(incoming ? e.source : e.target);- const label = incoming ? `${portLabel(self, e.targetHandle)} ← ${other ? nodeLabel(other) : "?"}` : `→ ${other ? nodeLabel(other) : "?"} · ${portLabel(other, e.targetHandle)}`;+ const from = incoming ? "" : outputLabel(self, e.sourceHandle);+ const label = incoming ? `${portLabel(self, e.targetHandle)} ← ${other ? nodeLabel(other) : "?"}` : `${from ? `${from} ` : ""}→ ${other ? nodeLabel(other) : "?"} · ${portLabel(other, e.targetHandle)}`;return (<kit.Item key={e.id} onSelect={() => actions.disconnect(e.id)}>{label}@@ -451,9 +480,10 @@ function NodeShell({</DropdownMenuContent></DropdownMenu>)}- {out && <OutPort type={out} />}+ {out && type !== "split-soundtrack" && <OutPort type={out} />}</div>{children}+ {type === "split-soundtrack" && <StemOutPorts />}{footer}</div></ContextMenuTrigger>@@ -1979,6 +2009,7 @@ export const NODE_TYPES = {tts: GeneratorNode,"voice-change": GeneratorNode,"clean-voice": GeneratorNode,+ "split-soundtrack": GeneratorNode,"clone-voice": CloneVoiceNode,translate: GeneratorNode,concat: GeneratorNode,diff --git a/src/components/captions/captions-studio.tsx b/src/components/captions/captions-studio.tsxindex 0a17db2a..c999d6a0 100644--- a/src/components/captions/captions-studio.tsx+++ b/src/components/captions/captions-studio.tsx@@ -15,6 +15,8 @@ import { StepList } from "@/components/av/step-list";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useGeneration } from "@/components/av/use-generation";import { useCreateGeneration, useEngine, useGenerations } from "@/lib/api";+import { useVoiceFirstLive, useVoiceFirstShown, VoiceFirstSwitch } from "@/components/audio-tools/voice-first-switch";+import { voiceFirstDefault } from "@/lib/av/voice-first";import { cueProblems } from "@/lib/av/cue-edit";import {BURN_CAPS,@@ -147,6 +149,11 @@ function Editor({ video, restored, onReplace }: { video: SlotValue; restored: Saconst [transcriptId, setTranscriptId] = useState<string | undefined>(restored?.transcriptId);const [source, setSource] = useState("auto");const [quick, setQuick] = useState(false);+ // "Clean the voice first": on for a video's speech on your GPU, off in the cloud (it adds a paid step there).+ const voiceFirstShown = useVoiceFirstShown();+ const voiceFirstLive = useVoiceFirstLive();+ const [voiceFirst, setVoiceFirst] = useState<boolean | null>(null);+ const cleanFirst = voiceFirstShown && (voiceFirst ?? (engine === "open" && voiceFirstDefault("video", voiceFirstLive)));const transcript = useGeneration(transcriptId);const player = useRef<HTMLVideoElement>(null);const [time, setTime] = useState<number | undefined>(undefined);@@ -179,7 +186,7 @@ function Editor({ video, restored, onReplace }: { video: SlotValue; restored: Sa}, [video, cues, look, transcriptId]);const transcribe = () =>- create.mutate(transcribeRequest({ engine, video: video.ref, sourceLanguage: source }), {+ create.mutate(transcribeRequest({ engine, video: video.ref, sourceLanguage: source, cleanVoiceFirst: cleanFirst, seconds: duration }), {onSuccess: (items) => {loaded.current = null;setTranscriptId(items[0].id);@@ -257,6 +264,7 @@ function Editor({ video, restored, onReplace }: { video: SlotValue; restored: Sa{transcribing ? "Transcribing…" : "Transcribe the speech"}</Button><p className="mt-2 text-[12px] text-muted-foreground">{engine === "open" ? "Detects 30 languages." : "ElevenLabs Scribe v2 (word timings, ≈ $0.008 per minute)."}</p>+ {voiceFirstShown && <VoiceFirstSwitch className="mt-3" engine={engine} on={cleanFirst} onChange={setVoiceFirst} seconds={duration} />}{t && <StepList className="mt-3" steps={[{ key: "t", label: "Transcript", g: t }]} />}</div>)}diff --git a/src/components/faceless/clip-bed.tsx b/src/components/faceless/clip-bed.tsxnew file mode 100644index 00000000..0c639a09--- /dev/null+++ b/src/components/faceless/clip-bed.tsx@@ -0,0 +1,52 @@+"use client";++import { useEffect, useState } from "react";+import { MediaDrop } from "@/components/av/media-drop";+import type { SlotValue } from "@/components/studio/media-slot";+import { CLIP_BED_HINT, CLIP_BED_LABEL, CLIP_BED_MAX, CLIP_BED_MIN, type BedClip } from "@/lib/catalog/faceless";+import type { Engine } from "@/lib/catalog/types";+import { ToggleRow } from "./controls";++/**+ * "Use a clip's soundtrack as the bed" under Background music (open engine): a video whose music and effects, with the+ * talking taken out, play under the narration. In the cloud the switch is off with a line saying where it runs.+ */+export function ClipBed({ engine, value, onChange }: { engine: Engine; value?: BedClip; onChange: (v: BedClip | undefined) => void }) {+ const cloud = engine === "cloud";+ const [on, setOn] = useState(!!value);+ const [slot, setSlot] = useState<SlotValue | null>(() => (value ? { ref: value.url, preview: value.url, kind: "video", name: value.name } : null));+ const [seconds, setSeconds] = useState<number | null>(value?.seconds ?? null);+ const ready = slot && !slot.uploading && slot.ref ? slot : null;+ const fits = seconds !== null && seconds >= CLIP_BED_MIN && seconds <= CLIP_BED_MAX;+ const key = on && ready && fits ? `${ready.ref}|${seconds}` : "";+ useEffect(() => {+ // The settings follow the finished upload and its length (nothing while it uploads or when it doesn't fit).+ const next = key && ready ? { url: ready.ref, seconds: seconds!, ...(ready.name && { name: ready.name }) } : undefined;+ if ((next?.url ?? "") !== (value?.url ?? "") || next?.seconds !== value?.seconds) onChange(next);+ // Only when the clip or its length changes; `value` follows it.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key]);+ const problem = seconds === null ? null : seconds < CLIP_BED_MIN ? `Pick a clip of at least ${CLIP_BED_MIN} seconds.` : seconds > CLIP_BED_MAX ? "Pick a clip of up to 10 minutes." : null;+ return (+ <div className="space-y-2 sm:col-span-2">+ <ToggleRow label={CLIP_BED_LABEL} hint={CLIP_BED_HINT[engine]} checked={on && !cloud} disabled={cloud} onChange={setOn} />+ {on && !cloud && (+ <>+ <MediaDrop+ kind="video"+ compact+ value={slot}+ onChange={(v) => {+ setSlot(v);+ if (!v) setSeconds(null);+ }}+ onDuration={(s) => setSeconds(Math.round(s * 100) / 100)}+ title="Add a clip for its soundtrack"+ hint={`A video of ${CLIP_BED_MIN} seconds to 10 minutes`}+ />+ {problem && <p className="text-[12px] text-destructive">{problem}</p>}+ </>+ )}+ </div>+ );+}diff --git a/src/components/faceless/episode-view.tsx b/src/components/faceless/episode-view.tsxindex 3e738105..71e4c1b6 100644--- a/src/components/faceless/episode-view.tsx+++ b/src/components/faceless/episode-view.tsx@@ -182,7 +182,9 @@ function TailSteps({ steps, onOpen }: { steps: StepView[]; onOpen: (g: Generatioconst last = list[list.length - 1];const g = last.generation;const all = list.filter((s) => done(s.generation)).length;- const audio = part === "narration" || part === "music" ? g?.outputs.find((o) => o.kind === "audio") : undefined;+ // A bed split from a clip's soundtrack plays its music and effects (the background stem), not the talking.+ const sounds = part === "narration" || part === "music" ? (g?.outputs ?? []).filter((o) => o.kind === "audio") : [];+ const audio = sounds.find((o) => o.meta?.stem === "background") ?? sounds[0];return (<buttonkey={part}diff --git a/src/components/faceless/settings-form.tsx b/src/components/faceless/settings-form.tsxindex 200a67d3..a7aa3711 100644--- a/src/components/faceless/settings-form.tsx+++ b/src/components/faceless/settings-form.tsx@@ -20,6 +20,7 @@ import {type PickerData,} from "@/lib/catalog/faceless";import { cn } from "@/lib/utils";+import { ClipBed } from "./clip-bed";import { Section, Segmented, ToggleRow } from "./controls";import { NarratorList } from "./narrator";import { StyleGrid } from "./style-art";@@ -198,6 +199,7 @@ export function EpisodeSettingsForm({<div className="grid gap-3 rounded-xl border p-3 sm:grid-cols-2"><ToggleRow label="Subtitles" hint="Burned into the video, timed to the voice" checked={value.subtitles} onChange={(subtitles) => onChange({ subtitles })} /><ToggleRow label="Background music" hint={MUSIC_HINT[value.engine]} checked={value.music} onChange={(music) => onChange({ music })} />+ {kind === "faceless" && value.music && <ClipBed engine={value.engine} value={value.bedClip} onChange={(bedClip) => onChange({ bedClip })} />}</div></Section>diff --git a/src/components/genjutsu/character-panel.tsx b/src/components/genjutsu/character-panel.tsxindex bf4eb950..81901512 100644--- a/src/components/genjutsu/character-panel.tsx+++ b/src/components/genjutsu/character-panel.tsx@@ -1,5 +1,6 @@"use client";+import { VoiceFirstSwitch } from "@/components/audio-tools/voice-first-switch";import { AudioLines, Cpu, Drama, Loader2, Sparkles, TriangleAlert } from "lucide-react";import Link from "next/link";import { Button } from "@/components/ui/button";@@ -79,6 +80,7 @@ export function CharacterControls({seedProblem,describe,words,+ voiceFirst,}: {engine: Engine;maker: Maker | null;@@ -94,6 +96,8 @@ export function CharacterControls({describe?: PanelHelper;/** "Use the clip's words": the part's lines from a transcription of the clip. */words?: PanelHelper;+ /** "Clean the voice first" for that transcription (shown when given). */+ voiceFirst?: { on: boolean; onChange: (on: boolean) => void; seconds?: number };}) {const set = (patch: Partial<CharacterOptions>) => onChange({ ...value, ...patch });const h3 = !!maker?.h3;@@ -255,6 +259,7 @@ export function CharacterControls({{words.busy ? <Loader2 className="size-3.5 animate-spin" /> : <AudioLines className="size-3.5" />} {words.busy ? "Listening to the clip…" : "Use the clip's words"}</Button>)}+ {words && voiceFirst && <VoiceFirstSwitch className="mt-2" engine={engine} on={voiceFirst.on} onChange={voiceFirst.onChange} seconds={voiceFirst.seconds} />}</Field>)}<Field label="Swap style" hint="How the swap is drawn">diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 73be80f5..e2d4a7c9 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -27,7 +27,7 @@ import { openInStudio } from "@/components/swap-studio/hooks";import { SelfHostNote } from "@/components/self-host-note";import { ExampleRow } from "@/components/studio/example-row";import { useEdgeFade } from "@/components/studio/use-edge-fade";-import { useEngine, useGenerations, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useEngine, useGenerations, useIsOwner, useLikelyVisitor, useModelAccess, useSoundLive } from "@/lib/api";import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterChoice, type CharacterOptions } from "@/lib/catalog/character-swap";import {chooseMaker,@@ -68,6 +68,10 @@ import type { ExampleRowData } from "@/lib/examples/types";import { cn } from "@/lib/utils";import { refusalShown, toastError } from "@/lib/refusals";import { CharacterControls, CharacterFacts, qualityOff } from "./character-panel";+import { voiceFirstDefault } from "@/lib/av/voice-first";+import { useVoiceFirstLive, useVoiceFirstShown } from "@/components/audio-tools/voice-first-switch";+import { ORIGINAL_SOUND_FEATURE, originalSoundDefault, originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";+import { OriginalSoundPicker } from "@/components/av/original-sound-picker";import { useDescribeCharacter, useDescribeScene, useGenjutsuEstimate, useGenjutsuRun, useTranscribeClip, waitForGeneration, type GenjutsuBody } from "./hooks";import { FinishFields, FrameCompare, LightPicker, More, OnlyYou, PERSON_COLOURS, PictureSteps, roleForTap, SceneEditFields, WhoBecomesWho } from "./openjutsu-panels";import { LookPicker, type LookSource } from "./look-picker";@@ -259,7 +263,13 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |};const describeMutation = useDescribeCharacter();const transcribeMutation = useTranscribeClip();- const [clipWords, setClipWords] = useState<{ url: string; g: Generation } | null>(null);+ const [clipWords, setClipWords] = useState<{ url: string; clean: boolean; g: Generation } | null>(null);+ // "Clean the voice first" for the clip's words: off until the chain has passed a real run, then on (the switch is under+ // "Use the clip's words").+ const voiceFirstShown = useVoiceFirstShown();+ const voiceFirstLive = useVoiceFirstLive();+ const [voiceFirst, setVoiceFirst] = useState<boolean | null>(null);+ const cleanFirst = voiceFirstShown && (voiceFirst ?? (engine === "open" && voiceFirstDefault("video", voiceFirstLive)));const [listening, setListening] = useState(false);const alive = useRef<AbortController | null>(null);useEffect(() => () => alive.current?.abort(), []);@@ -280,11 +290,12 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |const ctl = new AbortController();alive.current = ctl;try {- let g = clipWords?.url === url ? clipWords.g : null;+ let g = clipWords?.url === url && clipWords.clean === cleanFirst ? clipWords.g : null;if (!g) {- const { id } = await transcribeMutation.mutateAsync({ engine, source: { url, ...(duration ? { duration } : {}) } });+ // The clip's speech apart from its music and effects first, when "Clean the voice first" is on.+ const { id } = await transcribeMutation.mutateAsync({ engine, source: { url, ...(duration ? { duration } : {}) }, ...(cleanFirst && { cleanVoiceFirst: true }) });g = await waitForGeneration(id, { signal: ctl.signal });- setClipWords({ url, g });+ setClipWords({ url, clean: cleanFirst, g });}const out = g.outputs.find((o) => o.kind === "text");const cues = Array.isArray(out?.meta?.cues) ? (out.meta.cues as { start: number; end: number; text: string }[]) : undefined;@@ -502,6 +513,11 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |...(mode === "finish" ? { finish } : {}),}): null;+ // What of the clip's sound goes back where it's put back: Everything until the split has passed a real run, then Music & effects only when a character is swapped on your GPU.+ const [soundAsked, setOriginalSound] = useState<OriginalSound | null>(null);+ const soundEngine = maker?.engine ?? engine;+ const soundLiveNow = useSoundLive(ORIGINAL_SOUND_FEATURE);+ const originalSound = originalSoundOn(soundAsked ?? originalSoundDefault({ replacesPerson: isCharacter, engine: soundEngine, live: soundLiveNow }), soundEngine);const body: GenjutsuBody | null =uploaded && maker && !problem && !refs.some((r) => r.uploading) && !custom.some((r) => r.uploading)? {@@ -525,6 +541,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |...(sceneEdit ? { object: { ...objectEdit, action } } : {}),...(mode === "picture" ? { picture: { ...picture, stage: pictureStage, ...(frameUrl ? { frame: frameUrl } : {}), ...(scene.trim() ? { scene: scene.trim() } : {}) } } : {}),...(mode === "finish" ? { finish } : {}),+ ...(originalSound !== "everything" && { originalSound }),}: null;const estimate = useGenjutsuEstimate(body);@@ -937,6 +954,7 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |seedProblem={seedProblem(seedNumber)}describe={{ run: describeCharacter, busy: describeMutation.isPending, blocked: refs.some((r) => !r.uploading) ? null : "Add your character's picture to describe it" }}words={{ run: () => void fillClipWords(), busy: listening, blocked: clip?.url && !clip.uploading && range ? null : "Add the clip first" }}+ voiceFirst={voiceFirstShown ? { on: cleanFirst, onChange: setVoiceFirst, seconds: duration } : undefined}/>)}@@ -1001,6 +1019,8 @@ export function GenjutsuStudio({ examples, live }: { examples?: ExampleRowData |</Field>)}+ {clip?.info?.hasAudio !== false && mode !== "picture" && <OriginalSoundPicker engine={soundEngine} value={originalSound} onChange={setOriginalSound} />}+<div className="space-y-3 border-t pt-3"><div className="flex items-center gap-2"><div className="min-w-0 flex-1" aria-live="polite">diff --git a/src/components/genjutsu/hooks.ts b/src/components/genjutsu/hooks.tsindex ac441e76..96ba5db9 100644--- a/src/components/genjutsu/hooks.ts+++ b/src/components/genjutsu/hooks.ts@@ -1,5 +1,6 @@"use client";+import type { OriginalSound } from "@/lib/av/original-sound";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type { CharacterOptions } from "@/lib/catalog/character-swap";import type { FinishOptions, GenjutsuLook, GenjutsuMode, GenjutsuTarget, GenjutsuTier, MakerSource, ObjectEdit, PictureOptions } from "@/lib/catalog/genjutsu";@@ -34,6 +35,8 @@ export interface GenjutsuBody {object?: ObjectEdit;picture?: PictureOptions;finish?: FinishOptions;+ /** What of the clip's sound goes back where it is put back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}@@ -96,7 +99,7 @@ export function useDescribeScene() {/** The clip's words (one transcription; the page takes the part's lines from its cues). */export function useTranscribeClip() {- return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number } }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b) });+ return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number }; cleanVoiceFirst?: boolean }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b) });}/** Waits for one generation to finish (polling; the page's helpers that fill a field from it). */diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.tsindex 19caa897..bd71432c 100644--- a/src/components/mixed-media/hooks.ts+++ b/src/components/mixed-media/hooks.ts@@ -1,5 +1,6 @@"use client";+import type { OriginalSound } from "@/lib/av/original-sound";import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";import { useDeferredValue } from "react";import type { MixedMode, MixedResolution, MixedValues } from "@/lib/catalog/mixed-media";@@ -22,6 +23,8 @@ export interface MixedBody {mode?: MixedMode;anchor?: string;frameUrl?: string;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex 15ddeea4..a1c14048 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -1,5 +1,7 @@"use client";+import { OriginalSoundPicker } from "@/components/av/original-sound-picker";+import type { OriginalSound } from "@/lib/av/original-sound";import { ArrowDown, Cloud, Cpu, Download, ImageIcon, Info, Loader2, Search, Sparkles, Wand2, X } from "lucide-react";import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";@@ -398,6 +400,8 @@ function Editor({// Original needs no anchor: frame 1 is drawn exactly as the preview was (same look, LoRA and seed).const anchor = cloud && !original && (frameMode || (fast && model?.image)) && previewImage && !anchorOff ? previewImage.url : undefined;const size = clipSize(clip);+ // What of the clip's sound goes back (the cloud: all of it).+ const [originalSound, setOriginalSound] = useState<OriginalSound>("everything");const body: MixedBody | null =preset && mmRange && !problem@@ -420,6 +424,7 @@ function Editor({modelId,mode,...(anchor ? { anchor } : {}),+ ...(!cloud && originalSound !== "everything" && { originalSound }),}: null;const estimate = useMixedEstimate(body);@@ -698,6 +703,8 @@ function Editor({</button></div>+ {clip && clip.info?.hasAudio !== false && <OriginalSoundPicker engine={engine} value={originalSound} onChange={setOriginalSound} />}+<div className="space-y-3 border-t pt-4"><div className="flex items-baseline justify-between gap-2"><span className="text-[13px] text-muted-foreground">diff --git a/src/components/remove-object/hooks.ts b/src/components/remove-object/hooks.tsindex c232fc7a..e7802142 100644--- a/src/components/remove-object/hooks.ts+++ b/src/components/remove-object/hooks.ts@@ -1,5 +1,6 @@"use client";+import type { OriginalSound } from "@/lib/av/original-sound";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type { RemoveMode } from "@/lib/catalog/remove-object";import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";@@ -21,6 +22,8 @@ export interface RemovalBody {range?: { start: number; end: number };/** H3 Person Removal: the person's mask grown by this many pixels. */maskGrow?: number;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsxindex 76ba7c80..8ac1996e 100644--- a/src/components/remove-object/remove-object-tool.tsx+++ b/src/components/remove-object/remove-object-tool.tsx@@ -1,5 +1,7 @@"use client";+import { OriginalSoundPicker } from "@/components/av/original-sound-picker";+import { ORIGINAL_SOUND_FEATURE, originalSoundDefault, type OriginalSound } from "@/lib/av/original-sound";import { Brush, Cloud, Cpu, Dices, Download, Eraser as EraserIcon, Eye, Loader2, RotateCcw, Sparkles, Type, Undo2 } from "lucide-react";import Link from "next/link";import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";@@ -19,7 +21,7 @@ import { Feed } from "@/components/studio/feed";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { SketchEditor, type Stroke } from "@/components/studio/sketch-editor";import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";-import { useEngine, useGenerations, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useEngine, useGenerations, useLikelyVisitor, useModelAccess, useSoundLive } from "@/lib/api";import {CLICK_OPEN_PROBLEM,chooseEraser,@@ -204,6 +206,10 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})const ready = !!clip?.url && !clip.uploading && !clip.error && !!duration && !!range;const marked =mode === "type" ? everyone || !!prompt.trim() : mode === "click" ? points.some((p) => p.label !== "negative") : !!paint;+ // What of the clip's sound goes back: Everything until the split has passed a real run, then Music & effects only when a person is removed on your GPU.+ const [soundAsked, setOriginalSound] = useState<OriginalSound | null>(null);+ const soundLiveNow = useSoundLive(ORIGINAL_SOUND_FEATURE);+ const originalSound = soundAsked ?? originalSoundDefault({ replacesPerson: !!eraser?.cleanFrame, engine, live: soundLiveNow });const body: RemovalBody | null =ready && eraser && marked? {@@ -218,6 +224,7 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})...(h3 ? { maskGrow } : {}),source: { url: clip.url!, name: clip.name, duration, fps: clip.info?.fps, width: size.width, height: size.height, hasAudio: clip.info?.hasAudio },range: { start: range.startTime, end: range.endTime },+ ...(engine === "open" && originalSound !== "everything" && { originalSound }),}: null;const estimate = useRemovalEstimate(body);@@ -522,6 +529,7 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})</div></Field>)}+ {clip?.info?.hasAudio !== false && <OriginalSoundPicker engine={engine} value={originalSound} onChange={setOriginalSound} />}<div className="space-y-3 border-t pt-3">{body && est?.previewUsd != null && (diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.tsindex 5d40cedf..fde398a3 100644--- a/src/components/shorts/hooks.ts+++ b/src/components/shorts/hooks.ts@@ -1,5 +1,6 @@"use client";+import type { OriginalSound } from "@/lib/av/original-sound";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { nanoid } from "nanoid";import { useCallback, useDeferredValue, useRef } from "react";@@ -29,6 +30,8 @@ export interface ShortsBody {aspectRatio: ShortsRatio;language: string;modelId?: string;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex fb834e29..05baeca0 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -1,5 +1,7 @@"use client";+import { OriginalSoundPicker } from "@/components/av/original-sound-picker";+import type { OriginalSound } from "@/lib/av/original-sound";import { ArrowDown, ArrowRight, Cloud, Cpu, Info, Loader2, Search, Sparkles, X } from "lucide-react";import { useRouter } from "next/navigation";import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";@@ -335,6 +337,8 @@ function SetupPanel({const { clip } = source;const [ratio, setRatio] = useState<ShortsRatio>("9:16");const [language, setLanguage] = useState("auto");+ // What of the clip's sound goes back (the cloud: all of it).+ const [originalSound, setOriginalSound] = useState<OriginalSound>("everything");const [pickedModel, setModel] = useState<Record<Engine, string>>({ cloud: "", open: "" });// A custom preset is its reference images: on cloud, start on the first model that reads them// (Kling O3 4K Edit, then Happy Horse) unless a model was picked.@@ -368,6 +372,7 @@ function SetupPanel({aspectRatio: ratio,language,modelId,+ ...(engine === "open" && originalSound !== "everything" && { originalSound }),}: null;const estimate = useShortsEstimate(estimateBody);@@ -475,6 +480,8 @@ function SetupPanel({/></Field>+ {clip && clip.info?.hasAudio !== false && <OriginalSoundPicker engine={engine} value={originalSound} onChange={setOriginalSound} />}+<Field label="Language" hint={presetType ? "for the on-screen words" : "used by type presets"}><Select value={language} onValueChange={setLanguage}><SelectTrigger className="w-full" aria-label="Language">diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 152a3569..8e098d2a 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -116,6 +116,8 @@ import { RECENT_MODELS, useStoredList } from "./stored-list";import { usePresetUrl, useStartRequest, useStudio, type Draft } from "./studio-context";import { useEdgeFade } from "./use-edge-fade";import { CleanVoiceSlot, CleanVoiceSwitch, useVoiceCleaning } from "@/components/audio-tools/clean-voice-switch";+import { useVoiceFirstLive, useVoiceFirstShown, VoiceFirstSwitch } from "@/components/audio-tools/voice-first-switch";+import { VOICE_FIRST_PARAM, voiceFirstDefault } from "@/lib/av/voice-first";import { useSignature } from "../palettes/use-signature";import { placeholdersOn } from "@/lib/demo-mode";@@ -276,6 +278,12 @@ export function Composer({ docked }: { docked: boolean }) {// video is attached (lip re-sync keeps the clip's length).const voiceRef = config.voiceFacts && !typed.slots.video?.ref && !typed.slots.audio?.uploading ? typed.slots.audio?.ref : undefined;const voice = useClipFacts(voiceRef).data;+ // "Clean the voice first" (Transcribe, Lipsync): the recording or the video's speech apart from its music and effects+ // before the model hears it. On for a video's speech on your GPU, off for a recording (src/lib/av/voice-first.ts).+ const voiceFirstShown = useVoiceFirstShown();+ const voiceFirstLive = useVoiceFirstLive();+ const [voiceFirstAsked, setVoiceFirstAsked] = useState<boolean | null>(null);+ const voiceFirstKind: "audio" | "video" | null = !config.voiceFirst ? null : typed.slots.audio?.ref ? "audio" : typed.slots.video?.ref && config.ops.includes("transcribe") ? "video" : null;const draft = useMemo(() =>config.clipFacts@@ -753,7 +761,8 @@ export function Composer({ docked }: { docked: boolean }) {);// Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).const hosted = viewerInfo?.hosted ? { place: runOn, ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};- const body = { ...sent.request, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;+ const withVoiceFirst = cleanFirst ? { ...sent.request, params: { ...sent.request.params, extra: { ...sent.request.params?.extra, [VOICE_FIRST_PARAM]: true } } } : sent.request;+ const body = { ...withVoiceFirst, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;create.mutate(body, {// Accepted: nothing to try again (a card opened later never starts this run a second time).onSuccess: () => dropGpuRetry(),@@ -823,6 +832,8 @@ export function Composer({ docked }: { docked: boolean }) {}, [lightLeft, setSlot]);const setInsertRange = useCallback((startTime: number, endTime: number) => setDraft((d) => ({ params: { ...d.params, startTime, endTime } })), [setDraft]);const opNote = op && model ? routesFor(model, op)[0]?.note : undefined;+ const voiceFirstEngine: Engine = model?.engine ?? engine;+ const cleanFirst = voiceFirstShown && !!voiceFirstKind && (voiceFirstAsked ?? (voiceFirstEngine === "open" && voiceFirstDefault(voiceFirstKind, voiceFirstLive)));// Booleans in, not the model's options object: the React Compiler keeps the memos above.const showPrompt = showsPrompt({ hidePrompt: config.hidePrompt, modelPrompt: config.modelPrompt },@@ -1309,6 +1320,9 @@ export function Composer({ docked }: { docked: boolean }) {)}{/* On a phone the slot row scrolls sideways, so the switch gets its own line under it. */}{showAttachments && !collapsed && !framesOn && hasCleanVoice && <CleanVoiceSwitch status className="px-3 pb-2 sm:hidden" hint="first, free on your GPU" />}+ {showAttachments && !collapsed && !framesOn && voiceFirstShown && voiceFirstKind && (+ <VoiceFirstSwitch className="px-3 pb-2" engine={voiceFirstEngine} on={cleanFirst} onChange={setVoiceFirstAsked} seconds={voice?.duration} lip={!config.ops.includes("transcribe")} />+ )}{showPrompt && (<PromptInputdiff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsxindex 70159b47..5d87818b 100644--- a/src/components/studio/studio-context.tsx+++ b/src/components/studio/studio-context.tsx@@ -81,6 +81,11 @@ export interface StudioConfig {* seconds and the request carries them (params.sourceDuration). Not while a video is attached (lip re-sync).*/voiceFacts?: boolean;+ /**+ * "Clean the voice first" beside the voice or recording (src/lib/av/voice-first.ts): the speech apart from the music and+ * effects before the model hears it (params.extra.cleanVoiceFirst); after a lip re-sync on your GPU, they go back.+ */+ voiceFirst?: boolean;/** Offer every output format of the studio's models on this engine; picking one another model writes moves the request there (SDR to HDR, Export). */formatPicker?: boolean;/** The models' enum settings chip ("Director" by default; "Options" for a tool's settings such as Topaz's model). */diff --git a/src/components/swap-studio/hooks.ts b/src/components/swap-studio/hooks.tsindex 5626910e..39a2aa16 100644--- a/src/components/swap-studio/hooks.ts+++ b/src/components/swap-studio/hooks.ts@@ -1,5 +1,6 @@"use client";+import type { OriginalSound } from "@/lib/av/original-sound";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { studioHandOff, type HandOffInput, type QueueMode, type StudioEstimate, type SwapProject, type SwapProjectCard, type SwapProjectView } from "@/lib/catalog/swap-studio";import type { SwapEdit } from "@/lib/catalog/swap-studio-edit";@@ -118,7 +119,7 @@ function useAction<B, R extends SwapProject | QueueAnswer = SwapProject>(id: strexport const useAddClip = (id: string) => useAction<ClipInput>(id, "clips");export const usePrepareClip = (id: string) => useAction<{ clipId: string }>(id, "prepare");-export const useTranscribe = (id: string) => useAction<{ clipId: string }>(id, "transcribe");+export const useTranscribe = (id: string) => useAction<{ clipId: string; cleanVoiceFirst?: boolean }>(id, "transcribe");export const useMakeMask = (id: string) =>useAction<{ clipId: string; shotId: string; kind: "track" | "frame"; frame: number; points: PixelPoint[]; size?: { width: number; height: number }; base?: string }>(id, "masks");export const useMakeAnchor = (id: string) => useAction<{ clipId: string; shotId: string; segmentId?: string; modelId?: string; seed?: number }>(id, "anchors");@@ -126,7 +127,7 @@ export const useQueue = (id: string) => useAction<{ clipId: string; shotId: striexport const useStopTake = (id: string) => useAction<{ clipId: string; shotId: string; segmentId: string; takeId: string }>(id, "takes/stop");export const useStopJob = (id: string) =>useAction<{ kind: "mask" | "anchor" | "assembly" | "normalize" | "transcribe" | "finish"; clipId: string; shotId?: string; segmentId?: string; jobId?: string }>(id, "stop");-export const useAssemble = (id: string) => useAction<{ clipId: string }>(id, "assemble");+export const useAssemble = (id: string) => useAction<{ clipId: string; originalSound?: OriginalSound }>(id, "assemble");export const useSharpen = (id: string) => useAction<{ clipId: string; tier: SharpenTier }>(id, "sharpen");/**diff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsxindex b09d9703..5873bbc8 100644--- a/src/components/swap-studio/stage-review.tsx+++ b/src/components/swap-studio/stage-review.tsx@@ -1,5 +1,8 @@"use client";+import { useSoundLive } from "@/lib/api";+import { OriginalSoundPicker } from "@/components/av/original-sound-picker";+import { ORIGINAL_SOUND_FEATURE, originalSoundDefault, originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";import { Download, Film, Library, Loader2, Play, Sparkles, Star } from "lucide-react";import Link from "next/link";import { useRef, useState } from "react";@@ -320,7 +323,11 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)const a = clip.assembly;const state = jobState(a?.genId, a?.stepIds, gens);const result = state.status === "succeeded" && a?.genId ? gens[a.genId]?.url : undefined;- const current = "pieces" in found && !!a && JSON.stringify(a.takes) === JSON.stringify(assemblyTakes(found.pieces));+ // What of the clip's sound goes back: Everything until the split has passed a real run, then Music & effects only on your GPU (the new speech).+ const [soundAsked, setOriginalSound] = useState<OriginalSound | null>(null);+ const soundLiveNow = useSoundLive(ORIGINAL_SOUND_FEATURE);+ const originalSound = originalSoundOn(soundAsked ?? a?.originalSound ?? originalSoundDefault({ replacesPerson: true, engine: project.engine, live: soundLiveNow }), project.engine);+ const current = "pieces" in found && !!a && JSON.stringify(a.takes) === JSON.stringify(assemblyTakes(found.pieces)) && (a.originalSound ?? "everything") === originalSound;return (<div className="space-y-3"><Panel title="Assemble the clip" aside={<span className="font-mono text-[11px] text-muted-foreground">{priceText(estimate?.assembly[clip.id], { demo: estimate?.demo, engine: project.engine })}</span>}>@@ -348,11 +355,12 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)? "Each piece is fitted to the clip's size at 24 fps, joined packet by packet, and the clip's own sound goes back on.": "The clip's pieces are cut to their frames, every piece is scaled to one frame size, they're joined at 24 fps (H3's rate), and the clip's own sound — or its silence — goes back on."}</p>+ {clip.source.hasAudio && <OriginalSoundPicker engine={project.engine} value={originalSound} onChange={setOriginalSound} />}<div className="flex flex-wrap items-center gap-2"><ButtonclassName="h-9 rounded-full"disabled={"problem" in found || assemble.isPending || state.status === "queued" || state.status === "running" || (current && state.status === "succeeded")}- onClick={() => assemble.mutate({ clipId: clip.id }, { onSuccess: () => toast("Assembling the clip"), onError: (e) => toastError(e) })}+ onClick={() => assemble.mutate({ clipId: clip.id, ...(originalSound !== "everything" && { originalSound }) }, { onSuccess: () => toast("Assembling the clip"), onError: (e) => toastError(e) })}>{assemble.isPending ? <Loader2 className="size-4 animate-spin" /> : <Film className="size-4" />} {a ? "Assemble again" : "Assemble clip"}</Button>@@ -362,7 +370,7 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)Stop</Button>)}- {a && !current && state.status === "succeeded" && <span className="text-[12px] text-muted-foreground">The chosen takes changed since — assemble again for the new ones.</span>}+ {a && !current && state.status === "succeeded" && <span className="text-[12px] text-muted-foreground">The chosen takes or the sound changed since — assemble again for the new ones.</span>}</div><JobError genId={a?.genId} stepIds={a?.stepIds} gens={gens} />{result && (diff --git a/src/components/swap-studio/stage-words.tsx b/src/components/swap-studio/stage-words.tsxindex 862a91cd..a95c320a 100644--- a/src/components/swap-studio/stage-words.tsx+++ b/src/components/swap-studio/stage-words.tsx@@ -1,7 +1,10 @@"use client";import { Loader2, Mic, Wand2 } from "lucide-react";+import { useState } from "react";import { Button } from "@/components/ui/button";+import { useVoiceFirstLive, useVoiceFirstShown, VoiceFirstSwitch } from "@/components/audio-tools/voice-first-switch";+import { voiceFirstDefault } from "@/lib/av/voice-first";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Panel } from "@/components/av/tool-shell";import { buildShotPrompt, ROLE_LABELS, secondsLabel, shotDialogue, shotSpeaker, SWAP_STUDIO, voiceLabel, voicesOf, type SwapRole } from "@/lib/catalog/swap-studio";@@ -34,6 +37,11 @@ function RoleSelect({ value, onChange, label, auto }: { value: SwapRole | null;/** Words: the clip's transcript (both engines' speech to text), who each voice is, and each shot's speaker, words and prompt. */export function WordsStage({ id, project, clip, gens, estimate, edit }: StageProps) {const transcribe = useTranscribe(id);+ // "Clean the voice first": on for the clip's speech on your GPU, off in the cloud (a paid step there).+ const voiceFirstShown = useVoiceFirstShown();+ const voiceFirstLive = useVoiceFirstLive();+ const [voiceFirst, setVoiceFirst] = useState<boolean | null>(null);+ const cleanFirst = voiceFirstShown && (voiceFirst ?? (project.engine === "open" && voiceFirstDefault("video", voiceFirstLive)));const t = clip.transcript;const voices = voicesOf(t?.cues);const busy = !!t?.genId && (gens[t.genId]?.status === "queued" || gens[t.genId]?.status === "running");@@ -49,7 +57,7 @@ export function WordsStage({ id, project, clip, gens, estimate, edit }: StageProvariant={t?.cues ? "outline" : "default"}className="h-8 rounded-full"disabled={busy || transcribe.isPending || !clip.source.hasAudio}- onClick={() => transcribe.mutate({ clipId: clip.id }, { onError: (e) => toastError(e) })}+ onClick={() => transcribe.mutate({ clipId: clip.id, ...(cleanFirst && { cleanVoiceFirst: true }) }, { onError: (e) => toastError(e) })}>{busy || transcribe.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Mic className="size-3.5" />}{t?.cues ? "Transcribe again" : "Transcribe"}@@ -61,9 +69,12 @@ export function WordsStage({ id, project, clip, gens, estimate, edit }: StagePro{!clip.source.hasAudio ? (<Note>This clip has no sound: every shot is “No dialogue”.</Note>) : !t?.cues ? (- <Note>- {project.engine === "open" ? "Qwen3-ASR on your ComfyUI" : "ElevenLabs Scribe v2 (fal)"} writes the clip's words with their times{project.engine === "cloud" ? " and who says them" : ""}; each shot and segment then takes the words spoken in it.- </Note>+ <div className="space-y-3">+ <Note>+ {project.engine === "open" ? "Qwen3-ASR on your ComfyUI" : "ElevenLabs Scribe v2 (fal)"} writes the clip's words with their times{project.engine === "cloud" ? " and who says them" : ""}; each shot and segment then takes the words spoken in it.+ </Note>+ {voiceFirstShown && <VoiceFirstSwitch engine={project.engine} on={cleanFirst} onChange={setVoiceFirst} seconds={clip.source.duration} />}+ </div>) : (<div className="space-y-3">{voices.length > 0 && (diff --git a/src/lib/api.ts b/src/lib/api.tsindex e927163f..f928c9d5 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1136,6 +1136,8 @@ export interface ViewerInfo {computer?: boolean;/** The port their computer's tab last found ComfyUI on (a browser that remembers none starts there). */comfyPort?: number;+ /** The sound features that have passed a real run (src/server/sound-live.ts), e.g. "clean-voice-first". */+ soundLive?: string[];}export function useViewer() {@@ -1158,6 +1160,11 @@ export function useIsAccount(): boolean {return !!v?.account && !v.owner;}+/** Whether a sound feature has passed a real run (src/server/sound-live.ts; the viewer's soundLive). */+export function useSoundLive(feature: string): boolean {+ return !!useViewer().data?.soundLive?.includes(feature);+}+/** This browser's tabs hear on it that who is signed in changed (src/app/providers.tsx asks again). */export const AUTH_CHANNEL = "fuobe-auth";diff --git a/src/lib/av/captions.ts b/src/lib/av/captions.tsindex f0204d95..e9f647b4 100644--- a/src/lib/av/captions.ts+++ b/src/lib/av/captions.ts@@ -208,13 +208,19 @@ export function burnRequest(o: { route: BurnRoute; video: string; cues: Cue[]; l}/** The transcription job: the engine's transcriber, the spoken language if known. */-export function transcribeRequest(o: { engine: Engine; video: string; modelId?: string; sourceLanguage?: string }): GenerationRequest {+export function transcribeRequest(o: { engine: Engine; video: string; modelId?: string; sourceLanguage?: string; cleanVoiceFirst?: boolean; seconds?: number }): GenerationRequest {+ const params = {+ ...(o.sourceLanguage && o.sourceLanguage !== "auto" && { sourceLanguage: o.sourceLanguage }),+ ...(o.seconds && o.seconds > 0 && { sourceDuration: o.seconds }),+ // "Clean the voice first" (src/lib/av/voice-first.ts): the speech apart from the music and effects before it's read.+ ...(o.cleanVoiceFirst && { extra: { cleanVoiceFirst: true } }),+ };return {feature: CAPTIONS_FEATURE,modelId: o.modelId ?? (o.engine === "open" ? "oss-qwen3-asr" : "scribe-v2"),op: "transcribe",inputs: { video: o.video },- ...(o.sourceLanguage && o.sourceLanguage !== "auto" && { params: { sourceLanguage: o.sourceLanguage } }),+ ...(Object.keys(params).length && { params }),};}diff --git a/src/lib/av/clean-dialogue.ts b/src/lib/av/clean-dialogue.tsindex 20c04ad8..59a66c4a 100644--- a/src/lib/av/clean-dialogue.ts+++ b/src/lib/av/clean-dialogue.ts@@ -1,6 +1,6 @@import type { Engine, GenerationRequest } from "@/lib/catalog/types";import type { ToolPlan, ToolStep } from "./audio-tools";-import { DBS_MODELS, dbsChannelsFor, separationPasses, splitTime, surroundSource, type DbsChannels, type SplitQuality } from "./split";+import { CLOUD_SPLIT_PROBLEM, DBS_MODELS, dbLabel, dbsChannelsFor, planSplit, separationPasses, splitTime, stemLabel, surroundSource, type DbsChannels, type SplitInput, type SplitQuality } from "./split";/*** Audio → Split soundtrack → Clean up dialogue (DBS D5, docs/research/dbs-separation-7.md §9 D5): the speech in a noisy or@@ -228,3 +228,62 @@ export function planCleanDialogue(i: CleanDialogueInput): CleanDialoguePlan {export function cleanDialogueTime(o: { seconds: number; quality: SplitQuality; mode: DbsChannels; channels?: number | null; device?: string | null }): { low: number; high: number } {return splitTime(o);}++// ---------------------------------------------------------------------------+// Any remix at set levels on the same graph (Assist and MCP's split_soundtrack with parts or levels)++/** The feature a remix is saved under (one mixed file, not Split soundtrack's four stems). */+export const REMIX_FEATURE = "audio-remix";+/** The three stems graph C sets the level of. */+export type RemixStem = "voice" | "music" | "effects";+export const REMIX_STEMS: RemixStem[] = ["voice", "music", "effects"];+export const REMIX_MIN_DB = -60;+export const REMIX_MAX_DB = 12;+const REMIX_PARAM: Record<RemixStem, "voiceDb" | "musicDb" | "effectsDb"> = { voice: "voiceDb", music: "musicDb", effects: "effectsDb" };++export interface RemixInput extends SplitInput {+ /** The stems in the remix (default: all three). */+ keep?: RemixStem[];+ /** Each kept stem's level in dB (default 0, whole dB, REMIX_MIN_DB…REMIX_MAX_DB). */+ levels?: Partial<Record<RemixStem, number>>;+}++export interface RemixPlan extends ToolPlan {+ /** The level each stem goes in at (OFF_DB: left out). */+ levels: Record<RemixStem, number>;+ mode: DbsChannels;+}++/** "Dialogue, Music −12 dB": what a remix keeps, in words. */+export function remixWords(levels: Record<RemixStem, number>): string {+ const kept = REMIX_STEMS.filter((s) => levels[s] > OFF_DB).map((s) => `${stemLabel(s)}${levels[s] !== 0 ? ` ${dbLabel(levels[s])}` : ""}`);+ return kept.length ? kept.join(", ") : "Silence";+}++/** One job on graph C (oss-dbs-remix) that returns one mixed file; throws what's in the way. Open engine only. */+export function planRemix(i: RemixInput): RemixPlan {+ if (i.engine === "cloud") throw new Error(CLOUD_SPLIT_PROBLEM);+ if (!i.media) throw new Error(`Add the ${i.kind === "video" ? "video" : "audio"} to remix`);+ const keep = new Set(i.keep?.length ? i.keep : REMIX_STEMS);+ const levels = Object.fromEntries(+ REMIX_STEMS.map((s) => {+ const db = i.levels?.[s];+ return [s, keep.has(s) ? (typeof db === "number" && Number.isFinite(db) ? Math.max(REMIX_MIN_DB, Math.min(REMIX_MAX_DB, Math.round(db))) : 0) : OFF_DB];+ }),+ ) as Record<RemixStem, number>;+ if (REMIX_STEMS.every((s) => levels[s] === OFF_DB)) throw new Error("Keep at least one of dialogue, music or effects");+ // Graph C is graph A's split with the three stems mixed back: the same models, channels and notes.+ const split = planSplit(i);+ const req = split.steps[0].request;+ const words = remixWords(levels);+ const title = `Remix · ${words} · ${i.name?.trim() || (i.kind === "video" ? "video soundtrack" : "soundtrack")}`;+ const extra = { ...req.params?.extra, ...Object.fromEntries(REMIX_STEMS.map((s) => [REMIX_PARAM[s], levels[s]])) };+ return {+ steps: [{ key: "remix", request: { ...req, modelId: OPEN_MODEL, feature: REMIX_FEATURE, title, batchTitle: title, params: { ...req.params, extra }, step: { label: `Remix · ${words}`, index: 0, of: 1 } } }],+ length: split.length,+ levels,+ mode: split.mode,+ summary: `Splits ${i.kind === "video" ? "the video's soundtrack" : "it"} into dialogue, music and effects and mixes them back as one file: ${words}.`,+ notes: [...split.notes.filter((n) => !n.startsWith("Dialogue comes out clean")), "A mix that would go over full scale comes out a little quieter as a whole."],+ };+}diff --git a/src/lib/av/original-sound.ts b/src/lib/av/original-sound.tsnew file mode 100644index 00000000..15e9d77a--- /dev/null+++ b/src/lib/av/original-sound.ts@@ -0,0 +1,107 @@+import type { ChainSlot, Engine, GenerationRequest } from "@/lib/catalog/types";+import { clampLowerDb, LOWER_DEFAULT_DB } from "./remove-dialogue";+import { SPLIT_MODEL } from "./split";++/**+ * "Original sound" (DBS D7): when a studio puts a clip's sound back under its new picture (Shorts, Mixed Media,+ * Genjutsu, Remove object, Character Swap Studio), what goes back: Everything (as before), the music and effects only,+ * the dialogue only, or the dialogue over the music and effects lowered. Pure: each studio's plan runs its own put-back+ * step through {@link withOriginalSound}.+ *+ * - Open engine: DBS (graph A, oss-dbs-separate) on the working clip's sound, then the studio's own stream-copy mux with+ * the chosen stem (or the voice over the background at a lower level), as Remove dialogue does.+ * - Cloud: Everything only. DBS isn't hosted and no other model stands in for it: the other choices run on your GPU.+ */++export type OriginalSound = "everything" | "music-effects" | "dialogue" | "lower-music";+export const ORIGINAL_SOUNDS: { id: OriginalSound; label: string; hint: string }[] = [+ { id: "everything", label: "Everything", hint: "The clip's sound as it was" },+ { id: "music-effects", label: "Music & effects only", hint: "The talking taken out" },+ { id: "dialogue", 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 originalSoundLabel = (id: OriginalSound): string => ORIGINAL_SOUNDS.find((o) => o.id === id)!.label;+export const ORIGINAL_SOUND_IDS = ORIGINAL_SOUNDS.map((o) => o.id) as [OriginalSound, ...OriginalSound[]];++export const CLOUD_ORIGINAL_SOUND = "In the cloud the clip's sound goes back as it was. Music & effects only, Dialogue only and Lower the music run on your GPU (open source).";++/** The feature's key in the record of real runs (src/server/sound-live.ts). */+export const ORIGINAL_SOUND_FEATURE = "original-sound";++/**+ * What a studio starts on: Everything, except where the person in the clip is replaced or removed (their speech is new)+ * once the split and stem mux have passed a real run (live): then Music & effects only.+ */+export function originalSoundDefault(o: { replacesPerson?: boolean; engine: Engine; live?: boolean }): OriginalSound {+ return o.live && o.replacesPerson && o.engine === "open" ? "music-effects" : "everything";+}++/** The choice a run takes on this engine (the cloud has Everything only). */+export const originalSoundOn = (choice: OriginalSound | undefined, engine: Engine): OriginalSound => (engine === "cloud" ? "everything" : (choice ?? "everything"));++interface Step {+ key: string;+ request: GenerationRequest;+ after?: string[];+ chain?: ChainSlot[];+}++const AUDIO_FILE = /\.(wav|mp3|flac|m4a|aac|ogg|opus)(\?|$)/i;++/**+ * The plan with its put-back step (`muxKey`) taking the chosen part of the sound: a DBS split of what the mux would have+ * put back (a file, or an earlier step's clip), then the mux on its stem(s). Everything, the cloud, a mux with no sound+ * going in (a silent clip) or one already mixing two tracks: the plan as it was.+ */+export function withOriginalSound<T extends Step>(steps: T[], muxKey: string, choice: OriginalSound | undefined, engine: Engine, o: { lowerDb?: number; seconds?: number } = {}): T[] {+ const pick = originalSoundOn(choice, engine);+ const at = steps.findIndex((s) => s.key === muxKey);+ if (pick === "everything" || at < 0) return steps;+ const mux = steps[at];+ const chain = [...(mux.chain ?? mux.request.chain ?? [])];+ const after = [...(mux.after ?? [])];+ if (chain.some((c) => c.slot === "audio2") || mux.request.inputs?.audio2) return steps;+ const url = mux.request.inputs?.audio;+ const k = chain.findIndex((c) => c.slot === "audio");+ if (!url && k < 0) return steps;+ // A silent bed (the studio's own silence for a clip with no sound) has nothing to split.+ if (url && /silence/i.test(url)) return steps;+ const from = url ? null : after[k];+ if (!url) {+ chain.splice(k, 1);+ after.splice(k, 1);+ }+ const key = `${muxKey}-split`;+ const index = mux.request.step?.index;+ const split = {+ key,+ ...(from && { after: [from], chain: [{ slot: "audio" }] }),+ request: {+ feature: mux.request.feature,+ batchTitle: mux.request.batchTitle,+ modelId: SPLIT_MODEL,+ op: "separate-audio",+ title: `${mux.request.title ?? "Clip"} · its sound, split`,+ ...(url && { inputs: AUDIO_FILE.test(url) ? { audio: url } : { video: url } }),+ params: { extra: { channels: "mono" }, ...(o.seconds && o.seconds > 0 && { sourceDuration: o.seconds }) },+ step: { label: "The clip's sound, split", index: typeof index === "number" ? index - 1 : 0, of: mux.request.step?.of ?? 1 },+ },+ } as unknown as T;+ const lower = pick === "lower-music";+ const stems: ChainSlot[] = lower ? [{ slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }] : [{ slot: "audio", stem: pick === "dialogue" ? "voice" : "background" }];+ const inputs = { ...mux.request.inputs };+ delete inputs.audio;+ const next: T = {+ ...mux,+ after: [...after, ...stems.map(() => key)],+ chain: [...chain, ...stems],+ request: {+ ...mux.request,+ inputs: Object.keys(inputs).length ? inputs : undefined,+ chain: undefined,+ ...(lower && { params: { ...mux.request.params, extra: { ...mux.request.params?.extra, backgroundVolumeDb: clampLowerDb(o.lowerDb ?? LOWER_DEFAULT_DB) } } }),+ },+ };+ delete (next.request as Partial<GenerationRequest>).chain;+ return [...steps.slice(0, at), split, next, ...steps.slice(at + 1)];+}diff --git a/src/lib/av/voice-first.ts b/src/lib/av/voice-first.tsnew file mode 100644index 00000000..f392b9d0--- /dev/null+++ b/src/lib/av/voice-first.ts@@ -0,0 +1,130 @@+import { getModel } from "@/lib/catalog";+import { estimateCost } from "@/lib/catalog/plan";+import type { ChainSlot, Engine, GenerationRequest, Operation } from "@/lib/catalog/types";+import { durationWords, splitTime } from "./split";++/**+ * "Clean the voice first" (DBS D6): wherever speech feeds a model (Transcribe and Captions, Genjutsu's and Character+ * Swap Studio's transcripts, Lipsync & avatars), the speech is separated from the music and effects before the model+ * hears it, for tighter transcripts and lip sync. After a lip re-sync on the open engine, the music and effects of the+ * same recording go back under the new mouth movement.+ *+ * A request asks for it with params.extra.cleanVoiceFirst; createGenerations (src/server/chains.ts createVoiceFirst) runs+ * the plan below as one batch. Pure: the pages price the switch with it too.+ *+ * - Open engine: DBS (oss-dbs-separate, graph A) on the recording, its voice stem into the model; for lipsync and+ * avatars, then the stream-copy mux with the voice over the background stem at 0 dB.+ * - Cloud: ElevenLabs voice isolation (hosted) before the model. Putting the music and effects back is open-engine only:+ * DBS isn't hosted, and the cloud says so.+ */++export const VOICE_FIRST_PARAM = "cleanVoiceFirst";+export const VOICE_FIRST_OPS = new Set<Operation>(["transcribe", "lipsync", "avatar"]);+export const VOICE_FIRST_MODELS: Record<Engine, string> = { open: "oss-dbs-separate", cloud: "elevenlabs-voice-isolation" };+export const VOICE_FIRST_MUX = "oss-mux";++export const VOICE_FIRST_LABEL = "Clean the voice first";+export const VOICE_FIRST_HINT: Record<Engine, string> = {+ open: "Takes the music and effects out of the speech before it's read, with DBS on your GPU (open source).",+ cloud: "Takes the music and noise out of the speech before it's read, with ElevenLabs voice isolation.",+};+/** What a lip re-sync does with the music and effects, per engine. */+export const VOICE_FIRST_BED: Record<Engine, string> = {+ open: "The music and effects go back under the new lip sync.",+ cloud: "In the cloud the music and effects don't go back: that runs on your GPU (open source).",+};++/** The feature's key in the record of real runs (src/server/sound-live.ts). */+export const VOICE_FIRST_FEATURE = "clean-voice-first";++/**+ * Where the switch starts: off until the chain has passed a real run (live); then on for a video's speech, off for an+ * audio-only recording (until separation is measured on transcripts).+ */+export const voiceFirstDefault = (kind: "audio" | "video", live: boolean): boolean => live && kind === "video";++export const wantsVoiceFirst = (r: Pick<GenerationRequest, "op" | "params">): boolean => r.params?.extra?.[VOICE_FIRST_PARAM] === true && !!r.op && VOICE_FIRST_OPS.has(r.op);++/** The recording the switch cleans: the speech a transcription reads, or the voice a lip sync follows. */+export function voiceFirstSource(r: Pick<GenerationRequest, "op" | "inputs">): { slot: "audio" | "video"; url: string } | null {+ const i = r.inputs ?? {};+ if (r.op === "transcribe") return i.audio ? { slot: "audio", url: i.audio } : i.video ? { slot: "video", url: i.video } : null;+ return i.audio ? { slot: "audio", url: i.audio } : null;+}++export interface VoiceFirstStep {+ key: "voice" | "main" | "bed";+ request: GenerationRequest;+ after?: string[];+ chain?: ChainSlot[];+}++/** The steps for a request with the switch on (the result is the last one); throws what's in the way. */+export function planVoiceFirst(r: GenerationRequest, engine: Engine): VoiceFirstStep[] {+ if (!r.op || !VOICE_FIRST_OPS.has(r.op)) throw new Error(`${VOICE_FIRST_LABEL} works for transcripts, captions and lip sync`);+ const src = voiceFirstSource(r);+ if (!src) throw new Error(r.op === "transcribe" ? "Add the recording or video to transcribe" : "Add the voice");+ const seconds = r.params?.sourceDuration && r.params.sourceDuration > 0 ? r.params.sourceDuration : undefined;+ const extra = { ...r.params?.extra };+ delete extra[VOICE_FIRST_PARAM];+ const lip = r.op !== "transcribe";+ const bed = lip && engine === "open";+ const of = bed ? 3 : 2;+ const base = { feature: r.feature, batchTitle: r.batchTitle ?? r.title, engine };+ const inputs = { ...r.inputs };+ delete inputs[src.slot];+ // A lip sync's video slot stays (the clip it re-syncs); a transcription of a video reads the clean voice only.+ const steps: VoiceFirstStep[] = [+ {+ key: "voice",+ request: {+ ...base,+ modelId: VOICE_FIRST_MODELS[engine],+ op: "separate-audio",+ title: `${r.title ?? "Speech"} · the voice`,+ inputs: { [src.slot]: src.url },+ params: { ...(seconds && { sourceDuration: seconds }), ...(engine === "open" && { extra: { channels: "mono" } }) },+ step: { label: engine === "open" ? "The voice, apart from the music and effects" : "The voice, isolated", index: 0, of },+ },+ },+ {+ key: "main",+ after: ["voice"],+ // DBS names the stem; ElevenLabs returns the voice alone.+ chain: [{ slot: "audio", ...(engine === "open" && { stem: "voice" }) }],+ request: {+ ...r,+ engine,+ inputs: Object.keys(inputs).length ? inputs : undefined,+ params: { ...r.params, extra: Object.keys(extra).length ? extra : undefined },+ step: { label: r.step?.label ?? (lip ? "Lip sync on the clean voice" : "Transcript of the clean voice"), index: 1, of },+ },+ },+ ];+ if (bed) {+ steps.push({+ key: "bed",+ // The re-synced clip, and the voice over the background of the one split (two stems of one step).+ after: ["main", "voice", "voice"],+ chain: [{ slot: "video" }, { slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }],+ request: {+ ...base,+ modelId: VOICE_FIRST_MUX,+ op: "mux",+ title: `${r.title ?? "Lip sync"} · with its music and effects`,+ params: { extra: { backgroundVolumeDb: 0 } },+ step: { label: "Music and effects back under it · picture copied", index: 2, of },+ },+ });+ }+ return steps;+}++/** What the switch adds, in words: about how long on the open engine, its price in the cloud ("" when unknown). */+export function voiceFirstCost(engine: Engine, seconds?: number, device?: string | null): string {+ if (!seconds || seconds <= 0) return engine === "open" ? "adds a short step on your GPU" : "";+ if (engine === "open") return `adds ${durationWords(splitTime({ seconds, quality: device === "cuda" ? "best" : "fast", mode: "mono", device }))}`;+ const m = getModel(VOICE_FIRST_MODELS.cloud);+ const usd = m ? estimateCost(m, { sourceDuration: seconds }, 1, "separate-audio") : null;+ return usd === null ? "" : `adds $${usd.toFixed(2)}`;+}diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 916d11a4..89413ca6 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -11,6 +11,7 @@ import type { CanvasComment, CanvasGroup, CanvasPage, CanvasShape } from "./canvimport { EXAMPLE_SCENE, EXAMPLE_WORDS, beatsFrom, blockoutFramePrompt, compileBlockoutPrompt, type BlockoutRef } from "@/lib/blockout";import { QMA_MODEL } from "@/lib/qma";import type { TemplateSectionKey } from "@/lib/canvas-sections";+import { CLOUD_SPLIT_PROBLEM, SPLIT_MODEL } from "@/lib/av/split";import { getModel, getPreset, MODELS, supportsOp } from "./index";import { dualEngine, onEngine, runsOn } from "./engines";import { chainedWaitMessage, keyframeChain } from "./keyframes";@@ -66,6 +67,7 @@ export type CanvasNodeType =| "tts"| "voice-change"| "clean-voice"+ | "split-soundtrack"| "clone-voice"| "translate"| "concat"@@ -259,6 +261,8 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {"voice-change": { type: "voice-change", label: "Change voice", group: "Utilities", icon: "AudioWaveform", ops: ["voice-change"], description: "Say a recording again in another voice, keeping its timing" },// NVIDIA RE-USE on the open engine only (nothing like it is hosted on fal or Replicate): hidden on a cloud-only install."clean-voice": { type: "clean-voice", label: "Clean up voice", group: "Utilities", icon: "AudioLines", ops: ["enhance-voice"], description: "Remove noise, echo and room sound from speech" },+ // DBS on the open engine only (hosted nowhere): its four outputs wire each part of a soundtrack on (SPLIT_OUTPUTS).+ "split-soundtrack": { type: "split-soundtrack", label: "Split soundtrack", group: "Utilities", icon: "AudioWaveform", ops: ["separate-audio"], description: "Dialogue, music and effects of a soundtrack, each its own output" },"clone-voice": { type: "clone-voice", label: "Clone voice", group: "Inputs", icon: "UserRound", description: "A voice sample (or one of your saved voices) to speak with" },translate: { type: "translate", label: "Translate", group: "Utilities", icon: "Languages", ops: ["translate", "dub"], variants: ["text", "video"], description: "Translate a text, or dub a video into another language" },concat: { type: "concat", label: "Assemble film", group: "Utilities", icon: "Film", ops: ["concat"], description: "Up to 50 clips in one film: trim and mute each, pick the frame" },@@ -271,7 +275,7 @@ export const NODE_SPECS: Record<CanvasNodeType, NodeSpec> = {note: { type: "note", label: "Sticky note", group: "Output", icon: "StickyNote", description: "A note on the board (not run)" },};-export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "clean-voice", "translate", "concat", "restore", "fly-around"]);+export const GENERATOR_TYPES = new Set<CanvasNodeType>(["model", "join", "frame", "upscale", "bg-remove", "tts", "voice-change", "clean-voice", "split-soundtrack", "translate", "concat", "restore", "fly-around"]);export const isGenerator = (n: Pick<CanvasNode, "type">) => GENERATOR_TYPES.has(n.type);/** Entries of the Add-node palette (several entries can make the same node type). */@@ -315,6 +319,7 @@ export const PALETTE: PaletteItem[] = [{ ...pick("tts"), id: "tts", keywords: "voice speech narration clone" },{ ...pick("voice-change"), id: "voice-change", keywords: "voice changer speech to speech revoice convert" },{ ...pick("clean-voice"), id: "clean-voice", keywords: "denoise enhance speech noise clean up voice echo reverb podcast" },+ { ...pick("split-soundtrack"), id: "split-soundtrack", keywords: "stems separate dialogue music effects remove voice isolate soundtrack dbs" },{ ...pick("clone-voice"), id: "clone-voice", keywords: "voice sample clone my voice speaker" },{ ...pick("translate"), id: "translate", data: { mediaKind: "text" }, keywords: "language translate dub localize subtitles" },{ ...pick("concat"), id: "concat", keywords: "concatenate join merge stitch edit trim mute film assemble" },@@ -351,6 +356,8 @@ export function paletteItems(mode: "both" | "open" | "cloud" = "both", engine?:const items = PALETTE.filter((p) => (p.id !== "model-text" || MODELS.some((m) => m.kind === "text" && !m.hidden)) && !(mode === "cloud" && p.id === "clean-voice") && (p.id !== "upscale-regenerate" || REGEN_OFFERED)).map((p): PaletteItem => {const fixed = p.data?.modelId ? getModel(p.data.modelId) : undefined;if (fixed && !runsOn(fixed, "cloud") && (mode === "cloud" || engine === "cloud")) return { ...p, disabled: mode === "cloud" ? GPU_ONLY_INSTALL : GPU_ONLY_ENTRY };+ // Split soundtrack: DBS runs on the open engine only, and no other model stands in for it.+ if (p.type === "split-soundtrack" && (mode === "cloud" || engine === "cloud")) return { ...p, disabled: CLOUD_SPLIT_PROBLEM };if (mode === "both" || !isGenerator(p) || defaultModelForNode({ type: p.type, data: p.data ?? {} }, mode)) return p;return { ...p, disabled: `No ${mode === "open" ? "open-source" : "cloud"} model for ${p.label.toLowerCase()} yet` };});@@ -476,6 +483,8 @@ export function defaultModelForNode(n: Pick<CanvasNode, "type" | "data">, engine// Clean up voice is RE-USE, on your GPU only: the hosted cleaners (VEED, DeepFilterNet 3: Clean up dialogue's cloud// engine) share its op but are other tools, so the node doesn't take one of them on the cloud.if (n.type === "clean-voice" && engine === "cloud") return undefined;+ // Split soundtrack runs DBS, on the open engine only (never Demucs or a cloud isolation in its place).+ if (n.type === "split-soundtrack") return engine === "open" ? getModel(SPLIT_MODEL) : undefined;const op = nodeOps(n)[0];// The Upscale node's Regenerate choice starts on Open-H3 Regenerate (on the cloud the entry is disabled: paletteItems).const fixed = n.data.modelId === REGEN_MODEL ? getModel(REGEN_MODEL) : undefined;@@ -507,6 +516,7 @@ export function modelChoices(n: Pick<CanvasNode, "type" | "data">): ModelDef[] {}if (n.type === "concat") return Object.values(CONCAT_MODELS).flatMap((id) => getModel(id) ?? []);if (n.type === "fly-around") return [FLY_MODELS.cloud, FLY_MODELS.open].flatMap((id) => getModel(id) ?? []);+ if (n.type === "split-soundtrack") return [getModel(SPLIT_MODEL)!];const ops = nodeOps(n);// Clean up voice offers only what runs on your GPU (RE-USE): the hosted cleaners share its op but are Clean up// dialogue's cloud engine (defaultModelForNode).@@ -530,6 +540,34 @@ export interface PortDef {export const OUT = "out";export const PREVIEW_IN = "in";+/**+ * Split soundtrack's four output handles, each the stem it carries on (ChainSlot.stem). OUT, every other node's one output,+ * stands for Dialogue, so an edge saved before the node had four outputs keeps working.+ */+export const SPLIT_OUTPUTS: { id: "voice" | "music" | "effects" | "background"; label: string }[] = [+ { id: "voice", label: "Dialogue" },+ { id: "music", label: "Music" },+ { id: "effects", label: "Effects" },+ { id: "background", label: "Music & effects" },+];++/** The output handles a node has: Split soundtrack's four (and OUT, as Dialogue), else OUT. */+export function outputHandles(n: Pick<CanvasNode, "type">): string[] {+ return n.type === "split-soundtrack" ? [OUT, ...SPLIT_OUTPUTS.map((o) => o.id)] : [OUT];+}++/** The stem an edge out of a node carries (Split soundtrack: its handle's; OUT is Dialogue), or undefined. */+export function edgeStem(source: Pick<CanvasNode, "type"> | undefined, sourceHandle: string | null | undefined): string | undefined {+ if (source?.type !== "split-soundtrack") return undefined;+ return SPLIT_OUTPUTS.find((o) => o.id === sourceHandle)?.id ?? "voice";+}++/** "Music & effects": what an output handle is called ("" for a plain OUT). */+export function outputLabel(source: Pick<CanvasNode, "type"> | undefined, sourceHandle: string | null | undefined): string {+ const stem = edgeStem(source, sourceHandle);+ return stem ? SPLIT_OUTPUTS.find((o) => o.id === stem)!.label : "";+}+const INPUT_ORDER: InputPortId[] = ["prompt", "elements", "images", "endImage", "video", "videos", "audio", "voice", "path"];/** Which inputs each operation reads. */@@ -778,7 +816,7 @@ export function connectionError(graph: CanvasGraph, c: Connection): string | nulif (!s || !t) return "That node no longer exists";if (s.id === t.id) return "A node can't feed itself";const type = outputType(graph, s);- if (!type || (c.sourceHandle && c.sourceHandle !== OUT)) return `${nodeLabel(s)} has no output`;+ if (!type || (c.sourceHandle && !outputHandles(s).includes(c.sourceHandle))) return `${nodeLabel(s)} has no output`;if (t.type === "output") {if (c.targetHandle && c.targetHandle !== PREVIEW_IN) return "Unknown input";if (!acceptsType("preview", type)) return "Elements go into a model's Elements input";@@ -1024,6 +1062,8 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef, single.sort((a, b) => byPosition(nodes.get(a.source)!, nodes.get(b.source)!));if (!port.multiple && edges.length > 1) return { error: `${port.label} takes one input — remove a connection` };const list: Source[] = [];+ // The stem each edge carries (Split soundtrack's outputs), in the order of `list`.+ const stems: (string | undefined)[] = [];for (const e of edges) {const s = nodes.get(e.source)!;const type = outputType(graph, s);@@ -1031,6 +1071,7 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef, singleconst src = sourceOf(graph, s);if ("error" in src) return src;list.push(src);+ stems.push(edgeStem(s, e.sourceHandle));}if (port.id === "prompt") {for (const src of list) {@@ -1069,7 +1110,7 @@ function buildRequest(graph: CanvasGraph, n: CanvasNode, model: ModelDef, singleif (!field || !src) continue;if (src.kind === "media") inputs[field] = src.url;else if (src.kind === "node") {- chain.push({ slot: SLOT[port.id]! });+ chain.push({ slot: SLOT[port.id]!, ...(stems[0] && { stem: stems[0] }) });deps.push(src.nodeId);}}diff --git a/src/lib/catalog/faceless.ts b/src/lib/catalog/faceless.tsindex 922cbfd2..5bb3c0f2 100644--- a/src/lib/catalog/faceless.ts+++ b/src/lib/catalog/faceless.ts@@ -1,4 +1,5 @@import { describeMove, KEN_BURNS_FPS, sceneMoves } from "@/lib/av/ken-burns";+import { SPLIT_MODEL } from "@/lib/av/split";import { COPY_JOIN_VIDEOS, lengthRange, plannedDurations } from "./clip-lengths";import { estimateCost } from "./plan";import { pricingAt } from "./promo";@@ -415,6 +416,18 @@ export interface EpisodeSettings {auto?: boolean;/** Content Factory: a reference clip's style brief, applied to the script and the look. */brief?: BriefLook;+ /**+ * A clip whose soundtrack becomes the music bed (open engine, with music on): its music and effects, the talking+ * taken out, looped to the film's length (clipBedFor). The cloud makes the music instead.+ */+ bedClip?: BedClip;+}++/** A video or audio file whose soundtrack is the music bed, and how long it is. */+export interface BedClip {+ url: string;+ seconds: number;+ name?: string;}/**@@ -951,8 +964,9 @@ export interface MusicPlan {* The music for a film of `seconds`: the bed the music model makes (musicLength) and, when that is shorter* than the film, the loop that extends it. 0 seconds of music short means the whole film has music.*/-export function musicPlan(music: ModelDef | undefined, loop: ModelDef | undefined, seconds: number): MusicPlan {- const bed = musicLength(music, seconds);+export function musicPlan(music: ModelDef | undefined, loop: ModelDef | undefined, seconds: number, bedSeconds?: number): MusicPlan {+ // A clip's soundtrack is as long as the clip (it can't be made longer, only looped).+ const bed = bedSeconds && bedSeconds > 0 ? Math.round(bedSeconds * 100) / 100 : musicLength(music, seconds);// The bed runs a second past the film when it can; one that only misses that second needs no loop (a whole// second play of Sonilo's 600 s for a 600 s film would be a call for nothing).if (bed >= seconds || !loop) return { bed, loop: null, short: Math.max(0, Math.ceil(seconds - bed)) };@@ -1149,25 +1163,64 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph});let bedKey = "music";+ // The bed's stem when it comes from a clip's soundtrack (its music and effects, split from the talking).+ let bedStem: string | undefined;if (models.music) {const musicDef = pick(lookup, models.music);- const plan = musicPlan(musicDef, models.loop ? lookup(models.loop) : undefined, length);+ const clip = clipBedFor(settings);+ // A clip longer than the film is cut to the film's length and a second first, so DBS separates only what's played.+ const cutTo = clip && clip.seconds > Math.ceil(length) + 1 ? Math.ceil(length) + 1 : undefined;+ const plan = musicPlan(musicDef, models.loop ? lookup(models.loop) : undefined, length, cutTo ?? clip?.seconds);const bed = plan.bed;- steps.push({- key: "music",- part: "music",- label: "Music bed",- seconds: bed,- request: {- ...base,- modelId: models.music,- op: "music",- prompt: musicPrompt(input.genre, style, settings.brief?.music),- // A model that sings is asked for an instrumental (ACE-Step, MiniMax Music 3).- params: { duration: bed, numOutputs: 1, ...(musicDef.options.lyrics && { extra: { lyrics: "[Instrumental]" } }) },- step: { label: "Music", index: n, of: n },- },- });+ if (clip) {+ // A clip's soundtrack as the bed (DBS on your GPU): the talking taken out, its music and effects kept.+ bedStem = "background";+ if (cutTo)+ steps.push({+ key: "music-cut",+ part: "music",+ label: "Music bed · your clip cut to the film",+ seconds: cutTo,+ request: {+ ...base,+ modelId: CLIP_BED_CUT_MODEL,+ op: "timeline",+ inputs: { audio: clip.url },+ params: { duration: cutTo, extra: { timeline: { length: cutTo, clips: [{ start: 0, duration: cutTo }] } } },+ step: { label: "Your clip cut to the film", index: n, of: n },+ },+ });+ steps.push({+ key: "music",+ part: "music",+ label: "Music bed · from your clip",+ seconds: bed,+ ...(cutTo && { after: ["music-cut"], chain: [{ slot: "audio" as const }] }),+ request: {+ ...base,+ modelId: SPLIT_MODEL,+ op: "separate-audio",+ inputs: cutTo ? {} : CLIP_BED_AUDIO.test(clip.url) ? { audio: clip.url } : { video: clip.url },+ params: { sourceDuration: bed, extra: { channels: "mono" } },+ step: { label: "Music from your clip", index: n, of: n },+ },+ });+ } else+ steps.push({+ key: "music",+ part: "music",+ label: "Music bed",+ seconds: bed,+ request: {+ ...base,+ modelId: models.music,+ op: "music",+ prompt: musicPrompt(input.genre, style, settings.brief?.music),+ // A model that sings is asked for an instrumental (ACE-Step, MiniMax Music 3).+ params: { duration: bed, numOutputs: 1, ...(musicDef.options.lyrics && { extra: { lyrics: "[Instrumental]" } }) },+ step: { label: "Music", index: n, of: n },+ },+ });// A film longer than the bed: the bed looped (crossfaded seams, or whole plays the mix cuts to the film).if (plan.loop && models.loop) {const { duration, crossfade } = plan.loop;@@ -1176,7 +1229,7 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graphpart: "music",label: "Music bed · looped",after: ["music"],- chain: [{ slot: "audio" }],+ chain: [{ slot: "audio", ...(bedStem && { stem: bedStem }) }],seconds: duration,request: {...base,@@ -1187,6 +1240,7 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph},});bedKey = "music-loop";+ bedStem = undefined;}if (models.level) {steps.push({@@ -1211,7 +1265,7 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graphlabel: mixLabel,seconds: length,after: models.music ? [film, "narration", bedKey] : [film, "narration"],- chain: models.music ? [{ slot: "video" }, { slot: "audio" }, { slot: "audio2" }] : [{ slot: "video" }, { slot: "audio" }],+ chain: models.music ? [{ slot: "video" }, { slot: "audio" }, { slot: "audio2", ...(bedStem && { stem: bedStem }) }] : [{ slot: "video" }, { slot: "audio" }],request: {...base,modelId: models.mux,@@ -1996,6 +2050,29 @@ export function pickerData(lookup: ModelLookup): PickerData {}/** What the music switch does on each engine (settings, the Explainer's popover). */+/**+ * "Use a clip's soundtrack as the bed" (open engine): DBS splits the clip's sound, its music and effects (the talking+ * taken out) loop under the voice with crossfaded seams, at the same level as a made bed (BED_DB). The cloud has no+ * hosted DBS, so it makes the music instead.+ */+export const CLIP_BED_LABEL = "Use a clip's soundtrack as the bed";+export const CLIP_BED_HINT: Record<Engine, string> = {+ open: "Its music and effects, with the talking taken out, under the voice. A short clip loops with a soft crossfade.",+ cloud: "Runs on your GPU (open source). In the cloud the music is made for the film.",+};+/** Clip lengths a bed can come from: long enough for a crossfaded loop, at most as long as the longest film. */+export const CLIP_BED_MIN = 5;+/** Cuts a clip longer than the film to its length (and a second) before the split: the open audio timeline (core nodes, CPU). */+export const CLIP_BED_CUT_MODEL = "oss-audio-timeline";+export const CLIP_BED_MAX = 600;+const CLIP_BED_AUDIO = /[.](wav|mp3|flac|m4a|aac|ogg|opus)([?]|$)/i;++/** The clip whose soundtrack is the bed, when this episode uses one (open engine, music on), else null. */+export function clipBedFor(settings: Pick<EpisodeSettings, "engine" | "music" | "bedClip">): BedClip | null {+ const c = settings.bedClip;+ return settings.engine === "open" && settings.music && c?.url && c.seconds >= CLIP_BED_MIN ? c : null;+}+export const MUSIC_HINT: Record<Engine, string> = {cloud: "An instrumental bed under the voice, as long as the film (Sonilo makes up to 10 minutes; past that it plays again)",open: "An instrumental bed under the voice (ACE-Step); past 4 minutes it loops with a soft crossfade",diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.tsindex bd6dd969..0ca0ac57 100644--- a/src/lib/catalog/genjutsu.ts+++ b/src/lib/catalog/genjutsu.ts@@ -65,6 +65,7 @@ import { LOOK_IDS, lightWords, type LookId, type PaintKeyframe } from "../openjuimport { soulLook } from "./soul";import { filmSize, SHARPEN_COPY, sharpenPrompt, sharpenSteps, sharpenTierFor, type SharpenTier } from "./sharpen";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";+import { withOriginalSound, type OriginalSound } from "../av/original-sound";export type GenjutsuMode = "motion" | "character" | "swap" | "restyle" | "insert" | "picture" | "finish";/** How you say what changes (Object swap and Insert) or who (Character swap): words, clicks on the first frame, or paint on it. */@@ -1294,6 +1295,8 @@ export interface GenjutsuPlanInput {finish?: FinishOptions;/** Scene edit's painted area, as the pack's keyframe (the server reads it from the paint). */paint?: PaintKeyframe[];+ /** What of the clip's sound goes back where it is put back (src/lib/av/original-sound.ts; the cloud: Everything only). */+ originalSound?: OriginalSound;}export interface GenjutsuPlan {@@ -1335,7 +1338,9 @@ function pinEngines(steps: PlanStep[], engine: Engine): PlanStep[] {*/export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {const plan = planSteps(input);- return { ...plan, steps: pinEngines(plan.steps, input.maker.engine) };+ // Original sound: where the clip's sound is put back (a maker that drops it, or several pieces), the part chosen.+ const steps = plan.sound ? withOriginalSound(plan.steps, plan.final, input.originalSound, input.maker.engine, { seconds: input.range.end - input.range.start }) : plan.steps;+ return { ...plan, steps: pinEngines(steps, input.maker.engine) };}function planSteps(input: GenjutsuPlanInput): GenjutsuPlan {diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.tsindex 31056e88..cb26040d 100644--- a/src/lib/catalog/mixed-media.ts+++ b/src/lib/catalog/mixed-media.ts@@ -18,6 +18,7 @@ import { scenePoster, type PresetPreview, type PreviewFx, type PreviewScene } frimport { templateCover, templatePreview } from "../template-covers";import { planShorts, SHORTS_ORIGINAL, type PlanStep, type ShortsLook } from "./shorts";import type { Engine, GenerationRequest, LoraRef } from "./types";+import { originalSoundOn, withOriginalSound, type OriginalSound } from "../av/original-sound";export const MIXED = {minSeconds: 1,@@ -55,7 +56,8 @@ export const MIXED_MODELS: Record<Engine, string[]> = {};export const MIXED_TOOLS = {cloud: { cut: "trim-video", mux: "merge-audio-video", preview: "nano-banana-2-1", frames: "extract-frames", assemble: "images-to-video", join: "join-clips" },- open: { preview: MIXED_ORIGINAL },+ // Original sound other than Everything on your GPU: the selection's sound cut, split and put back under the render.+ open: { preview: MIXED_ORIGINAL, cut: "oss-trim", mux: "oss-mux" },} as const;/**@@ -668,6 +670,8 @@ export interface MixedPlanInput {* one without the key). None: the look runs on its words.*/loras?: LoraRef[];+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts; the cloud: Everything only). */+ originalSound?: OriginalSound;}/**@@ -685,7 +689,7 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: stconst seed = input.seed !== undefined ? { seed: input.seed } : original ? { seed: FRAME_SEED } : {};if (input.engine === "open") {const loras = original ? (input.loras ?? []) : [];- return {+ const plan: { steps: PlanStep[]; final: string } = {final: "render",steps: [{@@ -714,6 +718,17 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: st},],};+ // Original sound other than Everything: the selection's sound cut, then put back under the render as chosen.+ const pick = originalSoundOn(input.originalSound, "open");+ if (pick === "everything" || !input.source.hasAudio) return plan;+ const o = MIXED_TOOLS.open;+ const render = plan.steps[0];+ render.request = { ...render.request, feature: MIXED_STEP_FEATURE, title: undefined };+ plan.steps.push(+ { key: "cut", request: { ...base, feature: MIXED_STEP_FEATURE, modelId: o.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Cut", index: 1, of: 4 } } },+ { key: "final", request: { ...base, feature: MIXED_FEATURE, title: input.title, modelId: o.mux, op: "mux", step: { label: "Original sound", index: 3, of: 4 } }, after: ["render", "cut"], chain: [{ slot: "video" }, { slot: "audio" }] },+ );+ return { steps: withOriginalSound(plan.steps, "final", pick, "open", { seconds: input.range.end - input.range.start }), final: "final" };}const t = MIXED_TOOLS.cloud;const sound = !!input.source.hasAudio;@@ -912,6 +927,7 @@ export function planMixedSmooth(input: MixedPlanInput): { steps: PlanStep[]; finmaxRefs: 0,...(input.engine === "cloud" && { resolution: "720p" }),seed: input.seed ?? FRAME_SEED,+ ...(input.originalSound && { originalSound: input.originalSound }),});const final = plan.final ?? plan.takes[0].look;const frame = originalFrameRequest({ ...input, resolution: smoothFrameResolution(input.resolution) });diff --git a/src/lib/catalog/remove-object.ts b/src/lib/catalog/remove-object.tsindex e26ea963..5ef366c9 100644--- a/src/lib/catalog/remove-object.ts+++ b/src/lib/catalog/remove-object.ts@@ -13,6 +13,7 @@import { h3Canvas } from "./character-swap";import { joinGroups, type PlanStep } from "./shorts";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";+import { originalSoundOn, withOriginalSound, type OriginalSound } from "../av/original-sound";export type RemoveMode = "type" | "click" | "paint";@@ -572,6 +573,8 @@ export interface RemovalPlanInput {seed?: number;/** H3 Person Removal: how far the person's mask is grown, in pixels (default REMOVE.maskGrow.default). */maskGrow?: number;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts; the cloud: Everything only). */+ originalSound?: OriginalSound;}export interface RemovalPlan {@@ -633,7 +636,9 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {const steps: PlanStep[] = [];const op = "remove-object" as const;const tracked = e.engine === "cloud" && (e.id === "bria-video-erase-mask" || (e.id === "bria-video-erase-points" && n > 1));- const sound = !!input.source.hasAudio && (n > 1 || !e.keepsSound);+ // An eraser that keeps the clip's sound needs no sound step, unless only part of the sound goes back (Original sound).+ const partSound = originalSoundOn(input.originalSound, input.engine) !== "everything";+ const sound = !!input.source.hasAudio && (n > 1 || !e.keepsSound || partSound);const eraseFeature = (one: boolean) => (one && !sound ? { ...base, title: input.title } : helper);// What each piece's join input is: its erased window, or (an overlapping window) the window less its first frames.@@ -732,7 +737,7 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {// except on the open engine, whose mux trims the sound to the picture itself.const end = e.window && e.engine === "cloud" ? pieces[n - 1].end : input.range.end;const final = joinWithSound(steps, { engine: input.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: joined, sound, end });- return { steps, final, pieces, sound, tracked };+ return { steps: withOriginalSound(steps, final, input.originalSound, input.engine, { seconds: end - input.range.start }), final, pieces, sound, tracked };}/**@@ -817,7 +822,7 @@ function planPersonRemoval(input: RemovalPlanInput): RemovalPlan {];const piece: Piece = { index: 0, start: input.range.start, end: input.range.end };const final = joinWithSound(steps, { engine: "open", title: input.title, base, helper, source: input.source, range: input.range, pieces: ["erase0"], sound });- return { steps, final, pieces: [piece], sound, tracked: false };+ return { steps: withOriginalSound(steps, final, input.originalSound, "open", { seconds: input.range.end - input.range.start }), final, pieces: [piece], sound, tracked: false };}export interface JoinInput {diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.tsindex f9e4ab57..a9bf1d4e 100644--- a/src/lib/catalog/shorts.ts+++ b/src/lib/catalog/shorts.ts@@ -16,6 +16,7 @@import { scenePoster, type PresetPreview, type PreviewFx, type PreviewScene } from "../preset-cards";import { templateCover, templatePreview } from "../template-covers";import type { ChainSlot, Engine, Generation, GenerationRequest } from "./types";+import { withOriginalSound, type OriginalSound } from "../av/original-sound";// ---------------------------------------------------------------------------// Limits (Higgsfield's, from the upload dialog) and engine shapes@@ -465,6 +466,8 @@ export interface ShortsPlanInput {resolution?: string;/** Extra params for the restyle model (e.g. a seed for a new take). */seed?: number;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts; the cloud: Everything only). */+ originalSound?: OriginalSound;}export const SHORTS_FEATURE = "shorts";@@ -775,7 +778,8 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""request: { ...base, title: input.title, modelId: t.mux, op: "mux", inputs: Object.keys(inputs).length ? inputs : undefined, step: { label: "Final video", index: 1200, of: 1000 } },...(after.length ? { after, chain } : {}),});- return { steps, final: key };+ // Original sound: the music and effects, the dialogue, or the dialogue over lower music (DBS on your GPU).+ return { steps: withOriginalSound(steps, key, input.originalSound, input.engine, { seconds: input.range.end - input.range.start }), final: key };}/** The whole session: every segment's first take, the stitch and the soundtrack. */@@ -828,7 +832,7 @@ export interface ShortsSession {look: ShortsLook;source: { url: string; name?: string; duration?: number; hasAudio?: boolean; width?: number; height?: number; fps?: number };range: ShortsRange;- settings: { aspectRatio: ShortsRatio; language: string; modelId: string; resolution?: string; maxRefs: number; reframes?: boolean };+ settings: { aspectRatio: ShortsRatio; language: string; modelId: string; resolution?: string; maxRefs: number; reframes?: boolean; originalSound?: OriginalSound };segments: ShortsSessionSegment[];stitches: ShortsStitch[];createdAt: number;@@ -849,6 +853,7 @@ export function sessionPlanInput(s: ShortsSession, seed?: number): ShortsPlanInpmaxRefs: s.settings.maxRefs,resolution: s.settings.resolution,reframes: s.settings.reframes,+ ...(s.settings.originalSound && { originalSound: s.settings.originalSound }),...(seed !== undefined ? { seed } : {}),};}diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.tsindex 1018b4d1..00ef7d4d 100644--- a/src/lib/catalog/swap-studio-plan.ts+++ b/src/lib/catalog/swap-studio-plan.ts@@ -39,6 +39,7 @@ import {import { silenceRef } from "./canvas";import { getModel } from "./index";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";+import { withOriginalSound, type OriginalSound } from "../av/original-sound";/** The models each job runs on. */export const STUDIO_MODELS = {@@ -122,7 +123,7 @@ export function planPreview(clip: SwapClip): PlanStep[] | null {// ---------------------------------------------------------------------------// Transcript-export function planTranscribe(clip: SwapClip, engine: Engine): PlanStep[] {+export function planTranscribe(clip: SwapClip, engine: Engine, opts: { cleanVoiceFirst?: boolean } = {}): PlanStep[] {const s = clip.source.duration;return [{@@ -133,7 +134,8 @@ export function planTranscribe(clip: SwapClip, engine: Engine): PlanStep[] {modelId: STUDIO_MODELS[engine].transcribe,op: "transcribe",inputs: { video: workingClip(clip, engine) },- params: { duration: s, sourceDuration: s },+ // "Clean the voice first" (src/lib/av/voice-first.ts): the speech apart from the music and effects before it's read.+ params: { duration: s, sourceDuration: s, ...(opts.cleanVoiceFirst && { extra: { cleanVoiceFirst: true } }) },step: { label: "The clip's words", index: 0, of: 1 },},},@@ -533,6 +535,8 @@ export interface AssemblyPlanInput {pieces: AssemblyPiece[];/** Each take's finished video. */videoOf: (piece: Extract<AssemblyPiece, { kind: "take" }>) => string;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts; the cloud: Everything only). */+ originalSound?: OriginalSound;}/** Fold `keys` into joins of at most `max` (the last join is "join"). */@@ -614,5 +618,6 @@ export function planAssembly(a: AssemblyPlanInput): { steps: PlanStep[]; final:after: [picture],chain: [{ slot: "video" }],});- return { steps, final: "final" };+ // Original sound: the replaced person's speech is new, so Music & effects only is offered first (DBS on your GPU).+ return { steps: withOriginalSound(steps, "final", a.originalSound, a.engine, { seconds: clip.source.duration }), final: "final" };}diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.tsindex 6583c01d..ce4f643e 100644--- a/src/lib/catalog/swap-studio.ts+++ b/src/lib/catalog/swap-studio.ts@@ -18,6 +18,7 @@ import { STUDIO_FPS } from "@/lib/av/scene-cuts";import { filmSize, type SharpenTier } from "./sharpen";import { wholeClipBudget } from "@/lib/av/video-finish";import type { Engine, PixelPoint } from "./types";+import type { OriginalSound } from "../av/original-sound";export const SWAP_STUDIO = {feature: "swap-studio",@@ -320,7 +321,8 @@ export interface SwapClip {transcript: { genId?: string; modelId?: string; cues: TranscriptCue[] | null; voices: Record<string, SwapRole> } | null;review: Decision;reviewNotes: string;- assembly: { genId?: string; stepIds?: string[]; takes: string[]; createdAt: number } | null;+ /** originalSound: what of the clip's sound went back (absent: Everything). */+ assembly: { genId?: string; stepIds?: string[]; takes: string[]; originalSound?: OriginalSound; createdAt: number } | null;}export interface SwapProject {diff --git a/src/lib/studios.ts b/src/lib/studios.tsindex 38ad6438..75de6b88 100644--- a/src/lib/studios.ts+++ b/src/lib/studios.ts@@ -127,6 +127,7 @@ export const LIPSYNC_STUDIO: StudioConfig = {defaultModels: { cloud: "kling-avatar-2", open: "oss-infinitetalk" },promptOptional: true,voiceFacts: true,+ voiceFirst: true,};export const UPSCALE_STUDIO: StudioConfig = {@@ -297,6 +298,7 @@ export const TRANSCRIBE_STUDIO: StudioConfig = {defaultModels: { cloud: "scribe-v2", open: "oss-qwen3-asr" },promptOptional: true,hidePrompt: true,+ voiceFirst: true,};export const SFX_STUDIO: StudioConfig = {diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex da95cf27..f7012603 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -705,7 +705,7 @@ How you work:- Call generate (or create_storyboard) directly. The app shows the user a plan card with the cost and runs it when they approve — never ask "shall I go ahead?" in text.- For multi-step work (an image, then animate it; transcribe, translate, then voice it), put the steps in one generate call and set "after" on each later job: it starts by itself when the earlier job finishes and gets its result as input. When you need to judge a result before deciding the next step, wait with check_generations instead (look=true to see images) and pass the output URL into the next call.- Besides images, video and audio, models can transcribe speech, translate or write text (scripts, captions, ad copy), split images into layers, separate voice from background, trim, caption or re-sound clips, and turn an image into a 3D model: search_models with kind "text" or "model3d" finds the text and 3D ones.-- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor), restore_video (old or black-and-white footage restored and colourised, in Restore & colourise), remove_person (a person removed from a video and the scene rebuilt behind them, on the user's own GPU, in Remove a person), blockout_film (a grey-box 3D blockout from Blender or any 3D app filmed from reference stills and timed beats, as Cinema's Blockout does; in the Library), fly_around (a still filmed along an exact camera path: an orbit by its degrees, direction, tilt and pulse, or a ready move; in the Library) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).+- Whole studio jobs have their own tools, and each job opens in its studio, where the user can carry on: split_layers (a Layers project), restyle_footage (a Shorts Studio session), dub_video (a dub the user reviews line by line in Translate & dub), faceless_episode (a Faceless Studio episode), create_ads (an Ads Studio batch), add_captions (the Captions editor), restore_video (old or black-and-white footage restored and colourised, in Restore & colourise), remove_person (a person removed from a video and the scene rebuilt behind them, on the user's own GPU, in Remove a person), blockout_film (a grey-box 3D blockout from Blender or any 3D app filmed from reference stills and timed beats, as Cinema's Blockout does; in the Library), split_soundtrack (a soundtrack split into dialogue, music and effects, or remixed at set levels; on the open engine only), remove_dialogue (a video's talking taken out or kept alone, the picture copied; open engine only), fly_around (a still filmed along an exact camera path: an orbit by its degrees, direction, tilt and pulse, or a ready move; in the Library) and katana (a reference edit — a 1–30 s video — rebuilt shot for shot with the user's own subject from 1–5 photos, when they want "this edit, but with me / my product"). Use them instead of chaining those steps by hand; once one starts, say which studio it's in (the chat links to it).- Use the user's files by the URLs listed in their message. Earlier outputs are found with list_recent. Saved characters and products are Elements: check list_elements and write their @handle in prompts.- Results show up in the chat by themselves, so don't repeat URLs back. After starting jobs, say briefly what's coming; after they finish, give a short take and suggest a next step.- Be brief and friendly. Plain sentences, no headings. Prices are estimates in USD; open-source models run free on the user's own GPU.@@ -1056,6 +1056,52 @@ const engineFor = (preferred: Engine): Engine => {return mode === "both" ? preferred : mode;};+const TALK = "(?:dialogue|dialog|talking|speech|voices?|speaking|narration)";+const REMOVE_TALK = new RegExp(`\\b(?:remove|take out|strip|cut|get rid of|mute|drop|delete|without)\\b[^.?!]*\\b${TALK}\\b|\\bno ${TALK}\\b`);+const ONLY_TALK = new RegExp(`\\b(?:just|only|isolate|extract|keep)\\b[^.?!]*\\b${TALK}\\b|\\b${TALK} only\\b`);+const ONLY_MUSIC = /\b(?:just|only|isolate|extract|keep)\b[^.?!]*\bmusic\b|\bmusic only\b/;+const AND_EFFECTS = /\b(?:and|&|plus)\s+(?:the\s+)?(?:effects|sfx|sound effects)\b/;+const LOWER_MUSIC = /\b(?:lower|turn down|duck|quieter|reduce)\b[^.?!]*\b(?:music|background|score)\b/;+/**+ * Another studio's job owns the sentence ("dub this and keep the music", "restyle it as anime, keep the music", "transcribe+ * just the speech", "cut it down to 10 seconds and keep the speech"): the sound words describe that job, not a split.+ */+const OTHER_JOB =+ /\b(?:dub(?:bed|bing)?|translate|restyle|anime|cartoon|style|transcri(?:be|ption|pt)|subtitles?|captions?|lip ?sync|trim|shorten|upscale|animate|extend|loop)\b|\bcut\b[^.?!]*\bdown\b|\b\d+(?:\.\d+)?\s*(?:s|secs?|seconds?|minutes?|mins?)\b/;+/** A recording's own faults (noise, echo, hiss, hum, a clean-up) are Clean up voice's, not a split's. */+const VOICE_REPAIR = /\b(?:noise|noisy|echo|reverb|hiss|hum|crackle|clean(?:er|ed|up)?|denoise|muffled)\b/;+const SPLIT_SOUND = /\b(?:split|separate)\b[^.?!]*\b(?:soundtrack|audio|sound|stems?|dialogue|music|effects)\b|\bstems\b/;++/**+ * An attached clip's sound taken apart (split_soundtrack, remove_dialogue): the talking taken out or kept alone, just the+ * music, the music lowered, or the four stems. Null when the words ask for none of that or no audio or video is attached.+ */+export function soundPlan(t: string, files: { kind: string; url: string }[]): { tool: string; input: Record<string, unknown>; say: string } | null {+ const media = files.find((f) => f.kind === "video") ?? files.find((f) => f.kind === "audio");+ if (!media) return null;+ if (OTHER_JOB.test(t) || VOICE_REPAIR.test(t)) return null;+ const video = media.kind === "video";+ const removeTalk = REMOVE_TALK.test(t);+ const onlyTalk = ONLY_TALK.test(t);+ const db = /(-?\d{1,2})\s*db\b/.exec(t);+ const by = db ? -Math.min(30, Math.abs(Number(db[1]))) : -12;+ if (LOWER_MUSIC.test(t) && !removeTalk) {+ if (video) return { tool: "remove_dialogue", input: { video: media.url, keep: "dialogue", music_db: by }, say: `I'll keep the talking and lower the music and effects by ${-by} dB under it. The picture stays exactly as it is.` };+ return { tool: "split_soundtrack", input: { media: media.url, levels_db: { music: by, effects: by } }, say: `I'll remix it with the music and effects ${-by} dB lower under the talking.` };+ }+ if (removeTalk && !onlyTalk) {+ if (video) return { tool: "remove_dialogue", input: { video: media.url, keep: "bed" }, say: "I'll take the talking out and keep the music and sound effects. The picture stays exactly as it is." };+ return { tool: "split_soundtrack", input: { media: media.url, keep: ["music", "effects"] }, say: "I'll take the talking out and keep the music and sound effects." };+ }+ if (ONLY_MUSIC.test(t) && !AND_EFFECTS.test(t)) return { tool: "split_soundtrack", input: { media: media.url, keep: ["music"] }, say: "I'll pull out just the music." };+ if (onlyTalk) {+ if (video) return { tool: "remove_dialogue", input: { video: media.url, keep: "dialogue" }, say: "I'll keep only the talking: the music and effects go. The picture stays exactly as it is." };+ return { tool: "split_soundtrack", input: { media: media.url, keep: ["dialogue"] }, say: "I'll keep just the talking." };+ }+ if (SPLIT_SOUND.test(t)) return { tool: "split_soundtrack", input: { media: media.url }, say: "I'll split it into dialogue, music, effects and music & effects." };+ return null;+}+/*** Read a request into one tool call: counts ("3 vertical videos", "4 portraits"), formats, lengths,* attachments, multi-shot ("a 3-shot ad"), a still that is then animated (two chained jobs), several@@ -1170,6 +1216,9 @@ export function offlinePlan(message: string, preferred: Engine, hint?: SkillMetasay: `I'll translate that into ${language}.`,};}+ // A soundtrack taken apart (DBS on the open engine): "remove the dialogue from this video", "just the music".+ const sound = soundPlan(t, files);+ if (sound) return sound;const isMusic = /\b(music|song|soundtrack|beat|jingle)\b/.test(t);const isWriting =!isMusic &&diff --git a/src/server/assist/sound-tools.ts b/src/server/assist/sound-tools.tsnew file mode 100644index 00000000..9bfc15b1--- /dev/null+++ b/src/server/assist/sound-tools.ts@@ -0,0 +1,163 @@+import "server-only";+import { z } from "zod";+import type { PlannedJob } from "@/lib/assist";+import { LOWER_DEFAULT_DB, LOWER_MAX_DB, LOWER_MIN_DB, outcomeLabel, type DialogueOutcome } from "@/lib/av/remove-dialogue";+import { REMIX_MAX_DB, REMIX_MIN_DB, type RemixStem } from "@/lib/av/clean-dialogue";+import type { Engine } from "@/lib/catalog/types";+import { AudioToolError, planAudioTool, runAudioTool, type AudioToolRequest } from "../audio-tools";+import { ConnectComfyError } from "../generations";+import { engineMode } from "../settings";+import { storedMedia } from "../storage";+import { defineTool, type ToolContext, type ToolOutcome } from "./define";+import { planSteps } from "./studio-tools";++/**+ * Assist and MCP's sound tools (DBS D9): split a soundtrack into dialogue, music and effects (or one remix at set levels),+ * and take the dialogue out of a video, each in one call and priced first (the approval card, MCP's estimate_job). They+ * run the Audio hub's own planners (src/server/audio-tools.ts: Split soundtrack, Remove dialogue, and graph C for a remix),+ * so a run is the same batch the pages start and its results land in the Library.+ *+ * DBS is hosted nowhere: both tools run on the open engine (your GPU, or a CPU) and refuse on the cloud engine in words.+ */++const ref = z.string().describe("A file URL from the chat: an attachment, a project source or an earlier output (/api/files/…).");+const STEM_WORDS = { dialogue: "voice", music: "music", effects: "effects" } as const satisfies Record<string, RemixStem>;+const dB = z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB);++const SplitInput = z.object({+ media: ref.describe("The audio or video whose soundtrack to split."),+ keep: z+ .array(z.enum(["dialogue", "music", "effects"]))+ .min(1)+ .max(3)+ .optional()+ .describe("The parts to keep in one remixed file (e.g. ['music','effects'] for everything but the talking). Leave out (with no levels_db) for the four separate stems."),+ levels_db: z+ .object({ dialogue: dB.optional(), music: dB.optional(), effects: dB.optional() })+ .optional()+ .describe(`Each kept part's level in dB (${REMIX_MIN_DB} to +${REMIX_MAX_DB}, default 0), e.g. { music: -12 } to lower the music under the talking. Given, the result is one remixed file.`),+ quality: z.enum(["fast", "best"]).optional().describe("Fast (DBS-BSRNN) or Best (DBS-TIGER); default: the GPU's pick (Best on a GPU, Fast on a CPU)."),+ stereo: z.boolean().optional().describe("Stereo stems: every channel split on its own (about twice as long)."),+ engine: z.enum(["open", "cloud"]).optional().describe("Default: the chat's engine. DBS runs on the open engine only."),+});++const RemoveInput = z.object({+ video: ref.describe("The video to take the dialogue out of."),+ keep: z+ .enum(["bed", "dialogue"])+ .optional()+ .describe("'bed' (default): the music and sound effects stay and the talking goes. 'dialogue': only the talking stays (with music_db, the talking over the music and effects lowered by that much)."),+ music_db: z+ .number()+ .min(LOWER_MIN_DB)+ .max(LOWER_MAX_DB)+ .optional()+ .describe(`With keep 'dialogue': keep the music and effects under the talking at this level (${LOWER_MIN_DB} to ${LOWER_MAX_DB} dB, e.g. ${LOWER_DEFAULT_DB}).`),+ quality: z.enum(["fast", "best"]).optional().describe("Fast (DBS-BSRNN) or Best (DBS-TIGER); default: the GPU's pick."),+ engine: z.enum(["open", "cloud"]).optional().describe("Default: the chat's engine. DBS runs on the open engine only."),+});++export type SplitToolInput = z.infer<typeof SplitInput>;+export type RemoveToolInput = z.infer<typeof RemoveInput>;++const engineOf = (ctx: ToolContext, asked?: Engine): Engine => (engineMode() === "both" ? (asked ?? ctx.engine) : (engineMode() as Engine));++/** Audio or video, from the file's own header (a file it can't read counts as audio when it has no picture). */+function kindOf(url: string): "audio" | "video" {+ const info = storedMedia(url, { allContainers: true })?.info;+ if (info) return info.hasVideo ? "video" : "audio";+ return /\.(mp4|mov|m4v|webm|mkv|avi)(\?|$)/i.test(url) ? "video" : "audio";+}++/** The Audio hub's request for a split_soundtrack call: the four stems, or one remix when parts or levels are named. */+export function splitBody(i: SplitToolInput, ctx: ToolContext): AudioToolRequest {+ const engine = engineOf(ctx, i.engine);+ const kind = kindOf(i.media);+ const base = { engine, media: i.media, kind, ...(i.quality && { quality: i.quality }), ...(i.stereo && { stereo: true }) };+ const keep = i.keep ? [...new Set(i.keep)] : undefined;+ if (!i.levels_db && (!keep || keep.length === 3)) return { tool: "split", ...base };+ const levels = Object.fromEntries(Object.entries(i.levels_db ?? {}).filter(([, v]) => typeof v === "number").map(([k, v]) => [STEM_WORDS[k as keyof typeof STEM_WORDS], v])) as Partial<Record<RemixStem, number>>;+ return { tool: "remix", ...base, ...(keep && { keep: keep.map((k) => STEM_WORDS[k]) }), levels };+}++/** The Audio hub's request for a remove_dialogue call. */+export function removeBody(i: RemoveToolInput, ctx: ToolContext): AudioToolRequest {+ const outcome: DialogueOutcome = i.keep === "dialogue" ? (i.music_db !== undefined ? "lower-music" : "dialogue-only") : "no-dialogue";+ return { tool: "remove-dialogue", engine: engineOf(ctx, i.engine), video: i.video, outcome, ...(outcome === "lower-music" && { musicDb: i.music_db }), ...(i.quality && { quality: i.quality }) };+}++/** A call priced step by step (never throws: what's in the way is the card's error). */+function priced(tool: string, label: string, body: AudioToolRequest): PlannedJob[] {+ try {+ const p = planAudioTool(body);+ return planSteps(+ tool,+ p.steps.map((s) => ({ key: s.key, request: s.request, ...(s.after && { after: s.after }), ...(s.chain && { chain: s.chain }) })),+ ).map((j, k) => (k === 0 ? { ...j, note: [j.note, p.summary].filter(Boolean).join(" · ") } : j));+ } catch (e) {+ return [{ tool, modelId: body.tool === "remix" ? "oss-dbs-remix" : "oss-dbs-separate", modelName: label, kind: "audio", op: "separate-audio", prompt: label, count: 0, costUsd: 0, demo: false, atomic: true, error: (e as Error).message }];+ }+}++async function started(label: string, body: AudioToolRequest): Promise<ToolOutcome> {+ try {+ const p = planAudioTool(body);+ const run = await runAudioTool(body);+ const result = run.result;+ return {+ content: JSON.stringify({+ result: result.id,+ steps: run.items.map((g) => ({ step: g.request.step?.label ?? g.request.title, id: g.id })),+ summary: p.summary,+ notes: p.notes,+ demo: result.provider === "mock" || undefined,+ note: "The result appears in the chat when it finishes; its files are in the Library.",+ }),+ items: [+ { id: "", role: "tool", text: `${label}: started ${run.items.length} step${run.items.length === 1 ? "" : "s"}`, href: "/library" },+ { id: "", role: "generations", ids: [result.id] },+ ],+ };+ } catch (e) {+ if (e instanceof AudioToolError || e instanceof ConnectComfyError) return { content: JSON.stringify({ error: e.message }), isError: true };+ throw e;+ }+}++const HONEST =+ "There is no hosted DBS: it runs on the open engine (your GPU, or a CPU at about a quarter of real time) and refuses on the cloud engine. Dialogue separates cleanly; music and effects can bleed into each other.";++const splitSoundtrack = defineTool({+ name: "split_soundtrack",+ description:+ "Split the soundtrack of an audio file or a video into its dialogue, music and effects with DBS — Fuobe's Split soundtrack (Audio → Split soundtrack). " ++ "Without keep or levels_db it returns four stems: voice (the dialogue), music, effects and background (music & effects together, everything but the talking). " ++ "With keep and/or levels_db it returns one remixed file instead, e.g. keep ['music','effects'] for no talking, or levels_db { music: -12 } for the music lowered under the talking. " ++ `${HONEST} Price it with estimate_job first. Gated by the same approval card as generate.`,+ schema: SplitInput,+ gated: true,+ title: (i) => (i.keep || i.levels_db ? "Remix the soundtrack" : "Split the soundtrack"),+ place: () => ({ studio: "Split soundtrack", href: "/audio/split" }),+ plan: (i, ctx) => priced("split_soundtrack", "Split soundtrack", splitBody(i, ctx)),+ async run(i, ctx) {+ const body = splitBody(i, ctx);+ return started(body.tool === "remix" ? "Remix soundtrack" : "Split soundtrack", body);+ },+});++const removeDialogue = defineTool({+ name: "remove_dialogue",+ description:+ "Take the dialogue out of a video and keep its music and sound effects, or keep only the dialogue (optionally over the music lowered by music_db) — Fuobe's Remove dialogue (Video tools → Remove dialogue). " ++ `The picture is copied as it is, not re-encoded; the part taken out comes back as a download too. Singing counts as music, so it stays with the music. ${HONEST} Price it with estimate_job first. Gated by the same approval card as generate.`,+ schema: RemoveInput,+ gated: true,+ title: (i) => outcomeLabel(i.keep === "dialogue" ? (i.music_db !== undefined ? "lower-music" : "dialogue-only") : "no-dialogue"),+ place: () => ({ studio: "Remove dialogue", href: "/video-tools/remove-dialogue" }),+ plan: (i, ctx) => priced("remove_dialogue", "Remove dialogue", removeBody(i, ctx)),+ async run(i, ctx) {+ return started("Remove dialogue", removeBody(i, ctx));+ },+});++export const SOUND_TOOLS = [splitSoundtrack, removeDialogue];diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.tsindex b7d481de..479500d1 100644--- a/src/server/assist/tools.ts+++ b/src/server/assist/tools.ts@@ -30,6 +30,7 @@ import { defineTool, type JobPlace, type ResultContent, type ToolContext, type T// Fills STUDIO_ROUTES with the studio modules (Layers, Shorts, dub, Faceless, Ads, Captions).import "./studio-routes";import { SKILL_TOOLS } from "./skill-tools";+import { SOUND_TOOLS } from "./sound-tools";import { STUDIO_TOOLS } from "./studio-tools";export type { ToolContext, ToolOutcome };@@ -101,7 +102,7 @@ const searchModels = defineTool({.string().optional().describe(- "Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image, layers, text-layers, trim, transcribe, captions, mux, separate-audio, translate, write, image-to-3d, splat.",+ "Operation id to filter by, e.g. t2i, edit, t2v, i2v, flf2v, ref2v, extend, lipsync, avatar, tts, upscale-image, layers, text-layers, trim, transcribe, captions, mux, separate-audio, translate, write, image-to-3d, splat. separate-audio splits a soundtrack into stems named in each output's stem: voice (the dialogue) and background (everything else); DBS (oss-dbs-separate) also makes music and effects, so background is music & effects together. split_soundtrack and remove_dialogue do this in one call.",),query: z.string().optional().describe("Words to match in the model name, vendor or description, e.g. 'kling', 'cheap', 'photoreal'."),}),@@ -268,7 +269,9 @@ const Job = z.object({end_image: ref.optional().describe("End frame (first-and-last-frame video)."),video: ref.optional().describe("Input video (extend, edit, lipsync, upscale, trim, captions, transcribe…)."),audio: ref.optional().describe("Input audio (lipsync, avatar, transcribe, separate-audio, mux; for voice-change the recording to re-voice)."),- background_audio: ref.optional().describe("Mux: a second track mixed under the audio — the background stem from separate-audio, or a music bed."),+ background_audio: ref+ .optional()+ .describe("Mux: a second track mixed under the audio — the background stem from separate-audio (music & effects, everything but the talking; DBS also makes music and effects stems on their own), or a music bed."),voice_audio: ref.optional().describe("A recording of the voice to speak with (voice-cloning text to speech) or to change into (voice-change)."),aspect_ratio: z.string().optional().describe("e.g. 16:9, 9:16, 1:1 — one the model lists."),resolution: z.string().optional().describe("e.g. 1080p, 2K — one the model lists."),@@ -593,7 +596,7 @@ export const getTool = (name: string) => TOOLS.find((t) => t.name === name);// Skills, memory and project sources; then whole studios (layers, restyle, dub, faceless, ads, captions); then saved// skills that run by themselves (run_skill).-TOOLS.push(...CONTEXT_TOOLS, ...STUDIO_TOOLS, ...SKILL_TOOLS);+TOOLS.push(...CONTEXT_TOOLS, ...STUDIO_TOOLS, ...SOUND_TOOLS, ...SKILL_TOOLS);/** The approval card's heading for one gated call. */export function cardTitle(name: string, input: unknown): string {diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.tsindex 33d6575b..0c1af8fd 100644--- a/src/server/audio-tools.ts+++ b/src/server/audio-tools.ts@@ -3,7 +3,7 @@ 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 { planCleanDialogue } from "@/lib/av/clean-dialogue";+import { planCleanDialogue, planRemix, REMIX_MAX_DB, REMIX_MIN_DB } from "@/lib/av/clean-dialogue";import { CLOUD_ONLY_CLEAN_PROBLEM, missingReuse, NO_REUSE_PACK, planClean, planTime, tooLongProblem } from "@/lib/av/clean-voice";import type { Engine, Generation } from "@/lib/catalog/types";import { lastGpuDevice } from "./account-gpu";@@ -66,6 +66,22 @@ export const AudioToolBody = z.discriminatedUnion("tool", [channels: z.number().int().positive().max(64).optional(),sourceDuration: z.number().positive().max(36_000).optional(),}),+ z.object({+ /** A soundtrack mixed back on the server as one file at set levels (graph C, oss-dbs-remix): Assist and MCP's split_soundtrack. */+ tool: z.literal("remix"),+ engine: Engine,+ media: FileUrl,+ kind: z.enum(["audio", "video"]),+ name: z.string().max(200).optional(),+ quality: z.enum(["fast", "best"]).optional(),+ stereo: z.boolean().optional(),+ keep: z.array(z.enum(["voice", "music", "effects"])).min(1).max(3).optional(),+ levels: z+ .object({ voice: z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB).optional(), music: z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB).optional(), effects: z.number().min(REMIX_MIN_DB).max(REMIX_MAX_DB).optional() })+ .optional(),+ 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,@@ -165,11 +181,18 @@ function factsOf(url: string, gone = "That audio file is gone — add it again")return { ...(duration && { duration }), ...(info.channels && { channels: info.channels }), hasAudio: info.hasAudio };}-async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine; split?: ClipFacts; headerChannels?: number }> {+type AudioToolPlan = ToolPlan & { engine: Engine; split?: ClipFacts; headerChannels?: number };++async function plan(body: AudioToolRequest): Promise<AudioToolPlan> {+ return planAudioTool(body);+}++/** The plan of a run, from the files' headers (sync: Assist and MCP price a call with it before it runs). */+export function planAudioTool(body: AudioToolRequest): AudioToolPlan {const mode = engineMode();// 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 === "split" || body.tool === "remix") && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_PROBLEM);if (body.tool === "remove-dialogue" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_REMOVE_PROBLEM);if (body.tool === "clean" && mode === "cloud") throw new AudioToolError(CLOUD_ONLY_CLEAN_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)");@@ -182,6 +205,13 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engineconst channels = facts?.channels ?? body.channels;return { engine: body.engine, ...planSplit({ ...body, seconds, channels }), split: { duration: seconds, channels }, headerChannels: facts?.channels };}+ if (body.tool === "remix") {+ const facts = factsOf(body.media);+ if (facts?.hasAudio === false) throw new AudioToolError(body.kind === "video" ? "This video has no sound to remix" : "This file has no sound to remix");+ const seconds = facts?.duration ?? body.sourceDuration;+ const channels = facts?.channels ?? body.channels;+ return { engine: body.engine, ...planRemix({ ...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.@@ -235,7 +265,7 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioToocost = 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" || body.tool === "remove-dialogue" || (body.tool === "clean-dialogue" && body.engine === "open")) {+ if (body.tool === "split" || body.tool === "remix" || body.tool === "remove-dialogue" || (body.tool === "clean-dialogue" && body.engine === "open")) {// 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@@ -254,7 +284,7 @@ export async function previewAudioTool(body: AudioToolRequest): Promise<AudioTooif (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 }) });- const mode = dbsChannelsFor((body.tool === "split" || body.tool === "clean-dialogue") && body.stereo ? "each channel" : "mono", channels);+ const mode = dbsChannelsFor((body.tool === "split" || body.tool === "remix" || body.tool === "clean-dialogue") && body.stereo ? "each channel" : "mono", channels);if (seconds) out.estimate = (body.tool === "remove-dialogue" ? removeDialogueTime : splitTime)({ seconds, quality, mode, channels, device });}if (body.tool === "clean") {diff --git a/src/server/canvas.ts b/src/server/canvas.tsindex b3c4fb63..f83c30ee 100644--- a/src/server/canvas.ts+++ b/src/server/canvas.ts@@ -105,6 +105,7 @@ const NODE_TYPES = ["tts","voice-change","clean-voice",+ "split-soundtrack","clone-voice","translate","concat",diff --git a/src/server/chains.ts b/src/server/chains.tsindex df977293..014f4975 100644--- a/src/server/chains.ts+++ b/src/server/chains.ts@@ -5,6 +5,7 @@ import { MODEL3D_STEP_FEATURE, stillPromptFor3d } from "@/lib/av/model3d";import { chainTiming, chainedWaitMessage, frameTimes, framesWait, planKeyframeClips, spread, type KeyframeClip } from "@/lib/catalog/keyframes";import { gapPrompt, MAKE_FPS, requestTiming } from "@/lib/inbetween";import { faceMosaicStep } from "@/lib/catalog/open-tools";+import { planVoiceFirst } from "@/lib/av/voice-first";import { dualEngine, onEngine } from "@/lib/catalog/engines";import { routesFor } from "@/lib/catalog/plan";import type { ChainSlot, Engine, GenParams, Generation, GenerationRequest, LoraRef, ModelDef, ModelRoute, Operation, PresetEndStep } from "@/lib/catalog/types";@@ -786,3 +787,17 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}}return { batchId, items, byKey };}++/**+ * "Clean the voice first" (src/lib/av/voice-first.ts): the speech separated from the music and effects (DBS on your GPU,+ * ElevenLabs voice isolation in the cloud) before the transcriber or the lip sync hears it; after a lip re-sync on your+ * GPU, the music and effects of the same recording go back under it. One batch; the result comes first.+ */+export function createVoiceFirst(original: GenerationRequest, engine: Engine, opts: { batchId?: string } = {}): Generation[] {+ const steps = planVoiceFirst(original, engine);+ assertOneMode(steps.map((s) => ({ label: s.request.step?.label ?? s.key, modelId: s.request.modelId, op: s.request.op ?? "separate-audio", engine })));+ // In the caller's batch when it has one (a studio pipeline's transcript step), else a batch of its own.+ const run = createPipeline(steps.map((s) => ({ key: s.key, request: s.request, ...(s.after && { after: s.after }), ...(s.chain && { chain: s.chain }) })), { batchId: opts.batchId });+ const last = run.byKey[steps[steps.length - 1].key];+ return withAsked([last, ...run.items.filter((g) => g.id !== last.id)], original, engine);+}diff --git a/src/server/faceless.ts b/src/server/faceless.tsindex 83fe3302..f78f45c9 100644--- a/src/server/faceless.ts+++ b/src/server/faceless.ts@@ -19,6 +19,9 @@ import {MAX_SCRIPT,MAX_SOURCES,musicPlan,+ clipBedFor,+ CLIP_BED_MAX,+ CLIP_BED_MIN,narrationText,normalizeBlocks,OFFLINE_NOTE,@@ -1370,9 +1373,12 @@ function notesFor(settings: EpisodeSettings, seconds: number): { notes?: string[if (settings.styleRefs.length > limit) notes.push(`The open-source picture model follows the first ${limit} style references.`);if (settings.engine === "open" && settings.styleRefs.length && settings.sourceImages?.length) notes.push("Your style references set the look; the attached images aren't used for the open-source pictures.");if (m.music) {- const plan = musicPlan(getModel(m.music), m.loop ? getModel(m.loop) : undefined, seconds);- const minutes = (s: number) => `${Math.floor(s / 60)} min${s % 60 ? ` ${s % 60} s` : ""}`;- if (plan.loop?.crossfade) notes.push(`The music is made ${minutes(plan.bed)} long, then looped with a ${plan.loop.crossfade}-second crossfade to cover the film.`);+ const clip = clipBedFor(settings);+ const plan = musicPlan(getModel(m.music), m.loop ? getModel(m.loop) : undefined, seconds, clip?.seconds);+ const minutes = (s: number) => (s < 60 ? `${Math.round(s)} s` : `${Math.floor(s / 60)} min${Math.round(s % 60) ? ` ${Math.round(s % 60)} s` : ""}`);+ if (clip) notes.push("The music bed is your clip's soundtrack with the talking taken out.");+ if (clip && plan.loop?.crossfade) notes.push(`Your clip is ${minutes(plan.bed)} long, so its soundtrack loops with a ${plan.loop.crossfade}-second crossfade to cover the film.`);+ else if (plan.loop?.crossfade) notes.push(`The music is made ${minutes(plan.bed)} long, then looped with a ${plan.loop.crossfade}-second crossfade to cover the film.`);else if (plan.loop) notes.push(`The music is made ${minutes(plan.bed)} long and plays again to cover the film.`);if (plan.short) notes.push(`The music bed goes up to ${minutes(plan.loop?.duration ?? plan.bed)}, so the last ${plan.short} s play without music.`);}@@ -1530,6 +1536,14 @@ export const SettingsSchema = z.object({resolution: z.string().max(10).optional(),auto: z.boolean().optional(),brief: BriefLookSchema.optional(),+ /** A clip whose soundtrack is the music bed (open engine; the cloud makes the music). */+ bedClip: z+ .object({+ url: FileUrl,+ seconds: z.number().min(CLIP_BED_MIN, `Pick a clip of at least ${CLIP_BED_MIN} seconds for the music bed`).max(CLIP_BED_MAX, "Pick a clip of up to 10 minutes for the music bed"),+ name: z.string().max(200).optional(),+ })+ .optional(),});export const BlockSchema = z.object({diff --git a/src/server/generations.ts b/src/server/generations.tsindex c4ba1cdf..ba85dcd5 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -59,7 +59,8 @@ import { H3_TIER_PARAM, H3_UNET_PARAM } from "@/lib/gpu/h3-tier";import { DETAILS_MAX_IMAGES, GPU_PARAM, QWEN21_SPEED, speedLora } from "@/lib/qwen21-speed";import { BLOCKED_CARD_MESSAGE, looksBlocked } from "./safety-card";import { pollTrainings } from "./training";-import { createEndFrameClip, createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip, createShotFilm, createStillTo3d, joinClips } from "./chains";+import { createEndFrameClip, createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip, createShotFilm, createStillTo3d, createVoiceFirst, joinClips } from "./chains";+import { wantsVoiceFirst } from "@/lib/av/voice-first";import { createRegenerateRun } from "./regenerate";import { REGEN_MODEL, regenerateGraphLoras } from "@/lib/catalog/regenerate";import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";@@ -981,6 +982,8 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =// Fuobe DoP's relight effects: the start frame is relit first, then animated.const relight = !opts.dependsOn && shotModel ? relightStep(original, shotModel) : undefined;if (relight) return createRelitClip(original, relight);+ // "Clean the voice first": the speech apart from the music and effects before a transcriber or a lip sync hears it.+ if (!opts.dependsOn && shotModel && wantsVoiceFirst(original)) return createVoiceFirst(original, shotModel.engine, { batchId: opts.batchId });// Fuobe Soul's PixeletedFace look: the picture, then its faces pixelated (SAM 3.1 + a mosaic), also as a pipeline step or a// Canvas node (it waits for what they wait for). The picture made inside that run (postMade) runs as it is.if (!original.postMade && shotModel && soulPostStep(shotModel.id, original.presetId) === "face-mosaic") {diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.tsindex db9e9a96..613a741a 100644--- a/src/server/genjutsu.ts+++ b/src/server/genjutsu.ts@@ -1,4 +1,5 @@import "server-only";+import { ORIGINAL_SOUND_IDS, originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";import { z } from "zod";import { getModel } from "@/lib/catalog";import { onEngine } from "@/lib/catalog/engines";@@ -107,6 +108,8 @@ export interface GenjutsuBody {character?: CharacterOptions;/** Hard cuts the browser found in the clip (seconds), for the "one continuous shot" warning. */cuts?: number[];+ /** What of the clip's sound goes back where it is put back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;/** Object swap on Scene edit. */object?: ObjectEdit;/** From picture: the first frame, or the video from an approved one. */@@ -220,6 +223,8 @@ export const GenjutsuBodySchema = z.object({picture: picture.optional(),finish: finish.optional(),cuts: z.array(seconds).max(200).optional(),+ /** What of the clip's sound goes back where it is put back (src/lib/av/original-sound.ts). */+ originalSound: z.enum(ORIGINAL_SOUND_IDS).optional(),/** A client nonce for one submit: a repeat gets the first answer (see once()). */requestId: z.string().trim().min(8).max(64).optional(),});@@ -345,6 +350,8 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean; viewer?: Ge...(body.picture ? { picture: body.picture } : {}),...(body.finish ? { finish: body.finish } : {}),...(paint ? { paint } : {}),+ // What of the clip's sound goes back: the cloud puts it all back (DBS runs on your GPU).+ ...(body.originalSound && { originalSound: originalSoundOn(body.originalSound, maker.engine) }),},};}@@ -780,6 +787,8 @@ export const TRANSCRIBERS: Record<Engine, string> = { cloud: "scribe-v2", open:export const TranscribeSchema = z.object({engine: z.enum(["cloud", "open"]),source: z.object({ url: z.string().startsWith("/api/files/").max(500), duration: z.number().finite().positive().max(3600).optional() }),+ /** The speech apart from the music and effects before it's read (src/lib/av/voice-first.ts). */+ cleanVoiceFirst: z.boolean().optional(),});/**@@ -798,7 +807,7 @@ export function transcribeClip(body: z.infer<typeof TranscribeSchema>): { id: stmodelId,op: "transcribe",inputs: { video: body.source.url },- ...(seconds ? { params: { duration: seconds, sourceDuration: seconds } } : {}),+ ...((seconds || body.cleanVoiceFirst) && { params: { ...(seconds && { duration: seconds, sourceDuration: seconds }), ...(body.cleanVoiceFirst && { extra: { cleanVoiceFirst: true } }) } }),step: { label: "The clip's words", index: 0, of: 1 },});return { id: g.id, modelId };diff --git a/src/server/mcp.ts b/src/server/mcp.tsindex 8965f88c..b88eef13 100644--- a/src/server/mcp.ts+++ b/src/server/mcp.ts@@ -21,7 +21,7 @@ const INSTRUCTIONS ="Fuobe is an AI image, video and audio studio (paid cloud models and open-source ComfyUI workflows); it also transcribes, translates and writes text and turns images into 3D models. " +"Look up models with search_models (kinds image, video, audio, text, model3d), price a plan with estimate_cost and tell the user the cost before you call generate or create_storyboard. " +'Chain steps in one generate call with "after" (a still, then animate it). ' +- "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions, restore_video, and katana, which rebuilds a 1–30 s reference edit shot for shot with the user's own subject from 1–5 photos): price them with estimate_job first. " ++ "Whole studio jobs have their own tools (split_layers, restyle_footage, dub_video, faceless_episode, create_ads, add_captions, restore_video, split_soundtrack and remove_dialogue (a soundtrack's dialogue, music and effects, on the open engine only), and katana, which rebuilds a 1–30 s reference edit shot for shot with the user's own subject from 1–5 photos): price them with estimate_job first. " +"Each studio job opens in that Fuobe studio (a Layers project, a Shorts session, a dub to review, a Faceless episode, an Ads Studio batch, the Captions editor, Katana): the result's href is its page on this Fuobe server, so give the user that link; a call the studio can't take runs as plain steps and says why. " +"Skills are playbooks for kinds of jobs (product photos, UGC videos, thumbnails…): list_skills, then load_skill to read one — they're also offered as prompts. " +"A skill that runs by itself (list_skills marks it and names its inputs) runs with run_skill and values for those inputs, the same steps every time: price it with estimate_job first. " +diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.tsindex 409b4ca1..fdb6a412 100644--- a/src/server/mixed-media.ts+++ b/src/server/mixed-media.ts@@ -1,4 +1,5 @@import "server-only";+import { originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";import { getModel } from "@/lib/catalog";import {clampFps,@@ -63,6 +64,8 @@ export interface MixedBody {/** Cloud preview: the frame the browser grabbed at the start of the selection. */frameUrl?: string;seed?: number;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;}/**@@ -198,6 +201,8 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i// LTX follows the clip's outlines, like the open engine's canny ControlNet.extra: modelId === "ltx-2-3-restyle" ? { preprocessor: "canny" } : undefined,...(body.seed !== undefined ? { seed: body.seed } : {}),+ // What of the clip's sound goes back: the cloud puts it all back (DBS runs on your GPU).+ ...(body.originalSound && { originalSound: originalSoundOn(body.originalSound, body.engine) }),},};}diff --git a/src/server/remove-object.ts b/src/server/remove-object.tsindex 4626d6ee..04260c1b 100644--- a/src/server/remove-object.ts+++ b/src/server/remove-object.ts@@ -1,4 +1,5 @@import "server-only";+import { ORIGINAL_SOUND_IDS, originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";import { z } from "zod";import { getModel } from "@/lib/catalog";import { PERSON_REMOVER_LORA } from "@/lib/catalog/character-swap";@@ -70,6 +71,8 @@ export interface RemovalBody {seed?: number;/** H3 Person Removal: how far the person's mask is grown, in pixels. */maskGrow?: number;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;}const fileUrl = z.string().startsWith("/api/files/").max(500);@@ -99,6 +102,8 @@ export const RemovalBodySchema = z.object({range: z.object({ start: seconds, end: seconds }).optional(),seed: z.number().int().min(0).max(2 ** 48).optional(),maskGrow: z.number().int().min(REMOVE.maskGrow.min).max(REMOVE.maskGrow.max).optional(),+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound: z.enum(ORIGINAL_SOUND_IDS).optional(),/** A client nonce for one submit: a repeat gets the first answer (see once()). */requestId: z.string().trim().min(8).max(64).optional(),});@@ -256,6 +261,8 @@ function planInputNow(body: RemovalBody, opts: { probe: boolean; preview?: boolemask: body.mode === "paint" && eraser.engine === "open" ? body.mask : undefined,...(body.seed !== undefined ? { seed: body.seed } : {}),...(eraser.cleanFrame && body.maskGrow !== undefined ? { maskGrow: body.maskGrow } : {}),+ // What of the clip's sound goes back: the cloud puts it all back (DBS runs on your GPU).+ ...(body.originalSound && { originalSound: originalSoundOn(body.originalSound, body.engine) }),},};}diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.tsindex cbbbbac5..d585768a 100644--- a/src/server/shorts-schemas.ts+++ b/src/server/shorts-schemas.ts@@ -1,4 +1,5 @@import "server-only";+import { ORIGINAL_SOUND_IDS } from "@/lib/av/original-sound";import { z } from "zod";import { MIXED } from "@/lib/catalog/mixed-media";import { SHORTS } from "@/lib/catalog/shorts";@@ -29,6 +30,8 @@ export const ShortsBodySchema = z.object({aspectRatio: z.enum(["9:16", "16:9"]).default("9:16"),language: z.string().max(40).default("auto"),modelId: z.string().max(80).optional(),+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound: z.enum(ORIGINAL_SOUND_IDS).optional(),requestId,});@@ -57,6 +60,8 @@ export const MixedBodySchema = z.object({anchor: fileUrl.optional(),frameUrl: fileUrl.optional(),seed: z.number().int().min(0).max(2 ** 48).optional(),+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound: z.enum(ORIGINAL_SOUND_IDS).optional(),requestId,});diff --git a/src/server/shorts.ts b/src/server/shorts.tsindex 81c360a3..38f04706 100644--- a/src/server/shorts.ts+++ b/src/server/shorts.ts@@ -1,4 +1,5 @@import "server-only";+import { originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";import { nanoid } from "nanoid";import { getModel } from "@/lib/catalog";import { maxRefsFor, reframes, resolutionFor, sourceSeconds } from "@/lib/catalog/shorts-models";@@ -211,6 +212,8 @@ export interface ShortsBody {modelId?: string;/** A look of its own instead of a preset (Assist's words), kept on the session like a preset's. Server-side only. */look?: ShortsLook;+ /** What of the clip's sound goes back (src/lib/av/original-sound.ts). */+ originalSound?: OriginalSound;}function lookFor(presetId: string): ShortsLook {@@ -287,6 +290,8 @@ function planWith(body: ShortsBody, info: SourceInfo): { input: ShortsPlanInput;maxRefs: maxRefsFor(modelId, body.engine),resolution: resolutionFor(modelId, body.engine),reframes: body.engine === "open" || reframes(modelId, body.engine),+ // What of the clip's sound goes back: the cloud puts it all back (DBS runs on your GPU).+ ...(body.originalSound && { originalSound: originalSoundOn(body.originalSound, body.engine) }),},};}@@ -401,7 +406,7 @@ export async function createSession(body: ShortsBody, known?: SourceInfo): Promi...(input.source.fps ? { fps: input.source.fps } : {}),},range: input.range,- settings: { aspectRatio: input.aspectRatio, language: input.language, modelId: input.modelId, resolution: input.resolution, maxRefs: input.maxRefs, reframes: input.reframes },+ settings: { aspectRatio: input.aspectRatio, language: input.language, modelId: input.modelId, resolution: input.resolution, maxRefs: input.maxRefs, reframes: input.reframes, ...(input.originalSound && input.originalSound !== "everything" && { originalSound: input.originalSound }) },segments,stitches: [stitch],createdAt: now,diff --git a/src/server/sound-live.ts b/src/server/sound-live.tsnew file mode 100644index 00000000..812651d0--- /dev/null+++ b/src/server/sound-live.ts@@ -0,0 +1,44 @@+import "server-only";+import fs from "node:fs";+import path from "node:path";++const DIR = path.join(process.cwd(), "workflows", "comfyui");+const MANIFEST = path.join(DIR, "manifest.json");+/** The record of real runs that passed, one entry per feature (written when a feature passes its test). */+const GPU_TESTED = path.join(DIR, "gpu-tested.json");++/**+ * Sound features that open one by one, each after a real run passes (as Genjutsu's new modes do, genjutsu-live.ts):+ * - clean-voice-first: "Clean the voice first" before a transcript or a lip sync, and the music and effects put back+ * after a lip re-sync (src/lib/av/voice-first.ts): chains of graphs that each passed, not yet run end to end.+ * - original-sound: "Original sound" starting on Music & effects only where a person is replaced or removed (Remove+ * object, Character Swap, Genjutsu): a DBS split and a stem mux after the studio's own steps, not yet run end to end.+ * Until a feature opens, only the owner runs it, and it starts off (Original sound starts on Everything).+ */+export const SOUND_FEATURES = {+ "clean-voice-first": { workflows: ["separate-soundtrack-dbs"] },+ "original-sound": { workflows: ["separate-soundtrack-dbs"] },+} as const;+export type SoundFeature = keyof typeof SOUND_FEATURES;+export type SoundLive = Record<SoundFeature, boolean>;++const read = (file: string): unknown => {+ try {+ return JSON.parse(fs.readFileSync(file, "utf8"));+ } catch {+ return null;+ }+};++/**+ * Which sound features are open to everyone: every workflow a feature needs has been accepted by ComfyUI (the manifest's+ * `validated`) AND its record says a real run passed (`features[key].passed`). A file that can't be read opens nothing.+ */+export function soundLive(manifest = MANIFEST, record = GPU_TESTED): SoundLive {+ const m = read(manifest) as { workflows?: { id?: string; validated?: boolean }[] } | null;+ const r = read(record) as { features?: Record<string, { passed?: boolean }> } | null;+ const validated = new Set((m?.workflows ?? []).filter((w) => w.validated === true).map((w) => w.id));+ return Object.fromEntries(+ (Object.keys(SOUND_FEATURES) as SoundFeature[]).map((k) => [k, SOUND_FEATURES[k].workflows.every((id) => validated.has(id)) && r?.features?.[k]?.passed === true]),+ ) as SoundLive;+}diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.tsindex ae7656d2..c8103a89 100644--- a/src/server/swap-studio.ts+++ b/src/server/swap-studio.ts@@ -1,4 +1,5 @@import "server-only";+import { originalSoundOn, type OriginalSound } from "@/lib/av/original-sound";import { z } from "zod";import { getModel } from "@/lib/catalog";import { ANCHOR_MODELS, anchorModel, CHARACTER_SWAP, h3Canvas, SWAP_LORAS, swapLoraRef, TURBO_LORA } from "@/lib/catalog/character-swap";@@ -728,7 +729,7 @@ function prepareClipQuietly(projectId: string, clipId: string): void {// ---------------------------------------------------------------------------// Transcript-export function transcribe(projectId: string, clipId: string): SwapProject {+export function transcribe(projectId: string, clipId: string, opts: { cleanVoiceFirst?: boolean } = {}): SwapProject {const p = advanceProject(projectId);mustMatchMode(p.engine);const clip = mustClip(p, clipId);@@ -737,7 +738,7 @@ export function transcribe(projectId: string, clipId: string): SwapProject {mustOffer(modelId, p.engine, "type each shot's words instead");const busy = look1(clip.transcript?.genId);if (busy && ACTIVE.has(busy.status)) throw new ShortsError("The clip is being transcribed", 409);- const pipe = run(planTranscribe(clip, p.engine));+ const pipe = run(planTranscribe(clip, p.engine, opts));const genId = pipe.byKey.transcribe.id;return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, transcript: { genId, modelId, cues: null, voices: c.transcript?.voices ?? {} } })));}@@ -996,7 +997,7 @@ export async function stopTake(projectId: string, body: z.infer<typeof TakeRefSc// Assembly/** The clip with its chosen takes over the original timeline and its own sound (the result goes to the Library). */-export function assemble(projectId: string, clipId: string): SwapProject {+export function assemble(projectId: string, clipId: string, opts: { originalSound?: OriginalSound } = {}): SwapProject {const p = advanceProject(projectId);mustMatchMode(p.engine);const clip = mustClip(p, clipId);@@ -1004,8 +1005,10 @@ export function assemble(projectId: string, clipId: string): SwapProject {const found = assemblyPieces(p, clip);if ("problem" in found) throw new ShortsError(found.problem, 422);const takes = assemblyTakes(found.pieces);+ // What of the clip's sound goes back: the cloud puts it all back (DBS runs on your GPU).+ const sound = originalSoundOn(opts.originalSound, p.engine);const last = look(clip.assembly?.genId);- if (clip.assembly && last && last.status !== "failed" && last.status !== "canceled" && JSON.stringify(clip.assembly.takes) === JSON.stringify(takes)) {+ if (clip.assembly && last && last.status !== "failed" && last.status !== "canceled" && JSON.stringify(clip.assembly.takes) === JSON.stringify(takes) && (clip.assembly.originalSound ?? "everything") === sound) {throw new ShortsError(ACTIVE.has(last.status) ? "This clip is being assembled" : "Already assembled with these takes — download it below", 409);}if (p.engine === "open" && !clip.normalized?.url) throw new ShortsError("The clip is still being prepared at 24 fps — wait for it", 409);@@ -1019,7 +1022,7 @@ export function assemble(projectId: string, clipId: string): SwapProject {existing[`take-${piece.take.id}`] = g!.id;return url;};- const plan = planAssembly({ engine: p.engine, clip, pieces: found.pieces, videoOf });+ const plan = planAssembly({ engine: p.engine, clip, pieces: found.pieces, videoOf, originalSound: sound });// A silent clip's cloud assembly ends on its silence: the WAV is written now (silenceRef, as Genjutsu and Canvas do).const withSilence = silenceWriter();// The takes count as steps already made: a demo join of real takes is refused.@@ -1027,7 +1030,7 @@ export function assemble(projectId: string, clipId: string): SwapProject {plan.steps.map((s) => ({ ...s, request: withSilence(s.request) })),existing,);- const assembly = { genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id), takes, createdAt: Date.now() };+ const assembly = { genId: pipe.byKey[plan.final].id, stepIds: pipe.items.map((g) => g.id), takes, ...(sound !== "everything" && { originalSound: sound }), createdAt: Date.now() };return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, assembly })));}diff --git a/tests/canvas-split.test.ts b/tests/canvas-split.test.tsnew file mode 100644index 00000000..b33c403f--- /dev/null+++ b/tests/canvas-split.test.ts@@ -0,0 +1,160 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import {+ cleanGraph,+ connectionError,+ defaultModelForNode,+ describeNode,+ edgeStem,+ modelChoices,+ OUT,+ outputHandles,+ outputLabel,+ paletteItems,+ SPLIT_OUTPUTS,+ type Canvas,+ type CanvasGraph,+ type CanvasNode,+} from "@/lib/catalog/canvas";+import { CLOUD_SPLIT_PROBLEM, SPLIT_MODEL } from "@/lib/av/split";+import type { Generation } from "@/lib/catalog/types";++// Canvas → Split soundtrack (DBS D8): a utility node with four outputs (Dialogue, Music, Effects, Music & effects), each+// edge carrying its stem on to the next node's chain; OUT stays as Dialogue for boards saved before; DBS on the open+// engine only, so the node is disabled on the cloud with the reason.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-split-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const { db } = await import("@/server/db");+const list = await import("@/app/api/canvases/route");+const one = await import("@/app/api/canvases/[id]/route");+const run = await import("@/app/api/canvases/[id]/run/route");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const at = (x: number) => ({ x, y: 0 });+const clip: CanvasNode = { id: "clip", type: "video-input", position: at(0), data: { url: "/api/files/uploads/2026-11-01/interview.mp4" } };+const split: CanvasNode = { id: "split", type: "split-soundtrack", position: at(320), data: { modelId: SPLIT_MODEL } };+const words: CanvasNode = { id: "words", type: "model", position: at(640), data: { modelId: "oss-qwen3-asr", op: "transcribe" } };+const mux: CanvasNode = { id: "mux", type: "model", position: at(640), data: { modelId: "oss-mux", op: "mux" } };+const board = (edges: CanvasGraph["edges"]): CanvasGraph => ({ nodes: [clip, split, words, mux], edges: [{ id: "in", source: "clip", sourceHandle: OUT, target: "split", targetHandle: "video" }, ...edges] });++describe("the node and its outputs", () => {+ it("has four labelled outputs mapped to the stems, with OUT kept as Dialogue", () => {+ expect(SPLIT_OUTPUTS.map((o) => [o.id, o.label])).toEqual([+ ["voice", "Dialogue"],+ ["music", "Music"],+ ["effects", "Effects"],+ ["background", "Music & effects"],+ ]);+ expect(outputHandles(split)).toEqual([OUT, "voice", "music", "effects", "background"]);+ expect(outputHandles(words)).toEqual([OUT]);+ expect(edgeStem(split, "background")).toBe("background");+ expect(edgeStem(split, OUT)).toBe("voice");+ expect(edgeStem(split, null)).toBe("voice");+ expect(edgeStem(words, OUT)).toBeUndefined();+ expect(outputLabel(split, "music")).toBe("Music");+ expect(outputLabel(words, OUT)).toBe("");+ });++ it("runs DBS on the open engine and is disabled on the cloud with the reason (never another model in its place)", () => {+ expect(defaultModelForNode({ type: "split-soundtrack", data: {} }, "open")?.id).toBe(SPLIT_MODEL);+ expect(defaultModelForNode({ type: "split-soundtrack", data: {} }, "cloud")).toBeUndefined();+ expect(modelChoices(split).map((m) => m.id)).toEqual([SPLIT_MODEL]);+ expect(paletteItems("both").find((p) => p.id === "split-soundtrack")?.disabled).toBeUndefined();+ expect(paletteItems("both", "cloud").find((p) => p.id === "split-soundtrack")?.disabled).toBe(CLOUD_SPLIT_PROBLEM);+ expect(paletteItems("cloud").find((p) => p.id === "split-soundtrack")?.disabled).toBe(CLOUD_SPLIT_PROBLEM);+ });++ it("connects from each output, and refuses an output it doesn't have", () => {+ const g = board([]);+ for (const h of [OUT, "voice", "music", "effects", "background"]) expect(connectionError(g, { source: "split", sourceHandle: h, target: "words", targetHandle: "audio" }), h).toBeNull();+ expect(connectionError(g, { source: "split", sourceHandle: "drums", target: "words", targetHandle: "audio" })).toBe("Split soundtrack has no output");+ expect(connectionError(g, { source: "words", sourceHandle: "music", target: "mux", targetHandle: "audio" })).toMatch(/has no output/);+ });+});++describe("edges carry their stem into the next node's chain", () => {+ it("Dialogue into Transcribe and Music & effects into a mux", () => {+ const g = board([+ { id: "a", source: "split", sourceHandle: "voice", target: "words", targetHandle: "audio" },+ { id: "b", source: "split", sourceHandle: "background", target: "mux", targetHandle: "audio" },+ { id: "c", source: "clip", sourceHandle: OUT, target: "mux", targetHandle: "video" },+ ]);+ const s = describeNode(g, split);+ expect(s.error).toBeUndefined();+ expect(s.request).toMatchObject({ modelId: SPLIT_MODEL, op: "separate-audio", inputs: { video: clip.data.url } });+ expect(s.costUsd).toBe(0);+ expect(describeNode(g, words).request?.chain).toEqual([{ slot: "audio", stem: "voice" }]);+ const m = describeNode(g, mux);+ expect(m.request?.chain).toEqual([{ slot: "audio", stem: "background" }]);+ expect(m.request?.inputs).toEqual({ video: clip.data.url });+ expect(m.deps).toEqual(["split"]);+ });++ it("an old single-OUT edge carries the dialogue", () => {+ const g = board([{ id: "a", source: "split", sourceHandle: OUT, target: "words", targetHandle: "audio" }]);+ expect(describeNode(g, words).request?.chain).toEqual([{ slot: "audio", stem: "voice" }]);+ // Other nodes' edges carry no stem, as before.+ const tts: CanvasNode = { id: "t", type: "model", position: at(0), data: { modelId: "oss-ace-step", op: "music", prompt: "calm piano" } };+ const g2: CanvasGraph = { nodes: [clip, tts, mux], edges: [{ id: "x", source: "t", sourceHandle: OUT, target: "mux", targetHandle: "audio" }, { id: "y", source: "clip", sourceHandle: OUT, target: "mux", targetHandle: "video" }] };+ expect(describeNode(g2, mux).request?.chain).toEqual([{ slot: "audio" }]);+ });++ it("keeps every output's edge through the storage round trip, and drops an unknown one", () => {+ const g = board([+ { id: "a", source: "split", sourceHandle: "music", target: "words", targetHandle: "audio" },+ { id: "b", source: "split", sourceHandle: "effects", target: "mux", targetHandle: "audio" },+ { id: "c", source: "split", sourceHandle: "drums", target: "mux", targetHandle: "audio" },+ { id: "d", source: "split", sourceHandle: OUT, target: "mux", targetHandle: "audio" },+ ]);+ expect(cleanGraph(g).edges.map((e) => [e.id, e.sourceHandle])).toEqual([+ ["in", OUT],+ ["a", "music"],+ ["b", "effects"],+ ["d", OUT],+ ]);+ });+});++describe("a board whose DBS step runs (demo mode)", () => {+ const req = (method: string, body?: unknown) => new Request("http://localhost/api/canvases", { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as any;++ it("saves the four outputs' edges and runs the mux on the Music & effects stem of the split", async () => {+ const g = board([+ { id: "b", source: "split", sourceHandle: "background", target: "mux", targetHandle: "audio" },+ { id: "c", source: "clip", sourceHandle: OUT, target: "mux", targetHandle: "video" },+ ]);+ const { saveFile } = await import("@/server/storage");+ const url = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "interview.mp4" }).url;+ g.nodes = g.nodes.filter((n) => n.id !== "words").map((n) => (n.id === "clip" ? { ...n, data: { url } } : n));+ const created = (await (await list.POST(req("POST", {}))).json()) as Canvas;+ const patched = await one.PATCH(req("PATCH", { graph: g }), ctx(created.id));+ const saved = (await patched.json()) as Canvas;+ expect(patched.status, JSON.stringify(saved)).toBe(200);+ expect(saved.pages[0].graph.edges.find((e) => e.id === "b")?.sourceHandle).toBe("background");+ const res = await run.POST(req("POST", { targets: ["mux"] }), ctx(created.id));+ const body = (await res.json()) as { ran: string[]; items: Generation[]; errors: unknown[] };+ expect(body.errors).toEqual([]);+ expect(body.ran).toEqual(["split", "mux"]);+ const [s, m] = body.items;+ expect(s).toMatchObject({ modelId: SPLIT_MODEL, op: "separate-audio" });+ expect(m.request.chain).toEqual([{ slot: "audio", stem: "background" }]);+ expect((db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(m.id) as { depends_on: string }).depends_on).toBe(s.id);+ expect(gens.getGeneration(m.id)).toBeTruthy();+ });+});diff --git a/tests/faceless.test.ts b/tests/faceless.test.tsindex 45e93b05..fa22d90f 100644--- a/tests/faceless.test.ts+++ b/tests/faceless.test.ts@@ -48,6 +48,8 @@ import {filmSeconds,musicLength,musicPlan,+ clipBedFor,+ CLIP_BED_MIN,plannedTiming,resolveModels,sameCameraMove,@@ -709,6 +711,53 @@ describe("pictures from sources, style references, music length, frame pricing",// Short films need no loop.expect(graphFor({ engine: "open", music: true, voice: null }, six).some((s) => s.key === "music-loop")).toBe(false);});++ it("uses a clip's soundtrack as the bed on the open engine: split, the music and effects looped, mixed at -14 dB", () => {+ const clip = { url: "/api/files/uploads/beach.mp4", seconds: 42.5, name: "beach.mp4" };+ expect(musicPlan(getModel("oss-ace-step"), getModel("oss-audio-loop"), 300, 42.5)).toEqual({ bed: 42.5, loop: { duration: 301, crossfade: 3 }, short: 0 });+ expect(clipBedFor({ engine: "open", music: true, bedClip: clip })).toBe(clip);+ expect(clipBedFor({ engine: "open", music: false, bedClip: clip })).toBeNull();+ expect(clipBedFor({ engine: "cloud", music: true, bedClip: clip })).toBeNull();+ expect(clipBedFor({ engine: "open", music: true, bedClip: { ...clip, seconds: CLIP_BED_MIN - 1 } })).toBeNull();++ const open = graphFor({ engine: "open", music: true, voice: null, bedClip: clip }, placeholderBlocks(300));+ const length = open.filter((s) => s.part === "clip").reduce((n, s) => n + s.seconds!, 0);+ const split = open.find((s) => s.key === "music")!;+ expect(split).toMatchObject({ part: "music", seconds: 42.5 });+ expect(split.after).toBeUndefined();+ expect(split.request).toMatchObject({ modelId: "oss-dbs-separate", op: "separate-audio", inputs: { video: clip.url }, params: { sourceDuration: 42.5, extra: { channels: "mono" } } });+ expect(split.request.prompt).toBeUndefined();+ expect(open.some((s) => s.request.modelId === "oss-ace-step")).toBe(false);+ const loop = open.find((s) => s.key === "music-loop")!;+ expect(loop).toMatchObject({ after: ["music"], chain: [{ slot: "audio", stem: "background" }] });+ expect(loop.request).toMatchObject({ modelId: "oss-audio-loop", params: { duration: length + 1, sourceDuration: 42.5, crossfade: 3 } });+ const mix = open.find((s) => s.key === "mix")!;+ expect(mix.after).toEqual(["join", "narration", "music-loop"]);+ expect(mix.chain).toEqual([{ slot: "video" }, { slot: "audio" }, { slot: "audio2" }]);+ expect(mix.request.params?.extra).toEqual({ backgroundVolumeDb: -14 });++ // A clip longer than the film: no loop, the mix takes the background stem straight from the split.+ const long = graphFor({ engine: "open", music: true, voice: null, bedClip: { url: "/api/files/uploads/song.mp3", seconds: 400 } }, six);+ // The clip is cut to the film and a second first, so DBS separates only what's played.+ const film = long.filter((s) => s.part === "clip").reduce((n, s) => n + s.seconds!, 0);+ const cut = long.find((s) => s.key === "music-cut")!;+ expect(cut.request).toMatchObject({ modelId: "oss-audio-timeline", op: "timeline", inputs: { audio: "/api/files/uploads/song.mp3" }, params: { duration: Math.ceil(film) + 1 } });+ expect(long.find((s) => s.key === "music")).toMatchObject({ after: ["music-cut"], chain: [{ slot: "audio" }], seconds: Math.ceil(film) + 1 });+ expect(long.find((s) => s.key === "music")!.request.inputs).toEqual({});+ expect(long.some((s) => s.key === "music-loop")).toBe(false);+ // A clip about as long as the film is split whole.+ const near = graphFor({ engine: "open", music: true, voice: null, bedClip: { url: "/api/files/uploads/song.mp3", seconds: Math.ceil(film) + 1 } }, six);+ expect(near.some((s) => s.key === "music-cut")).toBe(false);+ expect(near.find((s) => s.key === "music")!.request.inputs).toEqual({ audio: "/api/files/uploads/song.mp3" });+ expect(long.find((s) => s.key === "mix")!.chain).toEqual([{ slot: "video" }, { slot: "audio" }, { slot: "audio2", stem: "background" }]);++ // The cloud makes the music as before; so does an open episode without a clip.+ const cloud = graphFor({ engine: "cloud", music: true, animation: "frames", bedClip: clip }, six);+ expect(cloud.find((s) => s.key === "music")!.request).toMatchObject({ modelId: "sonilo-music", op: "music" });+ const plain = graphFor({ engine: "open", music: true, voice: null }, six);+ expect(plain.find((s) => s.key === "music")!.request).toMatchObject({ modelId: "oss-ace-step", op: "music" });+ expect(plain.find((s) => s.key === "mix")!.chain).toEqual([{ slot: "video" }, { slot: "audio" }, { slot: "audio2" }]);+ });});describe("offline topic suggestions", () => {diff --git a/tests/original-sound.test.ts b/tests/original-sound.test.tsnew file mode 100644index 00000000..2b71d609--- /dev/null+++ b/tests/original-sound.test.ts@@ -0,0 +1,168 @@+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_ORIGINAL_SOUND, ORIGINAL_SOUNDS, originalSoundDefault, originalSoundOn, withOriginalSound } from "@/lib/av/original-sound";+import { getMaker, ORIGINALS, planGenjutsu, type GenjutsuPlanInput } from "@/lib/catalog/genjutsu";+import { defaultValues, getMixedPreset, planMixed, type MixedPlanInput } from "@/lib/catalog/mixed-media";+import { getEraser, planRemoval, type RemovalPlanInput } from "@/lib/catalog/remove-object";+import { lookFromPreset, planShorts, SHORTS_MODELS, SHORTS_PRESETS, type PlanStep, type ShortsPlanInput } from "@/lib/catalog/shorts";+import type { GenerationRequest } from "@/lib/catalog/types";++// "Original sound" (DBS D7): what of a clip's sound goes back under its new picture in Shorts, Mixed Media, Genjutsu,+// Remove object and Character Swap Studio. Everything stays as before; on your GPU the other choices split the sound with+// DBS and put the chosen stem(s) back with the studio's own mux; the cloud has Everything only.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-original-sound-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+const { setSetting } = await import("@/server/settings");+const { createPipeline } = await import("@/server/chains");+beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const mux = (over: Partial<PlanStep> = {}): PlanStep => ({ key: "final", request: { feature: "x", batchTitle: "T", title: "T", modelId: "oss-mux", op: "mux", step: { label: "Final", index: 1200, of: 1000 } }, ...over });+const muxOf = (steps: PlanStep[], key: string) => steps.find((s) => s.key === key)!;++describe("withOriginalSound", () => {+ it("Everything, the cloud, a silent bed or no mux: the plan as it was", () => {+ const steps = [mux({ after: ["join"], chain: [{ slot: "video" }], request: { ...mux().request, inputs: { audio: "/api/files/a.mp4" } } })];+ expect(withOriginalSound(steps, "final", "everything", "open")).toBe(steps);+ expect(withOriginalSound(steps, "final", undefined, "open")).toBe(steps);+ expect(withOriginalSound(steps, "final", "music-effects", "cloud")).toBe(steps);+ expect(withOriginalSound(steps, "nope", "music-effects", "open")).toBe(steps);+ const silent = [mux({ request: { ...mux().request, inputs: { audio: "/api/files/silence-12.wav" } } })];+ expect(withOriginalSound(silent, "final", "dialogue", "open")).toBe(silent);+ });++ it("a file going in: DBS on it, then the mux on its music & effects", () => {+ const steps = [mux({ after: ["join"], chain: [{ slot: "video" }], request: { ...mux().request, inputs: { audio: "/api/files/clip.mp4" } } })];+ const out = withOriginalSound(steps, "final", "music-effects", "open", { seconds: 9 });+ expect(out.map((s) => s.key)).toEqual(["final-split", "final"]);+ expect(out[0].request).toMatchObject({ modelId: "oss-dbs-separate", op: "separate-audio", inputs: { video: "/api/files/clip.mp4" }, params: { extra: { channels: "mono" }, sourceDuration: 9 }, step: { index: 1199 } });+ expect(out[1]).toMatchObject({ after: ["join", "final-split"], chain: [{ slot: "video" }, { slot: "audio", stem: "background" }] });+ expect(out[1].request.inputs).toBeUndefined();+ });++ it("an earlier step's clip going in: DBS waits for it; Lower the music takes two stems of the one split", () => {+ const steps: PlanStep[] = [+ { key: "sound", request: { feature: "x", modelId: "oss-segment", op: "trim" } },+ mux({ after: ["join", "sound"], chain: [{ slot: "video" }, { slot: "audio" }] }),+ ];+ const out = withOriginalSound(steps, "final", "lower-music", "open", { lowerDb: -18 });+ expect(out.map((s) => s.key)).toEqual(["sound", "final-split", "final"]);+ expect(out[1]).toMatchObject({ after: ["sound"], chain: [{ slot: "audio" }] });+ expect(out[2]).toMatchObject({+ after: ["join", "final-split", "final-split"],+ chain: [{ slot: "video" }, { slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }],+ request: { params: { extra: { backgroundVolumeDb: -18 } } },+ });+ expect(withOriginalSound(steps, "final", "dialogue", "open")[2].chain).toEqual([{ slot: "video" }, { slot: "audio", stem: "voice" }]);+ });++ it("knows its choices, defaults and the cloud's words", () => {+ expect(ORIGINAL_SOUNDS.map((o) => o.label)).toEqual(["Everything", "Music & effects only", "Dialogue only", "Lower the music"]);+ expect(originalSoundDefault({ engine: "open" })).toBe("everything");+ // Everything until the split and stem mux have passed a real run; then Music & effects only where a person is replaced.+ expect(originalSoundDefault({ engine: "open", replacesPerson: true })).toBe("everything");+ expect(originalSoundDefault({ engine: "open", replacesPerson: true, live: true })).toBe("music-effects");+ expect(originalSoundDefault({ engine: "open", live: true })).toBe("everything");+ expect(originalSoundDefault({ engine: "cloud", replacesPerson: true })).toBe("everything");+ expect(originalSoundOn("dialogue", "cloud")).toBe("everything");+ expect(CLOUD_ORIGINAL_SOUND).toMatch(/run on your GPU \(open source\)/);+ });+});++describe("each studio's plan", () => {+ const shorts = (over: Partial<ShortsPlanInput> = {}): ShortsPlanInput => ({+ engine: "open",+ title: "Claymation · beach",+ source: { url: "/api/files/uploads/beach.mp4", duration: 30, hasAudio: true },+ range: { start: 4, end: 14 },+ look: lookFromPreset(SHORTS_PRESETS[0]),+ aspectRatio: "9:16",+ language: "auto",+ modelId: SHORTS_MODELS.open[0],+ maxRefs: 0,+ ...over,+ });+ const final = (steps: PlanStep[]) => steps.find((s) => s.request.op === "mux" && !s.key.endsWith("-split"))!;++ it("Shorts: Everything is unchanged; Music & effects only puts the background stem of the selection's sound back", () => {+ const before = planShorts(shorts());+ expect(planShorts(shorts({ originalSound: "everything" })).steps).toEqual(before.steps);+ const p = planShorts(shorts({ originalSound: "music-effects" }));+ const m = final(p.steps);+ const split = p.steps.find((s) => s.key === `${m.key}-split`)!;+ expect(split.request.modelId).toBe("oss-dbs-separate");+ expect(m.chain?.at(-1)).toEqual({ slot: "audio", stem: "background" });+ // The cloud puts everything back.+ const cloud = planShorts(shorts({ engine: "cloud", modelId: "gemini-omni-flash", originalSound: "music-effects" }));+ expect(cloud.steps.some((s) => s.request.modelId === "oss-dbs-separate")).toBe(false);+ });++ it("Shorts' Lower the music runs as one pipeline (two stems of one split)", () => {+ const p = planShorts(shorts({ originalSound: "lower-music" }));+ const run = createPipeline(p.steps.map((s) => ({ key: s.key, request: s.request, ...(s.after && { after: s.after }), ...(s.chain && { chain: s.chain }) })));+ const m = final(p.steps);+ expect(run.byKey[m.key].request.chain?.filter((c) => c.stem)).toEqual([+ { slot: "audio", stem: "voice" },+ { slot: "audio2", stem: "background" },+ ]);+ });++ it("Mixed Media on your GPU: the render, the selection's sound cut, split and put back as chosen", () => {+ const sketch = getMixedPreset("mixed-sketch")!;+ const input = (over: Partial<MixedPlanInput> = {}): MixedPlanInput => ({ engine: "open", title: "Sketch · skate", preset: sketch, values: defaultValues(sketch), source: { url: "/api/files/uploads/skate.mp4", duration: 12, hasAudio: true }, range: { start: 2, end: 7 }, fps: 8, resolution: "1K", modelId: "oss-mixed-media", ...over });+ expect(planMixed(input()).steps.map((s) => s.key)).toEqual(["render"]);+ const p = planMixed(input({ originalSound: "dialogue" }));+ expect(p.final).toBe("final");+ expect(p.steps.map((s) => s.key)).toEqual(["render", "cut", "final-split", "final"]);+ expect(muxOf(p.steps, "final").chain).toEqual([{ slot: "video" }, { slot: "audio", stem: "voice" }]);+ expect(muxOf(p.steps, "cut").request).toMatchObject({ modelId: "oss-trim", op: "trim", params: { startTime: 2, endTime: 7 } });+ // A silent clip has nothing to put back.+ expect(planMixed(input({ originalSound: "dialogue", source: { url: "/api/files/x.mp4", hasAudio: false } })).steps.map((s) => s.key)).toEqual(["render"]);+ });++ it("Remove object: a person removed on your GPU gets their speech out with Music & effects only", () => {+ const eraser = getEraser("oss-h3-person-remove")!;+ const input = (over: Partial<RemovalPlanInput> = {}): RemovalPlanInput => ({ engine: "open", mode: "type", eraser, title: "Remove · the man", source: { url: "/api/files/uploads/clip.mp4", duration: 12, fps: 30, width: 1280, height: 720, hasAudio: true }, range: { start: 2, end: 9 }, prompt: "Remove the man", ...over });+ const before = planRemoval(input());+ expect(planRemoval(input({ originalSound: "everything" })).steps).toEqual(before.steps);+ const p = planRemoval(input({ originalSound: "music-effects" }));+ expect(muxOf(p.steps, p.final).chain?.at(-1)).toEqual({ slot: "audio", stem: "background" });+ expect(p.steps.some((s) => s.request.modelId === "oss-dbs-separate")).toBe(true);+ });++ it("Remove object: an eraser that keeps the clip's sound gets a sound step when only part of it goes back", () => {+ const vace = getEraser("oss-vace-remove")!;+ const input: RemovalPlanInput = { engine: "open", mode: "type", eraser: vace, title: "Remove · the cup", source: { url: "/api/files/uploads/clip.mp4", duration: 4, fps: 16, width: 832, height: 480, hasAudio: true }, range: { start: 0, end: 4 }, prompt: "the cup" };+ const plain = planRemoval(input);+ const p = planRemoval({ ...input, originalSound: "dialogue" });+ expect(p.sound).toBe(true);+ if (!plain.sound) expect(plain.steps.some((s) => s.request.op === "mux")).toBe(false);+ expect(muxOf(p.steps, p.final).chain?.at(-1)).toEqual({ slot: "audio", stem: "voice" });+ });++ it("Genjutsu: where the clip's sound is put back on your GPU, the part chosen", () => {+ const maker = getMaker(ORIGINALS.motion, "open")!;+ const base: GenjutsuPlanInput = { engine: "open", mode: "motion", maker, title: "Genjutsu", source: { url: "/api/files/clip.mp4", duration: 20, fps: 30, width: 1280, height: 720, hasAudio: true }, range: { start: 4, end: 14 }, quality: "720p", references: ["/api/files/hero.png"] };+ const before = planGenjutsu(base);+ expect(planGenjutsu({ ...base, originalSound: "everything" }).steps).toEqual(before.steps);+ const p = planGenjutsu({ ...base, originalSound: "lower-music" });+ if (before.sound) {+ expect(p.steps.some((s) => s.request.modelId === "oss-dbs-separate")).toBe(true);+ expect(muxOf(p.steps, p.final).request.params?.extra?.backgroundVolumeDb).toBe(-12);+ } else expect(p.steps).toEqual(before.steps);+ });++ it("Character Swap Studio's assembly shape: the clip's file going back is split, its music & effects kept", () => {+ const req: GenerationRequest = { feature: "swap", modelId: "oss-mux", op: "mux", inputs: { audio: "/api/files/clip-24fps.mp4" } };+ const out = withOriginalSound([{ key: "final", request: req, after: ["join"], chain: [{ slot: "video" }] }], "final", "music-effects", "open");+ expect(out[0].request.inputs).toEqual({ video: "/api/files/clip-24fps.mp4" });+ expect(out[1].chain).toEqual([{ slot: "video" }, { slot: "audio", stem: "background" }]);+ });+});diff --git a/tests/sound-tools-assist.test.ts b/tests/sound-tools-assist.test.tsnew file mode 100644index 00000000..18732ae2--- /dev/null+++ b/tests/sound-tools-assist.test.ts@@ -0,0 +1,188 @@+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_SPLIT_PROBLEM } from "@/lib/av/split";+import { OFF_DB, planRemix, REMIX_FEATURE, remixWords } from "@/lib/av/clean-dialogue";+import type { GenInput } from "@/lib/catalog/types";++// Assist and MCP's split_soundtrack and remove_dialogue (DBS D9), and the remix at set levels they run on graph C+// (oss-dbs-remix, the model Clean up dialogue runs on).+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-sound-assist-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const { saveFile } = await import("@/server/storage");+const { prepareWorkflow } = await import("@/server/providers/comfyui");+const { getTool, executeTool } = await import("@/server/assist/tools");+const { soundPlan, offlinePlan } = await import("@/server/assist/agent");+const { handleMcp } = await import("@/server/mcp");+const { getGeneration } = await import("@/server/generations");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++/** A 16-bit PCM WAV of `seconds` of silence. */+function wav(seconds: number, channels = 2, rate = 8000): Buffer {+ const frames = Math.round(seconds * rate);+ const b = Buffer.alloc(44 + frames * channels * 2);+ b.write("RIFF", 0);+ b.writeUInt32LE(36 + frames * channels * 2, 4);+ b.write("WAVE", 8);+ b.write("fmt ", 12);+ b.writeUInt32LE(16, 16);+ b.writeUInt16LE(1, 20);+ b.writeUInt16LE(channels, 22);+ b.writeUInt32LE(rate, 24);+ b.writeUInt32LE(rate * channels * 2, 28);+ b.writeUInt16LE(channels * 2, 32);+ b.writeUInt16LE(16, 34);+ b.write("data", 36);+ b.writeUInt32LE(frames * channels * 2, 40);+ return b;+}++const audioFile = () => saveFile({ data: wav(3), contentType: "audio/wav", source: "upload", name: "podcast.wav" }).url;+const videoFile = () => saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "interview.mp4" }).url;++describe("planRemix (graph C, oss-dbs-remix)", () => {+ it("keeps the named stems at their levels and leaves the others out", () => {+ const p = planRemix({ engine: "open", media: "/api/files/a.wav", kind: "audio", keep: ["voice", "music"], levels: { music: -12.4 } });+ expect(p.levels).toEqual({ voice: 0, music: -12, effects: OFF_DB });+ const r = p.steps[0].request;+ expect(r).toMatchObject({ modelId: "oss-dbs-remix", op: "separate-audio", feature: REMIX_FEATURE, inputs: { audio: "/api/files/a.wav" } });+ expect(r.params?.extra).toEqual({ channels: "mono", voiceDb: 0, musicDb: -12, effectsDb: OFF_DB });+ expect(remixWords(p.levels)).toBe("Dialogue, Music −12 dB");+ expect(p.summary).toMatch(/one file: Dialogue, Music −12 dB/);+ });++ it("clamps levels, keeps all three by default, and refuses the cloud", () => {+ expect(planRemix({ engine: "open", media: "/api/files/a.mp4", kind: "video", levels: { voice: 40, effects: -99 } }).levels).toEqual({ voice: 12, music: 0, effects: -60 });+ expect(() => planRemix({ engine: "cloud", media: "/api/files/a.wav", kind: "audio" })).toThrow(CLOUD_SPLIT_PROBLEM);+ expect(() => planRemix({ engine: "open", media: "/api/files/a.wav", kind: "audio", keep: [] as never })).not.toThrow();+ });++ it("binds each stem's level to graph C's AudioAdjustVolume nodes", async () => {+ const p = planRemix({ engine: "open", media: "/api/files/a.wav", kind: "audio", keep: ["music", "effects"], levels: { music: -6 } });+ const input: GenInput = { seed: 1, audio: "song.wav", extra: p.steps[0].request.params?.extra as Record<string, unknown> };+ const { manifest, workflow } = await prepareWorkflow("soundtrack-remix-dbs", input, {+ generationId: "g1",+ op: "separate-audio",+ upload: async (_d: unknown, _t: unknown, name: string) => `up_${name}`,+ media: () => undefined,+ device: async () => "cpu",+ dbsModels: async () => undefined,+ });+ expect(manifest.id).toBe("soundtrack-remix-dbs");+ expect([workflow["4"].inputs.volume, workflow["5"].inputs.volume, workflow["6"].inputs.volume]).toEqual([OFF_DB, -6, 0]);+ expect(workflow["1"].inputs.audio).toBe("song.wav");+ });+});++describe("Assist: split_soundtrack and remove_dialogue", () => {+ const ctx = { engine: "open" as const };+ it("prices a split first (free in demo mode, on graph A) and refuses the cloud engine in words", () => {+ const media = audioFile();+ const split = getTool("split_soundtrack")!;+ const jobs = split.plan!({ media }, ctx);+ expect(jobs).toHaveLength(1);+ expect(jobs[0]).toMatchObject({ tool: "split_soundtrack", modelId: "oss-dbs-separate", costUsd: 0, demo: true, atomic: true });+ expect(jobs[0].note).toMatch(/Splits it into dialogue, music, effects and music & effects/);+ const cloud = split.plan!({ media }, { engine: "cloud" });+ expect(cloud[0].error).toBe(CLOUD_SPLIT_PROBLEM);+ expect(split.place!({ media }, ctx)).toEqual({ studio: "Split soundtrack", href: "/audio/split" });+ });++ it("makes one remix when parts or levels are named, and four stems otherwise", async () => {+ const media = audioFile();+ const split = getTool("split_soundtrack")!;+ const out = await split.run({ media, keep: ["music", "effects"], levels_db: { music: -6 } }, ctx);+ expect(out.isError).toBeFalsy();+ const body = JSON.parse(out.content as string);+ const g = getGeneration(body.result)!;+ expect(g.request).toMatchObject({ modelId: "oss-dbs-remix", feature: REMIX_FEATURE });+ expect(g.request.params?.extra).toMatchObject({ voiceDb: OFF_DB, musicDb: -6, effectsDb: 0 });+ const stems = JSON.parse((await split.run({ media }, ctx)).content as string);+ expect(getGeneration(stems.result)!.request.modelId).toBe("oss-dbs-separate");+ expect(getGeneration(stems.result)!.request.feature).toBe("audio-split");+ });++ it("reads keep and music_db into Remove dialogue's three outcomes on the video", async () => {+ const video = videoFile();+ const tool = getTool("remove_dialogue")!;+ expect(tool.title!({ video })).toBe("No dialogue");+ expect(tool.title!({ video, keep: "dialogue" })).toBe("Dialogue only");+ expect(tool.title!({ video, keep: "dialogue", music_db: -18 })).toBe("Lower the music");+ const jobs = tool.plan!({ video, keep: "dialogue", music_db: -18 }, ctx);+ expect(jobs.map((j) => j.modelId)).toEqual(["oss-dbs-separate", "oss-mux"]);+ expect(jobs.every((j) => !j.error && j.costUsd === 0)).toBe(true);+ const run = JSON.parse((await tool.run({ video, keep: "dialogue", music_db: -18 }, ctx)).content as string);+ const mux = getGeneration(run.result)!;+ expect(mux.request.params?.extra?.backgroundVolumeDb).toBe(-18);+ expect(run.steps).toHaveLength(2);+ expect(tool.plan!({ video }, { engine: "cloud" })[0].error).toMatch(/Remove dialogue runs on your GPU/);+ });++ it("refuses a file that is gone, as a tool error", async () => {+ const out = await executeTool("split_soundtrack", { media: "/api/files/uploads/none.wav" }, ctx);+ expect(out.isError).toBe(true);+ });++ it("is offered over MCP and priced with estimate_job", async () => {+ const list = (await handleMcp({ jsonrpc: "2.0", id: 1, method: "tools/list" })) as { result: { tools: { name: string; description: string }[] } };+ const names = list.result.tools.map((t) => t.name);+ expect(names).toEqual(expect.arrayContaining(["split_soundtrack", "remove_dialogue"]));+ expect(list.result.tools.find((t) => t.name === "split_soundtrack")!.description).toMatch(/no hosted DBS/);+ const media = audioFile();+ const est = (await handleMcp({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "estimate_job", arguments: { tool: "split_soundtrack", arguments: { media, engine: "open" } } } })) as {+ result: { isError: boolean; content: { text: string }[] };+ };+ // MCP's calls run on the cloud engine unless one asks for the open one: there it says why it can't.+ const cloud = (await handleMcp({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "estimate_job", arguments: { tool: "split_soundtrack", arguments: { media } } } })) as { result: { content: { text: string }[] } };+ expect(cloud.result.content[0].text).toContain(CLOUD_SPLIT_PROBLEM);+ expect(est.result.isError, est.result.content[0].text).toBe(false);+ expect(est.result.content[0].text).toMatch(/oss-dbs-separate|DBS/);+ });+});++describe("the offline planner's sound suggestions", () => {+ const v = [{ kind: "video", url: "/api/files/v.mp4" }];+ const a = [{ kind: "audio", url: "/api/files/a.wav" }];+ it("reads 'remove the dialogue', 'just the music', 'lower the music' and 'split the soundtrack'", () => {+ expect(soundPlan("remove the dialogue from this video", v)).toMatchObject({ tool: "remove_dialogue", input: { video: "/api/files/v.mp4", keep: "bed" } });+ expect(soundPlan("just the music please", v)).toMatchObject({ tool: "split_soundtrack", input: { media: "/api/files/v.mp4", keep: ["music"] } });+ expect(soundPlan("lower the music by 18 db", v)).toMatchObject({ tool: "remove_dialogue", input: { keep: "dialogue", music_db: -18 } });+ expect(soundPlan("only the dialogue", v)).toMatchObject({ tool: "remove_dialogue", input: { keep: "dialogue" } });+ expect(soundPlan("take out the talking", a)).toMatchObject({ tool: "split_soundtrack", input: { keep: ["music", "effects"] } });+ expect(soundPlan("split the soundtrack into stems", a)).toMatchObject({ tool: "split_soundtrack", input: { media: "/api/files/a.wav" } });+ expect(soundPlan("remove the dialogue", [])).toBeNull();+ expect(soundPlan("make it cinematic", v)).toBeNull();+ });+ it("leaves a voice repair to Clean up voice and another studio's job to that studio", () => {+ for (const words of [+ "remove the background noise from the speech",+ "reduce the background noise in this voice recording",+ "get rid of the echo on the voice",+ "clean up the dialogue",+ "transcribe just the speech",+ "dub this video into spanish and keep the music",+ "restyle this as anime, keep the music",+ "cut this video down to 10 seconds and keep the speech",+ "add captions but only the dialogue",+ ])+ expect(soundPlan(words, v), words).toBeNull();+ expect(offlinePlan("Dub this video into Spanish and keep the music\n\nAttached files:\n- video 1: /api/files/v.mp4", "open")?.tool).not.toMatch(/split_soundtrack|remove_dialogue/);+ expect(offlinePlan("Transcribe just the speech\n\nAttached files:\n- video 1: /api/files/v.mp4", "open")?.tool).not.toMatch(/split_soundtrack|remove_dialogue/);+ });+ it("is what offlinePlan answers for an attached clip", () => {+ expect(offlinePlan("Remove the dialogue from this video\n\nAttached files:\n- video 1: /api/files/v.mp4", "open")).toMatchObject({ tool: "remove_dialogue" });+ // Without a clip, music is still a music track.+ expect(offlinePlan("just the music for a cafe", "open")!.tool).toBe("generate");+ });+});diff --git a/tests/split-soundtrack.test.ts b/tests/split-soundtrack.test.tsindex 2c0ea10d..93f56b0c 100644--- a/tests/split-soundtrack.test.ts+++ b/tests/split-soundtrack.test.ts@@ -237,7 +237,7 @@ describe("planSplit", () => {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(CLOUD_SPLIT_PROBLEM).toMatch(/works with open-source models/);expect(() => planSplit({ engine: "open", media: "", kind: "video" })).toThrow("Add the video to split");});diff --git a/tests/voice-first.test.ts b/tests/voice-first.test.tsnew file mode 100644index 00000000..ffa64830--- /dev/null+++ b/tests/voice-first.test.ts@@ -0,0 +1,156 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import { planVoiceFirst, voiceFirstCost, voiceFirstDefault, voiceFirstSource, wantsVoiceFirst, VOICE_FIRST_PARAM } from "@/lib/av/voice-first";+import { transcribeRequest } from "@/lib/av/captions";+import { planTranscribe } from "@/lib/catalog/swap-studio-plan";+import type { GenerationRequest } from "@/lib/catalog/types";++// "Clean the voice first" (DBS D6): the speech apart from the music and effects before a transcriber or a lip sync hears+// it (DBS on your GPU, ElevenLabs voice isolation in the cloud), and after a lip re-sync on your GPU the music and effects+// of the same recording go back under it. The studio owner's until it has passed a real run.+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-voice-first-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_PUBLIC_SIGNUP;++const { setSetting } = await import("@/server/settings");+const { saveFile } = await import("@/server/storage");+const { createGenerations } = await import("@/server/generations");+const { transcribeClip } = await import("@/server/genjutsu");+const auth = await import("@/server/auth");+const route = await import("@/app/api/generations/route");+const { soundLive } = await import("@/server/sound-live");+beforeAll(() => setSetting("demoMode", "auto"));+afterEach(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+});+afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++const flag = { extra: { [VOICE_FIRST_PARAM]: true } };+const clipUrl = () => saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "talk.mp4" }).url;++describe("the plan", () => {+ it("a transcript of a video on your GPU: DBS on the video, its voice stem into Qwen3-ASR", () => {+ const r: GenerationRequest = { feature: "captions", modelId: "oss-qwen3-asr", op: "transcribe", inputs: { video: "/api/files/v.mp4" }, params: { sourceDuration: 12, sourceLanguage: "en", ...flag } };+ expect(wantsVoiceFirst(r)).toBe(true);+ const [voice, main, ...rest] = planVoiceFirst(r, "open");+ expect(rest).toEqual([]);+ expect(voice.request).toMatchObject({ modelId: "oss-dbs-separate", op: "separate-audio", inputs: { video: "/api/files/v.mp4" }, params: { sourceDuration: 12, extra: { channels: "mono" } } });+ expect(main).toMatchObject({ after: ["voice"], chain: [{ slot: "audio", stem: "voice" }], request: { modelId: "oss-qwen3-asr", op: "transcribe", params: { sourceLanguage: "en" } } });+ expect(main.request.inputs).toBeUndefined();+ expect(main.request.params?.extra).toBeUndefined();+ });++ it("in the cloud: ElevenLabs voice isolation before Scribe v2", () => {+ const r: GenerationRequest = { feature: "captions", modelId: "scribe-v2", op: "transcribe", inputs: { video: "/api/files/v.mp4" }, params: flag };+ const steps = planVoiceFirst(r, "cloud");+ expect(steps.map((s) => s.request.modelId)).toEqual(["elevenlabs-voice-isolation", "scribe-v2"]);+ expect(steps[1].chain).toEqual([{ slot: "audio" }]);+ });++ it("a lip sync on your GPU: the voice drives it, then the music and effects of the same recording go back under it", () => {+ const r: GenerationRequest = { feature: "lipsync", modelId: "oss-infinitetalk", op: "lipsync", inputs: { video: "/api/files/face.mp4", audio: "/api/files/line.wav" }, params: flag };+ const steps = planVoiceFirst(r, "open");+ expect(steps.map((s) => s.key)).toEqual(["voice", "main", "bed"]);+ expect(steps[0].request.inputs).toEqual({ audio: "/api/files/line.wav" });+ expect(steps[1].request.inputs).toEqual({ video: "/api/files/face.mp4" });+ expect(steps[2]).toMatchObject({+ after: ["main", "voice", "voice"],+ chain: [{ slot: "video" }, { slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }],+ request: { modelId: "oss-mux", op: "mux", params: { extra: { backgroundVolumeDb: 0 } } },+ });+ // The cloud has no bed to put back (DBS isn't hosted).+ expect(planVoiceFirst({ ...r, modelId: "sync-lipsync-3" }, "cloud").map((s) => s.key)).toEqual(["voice", "main"]);+ });++ it("knows its source, its defaults and its cost line, and refuses what it can't clean", () => {+ expect(voiceFirstSource({ op: "transcribe", inputs: { audio: "/a.wav", video: "/v.mp4" } })).toEqual({ slot: "audio", url: "/a.wav" });+ expect(voiceFirstSource({ op: "avatar", inputs: { images: ["/p.png"] } })).toBeNull();+ // Off until the chain has passed a real run; then on for a video's speech.+ expect(voiceFirstDefault("video", false)).toBe(false);+ expect(voiceFirstDefault("video", true)).toBe(true);+ expect(voiceFirstDefault("audio", true)).toBe(false);+ expect(voiceFirstCost("cloud", 120)).toBe("adds $0.20");+ expect(voiceFirstCost("open", 30)).toMatch(/^adds (under a minute|about \d)/);+ expect(() => planVoiceFirst({ feature: "x", modelId: "oss-chatterbox", op: "tts", params: flag }, "open")).toThrow(/transcripts, captions and lip sync/);+ expect(wantsVoiceFirst({ op: "tts", params: flag })).toBe(false);+ });++ it("is asked for by Captions, Character Swap Studio and Genjutsu", () => {+ expect(transcribeRequest({ engine: "open", video: "/v.mp4", cleanVoiceFirst: true, seconds: 9 }).params).toEqual({ sourceDuration: 9, extra: { cleanVoiceFirst: true } });+ expect(transcribeRequest({ engine: "open", video: "/v.mp4" }).params).toBeUndefined();+ const clip = { id: "c", name: "Talk", source: { url: "/api/files/v.mp4", duration: 6, hasAudio: true } } as never;+ expect(planTranscribe(clip, "open", { cleanVoiceFirst: true })[0].request.params?.extra).toEqual({ cleanVoiceFirst: true });+ expect(planTranscribe(clip, "open")[0].request.params?.extra).toBeUndefined();+ });+});++describe("runs (demo mode)", () => {+ it("one batch, the transcript first: what Captions watches", () => {+ const made = createGenerations(transcribeRequest({ engine: "open", video: clipUrl(), cleanVoiceFirst: true, seconds: 12 }));+ expect(made.map((g) => [g.modelId, g.op])).toEqual([+ ["oss-qwen3-asr", "transcribe"],+ ["oss-dbs-separate", "separate-audio"],+ ]);+ expect(made[0].request.chain).toEqual([{ slot: "audio", stem: "voice" }]);+ expect(made[0].batchId).toBe(made[1].batchId);+ });++ it("joins the caller's batch when it has one", () => {+ const made = createGenerations(transcribeRequest({ engine: "open", video: clipUrl(), cleanVoiceFirst: true, seconds: 12 }), { batchId: "studio-batch" });+ expect(made.map((g) => g.batchId)).toEqual(["studio-batch", "studio-batch"]);+ });++ it("a lip sync on your GPU ends with the mux, which comes first", () => {+ const audio = saveFile({ data: Buffer.from("RIFF0000WAVEfmt "), contentType: "audio/wav", source: "upload", name: "line.wav" }).url;+ const made = createGenerations({ feature: "lipsync", modelId: "oss-infinitetalk", op: "avatar", inputs: { images: ["/api/files/placeholder.png"], audio }, params: flag });+ expect(made.map((g) => g.op)).toEqual(["mux", "separate-audio", "avatar"]);+ });++ it("Genjutsu's What's said takes it", () => {+ const { id } = transcribeClip({ engine: "open", source: { url: clipUrl(), duration: 12 }, cleanVoiceFirst: true });+ expect(id).toBeTruthy();+ });+});++describe("public sign-up: the studio owner's until it has passed a real run", () => {+ it("starts closed in this repository, and opens only with a validated graph and a passed run", () => {+ expect(soundLive()).toEqual({ "clean-voice-first": false, "original-sound": false });+ const d = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-sound-live-"));+ const files = (validated: boolean, passed: boolean) => {+ fs.writeFileSync(path.join(d, "m.json"), JSON.stringify({ workflows: [{ id: "separate-soundtrack-dbs", validated }] }));+ fs.writeFileSync(path.join(d, "r.json"), JSON.stringify({ features: { "clean-voice-first": { passed } } }));+ return [path.join(d, "m.json"), path.join(d, "r.json")] as const;+ };+ expect(soundLive(...files(true, true))["clean-voice-first"]).toBe(true);+ expect(soundLive(...files(false, true))["clean-voice-first"]).toBe(false);+ expect(soundLive(...files(true, false))["clean-voice-first"]).toBe(false);+ expect(soundLive(path.join(d, "none.json"), path.join(d, "none.json"))["clean-voice-first"]).toBe(false);+ });++ const call = (body: unknown, cookie?: string, preview = false) =>+ route.POST(+ new NextRequest(`http://localhost:3000/api/generations${preview ? "?preview=1" : ""}`, {+ method: "POST",+ headers: { "Content-Type": "application/json", ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) },+ body: JSON.stringify(body),+ }),+ );+ it("refuses it to an account in words", async () => {+ auth.setPassword("install password");+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ const cookie = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+ const asked = transcribeRequest({ engine: "open", video: "/api/files/uploads/none.mp4", cleanVoiceFirst: true });+ const r = await call(asked, cookie);+ expect(r.status).toBe(403);+ expect(await r.json()).toMatchObject({ code: "own-gpu-tool" });+ });+});