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
Dub: the cloud step-by-step dub keeps the music and effects
Claude504d31995ca4
diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxindex 05ff3974..1b61ea61 100644--- a/src/components/dub/dub-studio.tsx+++ b/src/components/dub/dub-studio.tsx@@ -17,7 +17,7 @@ import { StepList, type StepRow } from "@/components/av/step-list";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useEngine } from "@/lib/api";import { cueProblems } from "@/lib/av/cue-edit";-import { crowdedLines, dubResult, languageStage, ONE_SHOT_MODELS, priceLine, reviewCues, takeLines, translateKey, type DubPrice, type DubSessionView, type DubStage, type OneShotModel } from "@/lib/av/dub";+import { crowdedLines, dubResult, languageStage, ONE_SHOT_MODELS, priceLine, reviewCues, takeLines, translateKey, voiceOnly, type DubPrice, type DubSessionView, type DubStage, type OneShotModel } from "@/lib/av/dub";import { languageByCode, supportsTarget, type DubRoute } from "@/lib/av/languages";import type { Cue } from "@/lib/cues";import { cn } from "@/lib/utils";@@ -31,7 +31,7 @@ const ONE_SHOT: Record<OneShotModel, { name: string; note: string }> = {const ROUTE_LINE = {open: "Open source: MelBand RoFormer splits the voice from the music and Qwen3-ASR times it → your local LLM translates → you review → Chatterbox speaks each line in the cloned voice, at its time → InfiniteTalk re-syncs the lips → mixed back over the music.",- cloud: "Cloud: ElevenLabs isolates the voice → Scribe v2 times it → Claude (or Ollama) translates → you review → ElevenLabs speaks each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3. The cloud route keeps the voice only (no music stem on this route).",+ cloud: "Cloud: ElevenLabs isolates the voice and Demucs lifts out the music and effects → Scribe v2 times the voice → Claude (or Ollama) translates → you review → ElevenLabs speaks each line at its time and Chatterbox turns it into the speaker's voice → Sync Lipsync 3 → mixed back over the music and effects.",};const STAGE: Record<DubStage, { label: string; tone: string }> = {@@ -270,7 +270,7 @@ function RecentDubs({ sessions, loading, onOpen }: { sessions?: DubSessionView[]);}-const PREPARE_LABEL: Record<string, string> = { stems: "Voice, background and transcript", voice: "Clean voice", words: "Transcript" };+const PREPARE_LABEL: Record<string, string> = { stems: "Voice, background and transcript", voice: "Clean voice", words: "Transcript", sound: "Original sound", background: "Music and effects" };function prepareRows(s: DubSessionView, lang: string): StepRow[] {// Older open dubs transcribed in a step of their own.@@ -289,7 +289,9 @@ function voiceRows(s: DubSessionView, lang: string): StepRow[] {soundtrack: "Voice track",clone: "Their voice",lips: "Lips re-synced",- film: run.lipsync && !open ? "Lips re-synced" : "Dubbed video",+ mix: "Over the music and effects",+ // Older cloud dubs (and cloud dubs with no background) re-synced the lips as their last step.+ film: run.lipsync && !run.ids.lips ? "Lips re-synced" : "Dubbed video",};const entries = Object.entries(run.ids);const lines = entries.filter(([k]) => k.startsWith("line:")).map(([, id]) => s.generations[id]);@@ -423,7 +425,7 @@ function ResultCard({ s, lang }: { s: DubSessionView; lang: string }) {><video src={out.url} controls playsInline preload="metadata" className="max-h-[42vh] w-full rounded-xl bg-media object-contain" />{g.provider === "mock" && <p className="mt-2 text-[12px] text-muted-foreground">Demo result — connect a provider (or start ComfyUI) to dub for real.</p>}- {s.engine === "cloud" && s.mode === "steps" && <p className="mt-2 text-[12px] text-muted-foreground">Voice only: the cloud route has no music stem to mix back in (the open route and the one-shot models keep it).</p>}+ {voiceOnly(s) && <p className="mt-2 text-[12px] text-muted-foreground">Voice only: this dub's music and effects weren't separated, so the new voice plays alone.</p>}</Panel>);}@@ -523,6 +525,7 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ti</Button></div></div>+ {voiceOnly(s) && <p className="mt-3 text-[12px] text-muted-foreground">The music and effects weren't separated for this dub, so the new voice will play alone.</p>}{runs.length > 0 && <StepList steps={voiceRows(s, lang)} className="mt-4" />}</Panel></>diff --git a/src/lib/av/dub.ts b/src/lib/av/dub.tsindex 918a5639..27c6ebbe 100644--- a/src/lib/av/dub.ts+++ b/src/lib/av/dub.ts@@ -22,10 +22,13 @@ import { timelineFor } from "./timeline";* speaks each phrase in the cloned voice; the audio-timeline workflow lays them out; InfiniteTalk* re-syncs the lips and the mux mixes the voice over the background stem.* Cloud: ElevenLabs Voice Isolation (the clean voice to clone), Scribe v2 on it (transcript), Claude or- * Ollama (translation), ElevenLabs v4 speaks each phrase, fal's compose lays them out over a blank still+ * Ollama (translation), and in parallel the source's sound split by Demucs (drums, bass and other: the+ * music and effects). ElevenLabs v4 speaks each phrase, fal's compose lays them out over a blank still* (its soundtrack is read back as audio), Chatterbox voice conversion turns the track into the speaker's- * voice and Sync Lipsync 3 re-syncs the lips. The cloud result carries the dubbed voice only (that route- * has no background stem) — the music and effects are kept by the open route and the one-shot models.+ * voice and Sync Lipsync 3 re-syncs the lips; compose then mixes the new voice over the Demucs stems and+ * that mix replaces the video's sound. fal's compose has no volume control, so the stems keep their own+ * level (the open mux lowers its background stem by 3 dB). Dubs started before the background split, or+ * whose split failed, carry the dubbed voice only.*/export const DUB_FEATURE = "dub";@@ -38,6 +41,9 @@ export const DUB_STEP_MODELS = {voice: "elevenlabs-voice-isolation",words: "scribe-v2",translate: "text-llm",+ // The music and effects: the source's sound, split into stems (everything but the vocals is the background).+ sound: "extract-soundtrack",+ stems: "demucs",speech: "elevenlabs-v4",timeline: "compose-timeline",soundtrack: "extract-soundtrack",@@ -116,13 +122,24 @@ export function prepareSteps(o: PrepareInput): DubStep[] {...targets.map((l, i) => translate(l, i + 1, "stems", m)),];}+ const m = DUB_STEP_MODELS.cloud;+ const c = n + 2;return [- { key: "voice", request: { ...base, modelId: DUB_STEP_MODELS.cloud.voice, op: "separate-audio", inputs: { video: o.video }, step: step("Clean voice", 0, n) } },- { key: "words", after: "voice", chain: [{ slot: "audio" }], request: { ...base, modelId: DUB_STEP_MODELS.cloud.words, op: "transcribe", ...lang, step: step("Transcript", 1, n) } },- ...targets.map((l, i) => translate(l, i + 2, "words")),+ { key: "voice", request: { ...base, modelId: m.voice, op: "separate-audio", inputs: { video: o.video }, step: step("Clean voice", 0, c) } },+ { key: "words", after: "voice", chain: [{ slot: "audio" }], request: { ...base, modelId: m.words, op: "transcribe", ...lang, step: step("Transcript", 1, c) } },+ ...targets.map((l, i) => translate(l, i + 2, "words", c)),+ // Demucs reads audio, not a video: the soundtrack first, then the stems the new voice is mixed over.+ { key: "sound", request: { ...base, modelId: m.sound, op: "separate-audio", inputs: { video: o.video }, step: step("Original sound", n, c) } },+ { key: "background", after: "sound", chain: [{ slot: "audio" }], request: { ...base, modelId: m.stems, op: "separate-audio", step: step("Music and effects", n + 1, c) } },];}+/** Prepare steps a dub can do without: when the cloud background split fails, the dub keeps the voice only. */+export const OPTIONAL_PREPARE = new Set(["sound", "background"]);++const VOICE_STEMS = ["voice", "vocals", "speech", "target"];+const BACKGROUND_STEMS = ["background", "accompaniment", "instrumental", "residual", "no_vocals"];+export interface VoiceInput {engine: Engine;video: string;@@ -131,8 +148,11 @@ export interface VoiceInput {cues: Cue[];/** The clean voice to clone (the voice stem / isolated voice). */voiceRef: string;- /** Open engine: the background stem mixed back under the new voice. */- background?: string;+ /**+ * What the new voice is mixed over: the open engine's background stem (lowered by 3 dB), or on the cloud+ * the Demucs stems that aren't the voice (drums, bass, other), mixed at their own level.+ */+ background?: string | string[];/** Re-sync the lips (default on). Off: the new voice is laid over the original picture. */lipsync?: boolean;/** Length of the source video (seconds): the voice track is exactly this long. Unknown: a second past the last line. */@@ -189,8 +209,9 @@ export function trackLength(phrases: DubPhrase[], duration?: number): number {/*** Step 2: speak the reviewed translation in the cloned voice, one take per phrase, and lay the takes on* the video's timeline; then re-sync the lips and put the new voice on the video. Step keys: "line:0…"- * (the takes), "track" (the voice track, as long as the video), cloud "soundtrack" + "clone", open "lips",- * and "film" (the dubbed video).+ * (the takes), "track" (the voice track, as long as the video), cloud "soundtrack" + "clone", "lips"+ * (open; cloud when it mixes a background), cloud "mix" (the voice over the background stems) and+ * "film" (the dubbed video).*/export function voiceSteps(o: VoiceInput): DubStep[] {const lang = languageByCode(o.lang);@@ -204,6 +225,7 @@ export function voiceSteps(o: VoiceInput): DubStep[] {length,);const lips = o.lipsync !== false;+ const beds = o.background === undefined ? [] : Array.isArray(o.background) ? o.background : [o.background];const base = { feature: DUB_FEATURE, ...(o.title && { batchTitle: o.title }) };const tag = (label: string) => `${label} · ${lang.name}`;const k = phrases.length;@@ -234,16 +256,17 @@ export function voiceSteps(o: VoiceInput): DubStep[] {...base,modelId: m.mux,op: "mux",- inputs: { ...(lips ? {} : { video: o.video }), ...(o.background && { audio2: o.background }) },+ inputs: { ...(lips ? {} : { video: o.video }), ...(beds[0] && { audio2: beds[0] }) },// The background stem sits a little under the new voice.- ...(o.background && { params: { extra: { backgroundVolumeDb: -3 } } }),+ ...(beds[0] && { params: { extra: { backgroundVolumeDb: -3 } } }),step: step(tag("Dubbed video"), n - 1, n),},});return steps;}const m = DUB_STEP_MODELS.cloud;- const n = k + 4;+ const mixed = beds.length > 0;+ const n = k + 3 + (mixed ? (lips ? 3 : 2) : 1);// Seconds of media the per-second and per-minute steps bill for (their price estimate).const timed = { params: { duration: length } };const steps: DubStep[] = phrases.map((p, i) => ({@@ -254,8 +277,35 @@ export function voiceSteps(o: VoiceInput): DubStep[] {steps.push(track(m.timeline, n, { images: [BLANK_FRAME] }));steps.push({ key: "soundtrack", after: "track", chain: [{ slot: "video" }], request: { ...base, modelId: m.soundtrack, op: "separate-audio", ...timed, step: step(tag("Voice track"), k + 1, n) } });steps.push({ key: "clone", after: "soundtrack", chain: [{ slot: "audio" }], request: { ...base, modelId: m.clone, op: "voice-change", inputs: { voiceAudio: o.voiceRef }, ...timed, step: step(tag("Their voice"), k + 2, n) } });- const film = lips ? { modelId: m.lips, op: "lipsync" as const } : { modelId: m.mux, op: "mux" as const };- steps.push({ key: "film", after: "clone", chain: [{ slot: "audio" }], request: { ...base, ...film, inputs: { video: o.video }, ...timed, step: step(tag("Dubbed video"), k + 3, n) } });+ if (!mixed) {+ // No background to keep: the new voice alone goes on the video (re-synced, or over the original picture).+ const film = lips ? { modelId: m.lips, op: "lipsync" as const } : { modelId: m.mux, op: "mux" as const };+ steps.push({ key: "film", after: "clone", chain: [{ slot: "audio" }], request: { ...base, ...film, inputs: { video: o.video }, ...timed, step: step(tag("Dubbed video"), k + 3, n) } });+ return steps;+ }+ // The lips follow the clean voice; the mix is a compose over the blank still with the voice and every+ // background stem as tracks of their own for the whole length, and its sound replaces the video's.+ if (lips) steps.push({ key: "lips", after: "clone", chain: [{ slot: "audio" }], request: { ...base, modelId: m.lips, op: "lipsync", inputs: { video: o.video }, ...timed, step: step(tag("Lips"), k + 3, n) } });+ const whole = { start: 0, duration: length };+ steps.push({+ key: "mix",+ after: "clone",+ chain: [{ slot: "audios", position: "first" }],+ request: {+ ...base,+ modelId: m.timeline,+ op: "timeline",+ inputs: { images: [BLANK_FRAME], audios: beds },+ params: { duration: length, extra: { timeline: { length, clips: [whole, ...beds.map(() => whole)] } } },+ step: step(tag("Over the music and effects"), n - 2, n),+ },+ });+ steps.push({+ key: "film",+ after: lips ? ["lips", "mix"] : "mix",+ chain: lips ? [{ slot: "video" }, { slot: "audio" }] : [{ slot: "audio" }],+ request: { ...base, modelId: m.mux, op: "mux", ...(!lips && { inputs: { video: o.video } }), ...timed, step: step(tag("Dubbed video"), n - 1, n) },+ });return steps;}@@ -385,9 +435,12 @@ export function languageStage(s: DubSessionView, code: string): DubStage {const g = s.generations[s.oneshot?.[code] ?? ""];return done(g) ? "done" : broken(g) ? "failed" : "voicing";}- const prepIds = Object.entries(s.prepare ?? {}).filter(([k]) => !k.startsWith("translate:") || k === translateKey(code)).map(([, id]) => s.generations[id]);- if (prepIds.some(broken)) return "failed";- if (!prepIds.every(done)) return "preparing";+ const prep = Object.entries(s.prepare ?? {}).filter(([k]) => !k.startsWith("translate:") || k === translateKey(code));+ const needed = prep.filter(([k]) => !OPTIONAL_PREPARE.has(k)).map(([, id]) => s.generations[id]);+ // The background split is waited for (the voice is mixed over it), but a failure there only loses the music.+ const optional = prep.filter(([k]) => OPTIONAL_PREPARE.has(k)).map(([, id]) => s.generations[id]);+ if (needed.some(broken)) return "failed";+ if (!needed.every(done) || !optional.every((g) => !g || done(g) || broken(g))) return "preparing";const run = s.voices?.[code]?.at(-1);if (!run) return "review";const film = s.generations[run.ids.film];@@ -396,13 +449,28 @@ export function languageStage(s: DubSessionView, code: string): DubStage {return done(film) ? "done" : "voicing";}-/** The clean voice to clone and (open engine) the background, from the finished prepare step. */-export function prepareMedia(s: DubSessionView): { voice?: string; background?: string } {- const g = s.generations[s.prepare?.[s.engine === "open" ? "stems" : "voice"] ?? ""];- const audio = (g?.outputs ?? []).filter((o) => o.kind === "audio");- const stem = (names: string[]) => audio.find((o) => typeof o.meta?.stem === "string" && names.includes(String(o.meta.stem).toLowerCase()))?.url;- if (s.engine === "open") return { voice: stem(["voice", "vocals", "speech", "target"]) ?? audio[0]?.url, background: stem(["background", "accompaniment", "instrumental", "residual", "no_vocals"]) };- return { voice: audio[0]?.url };+const stemOf = (o: { meta?: Record<string, unknown> }) => (typeof o.meta?.stem === "string" ? o.meta.stem.toLowerCase() : "");++/**+ * The clean voice to clone and what it's mixed over, from the finished prepare steps: the open engine's+ * background stem, or the cloud's Demucs stems that aren't the voice (none when that split failed).+ */+export function prepareMedia(s: DubSessionView): { voice?: string; background?: string | string[] } {+ const audioOf = (key: string) => (s.generations[s.prepare?.[key] ?? ""]?.outputs ?? []).filter((o) => o.kind === "audio");+ if (s.engine === "open") {+ const audio = audioOf("stems");+ return { voice: audio.find((o) => VOICE_STEMS.includes(stemOf(o)))?.url ?? audio[0]?.url, background: audio.find((o) => BACKGROUND_STEMS.includes(stemOf(o)))?.url };+ }+ const split = s.generations[s.prepare?.background ?? ""];+ const beds = done(split) ? audioOf("background").filter((o) => !VOICE_STEMS.includes(stemOf(o))).map((o) => o.url) : [];+ return { voice: audioOf("voice")[0]?.url, ...(beds.length && { background: beds }) };+}++/** Whether a cloud step-by-step dub lost its music and effects: started before the split, or the split failed. */+export function voiceOnly(s: DubSessionView): boolean {+ if (s.engine !== "cloud" || s.mode !== "steps") return false;+ const split = s.generations[s.prepare?.background ?? ""];+ return !split || broken(split);}/** The finished dub of a language, if any. */diff --git a/src/lib/av/timeline.ts b/src/lib/av/timeline.tsindex 730b9185..915f5b04 100644--- a/src/lib/av/timeline.ts+++ b/src/lib/av/timeline.ts@@ -51,13 +51,26 @@ const ms = (s: number) => Math.round(s * 1000);/*** fal ffmpeg compose `tracks` for a timeline: exactly one visual track (a still image, else a video) for- * the whole length, then the clips as keyframes of one audio track.+ * the whole length, then the clips as keyframes of audio tracks. Clips that follow each other share a+ * track (a dub's lines are one "voice" track); a clip that starts before an earlier one has ended goes on+ * the next track that is free by then, so compose mixes them (a voice over background stems). ComfyUI's+ * timeline adds every clip onto one track, which mixes overlaps the same way.*/export function timelineTracks(spec: TimelineSpec, visual: { url: string; type: "image" | "video" }, audios: string[]): Record<string, unknown>[] {if (audios.length !== spec.clips.length) throw new Error(`The timeline places ${spec.clips.length} clip${spec.clips.length === 1 ? "" : "s"} but got ${audios.length}`);+ const lanes: { end: number; keyframes: { url: string; timestamp: number; duration: number }[] }[] = [];+ spec.clips.forEach((c, i) => {+ const key = { url: audios[i], timestamp: ms(c.start), duration: ms(c.duration) };+ // A millisecond of rounding between one line's end and the next one's start is no overlap.+ const lane = lanes.find((l) => l.end <= key.timestamp + 1);+ if (lane) {+ lane.keyframes.push(key);+ lane.end = key.timestamp + key.duration;+ } else lanes.push({ end: key.timestamp + key.duration, keyframes: [key] });+ });return [{ id: "picture", type: visual.type, keyframes: [{ url: visual.url, timestamp: 0, duration: ms(spec.length) }] },- { id: "voice", type: "audio", keyframes: spec.clips.map((c, i) => ({ url: audios[i], timestamp: ms(c.start), duration: ms(c.duration) })) },+ ...lanes.map((l, n) => ({ id: n ? `audio-${n + 1}` : "voice", type: "audio", keyframes: l.keyframes })),];}diff --git a/src/server/chains.ts b/src/server/chains.tsindex a35776e4..3107ec17 100644--- a/src/server/chains.ts+++ b/src/server/chains.ts@@ -292,7 +292,8 @@ function topoOrder(steps: PipelineStep[]): PipelineStep[] {* ]);* // byKey.film is the finished video; every step shares batchId and shows "Step n of 6".* // Paid route: demucs ("vocals" counts as "voice"), scribe-v2, text-llm, chatterbox-cloud, sync-lipsync-3;- * // its soundtrack model (merge-audio-video) takes one track, so it ends at "lips" or muxes the voice alone.+ * // merge-audio-video takes one track, so the voice and the other stems are mixed first by compose-timeline+ * // (overlapping clips go on tracks of their own) and that mix is the soundtrack (src/lib/av/dub.ts).* ```*/export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}): Pipeline {diff --git a/tests/av-dub.test.ts b/tests/av-dub.test.tsindex dc1b549f..b332be1b 100644--- a/tests/av-dub.test.ts+++ b/tests/av-dub.test.ts@@ -4,7 +4,8 @@ import path from "node:path";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import type { Generation } from "@/lib/catalog/types";import { cueReducer, cueProblems, formatCueTime, normalizeCues, parseCueTime } from "@/lib/av/cue-edit";-import { BLANK_FRAME, crowdedLines, dubPhrases, languageStage, oneShotRequests, PHRASE_MAX, prepareSteps, priceLine, reviewCues, spokenText, takeLines, voiceSteps, type DubSessionView } from "@/lib/av/dub";+import { BLANK_FRAME, crowdedLines, dubPhrases, languageStage, oneShotRequests, PHRASE_MAX, prepareMedia, prepareSteps, priceLine, reviewCues, spokenText, takeLines, voiceOnly, voiceSteps, type DubSessionView } from "@/lib/av/dub";+import { timelineFor, timelineTracks } from "@/lib/av/timeline";import { DUB_LANGUAGES, supportsTarget } from "@/lib/av/languages";import { getModel } from "@/lib/catalog";import { buildPayload } from "@/lib/catalog/payload";@@ -70,15 +71,28 @@ describe("dub pipeline DAGs", () => {expect(() => prepareSteps({ engine: "open", video, targets: ["th"] })).toThrow(/Thai isn't available on the open engine/);});- it("cloud: isolated voice → Scribe → translations", () => {+ it("cloud: isolated voice → Scribe → translations, and the soundtrack → Demucs stems for the background", () => {const steps = prepareSteps({ engine: "cloud", video, targets: ["fr"] });- expect(steps.map((s) => [s.key, s.request.modelId, s.after ?? null])).toEqual([- ["voice", "elevenlabs-voice-isolation", null],- ["words", "scribe-v2", "voice"],- ["translate:fr", "text-llm", "words"],+ expect(steps.map((s) => [s.key, s.request.modelId, s.request.op, s.after ?? null])).toEqual([+ ["voice", "elevenlabs-voice-isolation", "separate-audio", null],+ ["words", "scribe-v2", "transcribe", "voice"],+ ["translate:fr", "text-llm", "translate", "words"],+ ["sound", "extract-soundtrack", "separate-audio", null],+ ["background", "demucs", "separate-audio", "sound"],]);expect(steps[0].request.inputs).toEqual({ video });expect(steps[1].request.params).toBeUndefined(); // "auto" = detect+ // Demucs reads audio only: the video's soundtrack goes in through the chain.+ expect(steps[3].request.inputs).toEqual({ video });+ expect(steps[4].chain).toEqual([{ slot: "audio" }]);+ expect(steps[4].request.inputs).toBeUndefined();+ expect(steps.map((s) => s.request.step)).toEqual([+ { label: "Clean voice", index: 0, of: 5 },+ { label: "Transcript", index: 1, of: 5 },+ { label: "Translate · French", index: 2, of: 5 },+ { label: "Original sound", index: 3, of: 5 },+ { label: "Music and effects", index: 4, of: 5 },+ ]);});// Speech starts at 2 s, pauses at 7–12 s and ends at 26 s of a 30 s clip.@@ -174,6 +188,65 @@ describe("dub pipeline DAGs", () => {expect(() => voiceSteps({ engine: "cloud", video, lang: "ja", cues: [{ start: 40, end: 41, text: "late" }], voiceRef: "/v", duration: 30 })).toThrow(/after the end of the video/);});+ it("cloud voice with the background: lips on the clean voice, the voice mixed over the Demucs stems, that mix on the video", () => {+ const beds = ["/drums.mp3", "/bass.mp3", "/other.mp3"];+ const steps = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", background: beds, duration: 30 });+ expect(steps.map((s) => [s.key, s.request.modelId, s.request.op, s.after ?? null])).toEqual([+ ["line:0", "elevenlabs-v4", "tts", null],+ ["line:1", "elevenlabs-v4", "tts", null],+ ["line:2", "elevenlabs-v4", "tts", null],+ ["track", "compose-timeline", "timeline", ["line:0", "line:1", "line:2"]],+ ["soundtrack", "extract-soundtrack", "separate-audio", "track"],+ ["clone", "chatterbox-vc-cloud", "voice-change", "soundtrack"],+ ["lips", "sync-lipsync-3", "lipsync", "clone"],+ ["mix", "compose-timeline", "timeline", "clone"],+ ["film", "merge-audio-video", "mux", ["lips", "mix"]],+ ]);+ expect(steps.map((s) => s.request.step?.index)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);+ expect(steps.every((s) => s.request.step?.of === 9)).toBe(true);+ const [lips, mix, film] = steps.slice(6);+ expect(lips.request).toMatchObject({ inputs: { video }, params: { duration: 30 } });+ expect(lips.chain).toEqual([{ slot: "audio" }]);+ // The new voice goes first, then every stem, each for the whole length (so compose mixes them).+ expect(mix.chain).toEqual([{ slot: "audios", position: "first" }]);+ expect(mix.request.inputs).toEqual({ images: [BLANK_FRAME], audios: beds });+ expect(mix.request.params).toEqual({ duration: 30, extra: { timeline: { length: 30, clips: Array(4).fill({ start: 0, duration: 30 }) } } });+ expect(film.chain).toEqual([{ slot: "video" }, { slot: "audio" }]);+ expect(film.request.inputs).toBeUndefined();+ expect(film.request.params).toEqual({ duration: 30 });+ const payload = buildPayload(getModel("compose-timeline")!.routes[0].map!, { images: ["https://fal.media/still.png"], audios: ["https://a/voice.mp3", ...beds.map((b) => `https://a${b}`)], extra: mix.request.params?.extra });+ expect(payload.tracks).toEqual([+ { id: "picture", type: "image", keyframes: [{ url: "https://fal.media/still.png", timestamp: 0, duration: 30000 }] },+ { id: "voice", type: "audio", keyframes: [{ url: "https://a/voice.mp3", timestamp: 0, duration: 30000 }] },+ { id: "audio-2", type: "audio", keyframes: [{ url: "https://a/drums.mp3", timestamp: 0, duration: 30000 }] },+ { id: "audio-3", type: "audio", keyframes: [{ url: "https://a/bass.mp3", timestamp: 0, duration: 30000 }] },+ { id: "audio-4", type: "audio", keyframes: [{ url: "https://a/other.mp3", timestamp: 0, duration: 30000 }] },+ ]);+ // Without lip re-sync the mix goes over the original picture.+ const flat = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", background: beds, lipsync: false, duration: 30 });+ expect(flat.slice(5).map((s) => [s.key, s.after])).toEqual([+ ["clone", "soundtrack"],+ ["mix", "clone"],+ ["film", "mix"],+ ]);+ expect(flat.at(-1)!.request).toMatchObject({ modelId: "merge-audio-video", inputs: { video } });+ expect(flat.at(-1)!.chain).toEqual([{ slot: "audio" }]);+ expect(flat.every((s) => s.request.step?.of === 8)).toBe(true);+ });++ it("timeline tracks: lines that follow each other share the voice track, overlapping clips get tracks of their own", () => {+ const pic = { url: "p.png", type: "image" as const };+ // A millisecond of rounding between two lines isn't an overlap.+ const lines = timelineTracks({ length: 10, clips: [{ start: 0, duration: 2.0004 }, { start: 2, duration: 3 }, { start: 5, duration: 5 }] }, pic, ["a", "b", "c"]);+ expect(lines.map((t) => t.id)).toEqual(["picture", "voice"]);+ const mixed = timelineTracks({ length: 10, clips: [{ start: 0, duration: 4 }, { start: 2, duration: 2 }, { start: 4, duration: 6 }, { start: 5, duration: 1 }] }, pic, ["a", "b", "c", "d"]);+ expect(mixed.slice(1).map((t) => [t.id, (t.keyframes as { url: string }[]).map((k) => k.url)])).toEqual([+ ["voice", ["a", "c"]],+ ["audio-2", ["b", "d"]],+ ]);+ expect(timelineTracks(timelineFor([0, 3.3333, 7.0006], 12), pic, ["a", "b", "c"]).length).toBe(2);+ });+it("the cloud track is a fal compose timeline over the blank still", () => {const steps = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", duration: 30 });const route = getModel("compose-timeline")!.routes[0];@@ -275,7 +348,7 @@ describe("dub sessions (demo mode)", () => {expect(reviewCues(saved, "es")![0].text).toBe("Hola, esto es una prueba");const voiced = dub.voiceDub(view.id, "es");const run = voiced.voices!.es[0];- expect(Object.keys(run.ids)).toEqual(engine === "open" ? ["line:0", "track", "lips", "film"] : ["line:0", "track", "soundtrack", "clone", "film"]);+ expect(Object.keys(run.ids)).toEqual(engine === "open" ? ["line:0", "track", "lips", "film"] : ["line:0", "track", "soundtrack", "clone", "lips", "mix", "film"]);expect(voiced.generations[run.ids["line:0"]].request.prompt).toContain("Hola, esto es una prueba");// The voice track is exactly as long as the source (read from its MP4 header when the session was made).expect(view.duration).toBeGreaterThan(1);@@ -285,6 +358,13 @@ describe("dub sessions (demo mode)", () => {// The background stem rides along to the mix.expect(voiced.generations[run.ids.film].request.inputs?.audio2).toMatch(/^\/api\/files\//);expect(voiced.generations[run.ids["line:0"]].request.inputs?.voiceAudio).toMatch(/^\/api\/files\//);+ } else {+ // The background split's stems that aren't the voice are mixed under the new one.+ const split = view.generations[view.prepare!.background];+ const bed = split.outputs.filter((o) => o.meta?.stem !== "voice").map((o) => o.url);+ expect(bed.length).toBeGreaterThan(0);+ expect(voiced.generations[run.ids.mix].request.inputs?.audios).toEqual(bed);+ expect(voiceOnly(view)).toBe(false);}expect(languageStage(voiced, "es")).toBe("voicing");expect((await settle(run.ids.film)).status).toBe("succeeded");@@ -334,6 +414,49 @@ describe("dub sessions (demo mode)", () => {expect(priceLine({ engine: "cloud", costUsd: 0, unpriced: [], demo: true, steps: 4 })).toBe("Demo · free");});+ it("cloud: a failed background split still reaches review and voices over silence (voice only)", async () => {+ const view = await prepared("cloud");+ // As if Demucs had failed: the stage stays "review", the media has no background and the dub says so.+ const failed = { ...view, generations: { ...view.generations, [view.prepare!.background]: { ...view.generations[view.prepare!.background], status: "failed" as const } } };+ expect(languageStage(failed, "es")).toBe("review");+ expect(prepareMedia(failed).background).toBeUndefined();+ expect(voiceOnly(failed)).toBe(true);+ // A cloud dub made before the split existed has no background step at all.+ const older = { ...view, prepare: Object.fromEntries(Object.entries(view.prepare!).filter(([k]) => k !== "sound" && k !== "background")) };+ expect(voiceOnly(older)).toBe(true);+ expect(languageStage(older, "es")).toBe("review");+ // While the split is still running the language waits (the voice is mixed over it).+ const running = { ...view, generations: { ...view.generations, [view.prepare!.background]: { ...view.generations[view.prepare!.background], status: "running" as const } } };+ expect(languageStage(running, "es")).toBe("preparing");+ // A failed transcript still fails the dub.+ const broken = { ...view, generations: { ...view.generations, [view.prepare!.words]: { ...view.generations[view.prepare!.words], status: "failed" as const } } };+ expect(languageStage(broken, "es")).toBe("failed");+ });++ it("prices the background split and the mix before they run", () => {+ setSetting("falKey", "test-key");+ try {+ const lines = [+ { start: 2, end: 4, text: "Hola a todos" },+ { start: 12, end: 15, text: "Esto es una prueba" },+ ];+ const prep = prepareSteps({ engine: "cloud", video: "/api/files/uploads/clip.mp4", targets: ["es"] });+ const split = dub.priceSteps("cloud", prep.filter((s) => s.key === "sound" || s.key === "background"), 30);+ // The soundtrack ($0.0002/s) and Demucs ($0.0007/s) for 30 s.+ expect(split.costUsd).toBeCloseTo(30 * 0.0002 + 30 * 0.0007, 3);+ expect(dub.priceSteps("cloud", prep, 30).costUsd).toBeCloseTo(dub.priceSteps("cloud", prep.filter((s) => s.key !== "sound" && s.key !== "background"), 30).costUsd + split.costUsd, 3);+ const voice = (background?: string[]) => voiceSteps({ engine: "cloud", video: "/api/files/uploads/clip.mp4", lang: "es", cues: lines, voiceRef: "/api/files/uploads/voice.mp3", background, duration: 30 });+ const alone = dub.priceSteps("cloud", voice(), 30);+ const mixed = dub.priceSteps("cloud", voice(["/api/files/a.mp3", "/api/files/b.mp3", "/api/files/c.mp3"]), 30);+ expect(mixed.steps).toBe(alone.steps + 2);+ // Lips at $8 a minute either way; the mix and putting it on the video add $0.0002/s each.+ expect(mixed.costUsd).toBeCloseTo(alone.costUsd + 2 * 30 * 0.0002, 3);+ expect(mixed.unpriced).toEqual([]);+ } finally {+ setSetting("falKey", "");+ }+ });+it("removing a dub stops the steps that haven't finished (nothing more is spent)", async () => {const s = dub.createDubSession({ engine: "cloud", mode: "steps", video: clip(), targets: ["es"] });const ids = Object.values(s.prepare!);