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
Original sound: choice of what goes back in the studios (work in progress)
Claude0e18c80c4c90
diff --git a/src/app/api/shorts/sessions/[id]/stitch/route.ts b/src/app/api/shorts/sessions/[id]/stitch/route.tsindex e50cb4ef..fab84afa 100644--- a/src/app/api/shorts/sessions/[id]/stitch/route.ts+++ b/src/app/api/shorts/sessions/[id]/stitch/route.ts@@ -1,11 +1,11 @@import { stitchSession } from "@/server/shorts";-import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";+import { StitchSchema, handle, once, optionalBody } from "@/server/shorts-schemas";/** Stitch again: join the chosen takes and put the original sound back (a repeated requestId gets the first answer). */export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) {return handle(async () => {const { id } = await ctx.params;- const { requestId } = await optionalBody(request, NonceSchema);- return Response.json(await once(`shorts-stitch:${id}`, requestId, () => stitchSession(id)), { status: 201 });+ const { requestId, sound } = await optionalBody(request, StitchSchema);+ return Response.json(await once(`shorts-stitch:${id}`, requestId, () => stitchSession(id, sound)), { status: 201 });}, request);}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..c2bca713 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,14 @@import { z } from "zod";-import { body, handle } from "@/server/shorts-schemas";+import { body, handle, SoundChoiceSchema } from "@/server/shorts-schemas";import { assemble } from "@/server/swap-studio";-const Assemble = z.object({ clipId: z.string().min(1).max(80) });+const Assemble = z.object({ clipId: z.string().min(1).max(80), sound: SoundChoiceSchema.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, b.sound), { status: 201 });}, request);}diff --git a/src/components/faceless/settings-form.tsx b/src/components/faceless/settings-form.tsxindex 451c7dd7..fd35093b 100644--- a/src/components/faceless/settings-form.tsx+++ b/src/components/faceless/settings-form.tsx@@ -4,7 +4,7 @@ import { AtSign, ChevronDown, Film, Images, Plus, X } from "lucide-react";import Link from "next/link";import { useEffect, useState } from "react";import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";-import { fileToList, SlotPreview, type SlotValue } from "@/components/studio/media-slot";+import { fileToList, MediaSlot, SlotPreview, type SlotValue } from "@/components/studio/media-slot";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { useElements, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";@@ -14,7 +14,10 @@ import {ENGINE_MODELS,FACELESS_LENGTHS,MAX_STYLE_REFS,+ MUSIC_CLIP_HINT,+ MUSIC_CLIP_MIN_SECONDS,MUSIC_HINT,+ type MusicClip,type EpisodeSettings,type PickerData,} from "@/lib/catalog/faceless";@@ -109,6 +112,72 @@ export function ElementsPicker({ value, onChange }: { value: string[]; onChange:);}+/** Reads a clip's length in the browser (the bed's loop needs it); null when it can't be read. */+function clipSeconds(url: string): Promise<number | null> {+ return new Promise((resolve) => {+ const v = document.createElement("video");+ v.preload = "metadata";+ v.muted = true;+ const done = (n: number | null) => {+ v.removeAttribute("src");+ v.load();+ resolve(n);+ };+ v.onloadedmetadata = () => done(Number.isFinite(v.duration) && v.duration > 0 ? v.duration : null);+ v.onerror = () => done(null);+ v.src = url;+ });+}++/**+ * "Use a clip's soundtrack as the bed": its music and sound effects (the talking taken out on your GPU) looped under+ * the voice instead of a generated bed. The cloud says it runs on your GPU and makes its own bed.+ */+function MusicClipPicker({ engine, value, onChange }: { engine: Engine; value?: MusicClip; onChange: (v: MusicClip | undefined) => void }) {+ const [slot, setSlot] = useState<SlotValue | null>(() => (value ? { ref: value.url, preview: value.url, kind: "video", name: value.name } : null));+ const [problem, setProblem] = useState<string | null>(null);+ const ref = slot && !slot.uploading ? slot.ref : null;+ useEffect(() => {+ if (!ref || ref === value?.url) return;+ let live = true;+ void clipSeconds(ref).then((n) => {+ if (!live) return;+ if (n === null) return setProblem("Couldn't read this clip's length — try an MP4");+ if (n < MUSIC_CLIP_MIN_SECONDS) return setProblem(`Pick a clip of ${MUSIC_CLIP_MIN_SECONDS} s or more`);+ setProblem(null);+ onChange({ url: ref, ...(slot?.name ? { name: slot.name } : {}), duration: Math.round(n * 1000) / 1000 });+ });+ return () => {+ live = false;+ };+ // Only when the uploaded clip changes; `value` follows it.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ref]);+ const open = engine === "open";+ return (+ <div className="flex min-w-0 items-start gap-3 rounded-xl border p-3" data-testid="music-clip">+ {open && (+ <MediaSlot+ label="Clip for the music bed"+ kind="video"+ value={slot}+ onChange={(v) => {+ setSlot(v);+ setProblem(null);+ if (!v) onChange(undefined);+ }}+ />+ )}+ <div className="min-w-0 flex-1">+ <span className="block text-[13px] font-medium">Use a clip's soundtrack as the bed</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{MUSIC_CLIP_HINT[engine]}</span>+ {open && value && !problem && <span className="mt-1 block truncate text-[12px] text-muted-foreground">{value.name ?? "Your clip"} · {Math.round(value.duration)} s{value.duration < 60 ? " · loops with a soft crossfade" : ""}</span>}+ {open && problem && <span className="mt-1 block text-[12px] text-warning">{problem}</span>}+ </div>+ </div>+ );+}+/*** Video settings for an episode (Faceless) or an explainer: length, animation, format, style (or style* references), narrator, the characters to use, and the video model and quality.@@ -195,6 +264,7 @@ export function EpisodeSettingsForm({<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 })} /></div>+ {value.music && <MusicClipPicker engine={value.engine} value={value.musicClip} onChange={(musicClip) => onChange({ musicClip })} />}</Section><Section title="Style" hint="Choose either a style preset or your own style references.">diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 7ef2bfbf..689443ba 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -62,6 +62,8 @@ import { refusalShown, toastError } from "@/lib/refusals";import { CharacterControls, CharacterFacts } from "./character-panel";import { useDescribeCharacter, useGenjutsuEstimate, useGenjutsuRun, useTranscribeClip, waitForGeneration, type GenjutsuBody } from "./hooks";import { LookPicker, type LookSource } from "./look-picker";+import { OriginalSoundField, soundBody } from "@/components/studio/original-sound-field";+import { defaultSound, type SoundChoice } from "@/lib/av/original-sound";import { SetupCode } from "./setup-code";import { useClipCuts } from "./use-cuts";@@ -110,6 +112,7 @@ export function GenjutsuStudio() {const clip = source.clip;const trimmer = useRef<VideoTrimmerHandle>(null);const [range, setRange] = useState<TrimRange | null>(null);+ const [soundPick, setSoundPick] = useState<SoundChoice | null>(null);const [refs, setRefs] = useState<SlotValue[]>([]);const [targets, setTargets] = useState<Partial<Record<GenjutsuMode, GenjutsuTarget>>>({});const [subject, setSubject] = useState("");@@ -410,6 +413,9 @@ export function GenjutsuStudio() {...(isCharacter ? { seed: seedNumber, character } : {}),}): null;+ // Original sound: a character swap suggests Music & effects only (the new person's speech isn't theirs); a pick stays.+ const soundSuggested = defaultSound(engine, { personReplaced: isCharacter });+ const sound: SoundChoice = soundPick ?? { sound: soundSuggested };const body: GenjutsuBody | null =uploaded && maker && !problem && !refs.some((r) => r.uploading) && !custom.some((r) => r.uploading)? {@@ -429,6 +435,7 @@ export function GenjutsuStudio() {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 },...(isCharacter ? { character, ...(seedNumber !== undefined ? { seed: seedNumber } : {}), ...(cuts?.length ? { cuts } : {}) } : {}),+ ...soundBody(engine, sound),}: null;const estimate = useGenjutsuEstimate(body);@@ -740,6 +747,8 @@ export function GenjutsuStudio() {</Field>)}+ {clip && <OriginalSoundField engine={engine} value={sound} onChange={setSoundPick} hasAudio={clip.info?.hasAudio} suggested={soundSuggested} />}+<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 384c4fad..93eee533 100644--- a/src/components/genjutsu/hooks.ts+++ b/src/components/genjutsu/hooks.ts@@ -6,6 +6,7 @@ import type { GenjutsuLook, GenjutsuMode, GenjutsuTarget, GenjutsuTier, MakerSouimport type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";import { useDebounced } from "@/components/faceless/hooks";import { send } from "@/components/shorts/hooks";+import type { SoundChoice } from "@/lib/av/original-sound";/** React Query hooks for /api/genjutsu/**. */@@ -30,6 +31,8 @@ export interface GenjutsuBody {character?: CharacterOptions;/** Hard cuts the browser found in the clip (seconds): the server warns when the part has one. */cuts?: number[];+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.tsindex 19caa897..d85b6a1a 100644--- a/src/components/mixed-media/hooks.ts+++ b/src/components/mixed-media/hooks.ts@@ -3,6 +3,7 @@import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";import { useDeferredValue } from "react";import type { MixedMode, MixedResolution, MixedValues } from "@/lib/catalog/mixed-media";+import type { SoundChoice } from "@/lib/av/original-sound";import type { Engine, Generation } from "@/lib/catalog/types";import { useGenerationEvents } from "@/lib/api";import { send } from "@/components/shorts/hooks";@@ -22,6 +23,8 @@ export interface MixedBody {mode?: MixedMode;anchor?: string;frameUrl?: string;+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;/** 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 232cf873..162a6f69 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -7,6 +7,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@import { SidebarTrigger } from "@/components/ui/sidebar";import { SelfHostNote } from "@/components/self-host-note";import { EngineSwitch } from "@/components/studio/engine-switch";+import { OriginalSoundField, soundBody } from "@/components/studio/original-sound-field";+import type { SoundChoice } from "@/lib/av/original-sound";import { MediaThumb } from "@/components/studio/result-media";import { VideoTrimmer, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";import { LookCard } from "@/components/shorts/preset-card";@@ -318,6 +320,7 @@ function Editor({const [fpsChoice, setFpsChoice] = useState<FpsChoice>(MIXED.defaultFps as number);const [manual, setManual] = useState<number>(MIXED.defaultFps);const [resolution, setResolution] = useState<MixedResolution>("1K");+ const [sound, setSound] = useState<SoundChoice>({ sound: "everything" });// Frame by frame (the default, priced per frame), Smooth (the first frame, then carried through by depth) or, on the// cloud, Fast (one video-to-video pass). A mode the engine hasn't (Fast on your GPU) reads as Per frame.const [picked, setMode] = useState<MixedMode>("frames");@@ -403,6 +406,7 @@ function Editor({modelId,mode,...(anchor ? { anchor } : {}),+ ...soundBody(engine, sound),}: null;const estimate = useMixedEstimate(body);@@ -573,6 +577,8 @@ function Editor({</Field>)}+ <OriginalSoundField engine={engine} value={sound} onChange={setSound} hasAudio={clip?.info?.hasAudio} />+{preset && <AdvancedSettings preset={preset} values={values} onChange={setValues} />}<Fielddiff --git a/src/components/remove-object/hooks.ts b/src/components/remove-object/hooks.tsindex f0aa1e30..3f325809 100644--- a/src/components/remove-object/hooks.ts+++ b/src/components/remove-object/hooks.ts@@ -5,6 +5,7 @@ import type { RemoveMode } from "@/lib/catalog/remove-object";import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";import { useDebounced } from "@/components/faceless/hooks";import { send } from "@/components/shorts/hooks";+import type { SoundChoice } from "@/lib/av/original-sound";/** React Query hooks for /api/remove-object/** (the Remove object tab of Video tools). */@@ -19,6 +20,8 @@ export interface RemovalBody {mask?: string;source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };range?: { start: number; end: number };+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;/** 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 ca5d2932..c8de0283 100644--- a/src/components/remove-object/remove-object-tool.tsx+++ b/src/components/remove-object/remove-object-tool.tsx@@ -35,6 +35,8 @@ import { downloadHref, downloadName } from "@/lib/library";import { keepOffered, offered } from "@/lib/model-access";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { OriginalSoundField, soundBody } from "@/components/studio/original-sound-field";+import { defaultSound, type SoundChoice } from "@/lib/av/original-sound";import { FrameStage, frameFromBlob, type Frame } from "./frame-stage";import { useRemovalActions, useRemovalEstimate, type RemovalBody } from "./hooks";import { VideoCompare } from "./video-compare";@@ -84,6 +86,7 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {const [mode, setMode] = useState<RemoveMode>("type");const [prompt, setPrompt] = useState("");const [effects, setEffects] = useState(false);+ const [soundPick, setSoundPick] = useState<SoundChoice | null>(null);const [picked, setPicked] = useState<Record<string, string>>({});const [points, setPoints] = useState<PixelPoint[]>([]);const [pointLabel, setPointLabel] = useState<"positive" | "negative">("positive");@@ -171,6 +174,9 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {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;+ // Original sound: a person removed suggests Music & effects only (their speech goes too); a pick of your own stays.+ const soundSuggested = defaultSound(engine, { personReplaced: !!eraser?.cleanFrame });+ const sound: SoundChoice = soundPick ?? { sound: soundSuggested };const body: RemovalBody | null =ready && eraser && marked? {@@ -184,6 +190,7 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {...(mode !== "type" && frame ? { frame: { width: frame.width, height: frame.height } } : {}),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 },+ ...soundBody(engine, sound),}: null;const estimate = useRemovalEstimate(body);@@ -442,6 +449,8 @@ export function RemoveObjectTool({ tabs }: { tabs?: React.ReactNode }) {</p>)}+ {clip && <OriginalSoundField engine={engine} value={sound} onChange={setSoundPick} hasAudio={clip.info?.hasAudio} suggested={soundSuggested} />}+<div className="space-y-3 border-t pt-3">{body && est?.previewUsd != null && (<div className="flex items-center gap-2">diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.tsindex 5d40cedf..88ddd924 100644--- a/src/components/shorts/hooks.ts+++ b/src/components/shorts/hooks.ts@@ -5,6 +5,7 @@ import { nanoid } from "nanoid";import { useCallback, useDeferredValue, useRef } from "react";import type { ShortsCustomPreset, ShortsRange, ShortsRatio, ShortsSession } from "@/lib/catalog/shorts";import type { Engine, Generation } from "@/lib/catalog/types";+import type { SoundChoice } from "@/lib/av/original-sound";import { useGenerationEvents } from "@/lib/api";import { responseError } from "@/lib/refusals";@@ -29,6 +30,8 @@ export interface ShortsBody {aspectRatio: ShortsRatio;language: string;modelId?: string;+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;/** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */requestId?: string;}diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex 36343143..742caa9e 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -22,6 +22,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { MediaThumb } from "@/components/studio/result-media";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { Viewer } from "@/components/studio/viewer";+import { soundSummary } from "@/lib/av/original-sound";import { chainState, formatSeconds, stitchCurrent, stitchSteps, takeSteps, type ChainState, type ShortsSessionSegment } from "@/lib/catalog/shorts";import type { Generation } from "@/lib/catalog/types";import { formatCost, ratioValue, timeAgo } from "@/lib/format";@@ -204,6 +205,12 @@ function Session({ s }: { s: View }) {<dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 rounded-xl bg-muted/50 p-3 text-[12px]"><dt className="text-muted-foreground">Preset</dt><dd className="truncate">{s.look.name}</dd>+ {s.source.hasAudio && (+ <>+ <dt className="text-muted-foreground">Sound</dt>+ <dd className="truncate">{soundSummary(s.settings.sound)}</dd>+ </>+ )}<dt className="text-muted-foreground">Engine</dt><dd className="flex items-center gap-1">{s.engine === "open" ? <Cpu className="size-3" /> : <Cloud className="size-3" />}diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex ea2e2122..63491b7c 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -9,6 +9,8 @@ import { SidebarTrigger } from "@/components/ui/sidebar";import { OldFootageOffer } from "@/components/restore/old-footage";import { SelfHostNote } from "@/components/self-host-note";import { EngineSwitch } from "@/components/studio/engine-switch";+import { OriginalSoundField, soundBody } from "@/components/studio/original-sound-field";+import type { SoundChoice } from "@/lib/av/original-sound";import { VideoTrimmer } from "@/components/studio/video-trimmer";import { useEngine, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";import {@@ -334,6 +336,7 @@ function SetupPanel({const { clip } = source;const [ratio, setRatio] = useState<ShortsRatio>("9:16");const [language, setLanguage] = useState("auto");+ const [sound, setSound] = useState<SoundChoice>({ sound: "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.@@ -367,6 +370,7 @@ function SetupPanel({aspectRatio: ratio,language,modelId,+ ...soundBody(engine, sound),}: null;const estimate = useShortsEstimate(estimateBody);@@ -490,6 +494,8 @@ function SetupPanel({</Select></Field>+ <OriginalSoundField engine={engine} value={sound} onChange={setSound} hasAudio={clip?.info?.hasAudio} />+<Field label="Model" hint={engine === "open" ? <span className="inline-flex items-center gap-1"><Cpu className="size-3" /> Open source</span> : <span className="inline-flex items-center gap-1"><Cloud className="size-3" /> Cloud</span>}>{models.length > 1 ? (<Select value={modelId} onValueChange={(v) => setModel((m) => ({ ...m, [engine]: v }))}>diff --git a/src/components/studio/original-sound-field.tsx b/src/components/studio/original-sound-field.tsxnew file mode 100644index 00000000..9e5e660a--- /dev/null+++ b/src/components/studio/original-sound-field.tsx@@ -0,0 +1,121 @@+"use client";++import { Cloud, Cpu } from "lucide-react";+import { useId } from "react";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Slider } from "@/components/ui/slider";+import {+ CLOUD_SOUND_NOTE,+ ORIGINAL_SOUNDS,+ originalSoundLabel,+ soundOf,+ SOUND_LOWER_DEFAULT_DB,+ SOUND_LOWER_MAX_DB,+ SOUND_LOWER_MIN_DB,+ type OriginalSound,+ type SoundChoice,+} from "@/lib/av/original-sound";+import type { Engine } from "@/lib/catalog/types";++/**+ * "Original sound" (src/lib/av/original-sound.ts): what of a clip's sound a studio puts back under its result.+ * Everything on both engines; Music & effects only, Dialogue only and Lower the music on your GPU (the cloud lists them+ * turned off, with the reason). `suggested` marks the studio's own suggestion (a person replaced: Music & effects only).+ */+export function OriginalSoundField({+ engine,+ value,+ onChange,+ hasAudio,+ suggested,+ disabled,+ label = "Original sound",+}: {+ engine: Engine;+ value: SoundChoice;+ onChange: (v: SoundChoice) => void;+ /** False: the clip has no sound (the field says so and stays off). */+ hasAudio?: boolean;+ suggested?: OriginalSound;+ disabled?: boolean;+ label?: string;+}) {+ const id = useId();+ const cloud = engine === "cloud";+ // The cloud puts back everything: a choice made on your GPU shows as Everything there (and is kept for the switch back).+ const shown: OriginalSound = cloud ? "everything" : soundOf(value);+ const musicDb = value.musicDb ?? SOUND_LOWER_DEFAULT_DB;+ const silent = hasAudio === false;+ const hint = ORIGINAL_SOUNDS.find((o) => o.id === shown)?.hint;+ return (+ <div className="min-w-0 space-y-1.5" data-testid="original-sound">+ <div className="flex items-baseline justify-between gap-2">+ <label htmlFor={`${id}-sound`} className="text-[13px] font-medium">+ {label}+ </label>+ <span className="inline-flex min-w-0 items-center gap-1 truncate text-[12px] text-muted-foreground">+ {cloud ? <Cloud className="size-3 shrink-0" /> : <Cpu className="size-3 shrink-0" />}+ {cloud ? "Everything in the cloud" : "Free on your GPU"}+ </span>+ </div>+ <Select+ value={shown}+ onValueChange={(v) => onChange({ ...value, sound: v as OriginalSound, ...(v === "lower-music" && value.musicDb === undefined ? { musicDb: SOUND_LOWER_DEFAULT_DB } : {}) })}+ disabled={disabled || silent}+ >+ <SelectTrigger id={`${id}-sound`} className="w-full" aria-label={label}>+ <SelectValue>{originalSoundLabel(shown)}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {ORIGINAL_SOUNDS.map((o) => (+ <SelectItem key={o.id} value={o.id} disabled={cloud && o.id !== "everything"}>+ <span className="flex min-w-0 flex-col">+ <span className="truncate">+ {o.label}+ {suggested === o.id && o.id !== "everything" && !cloud && <span className="ml-1.5 rounded bg-brand-faint px-1 text-[10px] text-brand-text">suggested</span>}+ </span>+ <span className="truncate text-[11px] text-muted-foreground">{cloud && o.id !== "everything" ? "On your GPU (open source)" : o.hint}</span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {silent ? (+ <p className="text-[12px] leading-snug text-muted-foreground">This clip has no sound to put back.</p>+ ) : cloud ? (+ <p className="text-[12px] leading-snug text-muted-foreground">{CLOUD_SOUND_NOTE}</p>+ ) : shown === "lower-music" ? (+ <div className="flex min-w-0 items-center gap-3 pt-1">+ <label htmlFor={`${id}-db`} className="shrink-0 text-[12px] text-muted-foreground">+ Music & effects+ </label>+ <Slider+ id={`${id}-db`}+ min={SOUND_LOWER_MIN_DB}+ max={SOUND_LOWER_MAX_DB}+ step={1}+ value={[musicDb]}+ onValueChange={([v]) => onChange({ ...value, sound: "lower-music", musicDb: v })}+ aria-label="Music and effects level"+ aria-valuetext={`${musicDb} dB`}+ disabled={disabled}+ className="min-w-0 flex-1"+ />+ <span className="w-14 shrink-0 text-right font-mono text-[12px] tabular-nums">{musicDb === 0 ? "0 dB" : `−${Math.abs(musicDb)} dB`}</span>+ </div>+ ) : (+ <p className="text-[12px] leading-snug text-muted-foreground">+ {hint}+ {shown !== "everything" ? ". The clip's sound is split into dialogue, music and effects first." : "."}+ </p>+ )}+ </div>+ );+}++/** What the run asks the server for: nothing for Everything (the studios' default), the choice otherwise. */+export function soundBody(engine: Engine, v: SoundChoice): { sound?: SoundChoice } {+ const s = soundOf(v);+ if (engine === "cloud" || s === "everything") return {};+ return { sound: s === "lower-music" ? { sound: s, musicDb: v.musicDb ?? SOUND_LOWER_DEFAULT_DB } : { sound: s } };+}diff --git a/src/components/swap-studio/hooks.ts b/src/components/swap-studio/hooks.tsindex 4e65c4fa..10962367 100644--- a/src/components/swap-studio/hooks.ts+++ b/src/components/swap-studio/hooks.ts@@ -5,6 +5,7 @@ import { studioHandOff, type HandOffInput, type QueueMode, type StudioEstimate,import type { SwapEdit } from "@/lib/catalog/swap-studio-edit";import type { Engine, PixelPoint } from "@/lib/catalog/types";import { responseError } from "@/lib/refusals";+import type { SoundChoice } from "@/lib/av/original-sound";/** React Query hooks for /api/swap-studio/** (Character Swap Studio). */@@ -125,7 +126,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"; 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; sound?: SoundChoice }>(id, "assemble");/*** Genjutsu's "Open in Character Swap Studio": a new project with the character, and the clip added (the clip'sdiff --git a/src/components/swap-studio/stage-review.tsx b/src/components/swap-studio/stage-review.tsxindex 3d99ed3e..f7cd77d2 100644--- a/src/components/swap-studio/stage-review.tsx+++ b/src/components/swap-studio/stage-review.tsx@@ -15,6 +15,8 @@ import { downloadHref } from "@/lib/library";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { decisionsHref, useAssemble, useStopJob } from "./hooks";+import { OriginalSoundField, soundBody } from "@/components/studio/original-sound-field";+import { defaultSound, sameSound, type SoundChoice } from "@/lib/av/original-sound";import { GenChip, JobError, Note, priceText, SavedText } from "./parts";import type { StageProps } from "./workbench";@@ -180,7 +182,12 @@ 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));+ // Original sound: the person is replaced, so their speech usually goes too (Music & effects only on your GPU).+ const suggested = defaultSound(project.engine, { personReplaced: true });+ const [soundPick, setSoundPick] = useState<SoundChoice | null>(null);+ const sound: SoundChoice = soundPick ?? a?.sound ?? { sound: a ? "everything" : suggested };+ const asked = soundBody(project.engine, sound).sound;+ const current = "pieces" in found && !!a && JSON.stringify(a.takes) === JSON.stringify(assemblyTakes(found.pieces)) && sameSound(a.sound, asked);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>}>@@ -203,6 +210,7 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)</ol></>)}+ {clip.source.hasAudio && <OriginalSoundField engine={project.engine} value={sound} onChange={setSoundPick} suggested={suggested} />}<p className="text-[12px] text-muted-foreground">{project.engine === "open"? "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."@@ -212,7 +220,7 @@ export function AssembleStage({ id, project, clip, gens, estimate }: StageProps)<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, ...(asked && { sound: asked }) }, { 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>@@ -222,7 +230,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">{sameSound(a.sound, asked) ? "The chosen takes changed since — assemble again for the new ones." : "The sound choice changed — assemble again to hear it."}</span>}</div><JobError genId={a?.genId} stepIds={a?.stepIds} gens={gens} />{result && (diff --git a/src/lib/av/original-sound.ts b/src/lib/av/original-sound.tsnew file mode 100644index 00000000..f841c70a--- /dev/null+++ b/src/lib/av/original-sound.ts@@ -0,0 +1,134 @@+import type { ChainSlot, Engine, GenerationRequest } from "@/lib/catalog/types";+import type { PlanStep } from "@/lib/catalog/shorts";+import { clampLowerDb, LOWER_DEFAULT_DB, LOWER_MAX_DB, LOWER_MIN_DB, muxChain, type DialogueOutcome } from "./remove-dialogue";+import { dbsChannelsFor, SPLIT_MODEL } from "./split";++/**+ * "Original sound" (DBS D7, docs/research/dbs-separation-7.md §8 and §9 D7): when a studio puts a clip's own sound back+ * under its result (Shorts, Mixed Media, Genjutsu, Remove object, Character Swap Studio), the user picks what goes+ * back: Everything (as before), Music & effects only, Dialogue only, or the dialogue with the music lowered. Pure: the+ * studios' planners and pages share it.+ *+ * - Open engine: graph A (separate-soundtrack-dbs on oss-dbs-separate) splits the working clip's soundtrack (the+ * trimmed source, not the result), then the studio's own stream-copy mux (oss-mux) takes the chosen stem: background+ * or voice (video-mux-audio-replace), or the voice over the background at a lower level (video-mux-audio). No new graph.+ * - Cloud: Everything only. DBS is hosted nowhere and SAM Audio in its place is the owner's call, not taken+ * (docs/handoff/owner-decisions.json samAudioCloud: false), so the other choices say they run on your GPU.+ */++export type OriginalSound = "everything" | DialogueOutcome;++export const ORIGINAL_SOUNDS: { id: OriginalSound; label: string; hint: string }[] = [+ { id: "everything", label: "Everything", hint: "The clip's sound as it was" },+ { id: "no-dialogue", label: "Music & effects only", hint: "The talking taken out" },+ { id: "dialogue-only", label: "Dialogue only", hint: "Just the talking" },+ { id: "lower-music", label: "Lower the music", hint: "The talking, with the music and effects quieter" },+];+export const originalSoundLabel = (id: OriginalSound): string => ORIGINAL_SOUNDS.find((o) => o.id === id)?.label ?? "Everything";+export const isOriginalSound = (v: unknown): v is OriginalSound => ORIGINAL_SOUNDS.some((o) => o.id === v);++export { LOWER_DEFAULT_DB as SOUND_LOWER_DEFAULT_DB, LOWER_MAX_DB as SOUND_LOWER_MAX_DB, LOWER_MIN_DB as SOUND_LOWER_MIN_DB };++/** What a studio was asked to put back (stored with its run). */+export interface SoundChoice {+ sound?: OriginalSound;+ /** Lower the music: the music and effects' level (dB, −30…0). */+ musicDb?: number;+}++/** The choice to run on an engine: anything unknown is Everything. */+export const soundOf = (c?: SoundChoice | null): OriginalSound => (isOriginalSound(c?.sound) ? c!.sound! : "everything");++/** Whether two stored choices put back the same sound (unset is Everything). */+export function sameSound(a?: SoundChoice | null, b?: SoundChoice | null): boolean {+ const x = soundOf(a);+ if (x !== soundOf(b)) return false;+ return x !== "lower-music" || clampLowerDb(a?.musicDb) === clampLowerDb(b?.musicDb);+}++/** Whether the clip's sound is split before it goes back (the open engine, anything but Everything). */+export const separates = (engine: Engine, c?: SoundChoice | null): boolean => engine === "open" && soundOf(c) !== "everything";++/** What the cloud says about the choices it doesn't have (the studios' sound setting). */+export const CLOUD_SOUND_NOTE = "Music & effects only, Dialogue only and Lower the music run on your GPU (open source). The cloud puts the whole sound back.";++/** Why a run can't go as asked (in words the page shows), or null. */+export function originalSoundProblem(engine: Engine, c?: SoundChoice | null): string | null {+ const s = soundOf(c);+ if (engine === "cloud" && s !== "everything") return `${originalSoundLabel(s)} runs on your GPU (open source) — switch to the open engine, or put back Everything`;+ return null;+}++/**+ * The choice a studio starts with. Everything, except where the person on screen is replaced or removed (Character+ * Swap Studio, Remove object's person removal): their speech no longer belongs, so Music & effects only on your GPU.+ */+export function defaultSound(engine: Engine, o: { personReplaced?: boolean } = {}): OriginalSound {+ return engine === "open" && o.personReplaced ? "no-dialogue" : "everything";+}++/** One line for a run's summary: what goes back. */+export function soundSummary(c?: SoundChoice | null): string {+ const s = soundOf(c);+ if (s === "lower-music") return `Dialogue, with the music and effects ${Math.abs(clampLowerDb(c?.musicDb))} dB lower`;+ return originalSoundLabel(s);+}++/** The mux's sound: what it waits on (after/chain), the file it reads (inputs.audio) and its extra settings. */+export interface SoundBack {+ after: string[];+ chain: ChainSlot[];+ inputs?: { audio: string };+ extra?: Record<string, unknown>;+}++/**+ * The sound a studio's mux takes. `from` is the working clip: a file (the upload, the 24 fps copy) or an earlier+ * step's clip (the selection cut out). Everything: that clip as it is (the mux reads its soundtrack). Otherwise (open+ * engine) a split step on it is pushed, and the mux takes its stems. Throws what's in the way on the cloud.+ */+export function soundBack(+ steps: PlanStep[],+ o: { engine: Engine; choice?: SoundChoice | null; from: { url: string } | { key: string }; helper: Partial<GenerationRequest>; key?: string; channels?: number; seconds?: number; name?: string },+): SoundBack {+ const problem = originalSoundProblem(o.engine, o.choice);+ if (problem) throw new Error(problem);+ if (!separates(o.engine, o.choice)) return "url" in o.from ? { after: [], chain: [], inputs: { audio: o.from.url } } : { after: [o.from.key], chain: [{ slot: "audio" }] };+ const outcome = soundOf(o.choice) as DialogueOutcome;+ const key = o.key ?? "split";+ const extra: Record<string, unknown> = { channels: dbsChannelsFor("mono", o.channels) };+ if (o.channels && o.channels > 0) extra.sourceChannels = Math.round(o.channels);+ steps.push({+ key,+ request: {+ ...o.helper,+ modelId: SPLIT_MODEL,+ op: "separate-audio",+ title: `Stems · ${o.name?.trim() || "the clip's sound"}`,+ ...("url" in o.from ? { inputs: { video: o.from.url } } : {}),+ params: { extra, ...(o.seconds && o.seconds > 0 ? { sourceDuration: Math.round(o.seconds * 1000) / 1000 } : {}) },+ step: { label: "Dialogue, music, effects", index: 1150, of: 1000 },+ } as GenerationRequest,+ ...("key" in o.from ? { after: [o.from.key], chain: [{ slot: "video" as const }] } : {}),+ });+ const lower = outcome === "lower-music";+ return {+ after: lower ? [key, key] : [key],+ chain: muxChain(outcome),+ ...(lower && { extra: { backgroundVolumeDb: clampLowerDb(o.choice?.musicDb) } }),+ };+}++/** A mux request with its sound settings merged in (keeps the request's own params). */+export function withSoundExtra(request: GenerationRequest, back: SoundBack): GenerationRequest {+ if (!back.extra) return request;+ return { ...request, params: { ...request.params, extra: { ...request.params?.extra, ...back.extra } } };+}++/** Labels for the mux step: what goes back. */+export const SOUND_STEP_LABEL: Record<OriginalSound, string> = {+ everything: "Put the sound back",+ "no-dialogue": "Music and effects back",+ "dialogue-only": "Dialogue back",+ "lower-music": "Dialogue over the lowered music",+};diff --git a/src/lib/catalog/faceless.ts b/src/lib/catalog/faceless.tsindex aa582fbd..97215736 100644--- a/src/lib/catalog/faceless.ts+++ b/src/lib/catalog/faceless.ts@@ -3,6 +3,7 @@ import { COPY_JOIN_VIDEOS, lengthRange, plannedDurations } from "./clip-lengths"import { estimateCost } from "./plan";import { pricingAt } from "./promo";import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef } from "./types";+import { SPLIT_MODEL } from "../av/split";/** Faceless Studio and the Explainer: the data and the pure planning shared by the browser (wizard,@@ -413,8 +414,27 @@ export interface EpisodeSettings {auto?: boolean;/** Content Factory: a reference clip's style brief, applied to the script and the look. */brief?: BriefLook;+ /**+ * "Use a clip's soundtrack as the bed" (your GPU): the clip's music and effects, its dialogue taken out (DBS), looped+ * under the voice instead of a generated bed. duration: the clip's seconds (the loop reads it).+ */+ musicClip?: MusicClip;+}++export interface MusicClip {+ url: string;+ name?: string;+ duration: number;}+/** The shortest clip whose soundtrack can be a bed (the loop crossfades 3 s at each seam). */+export const MUSIC_CLIP_MIN_SECONDS = 8;+/** What a clip's soundtrack as the bed does, and that it runs on your GPU. */+export const MUSIC_CLIP_HINT: Record<Engine, string> = {+ open: "Its music and sound effects, with the talking taken out, looped under the voice",+ cloud: "Runs on your GPU (open source) — the cloud makes a new instrumental bed",+};+/*** How a style brief (src/lib/catalog/content-factory.ts) shapes an episode: lines for the script writer, words* added to every picture and motion prompt, the music's mood, the scene length the writer aims for, the captions.@@ -831,6 +851,8 @@ export interface ResolvedModels {resolution: string;narration: string;music: string | null;+ /** The bed is a clip's soundtrack split by DBS (its background stem), not a generated one (your GPU). */+ bedClip?: MusicClip;/** Extends the bed past what the music model makes. */loop: string | null;/** Brings the bed down under the voice before the mix (cloud). */@@ -867,7 +889,9 @@ export function resolveModels(settings: EpisodeSettings, narrationChars: number,video,resolution: wanted,narration,- music: settings.music ? m.music : null,+ // A clip's soundtrack as the bed: DBS on your GPU (no hosted DBS; the cloud makes its own bed).+ music: settings.music ? (settings.engine === "open" && settings.musicClip ? SPLIT_MODEL : m.music) : null,+ ...(settings.music && settings.engine === "open" && settings.musicClip && { bedClip: settings.musicClip }),loop: settings.music ? m.loop : null,level: settings.music ? (m.levelMusic ?? null) : null,mux: settings.music ? m.mixMusic : m.mux,@@ -1140,7 +1164,49 @@ export function buildEpisodeGraph(input: GraphInput, lookup: ModelLookup): Graph});let bedKey = "music";- if (models.music) {+ // The clip's split: its music and effects (the "background" stem) are the bed.+ let bedStem: string | undefined;+ if (models.music && models.bedClip) {+ const clip = models.bedClip;+ const clipSeconds = Math.max(1, clip.duration);+ bedStem = "background";+ steps.push({+ key: "music",+ part: "music",+ label: "Music bed · from your clip",+ seconds: clipSeconds,+ request: {+ ...base,+ modelId: models.music,+ op: "separate-audio",+ title: `Stems · ${clip.name?.trim() || "music bed"}`,+ inputs: { video: clip.url },+ params: { sourceDuration: Math.round(clipSeconds * 1000) / 1000, extra: { channels: "mono" } },+ step: { label: "Music bed", index: n, of: n },+ },+ });+ const loopDef = models.loop ? lookup(models.loop) : undefined;+ if (clipSeconds < length && loopDef) {+ const duration = Math.min(LOOP_MAX[loopDef.id] ?? Infinity, Math.ceil(length) + 1);+ steps.push({+ key: "music-loop",+ part: "music",+ label: "Music bed · looped",+ after: ["music"],+ chain: [{ slot: "audio", stem: bedStem }],+ seconds: duration,+ request: {+ ...base,+ modelId: models.loop!,+ op: "audio-loop",+ params: { duration, sourceDuration: Math.round(clipSeconds * 1000) / 1000, crossfade: BED_CROSSFADE },+ step: { label: "Music loop", index: n, of: n },+ },+ });+ bedKey = "music-loop";+ bedStem = undefined;+ }+ } else if (models.music) {const musicDef = pick(lookup, models.music);const plan = musicPlan(musicDef, models.loop ? lookup(models.loop) : undefined, length);const bed = plan.bed;@@ -1201,7 +1267,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,diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.tsindex 00ce0dae..f1de44e2 100644--- a/src/lib/catalog/genjutsu.ts+++ b/src/lib/catalog/genjutsu.ts@@ -60,6 +60,7 @@ import { getModel } from "./index";import { REPLACED_BY } from "./replaced";import { soulLook } from "./soul";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";+import { originalSoundProblem, separates, type SoundChoice } from "../av/original-sound";export type GenjutsuMode = "motion" | "character" | "swap" | "restyle" | "insert";/** How you say what changes (Object swap and Insert) or who (Character swap): words, clicks on the first frame, or paint on it. */@@ -994,6 +995,8 @@ export interface GenjutsuPlanInput {seed?: number;/** Character swap's settings. */character?: CharacterOptions;+ /** Original sound: what of the clip's sound goes back (src/lib/av/original-sound.ts; unset = Everything). */+ sound?: SoundChoice;}export interface GenjutsuPlan {@@ -1034,6 +1037,8 @@ function pinEngines(steps: PlanStep[], engine: Engine): PlanStep[] {* - then the pieces joined and the clip's own sound put back.*/export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {+ const soundProblem = originalSoundProblem(input.maker.engine, input.sound);+ if (soundProblem) throw new Error(soundProblem);const plan = planSteps(input);return { ...plan, steps: pinEngines(plan.steps, input.maker.engine) };}@@ -1052,7 +1057,8 @@ function planSteps(input: GenjutsuPlanInput): GenjutsuPlan {const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };const steps: PlanStep[] = [];const op = OP[input.mode];- const sound = !!input.source.hasAudio && (n > 1 || !m.keepsSound);+ // A maker that keeps the clip's sound still gets the chosen stems put back when the sound is split (Original sound).+ const sound = !!input.source.hasAudio && (n > 1 || !m.keepsSound || separates(m.engine, input.sound));const own = (one: boolean) => (one && !sound ? { ...base, title: input.title } : helper);const refs = input.references.slice(0, m.refs.max);const images = refs.length ? { images: refs } : {};@@ -1179,10 +1185,10 @@ function planSteps(input: GenjutsuPlanInput): GenjutsuPlan {});});const end = m.window ? pieces[n - 1].end : input.range.end;- const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: m.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound, end });+ const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: m.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound, end, choice: input.sound });return { steps, final, pieces: n, sound, tracked };}- const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: m.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound });+ const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: m.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound, choice: input.sound });return { steps, final, pieces: n, sound, tracked: false };}@@ -1276,6 +1282,13 @@ function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {},...(anchorOn ? { after: ["anchor"], chain: [anchorSlot()] } : {}),});+ // The graph keeps the clip's sound; Original sound other than Everything lays the chosen stems over it instead.+ if (input.source.hasAudio && separates("open", input.sound)) {+ const swap = steps.find((s) => s.key === "swap")!;+ swap.request = { ...swap.request, ...helper };+ const final = joinWithSound(steps, { engine: "open", title: input.title, base, helper, source: input.source, range: input.range, pieces: ["swap"], sound: true, choice: input.sound });+ return { steps, final, pieces: 1, sound: true, tracked: false, anchors: anchorOn ? 1 : 0 };+ }return { steps, final: "swap", pieces: 1, sound: false, tracked: false, anchors: anchorOn ? 1 : 0 };}@@ -1377,6 +1390,7 @@ function planFuobeRestyle(input: GenjutsuPlanInput): GenjutsuPlan {maxRefs: m.readsLookImages ?? 0,...(qualityFor(m, input.quality) ? { resolution: qualityFor(m, input.quality) } : {}),...(input.seed !== undefined ? { seed: input.seed } : {}),+ ...(input.sound && { sound: input.sound }),});// Only the finished video is a result; the segments are steps (Shorts keeps each take as a result of its own).const final = plan.final ?? plan.takes[0].look;diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.tsindex 31056e88..5badddcd 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 { originalSoundProblem, separates, SOUND_STEP_LABEL, soundBack, soundOf, withSoundExtra, type SoundChoice } 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 },+ /** cut / mux: Original sound other than Everything (the per-frame graph keeps the clip's sound itself). */+ 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[];+ /** Original sound: what of the clip's sound goes back (src/lib/av/original-sound.ts; unset = Everything). */+ sound?: SoundChoice;}/**@@ -685,7 +689,8 @@ 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 split = !!input.source.hasAudio && separates("open", input.sound);+ const plan: { steps: PlanStep[]; final: string } = {final: "render",steps: [{@@ -714,7 +719,27 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: st},],};+ if (!split) return plan;+ // Original sound other than Everything: the render keeps the clip's sound, so the selection is cut, its sound split,+ // and the chosen stems laid over the render (the picture stream-copied).+ const render = plan.steps[0];+ const { title: _made, ...rest } = render.request;+ void _made;+ render.request = { ...rest, feature: MIXED_STEP_FEATURE };+ const t = MIXED_TOOLS.open;+ const helper = { ...base, feature: MIXED_STEP_FEATURE };+ plan.steps.push({ key: "cut", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Original sound", index: 1100, of: 1000 } } });+ const back = soundBack(plan.steps, { engine: "open", choice: input.sound, from: { key: "cut" }, helper, seconds: input.range.end - input.range.start });+ plan.steps.push({+ key: "final",+ request: withSoundExtra({ ...base, feature: MIXED_FEATURE, title: input.title, modelId: t.mux, op: "mux", step: { label: SOUND_STEP_LABEL[soundOf(input.sound)], index: 1200, of: 1000 } }, back),+ after: ["render", ...back.after],+ chain: [{ slot: "video" }, ...back.chain],+ });+ return { steps: plan.steps, final: "final" };}+ const soundProblem = originalSoundProblem(input.engine, input.sound);+ if (soundProblem) throw new Error(soundProblem);const t = MIXED_TOOLS.cloud;const sound = !!input.source.hasAudio;const steps: PlanStep[] = [@@ -765,6 +790,8 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: st* (joined when there are several) → the cut's own sound.*/export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; final: string } {+ const soundProblem = originalSoundProblem(input.engine, input.sound);+ if (soundProblem) throw new Error(soundProblem);const t = MIXED_TOOLS.cloud;const prompts = mixedPrompts(input.preset, input.values);const len = Math.round((input.range.end - input.range.start) * 1000) / 1000;@@ -912,6 +939,7 @@ export function planMixedSmooth(input: MixedPlanInput): { steps: PlanStep[]; finmaxRefs: 0,...(input.engine === "cloud" && { resolution: "720p" }),seed: input.seed ?? FRAME_SEED,+ ...(input.sound && { sound: input.sound }),});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 1be277f0..5e9121b3 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 { originalSoundProblem, separates, soundBack, SOUND_STEP_LABEL, soundOf, withSoundExtra, type SoundChoice } from "../av/original-sound";export type RemoveMode = "type" | "click" | "paint";@@ -568,6 +569,8 @@ export interface RemovalPlanInput {/** Paint it: the mask of the range's first frame (white = remove). */mask?: string;seed?: number;+ /** Original sound: what of the clip's sound goes back (src/lib/av/original-sound.ts; unset = Everything). */+ sound?: SoundChoice;}export interface RemovalPlan {@@ -617,6 +620,8 @@ function eraseRequest(input: RemovalPlanInput, p: Piece): Partial<GenerationRequ* - then the pieces are joined (folded when the join takes fewer clips) and the clip's own sound put back.*/export function planRemoval(input: RemovalPlanInput): RemovalPlan {+ const soundProblem = originalSoundProblem(input.engine, input.sound);+ if (soundProblem) throw new Error(soundProblem);if (input.eraser.cleanFrame) return planPersonRemoval(input);const e = input.eraser;const t = REMOVE_TOOLS[input.engine];@@ -629,7 +634,8 @@ 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);+ // A result that keeps its own sound still gets the chosen stems put back when the sound is split (Original sound).+ const sound = !!input.source.hasAudio && (n > 1 || !e.keepsSound || separates(input.engine, input.sound));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.@@ -727,7 +733,7 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {// Erasers that work in whole frames leave out the last few (fewer than a step): the sound is cut to the picture's end,// 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 });+ const final = joinWithSound(steps, { engine: input.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: joined, sound, end, choice: input.sound });return { steps, final, pieces, sound, tracked };}@@ -804,7 +810,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 });+ const final = joinWithSound(steps, { engine: "open", title: input.title, base, helper, source: input.source, range: input.range, pieces: ["erase0"], sound, choice: input.sound });return { steps, final, pieces: [piece], sound, tracked: false };}@@ -824,6 +830,8 @@ export interface JoinInput {end?: number;/** What the sound step says (default "Put the sound back"). */soundLabel?: string;+ /** Original sound: what of the clip's sound goes back (src/lib/av/original-sound.ts; unset = Everything). */+ choice?: SoundChoice;}/**@@ -866,15 +874,21 @@ export function joinWithSound(steps: PlanStep[], j: JoinInput): string {const chain: ChainSlot[] = [{ slot: "video" }];const inputs: GenerationRequest["inputs"] = {};const end = j.end ?? j.range.end;- if (wholeClip(j.range, j.source.duration) && end >= (j.source.duration ?? 0) - 0.05) inputs.audio = j.source.url;- else {+ let from: { url: string } | { key: string } = { url: j.source.url };+ if (!(wholeClip(j.range, j.source.duration) && end >= (j.source.duration ?? 0) - 0.05)) {steps.push({ key: "sound", request: { ...j.helper, modelId: t.cut, op: "trim", inputs: { video: j.source.url }, params: { startTime: j.range.start, endTime: end }, step: { label: "Original sound", index: 1100, of: 1000 } } });- after.push("sound");- chain.push({ slot: "audio" });+ from = { key: "sound" };}+ // Original sound: all of it, or (open engine) the chosen stems of a split of that working clip.+ const back = soundBack(steps, { engine: j.engine, choice: j.choice, from, helper: j.helper, seconds: end - j.range.start });+ after.push(...back.after);+ chain.push(...back.chain);+ if (back.inputs) inputs.audio = back.inputs.audio;+ const s = soundOf(j.choice);+ const label = s === "everything" || j.engine !== "open" ? (j.soundLabel ?? "Put the sound back") : SOUND_STEP_LABEL[s];steps.push({key: "final",- request: { ...j.base, title: j.title, modelId: t.mux, op: "mux", ...(Object.keys(inputs).length ? { inputs } : {}), step: { label: j.soundLabel ?? "Put the sound back", index: 1200, of: 1000 } },+ request: withSoundExtra({ ...j.base, title: j.title, modelId: t.mux, op: "mux", ...(Object.keys(inputs).length ? { inputs } : {}), step: { label, index: 1200, of: 1000 } }, back),after,chain,});diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.tsindex a9a236a2..448e49a7 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 { soundBack, withSoundExtra, SOUND_STEP_LABEL, soundOf, type SoundChoice } from "../av/original-sound";// ---------------------------------------------------------------------------// Limits (Higgsfield's, from the upload dialog) and engine shapes@@ -460,6 +461,8 @@ export interface ShortsPlanInput {resolution?: string;/** Extra params for the restyle model (e.g. a seed for a new take). */seed?: number;+ /** Original sound: what of the clip's sound goes back (src/lib/av/original-sound.ts; unset = Everything). */+ sound?: SoundChoice;}export const SHORTS_FEATURE = "shorts";@@ -753,21 +756,26 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""after.push(picture.key);chain.push({ slot: "video" });} else inputs.video = picture.url;- if (whole) inputs.audio = input.source.url;- else {+ let from: { url: string } | { key: string } = { url: input.source.url };+ if (!whole) {// The sound of the selection: the source cut to the same window (the mux reads a clip's soundtrack).const key = `sound${suffix}`;steps.push({key,request: { ...helper, modelId: t.trim, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Original sound", index: 1100, of: 1000 } },});- after.push(key);- chain.push({ slot: "audio" });+ from = { key };}+ // Original sound: all of it, or (open engine) the stems chosen from a split of that working clip.+ const back = soundBack(steps, { engine: input.engine, choice: input.sound, from, helper, key: `split${suffix}`, seconds: input.range.end - input.range.start });+ after.push(...back.after);+ chain.push(...back.chain);+ if (back.inputs) inputs.audio = back.inputs.audio;const key = `final${suffix}`;+ const label = soundOf(input.sound) === "everything" ? "Final video" : `Final video · ${SOUND_STEP_LABEL[soundOf(input.sound)].toLowerCase()}`;steps.push({key,- 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 } },+ request: withSoundExtra({ ...base, title: input.title, modelId: t.mux, op: "mux", inputs: Object.keys(inputs).length ? inputs : undefined, step: { label, index: 1200, of: 1000 } }, back),...(after.length ? { after, chain } : {}),});return { steps, final: key };@@ -823,7 +831,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; sound?: SoundChoice };segments: ShortsSessionSegment[];stitches: ShortsStitch[];createdAt: number;@@ -844,6 +852,7 @@ export function sessionPlanInput(s: ShortsSession, seed?: number): ShortsPlanInpmaxRefs: s.settings.maxRefs,resolution: s.settings.resolution,reframes: s.settings.reframes,+ ...(s.settings.sound ? { sound: s.settings.sound } : {}),...(seed !== undefined ? { seed } : {}),};}@@ -917,7 +926,7 @@ export function stitchSteps(s: Pick<ShortsStitch, "ids" | "final">, gens: Recordconst ids = s.ids.includes(s.final) ? s.ids : [...s.ids, s.final];return ids.map((id) => {const g = gens[id];- const label = !g ? "A step" : g.op === "concat" ? "Stitching the segments" : g.op === "trim" ? "Cutting the original sound" : g.op === "mux" ? "Putting the sound back" : "Restyling";+ const label = !g ? "A step" : g.op === "concat" ? "Stitching the segments" : g.op === "trim" ? "Cutting the original sound" : g.op === "separate-audio" ? "Splitting the sound" : g.op === "mux" ? "Putting the sound back" : "Restyling";return { g, label };});}diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.tsindex 4ed714c4..9df91bed 100644--- a/src/lib/catalog/swap-studio-plan.ts+++ b/src/lib/catalog/swap-studio-plan.ts@@ -35,6 +35,7 @@ import {type WhoToSwap,} from "./swap-studio";import { silenceRef } from "./canvas";+import { soundBack, SOUND_STEP_LABEL, soundOf, withSoundExtra, type SoundBack, type SoundChoice } from "../av/original-sound";import { getModel } from "./index";import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";@@ -469,6 +470,8 @@ export interface AssemblyPlanInput {pieces: AssemblyPiece[];/** Each take's finished video. */videoOf: (piece: Extract<AssemblyPiece, { kind: "take" }>) => string;+ /** Original sound: what of the clip's sound goes back (src/lib/av/original-sound.ts; unset = Everything). */+ sound?: SoundChoice;}/** Fold `keys` into joins of at most `max` (the last join is "join"). */@@ -537,18 +540,23 @@ export function planAssembly(a: AssemblyPlanInput): { steps: PlanStep[]; final:const m = STUDIO_MODELS[a.engine];const rate = a.engine === "cloud" ? { params: { extra: { target_fps: SWAP_STUDIO.fps } } } : {};const picture = joins(steps, keys, m.joinMax, (_n, last) => ({ ...helper(title), modelId: m.join, op: "concat", prompt: title, ...rate, step: { label: last ? "Join the parts" : "Joining", index: 1000, of: 1000 } }));- const sound: GenerationRequest["inputs"] = clip.source.hasAudio ? { audio: workingClip(clip, a.engine) } : a.engine === "cloud" ? { audio: silenceRef(clip.source.duration) } : undefined;- if (!sound) {+ if (!clip.source.hasAudio && a.engine === "open") {// Your GPU, a silent clip: the fit graph already gave every part silence; the join is the result.const last = steps.find((s) => s.key === picture)!;last.request = { ...last.request, ...base };return { steps, final: picture };}+ // Original sound: the working clip's sound as it is, or (your GPU) the chosen stems of a split of it.+ const back: SoundBack = clip.source.hasAudio+ ? soundBack(steps, { engine: a.engine, choice: a.sound, from: { url: workingClip(clip, a.engine) }, helper: helper(title), seconds: clip.source.duration, name: clip.name })+ : { after: [], chain: [], inputs: { audio: silenceRef(clip.source.duration) } };+ const choice = soundOf(a.sound);+ const label = !clip.source.hasAudio ? "Keep it silent, like the clip" : choice === "everything" ? "Put the clip's sound back" : SOUND_STEP_LABEL[choice];steps.push({key: "final",- request: { ...base, modelId: m.mux, op: "mux", inputs: sound, step: { label: clip.source.hasAudio ? "Put the clip's sound back" : "Keep it silent, like the clip", index: 1200, of: 1000 } },- after: [picture],- chain: [{ slot: "video" }],+ request: withSoundExtra({ ...base, modelId: m.mux, op: "mux", ...(back.inputs && { inputs: back.inputs }), step: { label, index: 1200, of: 1000 } }, back),+ after: [picture, ...back.after],+ chain: [{ slot: "video" }, ...back.chain],});return { steps, final: "final" };}diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.tsindex afb11653..7eafd705 100644--- a/src/lib/catalog/swap-studio.ts+++ b/src/lib/catalog/swap-studio.ts@@ -17,6 +17,7 @@ import { CHARACTER_SWAP, h3Canvas, HISTORY_CHOICES, WINDOW_CHOICES, whoWords, tyimport { STUDIO_FPS } from "@/lib/av/scene-cuts";import { wholeClipBudget } from "@/lib/av/video-finish";import type { Engine, PixelPoint } from "./types";+import type { SoundChoice } from "../av/original-sound";export const SWAP_STUDIO = {feature: "swap-studio",@@ -300,7 +301,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;+ /** sound: the Original sound it was assembled with (unset = Everything). */+ assembly: { genId?: string; stepIds?: string[]; takes: string[]; createdAt: number; sound?: SoundChoice } | null;}export interface SwapProject {diff --git a/src/server/faceless.ts b/src/server/faceless.tsindex 4c1d4b40..7b235de4 100644--- a/src/server/faceless.ts+++ b/src/server/faceless.ts@@ -4,6 +4,7 @@ import { z } from "zod";import { getModel } from "@/lib/catalog";import {AUTO_SECONDS,+ MUSIC_CLIP_MIN_SECONDS,blockCount,buildEpisodeGraph,CAMERA_WORDS,@@ -1513,6 +1514,14 @@ export const SettingsSchema = z.object({resolution: z.string().max(10).optional(),auto: z.boolean().optional(),brief: BriefLookSchema.optional(),+ /** "Use a clip's soundtrack as the bed" (your GPU): the clip, and its seconds as the browser read them. */+ musicClip: z+ .object({+ url: FileUrl,+ name: z.string().max(200).optional(),+ duration: z.number().finite().min(MUSIC_CLIP_MIN_SECONDS, `Pick a clip of ${MUSIC_CLIP_MIN_SECONDS} s or more for the bed`).max(3600),+ })+ .optional(),});export const BlockSchema = z.object({diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.tsindex 5653d00a..92ee8273 100644--- a/src/server/genjutsu.ts+++ b/src/server/genjutsu.ts@@ -1,4 +1,6 @@import "server-only";+import { originalSoundProblem, separates, soundSummary, type SoundChoice } from "@/lib/av/original-sound";+import { SoundChoiceSchema } from "./shorts-schemas";import { z } from "zod";import { getModel } from "@/lib/catalog";import { onEngine } from "@/lib/catalog/engines";@@ -91,6 +93,8 @@ export interface GenjutsuBody {character?: CharacterOptions;/** Hard cuts the browser found in the clip (seconds), for the "one continuous shot" warning. */cuts?: number[];+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;}const fileUrl = z.string().startsWith("/api/files/").max(500);@@ -146,6 +150,7 @@ export const GenjutsuBodySchema = z.object({seed: z.number().int().min(0).max(2 ** 48).optional(),character: character.optional(),cuts: z.array(seconds).max(200).optional(),+ sound: SoundChoiceSchema.optional(),/** A client nonce for one submit: a repeat gets the first answer (see once()). */requestId: z.string().trim().min(8).max(64).optional(),});@@ -203,6 +208,8 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<const clicks = (body.points ?? []).filter((p) => p.label !== "negative").length;const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look, seed: body.seed, character: body.character });if (problem) throw new ShortsError(problem, 422);+ const soundProblem = originalSoundProblem(maker.engine, body.sound);+ if (soundProblem) throw new ShortsError(soundProblem, 422);const switched = body.mode === "character" && maker.h3 ? characterSwitches(maker, body.character ?? {}) : { character: body.character, notes: [] };// Clicks on the first frame, in the clip's pixels; paint is followed from its deepest points (SAM 3.1 on fal).@@ -217,6 +224,8 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<if (tracksPaint) points = opts.probe ? await pointsFromPaint(body.mask!, source, "Paint over what to swap first") : [{ x: 1, y: 1, label: "positive" }];const notes = [...switched.notes, ...notesFor({ ...body, character: switched.character }, maker, source, range, n, references.length)];+ const split = separates(maker.engine, body.sound) && source.hasAudio;+ if (split) notes.push(`Original sound: ${soundSummary(body.sound).toLowerCase()} — your GPU splits the clip's sound first (free)`);const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);const title = genjutsuTitle({ mode: body.mode, subject: body.subject, look: body.look });return {@@ -239,6 +248,7 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<look: body.look,...(body.seed !== undefined ? { seed: body.seed } : {}),...(body.mode === "character" ? { character: switched.character ?? {} } : {}),+ ...(split && body.sound && { sound: body.sound }),},};}diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.tsindex 409b4ca1..d2b1d0db 100644--- a/src/server/mixed-media.ts+++ b/src/server/mixed-media.ts@@ -1,4 +1,5 @@import "server-only";+import { originalSoundProblem, separates, soundSummary, type SoundChoice } 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;+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;}/**@@ -173,6 +176,10 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ ireach = { loras: onComfy.loras, notes: [...reach.notes, ...onComfy.notes] };}if (reach) notes.push(...reach.notes);+ const soundProblem = originalSoundProblem(body.engine, body.sound);+ if (soundProblem) throw new ShortsError(soundProblem, 422);+ const split = separates(body.engine, body.sound) && info.hasAudio !== false;+ if (split) notes.push(`Original sound: ${soundSummary(body.sound).toLowerCase()} — your GPU splits the clip's sound first (free)`);const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);return {frames,@@ -198,6 +205,7 @@ 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 } : {}),+ ...(split && body.sound && { sound: body.sound }),},};}diff --git a/src/server/remove-object.ts b/src/server/remove-object.tsindex 4b31f22a..b6e4fdfa 100644--- a/src/server/remove-object.ts+++ b/src/server/remove-object.ts@@ -1,4 +1,6 @@import "server-only";+import { originalSoundProblem, separates, soundSummary, type SoundChoice } from "@/lib/av/original-sound";+import { SoundChoiceSchema } from "./shorts-schemas";import { z } from "zod";import { getModel } from "@/lib/catalog";import { characterLicenceLine, PERSON_REMOVER_LORA } from "@/lib/catalog/character-swap";@@ -60,6 +62,8 @@ export interface RemovalBody {source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };range?: RemoveRange;seed?: number;+ /** Original sound (unset = Everything). */+ sound?: SoundChoice;}const fileUrl = z.string().startsWith("/api/files/").max(500);@@ -88,6 +92,7 @@ export const RemovalBodySchema = z.object({}),range: z.object({ start: seconds, end: seconds }).optional(),seed: z.number().int().min(0).max(2 ** 48).optional(),+ sound: SoundChoiceSchema.optional(),/** A client nonce for one submit: a repeat gets the first answer (see once()). */requestId: z.string().trim().min(8).max(64).optional(),});@@ -220,6 +225,10 @@ async function planInput(body: RemovalBody, opts: { probe: boolean; preview?: boif (eraser.everyone) notes.push("LTX Clean Plate removes every person in the shot — it doesn't take a target");}if (!wholeClip(range, source.duration)) notes.push("Only the selected part comes out (the rest of the clip isn't kept)");+ const soundProblem = originalSoundProblem(eraser.engine, body.sound);+ if (soundProblem) throw new ShortsError(soundProblem, 422);+ const split = separates(eraser.engine, body.sound) && !!source.hasAudio;+ if (split) notes.push(`Original sound: ${soundSummary(body.sound).toLowerCase()} — your GPU splits the clip's sound first (free)`);const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);const title = removalTitle({ mode: body.mode, prompt: body.prompt, everyone: eraser.everyone });@@ -237,6 +246,7 @@ async function planInput(body: RemovalBody, opts: { probe: boolean; preview?: bopoints,mask: body.mode === "paint" && eraser.engine === "open" ? body.mask : undefined,...(body.seed !== undefined ? { seed: body.seed } : {}),+ ...(split && body.sound && { sound: body.sound }),},};}diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.tsindex cbbbbac5..b62634d0 100644--- a/src/server/shorts-schemas.ts+++ b/src/server/shorts-schemas.ts@@ -2,6 +2,7 @@ import "server-only";import { z } from "zod";import { MIXED } from "@/lib/catalog/mixed-media";import { SHORTS } from "@/lib/catalog/shorts";+import { ORIGINAL_SOUNDS, SOUND_LOWER_MAX_DB, SOUND_LOWER_MIN_DB, type OriginalSound } from "@/lib/av/original-sound";import { connectRefusal } from "./connect-refusal";import { ShortsError } from "./shorts";@@ -12,6 +13,12 @@ const seconds = z.number().finite().min(0).max(3600);/** A client nonce for one submit: a repeated id gets the first answer instead of a second paid run (see once()). */const requestId = z.string().trim().min(8).max(64).optional();+/** Original sound: what of the clip's sound a studio puts back (src/lib/av/original-sound.ts). */+export const SoundChoiceSchema = z.object({+ sound: z.enum(ORIGINAL_SOUNDS.map((o) => o.id) as [OriginalSound, ...OriginalSound[]]),+ musicDb: z.number().finite().min(SOUND_LOWER_MIN_DB).max(SOUND_LOWER_MAX_DB).optional(),+});+const source = z.object({url: fileUrl,name: z.string().max(200).optional(),@@ -29,6 +36,7 @@ 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(),+ sound: SoundChoiceSchema.optional(),requestId,});@@ -57,12 +65,16 @@ export const MixedBodySchema = z.object({anchor: fileUrl.optional(),frameUrl: fileUrl.optional(),seed: z.number().int().min(0).max(2 ** 48).optional(),+ sound: SoundChoiceSchema.optional(),requestId,});/** Bodies of the session actions that only carry a nonce (stitch again, regenerate a segment). */export const NonceSchema = z.object({ requestId }).default({});+/** Stitch again: a nonce, and optionally a new Original sound choice (kept for the stitches after it). */+export const StitchSchema = z.object({ requestId, sound: SoundChoiceSchema.optional() }).default({});+export const MixedEstimateSchema = MixedBodySchema.extend({ source: source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }) });/** A user-facing error answer: ShortsError keeps its status; anything else from the planner is a 422. */diff --git a/src/server/shorts.ts b/src/server/shorts.tsindex 81c360a3..018ed32e 100644--- a/src/server/shorts.ts+++ b/src/server/shorts.ts@@ -35,6 +35,7 @@ import {type TakeKeys,} from "@/lib/catalog/shorts";import type { Engine, Generation } from "@/lib/catalog/types";+import { originalSoundProblem, separates, soundSummary, type SoundChoice } from "@/lib/av/original-sound";import { createPipeline } from "./chains";import { db } from "./db";import { getGeneration, previewChained } from "./generations";@@ -133,8 +134,8 @@ function readSession(id: string): ShortsSession {function saveSession(s: ShortsSession): ShortsSession {const now = Date.now();db()- .prepare("UPDATE shorts_sessions SET segments_json = ?, stitches_json = ?, title = ?, updated_at = ? WHERE id = ?")- .run(JSON.stringify(s.segments), JSON.stringify(s.stitches), s.title, now, s.id);+ .prepare("UPDATE shorts_sessions SET segments_json = ?, stitches_json = ?, settings_json = ?, title = ?, updated_at = ? WHERE id = ?")+ .run(JSON.stringify(s.segments), JSON.stringify(s.stitches), JSON.stringify(s.settings), s.title, now, s.id);return { ...s, updatedAt: now };}@@ -209,6 +210,8 @@ export interface ShortsBody {aspectRatio: ShortsRatio;language: string;modelId?: string;+ /** Original sound: what of the clip's sound goes back (unset = Everything). */+ sound?: SoundChoice;/** 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;}@@ -263,6 +266,8 @@ function planWith(body: ShortsBody, info: SourceInfo): { input: ShortsPlanInput;const readers = SHORTS_MODELS.cloud.filter((id) => maxRefsFor(id, "cloud") > 0).map((id) => getModel(id)?.name ?? id);throw new ShortsError(`${getModel(modelId)?.name ?? "This model"} restyles from words only — describe the look in your preset, or pick ${readers.join(" or ")}`, 422);}+ const soundProblem = originalSoundProblem(body.engine, body.sound);+ if (soundProblem) throw new ShortsError(soundProblem, 422);const name = fileTitle(body.source.name);return {info,@@ -287,6 +292,7 @@ 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),+ ...(body.sound && body.sound.sound !== "everything" ? { sound: body.sound } : {}),},};}@@ -330,6 +336,7 @@ function notesFor(input: ShortsPlanInput, segments: number): string[] {if (vaceDownsample(fps)) notes.push(`Wan 2.2 Fun VACE works this ${Math.round(fps!)} fps clip at ${Math.round(fps! / (vaceDownsample(fps) + 1))} fps and brings it back to its own rate`);} else notes.push("Fuobe Shorts on your GPU renders 480p at 16 fps, 5 s a segment");}+ if (separates(input.engine, input.sound) && input.source.hasAudio !== false) notes.push(`Original sound: ${soundSummary(input.sound).toLowerCase()} — your GPU splits the clip's sound first (DBS, free)`);if (input.engine === "cloud") {const { width: w, height: h } = input.source;if (!input.reframes && w && h && needsFit(input.source, input.aspectRatio)) notes.push(`Your ${w}×${h} clip is centre-cropped to ${input.aspectRatio} before the restyle`);@@ -401,7 +408,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.sound && { sound: input.sound }) },segments,stitches: [stitch],createdAt: now,@@ -555,8 +562,12 @@ export function makePrimary(id: string, index: number, lookId: string): ShortsSe}/** Join the chosen takes again (after a regenerate or a new choice) and put the sound back. */-export function stitchSession(id: string): ShortsSessionView {- const s = readSession(id);+export function stitchSession(id: string, sound?: SoundChoice): ShortsSessionView {+ const read = readSession(id);+ // A new Original sound choice is kept for this stitch and the ones after it.+ const s: ShortsSession = sound ? { ...read, settings: { ...read.settings, sound } } : read;+ const soundProblem = originalSoundProblem(s.engine, s.settings.sound);+ if (soundProblem) throw new ShortsError(soundProblem, 422);checkEngine(s.engine);const clips = s.segments.map((seg, i) => {const g = getGeneration(seg.primary);diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.tsindex 3601cc11..059be78e 100644--- a/src/server/swap-studio.ts+++ b/src/server/swap-studio.ts@@ -1,4 +1,5 @@import "server-only";+import { originalSoundProblem, sameSound, soundOf, type SoundChoice } from "@/lib/av/original-sound";import { z } from "zod";import { getModel } from "@/lib/catalog";import { ANCHOR_MODELS, anchorModel, characterLicenceLine, SWAP_LORAS, swapLoraRef, TURBO_LORA } from "@/lib/catalog/character-swap";@@ -978,16 +979,20 @@ 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, sound?: SoundChoice): SwapProject {const p = advanceProject(projectId);mustMatchMode(p.engine);const clip = mustClip(p, clipId);+ const soundProblem = originalSoundProblem(p.engine, sound);+ if (soundProblem) throw new ShortsError(soundProblem, 422);+ // Original sound: Everything is stored as nothing (as before); another choice is kept with the assembly.+ const choice = clip.source.hasAudio && soundOf(sound) !== "everything" ? sound : undefined;const look = lookup();const found = assemblyPieces(p, clip);if ("problem" in found) throw new ShortsError(found.problem, 422);const takes = assemblyTakes(found.pieces);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) && sameSound(clip.assembly.sound, choice)) {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);@@ -999,10 +1004,10 @@ 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, ...(choice && { sound: choice }) });// The takes count as steps already made: a demo join of real takes is refused.const pipe = run(plan.steps, 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, createdAt: Date.now(), ...(choice && { sound: choice }) };return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, assembly })));}