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 background sits 3 dB under its level, like the open route
Claude2eabd6ee56a3
diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxindex 1b61ea61..12575d69 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, voiceOnly, type DubPrice, type DubSessionView, type DubStage, type OneShotModel } from "@/lib/av/dub";+import { BACKGROUND_DB, 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";@@ -295,10 +295,13 @@ function voiceRows(s: DubSessionView, lang: string): StepRow[] {};const entries = Object.entries(run.ids);const lines = entries.filter(([k]) => k.startsWith("line:")).map(([, id]) => s.generations[id]);+ const beds = entries.filter(([k]) => k.startsWith("bed:")).map(([, id]) => s.generations[id]);const rows: StepRow[] = [];// One row for the takes: a dub of 30 lines would otherwise list 30 near-identical steps.if (lines.length) rows.push({ key: "lines", label: `${lines.length} line${lines.length === 1 ? "" : "s"} ${open ? "in their voice" : "spoken"}`, group: lines });- for (const [k, id] of entries) if (!k.startsWith("line:")) rows.push({ key: k, label: label[k] ?? k, g: s.generations[id] });+ // And one for the background stems, each lowered a little before the mix.+ if (beds.length) rows.push({ key: "beds", label: `Music and effects ${Math.abs(BACKGROUND_DB)} dB lower`, group: beds });+ for (const [k, id] of entries) if (!k.startsWith("line:") && !k.startsWith("bed:")) rows.push({ key: k, label: label[k] ?? k, g: s.generations[id] });return rows;}@@ -425,7 +428,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>}- {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>}+ {voiceOnly(s) && <p className="mt-2 text-[12px] text-muted-foreground">Voice only: no music or effects were separated from this clip, so the new voice plays alone.</p>}</Panel>);}@@ -525,7 +528,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>}+ {voiceOnly(s) && <p className="mt-3 text-[12px] text-muted-foreground">No music or effects were separated from this clip, 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 27c6ebbe..9ba412d7 100644--- a/src/lib/av/dub.ts+++ b/src/lib/av/dub.ts@@ -26,9 +26,10 @@ import { timelineFor } from "./timeline";* 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; 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.+ * that mix replaces the video's sound. Like the open mux, the background sits BACKGROUND_DB under its+ * original level: fal's compose has no volume control, so each stem is lowered first by fal's loudnorm+ * in linear mode (see linearGain). Dubs started before the background split, or whose split failed (or+ * found nothing but the voice), carry the dubbed voice only.*/export const DUB_FEATURE = "dub";@@ -48,6 +49,8 @@ export const DUB_STEP_MODELS = {timeline: "compose-timeline",soundtrack: "extract-soundtrack",clone: "chatterbox-vc-cloud",+ // Each background stem a little lower before the mix (compose has no volume control).+ level: "ffmpeg-loudnorm",lips: "sync-lipsync-3",mux: "merge-audio-video",},@@ -55,6 +58,22 @@ export const DUB_STEP_MODELS = {open: { stems: "oss-voice-separate", translate: "oss-text-llm", speech: "oss-chatterbox", timeline: "oss-audio-timeline", lips: "oss-infinitetalk-v2v", mux: "oss-mux" },} as const;+/** How far the background (music and effects) sits under its original level once the new voice is on, both engines. */+export const BACKGROUND_DB = -3;++/**+ * fal loudnorm parameters (ffmpeg's loudnorm filter) that change a track's level by `db` and nothing else.+ * In linear mode loudnorm doesn't measure: it trusts the measurements it's given and scales the whole+ * track by (target − measured_I) dB, as long as the "measured" true peak plus that gain stays under the+ * target peak and the "measured" range under the target range — true here. So the gain is exact whatever+ * the track's real loudness, with no dynamics and no limiter, which is why it only lowers (a raise could clip).+ */+export function linearGain(db: number): Record<string, number | boolean> {+ const gain = Math.min(0, db);+ const target = -24;+ return { linear: true, integrated_loudness: target, measured_i: target - gain, measured_tp: -12, measured_lra: 1, measured_thresh: target - 10, loudness_range: 7 };+}+/** The ElevenLabs voice the cloud route speaks with before it's converted into the speaker's own voice. */export const CLOUD_BASE_VOICE = "JBFqnCBsd6RMkjVDRZzb"; // George@@ -149,8 +168,8 @@ export interface VoiceInput {/** The clean voice to clone (the voice stem / isolated voice). */voiceRef: 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.+ * What the new voice is mixed over: the open engine's background stem, or on the cloud the Demucs stems+ * that aren't the voice (drums, bass, other). Either way it's lowered by BACKGROUND_DB.*/background?: string | string[];/** Re-sync the lips (default on). Off: the new voice is laid over the original picture. */@@ -210,8 +229,8 @@ 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", "lips"- * (open; cloud when it mixes a background), cloud "mix" (the voice over the background stems) and- * "film" (the dubbed video).+ * (open; cloud when it mixes a background), cloud "bed:0…" (each background stem lowered) and "mix"+ * (the voice over them), and "film" (the dubbed video).*/export function voiceSteps(o: VoiceInput): DubStep[] {const lang = languageByCode(o.lang);@@ -258,7 +277,7 @@ export function voiceSteps(o: VoiceInput): DubStep[] {op: "mux",inputs: { ...(lips ? {} : { video: o.video }), ...(beds[0] && { audio2: beds[0] }) },// The background stem sits a little under the new voice.- ...(beds[0] && { params: { extra: { backgroundVolumeDb: -3 } } }),+ ...(beds[0] && { params: { extra: { backgroundVolumeDb: BACKGROUND_DB } } }),step: step(tag("Dubbed video"), n - 1, n),},});@@ -266,7 +285,7 @@ export function voiceSteps(o: VoiceInput): DubStep[] {}const m = DUB_STEP_MODELS.cloud;const mixed = beds.length > 0;- const n = k + 3 + (mixed ? (lips ? 3 : 2) : 1);+ const n = k + 3 + (mixed ? beds.length + (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) => ({@@ -283,19 +302,27 @@ export function voiceSteps(o: VoiceInput): DubStep[] {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) } });+ // Each background stem lowered by BACKGROUND_DB (these start at once, next to the takes); the lips follow+ // the clean voice; the mix is a compose over the blank still with the voice and every lowered stem as+ // tracks of their own for the whole length, and its sound replaces the video's.+ const bedKeys = beds.map((_, i) => `bed:${i}`);+ beds.forEach((url, i) =>+ steps.push({+ key: bedKeys[i],+ request: { ...base, modelId: m.level, op: "level", inputs: { audio: url }, params: { extra: linearGain(BACKGROUND_DB) }, step: step(tag(`Music and effects ${i + 1} of ${beds.length}`), k + 3 + i, n) },+ }),+ );+ 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 + beds.length, n) } });const whole = { start: 0, duration: length };steps.push({key: "mix",- after: "clone",- chain: [{ slot: "audios", position: "first" }],+ after: ["clone", ...bedKeys],+ chain: ["clone", ...bedKeys].map(() => ({ slot: "audios" as const, position: "first" as const })),request: {...base,modelId: m.timeline,op: "timeline",- inputs: { images: [BLANK_FRAME], audios: beds },+ inputs: { images: [BLANK_FRAME] },params: { duration: length, extra: { timeline: { length, clips: [whole, ...beds.map(() => whole)] } } },step: step(tag("Over the music and effects"), n - 2, n),},@@ -466,11 +493,15 @@ export function prepareMedia(s: DubSessionView): { voice?: string; background?: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. */+/**+ * Whether a cloud step-by-step dub lost its music and effects: started before the split, the split+ * failed, or it found nothing but the voice. (While the split runs, the language is still preparing.)+ */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);+ if (!split || broken(split)) return true;+ return done(split) && !prepareMedia(s).background;}/** The finished dub of a language, if any. */diff --git a/tests/av-dub.test.ts b/tests/av-dub.test.tsindex b332be1b..dd549b6f 100644--- a/tests/av-dub.test.ts+++ b/tests/av-dub.test.ts@@ -4,7 +4,7 @@ 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, prepareMedia, prepareSteps, priceLine, reviewCues, spokenText, takeLines, voiceOnly, voiceSteps, type DubSessionView } from "@/lib/av/dub";+import { BLANK_FRAME, crowdedLines, linearGain, 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";@@ -188,7 +188,7 @@ 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", () => {+ it("cloud voice with the background: lips on the clean voice, the voice mixed over the lowered 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([@@ -198,18 +198,25 @@ describe("dub pipeline DAGs", () => {["track", "compose-timeline", "timeline", ["line:0", "line:1", "line:2"]],["soundtrack", "extract-soundtrack", "separate-audio", "track"],["clone", "chatterbox-vc-cloud", "voice-change", "soundtrack"],+ ["bed:0", "ffmpeg-loudnorm", "level", null],+ ["bed:1", "ffmpeg-loudnorm", "level", null],+ ["bed:2", "ffmpeg-loudnorm", "level", null],["lips", "sync-lipsync-3", "lipsync", "clone"],- ["mix", "compose-timeline", "timeline", "clone"],+ ["mix", "compose-timeline", "timeline", ["clone", "bed:0", "bed:1", "bed:2"]],["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(steps.map((s) => s.request.step?.index)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);+ expect(steps.every((s) => s.request.step?.of === 12)).toBe(true);+ // Each stem 3 dB down, like the open route's background (compose itself has no volume control).+ expect(steps.slice(6, 9).map((s) => s.request.inputs)).toEqual(beds.map((audio) => ({ audio })));+ expect(steps[6].request.params).toEqual({ extra: linearGain(-3) });+ expect(steps[6].request.step?.label).toBe("Music and effects 1 of 3 · Japanese");+ const [lips, mix, film] = steps.slice(9);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 });+ // The new voice goes first, then every lowered stem, each for the whole length (so compose mixes them).+ expect(mix.chain).toEqual(Array(4).fill({ slot: "audios", position: "first" }));+ expect(mix.request.inputs).toEqual({ images: [BLANK_FRAME] });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();@@ -226,12 +233,36 @@ describe("dub pipeline DAGs", () => {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"],+ ["bed:0", undefined],+ ["bed:1", undefined],+ ["bed:2", undefined],+ ["mix", ["clone", "bed:0", "bed:1", "bed:2"]],["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);+ expect(flat.every((s) => s.request.step?.of === 11)).toBe(true);+ expect(flat.map((s) => s.request.step?.index)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);+ });++ it("lowers a track by an exact gain with loudnorm's linear mode (target − measured), never raising it", () => {+ const p = linearGain(-3);+ // ffmpeg's loudnorm takes linear mode when measured TP + gain ≤ target TP (−0.1 on fal) and measured LRA ≤ target LRA.+ expect(p).toMatchObject({ linear: true });+ expect(Number(p.integrated_loudness) - Number(p.measured_i)).toBe(-3);+ expect(Number(p.measured_tp) - 3).toBeLessThanOrEqual(-0.1);+ expect(Number(p.measured_lra)).toBeGreaterThan(0);+ expect(Number(p.measured_lra)).toBeLessThanOrEqual(Number(p.loudness_range));+ expect(p.measured_thresh).not.toBe(-70);+ // Inside fal's ranges.+ expect(Number(p.integrated_loudness)).toBeGreaterThanOrEqual(-70);+ expect(Number(p.measured_i)).toBeLessThanOrEqual(0);+ expect(Number(p.measured_thresh)).toBeGreaterThanOrEqual(-99);+ // A raise would clip with no limiter: it's held at 0 dB.+ expect(Number(linearGain(6).integrated_loudness) - Number(linearGain(6).measured_i)).toBe(0);+ // The payload fal gets: the stem as audio_url with the parameters as they are.+ const body = buildPayload(getModel("ffmpeg-loudnorm")!.routes[0].map!, { audio: "https://a/drums.mp3", extra: p });+ expect(body).toEqual({ audio_url: "https://a/drums.mp3", ...p });});it("timeline tracks: lines that follow each other share the voice track, overlapping clips get tracks of their own", () => {@@ -348,7 +379,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", "lips", "mix", "film"]);+ expect(Object.keys(run.ids)).toEqual(engine === "open" ? ["line:0", "track", "lips", "film"] : ["line:0", "bed: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);@@ -363,7 +394,11 @@ describe("dub sessions (demo mode)", () => {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);+ // Each lowered first: the mix takes the new voice, then the lowered stems.+ const levelled = bed.map((_, i) => voiced.generations[run.ids[`bed:${i}`]]);+ expect(levelled.map((g) => [g.modelId, g.request.inputs?.audio])).toEqual(bed.map((url) => ["ffmpeg-loudnorm", url]));+ expect(voiced.generations[run.ids.mix].request.inputs?.images).toEqual([BLANK_FRAME]);+ expect((await settle(run.ids.mix)).request.inputs?.audios).toEqual([(await settle(run.ids.clone)).outputs[0].url, ...(await Promise.all(levelled.map(async (g) => (await settle(g.id)).outputs[0].url)))]);expect(voiceOnly(view)).toBe(false);}expect(languageStage(voiced, "es")).toBe("voicing");@@ -421,6 +456,13 @@ describe("dub sessions (demo mode)", () => {expect(languageStage(failed, "es")).toBe("review");expect(prepareMedia(failed).background).toBeUndefined();expect(voiceOnly(failed)).toBe(true);+ // A split that found nothing but the voice leaves nothing to mix under it: voice only too.+ const split = view.generations[view.prepare!.background];+ const vocals = { ...view, generations: { ...view.generations, [split.id]: { ...split, outputs: split.outputs.filter((o) => o.meta?.stem === "voice") } } };+ expect(languageStage(vocals, "es")).toBe("review");+ expect(prepareMedia(vocals).background).toBeUndefined();+ expect(voiceOnly(vocals)).toBe(true);+ expect(voiceOnly(view)).toBe(false);// 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);@@ -448,8 +490,8 @@ describe("dub sessions (demo mode)", () => {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.steps).toBe(alone.steps + 5);+ // Lips at $8 a minute either way; levelling the stems is free, 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 {