Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Dub: the new voice follows the reviewed cue timing on both engines

Claude31e6a35ac640
diff --git a/scripts/comfy/hand-built/audio-timeline.json b/scripts/comfy/hand-built/audio-timeline.json
new file mode 100644
index 00000000..6953e14a
--- /dev/null
+++ b/scripts/comfy/hand-built/audio-timeline.json
@@ -0,0 +1,94 @@
+{
+ "1": {
+ "class_type": "EmptyAudio",
+ "inputs": {
+ "duration": 10.0,
+ "sample_rate": 44100,
+ "channels": 2
+ },
+ "_meta": {
+ "title": "The track: silence as long as the video (duration)"
+ }
+ },
+ "2": {
+ "class_type": "LoadAudio",
+ "inputs": {
+ "audio": "line.wav"
+ },
+ "_meta": {
+ "title": "A spoken line (audio; the provider adds one per line)"
+ }
+ },
+ "3": {
+ "class_type": "TrimAudioDuration",
+ "inputs": {
+ "audio": [
+ "2",
+ 0
+ ],
+ "start_index": 0.0,
+ "duration": 600.0
+ },
+ "_meta": {
+ "title": "Cut where the next line starts"
+ }
+ },
+ "4": {
+ "class_type": "EmptyAudio",
+ "inputs": {
+ "duration": 0.5,
+ "sample_rate": 44100,
+ "channels": 2
+ },
+ "_meta": {
+ "title": "Silence before the line (startTime)"
+ }
+ },
+ "5": {
+ "class_type": "AudioConcat",
+ "inputs": {
+ "audio1": [
+ "4",
+ 0
+ ],
+ "audio2": [
+ "3",
+ 0
+ ],
+ "direction": "after"
+ },
+ "_meta": {
+ "title": "The line at its start time"
+ }
+ },
+ "6": {
+ "class_type": "AudioMerge",
+ "inputs": {
+ "audio1": [
+ "1",
+ 0
+ ],
+ "audio2": [
+ "5",
+ 0
+ ],
+ "merge_method": "add"
+ },
+ "_meta": {
+ "title": "Laid on the track (cut or padded to its length)"
+ }
+ },
+ "7": {
+ "class_type": "SaveAudio",
+ "inputs": {
+ "audio": [
+ "6",
+ 0
+ ],
+ "filename_prefix": "fuobe/audio-timeline"
+ },
+ "_meta": {
+ "title": "Save the track (FLAC, lossless: no encoder delay shifts the lines)"
+ }
+ }
+}
diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjs
index a3c9eb69..53cdc07a 100644
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@ -2356,4 +2356,23 @@ export const SPEC = [
'then Qwen-Image-Edit 2509 + Lightning (4 steps, cfg 1) + dx8152 White_to_Scene LoRA (trigger "白底图转场景," = "white background to scene", prefixed by node 1002) places and relights it in the scene the prompt describes. ' +
'The open route of the Product shot app (Bria Product Shot / Product Photography on the cloud).',
},
+ {
+ id: 'audio-timeline',
+ title: 'Voice track on the video\'s timeline: spoken lines placed at their start times over silence (core audio nodes)',
+ capability: 'timeline',
+ handBuilt: 'hand-built/audio-timeline.json',
+ bindings: {
+ audio: [b('2', 'audio')], duration: [b('1', 'duration')], startTime: [b('4', 'duration')],
+ },
+ outputs: [{ node: '7', kind: 'audio' }],
+ expand: 'timeline',
+ vramGb: 0,
+ license: 'n/a (no model; ComfyUI core audio nodes)',
+ notes:
+ 'The dub voice track, all core nodes. The template places one line: EmptyAudio of the video\'s length (duration) is the track, the line (audio) is cut where the next line starts ' +
+ '(TrimAudioDuration), put after startTime seconds of silence (AudioConcat after EmptyAudio) and added onto the track (AudioMerge add: pads or cuts the line to the track). ' +
+ 'The provider rewrites the graph per request (expandTimelineWorkflow, src/lib/av/timeline.ts): params.extra.timeline = {length, clips:[{start, duration}]} with one inputs.audios clip per entry, ' +
+ 'each loaded, cut, led in and added in turn, so the saved track is exactly as long as the video with every line at its cue time (pauses kept). ' +
+ 'SaveAudio writes FLAC (lossless, no MP3 priming delay). Feeds lip re-sync (InfiniteTalk frames = the track\'s length = the video\'s) and video-mux-audio. Runs on CPU.',
+ },
];
diff --git a/scripts/comfy/validation-state.json b/scripts/comfy/validation-state.json
index a804b515..b6d26e56 100644
--- a/scripts/comfy/validation-state.json
+++ b/scripts/comfy/validation-state.json
@@ -1,4 +1,10 @@
{
+ "audio-timeline": {
+ "sha256": "b483019231d6add28874dc3c835a85726eaccdaf0c1d60c0d2f0431159a7711a",
+ "validated": true,
+ "error": null,
+ "at": "2026-10-21T15:16:09.609Z"
+ },
"bg-remove-birefnet": {
"sha256": "8d12248b956c8cd91d207b5ec9a8585c681259aff216ac38745fa4bffdaae988",
"validated": true,
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index 623f8fa9..88d37452 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -523,6 +523,12 @@ model("whisper", "Whisper large-v3", "OpenAI", "whisper", "text", "Whisper large
model("demucs", "Demucs stem split", "Meta", "demucs", "audio", "Split a track into vocals, drums, bass and the rest",
[("separate-audio", "fal-ai/demucs")], fixed={"model": "htdemucs"})
# Translate & dub (cloud, step by step): the clean voice straight from the video, to clone in the new language.
+# The cloud dub's voice track (av-tools): the spoken lines placed at their cue times over a still for the video's
+# length (compose renders a video), then its soundtrack read back as audio for voice conversion and lip re-sync.
+model("compose-timeline", "Voice timeline", "fal", "utility", "video", "Place audio clips at their start times on a timeline",
+ [("timeline", "fal-ai/ffmpeg-api/compose")], pricing=("second", 0.0002), hidden=True)
+model("extract-soundtrack", "Extract soundtrack", "fal", "utility", "audio", "A video's soundtrack as an audio file",
+ [("separate-audio", "fal-ai/workflow-utilities/extract-audio")], pricing=("second", 0.0002, "billed by compute time"), hidden=True)
model("elevenlabs-voice-isolation", "ElevenLabs Voice Isolation", "ElevenLabs", "elevenlabs", "audio", "Clean speech from a video or recording — music and noise removed",
[("separate-audio", "fal-ai/elevenlabs/audio-isolation")], pricing=("minute", 0.1))
@@ -796,6 +802,9 @@ def build_route(op, ep, provider, m, opts, ropts=None):
fmap["styleId"] = kf["styleId"]
if "numLayers" in kf:
fmap["numLayers"] = kf["numLayers"]
+ # fal compose: the timeline's tracks are built from the clips and their start times (FieldMap.timeline).
+ if "tracks" in kf and op == "timeline":
+ fmap["timeline"] = kf["tracks"]
if "palette" in kf:
fmt = palette_format(inputs.get(kf["palette"]))
if fmt:
diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.ts
index 771da13a..88efd6d9 100644
--- a/src/app/api/dub/[id]/voice/route.ts
+++ b/src/app/api/dub/[id]/voice/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { CueSchema, getDubSession, voiceDub } from "@/server/dub";
+import { CueSchema, getDubSession, previewVoiceDub, voiceDub } from "@/server/dub";
const Body = z.object({
lang: z.string().min(2).max(12),
@@ -8,14 +8,16 @@ const Body = z.object({
lipsync: z.boolean().optional(),
});
-/** Speak one language's reviewed lines in the cloned voice: the voice pipeline. */
+/** Speak one language's reviewed lines in the cloned voice: the voice pipeline; `?preview=1` only prices it. */
export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">) {
const { id } = await ctx.params;
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Pick the language to voice" }, { status: 400 });
if (!getDubSession(id)) return Response.json({ error: "Not found" }, { status: 404 });
try {
- return Response.json(voiceDub(id, parsed.data.lang, { cues: parsed.data.cues, lipsync: parsed.data.lipsync }), { status: 201 });
+ const opts = { cues: parsed.data.cues, lipsync: parsed.data.lipsync };
+ if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewVoiceDub(id, parsed.data.lang, opts));
+ return Response.json(voiceDub(id, parsed.data.lang, opts), { status: 201 });
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 422 });
}
diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.ts
index 74b3f554..d0ed2bdb 100644
--- a/src/app/api/dub/route.ts
+++ b/src/app/api/dub/route.ts
@@ -1,7 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
import { ONE_SHOT_MODELS } from "@/lib/av/dub";
-import { createDubSession, listDubSessions } from "@/server/dub";
+import { createDubSession, listDubSessions, previewDub } from "@/server/dub";
const Body = z.object({
engine: z.enum(["cloud", "open"]),
@@ -11,6 +11,8 @@ const Body = z.object({
source: z.string().max(12).optional(),
targets: z.array(z.string().min(2).max(12)).min(1).max(8),
model: z.enum(ONE_SHOT_MODELS).optional(),
+ /** The video's length as the browser measured it (seconds). */
+ duration: z.number().positive().max(36_000).optional(),
});
/** Recent dubs with the state of every step. */
@@ -20,7 +22,7 @@ export async function GET(request: Request) {
return Response.json({ items: listDubSessions(Number.isFinite(limit) ? limit : 30) });
}
-/** Start a dub: one-shot jobs (cloud) or the prepare pipeline (both engines). */
+/** Start a dub: one-shot jobs (cloud) or the prepare pipeline (both engines); `?preview=1` only prices it. */
export async function POST(request: Request) {
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
@@ -29,6 +31,7 @@ export async function POST(request: Request) {
return Response.json({ error: msg }, { status: 400 });
}
try {
+ if (new URL(request.url).searchParams.get("preview") === "1") return Response.json(previewDub(parsed.data));
return Response.json(createDubSession(parsed.data), { status: 201 });
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: 422 });
diff --git a/src/lib/av/dub.ts b/src/lib/av/dub.ts
index 09aeadb8..4022ec2a 100644
--- a/src/lib/av/dub.ts
+++ b/src/lib/av/dub.ts
@@ -1,6 +1,7 @@
import type { Cue } from "@/lib/cues";
import type { ChainSlot, Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { languageByCode, supportsTarget, type DubLanguage, type DubRoute } from "./languages";
+import { timelineFor } from "./timeline";
/**
* Translate & dub, planned as plain data (client and server). Two ways to dub:
@@ -11,14 +12,20 @@ import { languageByCode, supportsTarget, type DubLanguage, type DubRoute } from
* review: the person edits the translated lines (nothing is spoken yet)
* voice: speech in the cloned voice → lips re-synced → the new voice over the background
*
- * Open engine: MelBand RoFormer splits voice and background (oss-voice-separate), Qwen3-ASR times the
- * voice stem, the local LLM translates the cues (oss-text-llm), Chatterbox Multilingual speaks in the
- * cloned voice, 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 it and Chatterbox voice conversion turns it into the speaker's voice,
- * Sync Lipsync 3 re-syncs the lips. No cloud model in the catalog mixes two audio tracks (fal's
- * merge-audio-video takes one), so the cloud result carries the dubbed voice only — the background
- * music and effects are kept by the open route and by the one-shot models.
+ * The new voice follows the reviewed timing: the lines are grouped into phrases (lines less than
+ * PHRASE_GAP apart are spoken in one take), each phrase is spoken on its own and placed at its cue's
+ * start on a silent track exactly as long as the source (the "timeline" step), so pauses are kept, the
+ * lip re-sync covers the whole clip and the dubbed video is as long as the original.
+ *
+ * Open engine: MelBand RoFormer splits voice and background and Qwen3-ASR 1.7B times the voice stem, in
+ * one job (oss-voice-separate); the local LLM translates the cues (oss-text-llm); Chatterbox Multilingual
+ * 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
+ * (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.
*/
export const DUB_FEATURE = "dub";
@@ -27,13 +34,27 @@ export const ONE_SHOT_MODELS = ["heygen-translate", "heygen-translate-fast", "el
export type OneShotModel = (typeof ONE_SHOT_MODELS)[number];
export const DUB_STEP_MODELS = {
- cloud: { voice: "elevenlabs-voice-isolation", words: "scribe-v2", translate: "text-llm", speech: "elevenlabs-v4", clone: "chatterbox-vc-cloud", lips: "sync-lipsync-3", mux: "merge-audio-video" },
- open: { stems: "oss-voice-separate", words: "oss-qwen3-asr", translate: "oss-text-llm", speech: "oss-chatterbox", lips: "oss-infinitetalk-v2v", mux: "oss-mux" },
+ cloud: {
+ voice: "elevenlabs-voice-isolation",
+ words: "scribe-v2",
+ translate: "text-llm",
+ speech: "elevenlabs-v4",
+ timeline: "compose-timeline",
+ soundtrack: "extract-soundtrack",
+ clone: "chatterbox-vc-cloud",
+ lips: "sync-lipsync-3",
+ mux: "merge-audio-video",
+ },
+ // The stems step also times the voice (Qwen3-ASR 1.7B + forced aligner inside the same workflow).
+ 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;
/** 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
+/** A 64×64 black PNG: the picture fal's compose renders the cloud voice track over (only its soundtrack is kept). */
+export const BLANK_FRAME = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAAAAACPAi4CAAAAG0lEQVR42u3BgQAAAADDoPlT3+AEVQEAAAB8AxBAAAG9PLePAAAAAElFTkSuQmCC";
+
export interface DubStep {
key: string;
request: GenerationRequest;
@@ -73,7 +94,7 @@ export function prepareSteps(o: PrepareInput): DubStep[] {
const from = languageByCode(source)?.name;
const n = targets.length + 2;
const base = { feature: DUB_FEATURE, ...(o.title && { batchTitle: o.title }) };
- const translate = (lang: DubLanguage, i: number, after: string): DubStep => ({
+ const translate = (lang: DubLanguage, i: number, after: string, of = n): DubStep => ({
key: translateKey(lang.code),
after,
chain: [{ slot: "prompt" }],
@@ -82,16 +103,17 @@ export function prepareSteps(o: PrepareInput): DubStep[] {
modelId: o.engine === "open" ? DUB_STEP_MODELS.open.translate : DUB_STEP_MODELS.cloud.translate,
op: "translate",
params: { targetLanguage: lang.name, ...(from && { sourceLanguage: from }) },
- step: step(`Translate · ${lang.name}`, i, n),
+ step: step(`Translate · ${lang.name}`, i, of),
},
});
const lang = source ? { params: { sourceLanguage: source } } : {};
// The transcript is made from the clean voice stem (music and effects removed), so the timings follow the speech.
if (o.engine === "open") {
+ // One job splits the stems and times the voice stem (Qwen3-ASR 1.7B); the translations read its cues.
+ const m = targets.length + 1;
return [
- { key: "stems", request: { ...base, modelId: DUB_STEP_MODELS.open.stems, op: "separate-audio", inputs: { video: o.video }, step: step("Voice and background", 0, n) } },
- { key: "words", after: "stems", chain: [{ slot: "audio", stem: "voice" }], request: { ...base, modelId: DUB_STEP_MODELS.open.words, op: "transcribe", ...lang, step: step("Transcript", 1, n) } },
- ...targets.map((l, i) => translate(l, i + 2, "words")),
+ { key: "stems", request: { ...base, modelId: DUB_STEP_MODELS.open.stems, op: "separate-audio", inputs: { video: o.video }, ...lang, step: step("Voice, background and transcript", 0, m) } },
+ ...targets.map((l, i) => translate(l, i + 1, "stems", m)),
];
}
return [
@@ -113,6 +135,8 @@ export interface VoiceInput {
background?: 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. */
+ duration?: number;
title?: string;
}
@@ -124,31 +148,87 @@ export function spokenText(cues: Cue[]): string {
.join("\n");
}
-/** Step 2: speak the reviewed translation in the cloned voice, re-sync the lips and put the new voice on the video. */
+/** Lines closer than this (seconds) are one breath: spoken in one take, so the speech flows. */
+export const PHRASE_GAP = 0.4;
+/** A take this long (seconds) starts a new phrase anyway, so long speech re-syncs to the cues often. */
+export const PHRASE_MAX = 12;
+
+/** One take of the new voice: it starts at `start`; `end` is where its lines end in the source. */
+export interface DubPhrase {
+ start: number;
+ end: number;
+ text: string;
+}
+
+/**
+ * The reviewed lines as takes: lines less than PHRASE_GAP apart join (up to PHRASE_MAX seconds), empty
+ * lines are skipped and lines at or past the end of the video (when its length is known) are dropped.
+ */
+export function dubPhrases(cues: Cue[], length?: number): DubPhrase[] {
+ const lines = cues
+ .map((c) => ({ start: Math.max(0, c.start), end: Math.max(c.start, c.end), text: c.text.replace(/\s+/g, " ").trim() }))
+ .filter((c) => c.text && (!length || c.start < length))
+ .sort((a, b) => a.start - b.start);
+ const out: DubPhrase[] = [];
+ for (const c of lines) {
+ const last = out.at(-1);
+ if (last && c.start - last.end < PHRASE_GAP && c.end - last.start <= PHRASE_MAX) {
+ last.end = Math.max(last.end, c.end);
+ last.text = `${last.text} ${c.text}`;
+ } else out.push({ ...c });
+ }
+ return out;
+}
+
+/** The voice track's length: the video's, else a second past the last line. */
+export function trackLength(phrases: DubPhrase[], duration?: number): number {
+ if (duration && duration > 0) return duration;
+ return Math.ceil(((phrases.at(-1)?.end ?? 0) + 1) * 10) / 10;
+}
+
+/**
+ * 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).
+ */
export function voiceSteps(o: VoiceInput): DubStep[] {
const lang = languageByCode(o.lang);
if (!lang) throw new Error(`Unknown language “${o.lang}”`);
- const text = spokenText(o.cues);
- if (!text) throw new Error("There are no lines to speak — write at least one");
+ if (o.engine === "open" && !supportsTarget("open", lang)) throw new Error(`${lang.name} isn't available on the open engine`);
+ const phrases = dubPhrases(o.cues, o.duration);
+ if (!phrases.length) throw new Error(o.cues.some((c) => c.text.trim()) ? "Every line starts after the end of the video — check the times" : "There are no lines to speak — write at least one");
+ const length = trackLength(phrases, o.duration);
+ const timeline = timelineFor(
+ phrases.map((p) => p.start),
+ length,
+ );
const lips = o.lipsync !== false;
const base = { feature: DUB_FEATURE, ...(o.title && { batchTitle: o.title }) };
const tag = (label: string) => `${label} · ${lang.name}`;
+ const k = phrases.length;
+ const lineKeys = phrases.map((_, i) => `line:${i}`);
+ // Every take at its cue time over silence as long as the video.
+ const track = (modelId: string, of: number, inputs?: GenerationRequest["inputs"]): DubStep => ({
+ key: "track",
+ after: lineKeys,
+ chain: lineKeys.map(() => ({ slot: "audios" as const })),
+ request: { ...base, modelId, op: "timeline", ...(inputs && { inputs }), params: { duration: length, extra: { timeline } }, step: step(tag("Voice on the timeline"), k, of) },
+ });
if (o.engine === "open") {
- if (!supportsTarget("open", lang)) throw new Error(`${lang.name} isn't available on the open engine`);
const m = DUB_STEP_MODELS.open;
- const n = lips ? 3 : 2;
- const steps: DubStep[] = [
- {
- key: "speech",
- request: { ...base, modelId: m.speech, op: "tts", prompt: text, inputs: { voiceAudio: o.voiceRef }, params: { targetLanguage: lang.chatterbox }, step: step(tag("Voice"), 0, n) },
- },
- ];
+ const n = k + (lips ? 3 : 2);
+ const steps: DubStep[] = phrases.map((p, i) => ({
+ key: lineKeys[i],
+ request: { ...base, modelId: m.speech, op: "tts", prompt: p.text, inputs: { voiceAudio: o.voiceRef }, params: { targetLanguage: lang.chatterbox }, step: step(tag(`Line ${i + 1} of ${k}`), i, n) },
+ }));
+ steps.push(track(m.timeline, n));
if (lips) {
- steps.push({ key: "lips", after: "speech", chain: [{ slot: "audio" }], request: { ...base, modelId: m.lips, op: "lipsync", inputs: { video: o.video }, step: step(tag("Lips"), 1, n) } });
+ steps.push({ key: "lips", after: "track", chain: [{ slot: "audio" }], request: { ...base, modelId: m.lips, op: "lipsync", inputs: { video: o.video }, step: step(tag("Lips"), k + 1, n) } });
}
steps.push({
key: "film",
- after: lips ? ["lips", "speech"] : "speech",
+ after: lips ? ["lips", "track"] : "track",
chain: lips ? [{ slot: "video" }, { slot: "audio" }] : [{ slot: "audio" }],
request: {
...base,
@@ -163,16 +243,19 @@ export function voiceSteps(o: VoiceInput): DubStep[] {
return steps;
}
const m = DUB_STEP_MODELS.cloud;
- const n = 3;
- const steps: DubStep[] = [
- { key: "speech", request: { ...base, modelId: m.speech, op: "tts", prompt: text, params: { voice: CLOUD_BASE_VOICE }, step: step(tag("Speech"), 0, n) } },
- { key: "clone", after: "speech", chain: [{ slot: "audio" }], request: { ...base, modelId: m.clone, op: "voice-change", inputs: { voiceAudio: o.voiceRef }, step: step(tag("Their voice"), 1, n) } },
- ];
- steps.push(
- lips
- ? { key: "film", after: "clone", chain: [{ slot: "audio" }], request: { ...base, modelId: m.lips, op: "lipsync", inputs: { video: o.video }, step: step(tag("Dubbed video"), 2, n) } }
- : { key: "film", after: "clone", chain: [{ slot: "audio" }], request: { ...base, modelId: m.mux, op: "mux", inputs: { video: o.video }, step: step(tag("Dubbed video"), 2, n) } },
- );
+ const n = k + 4;
+ // 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) => ({
+ key: lineKeys[i],
+ request: { ...base, modelId: m.speech, op: "tts", prompt: p.text, params: { voice: CLOUD_BASE_VOICE }, step: step(tag(`Line ${i + 1} of ${k}`), i, n) },
+ }));
+ // fal's compose renders a video: the track goes over a blank still and its soundtrack is read back as audio.
+ 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) } });
return steps;
}
@@ -216,6 +299,8 @@ export interface DubSession {
source: string;
targets: string[];
model?: OneShotModel;
+ /** Length of the source video (seconds), when known: the dubbed voice track is made this long. */
+ duration?: number;
batchId: string;
/** Step mode: the prepare pipeline's generation ids by step key. */
prepare?: Record<string, string>;
@@ -231,6 +316,44 @@ export interface DubSession {
export type DubStage = "preparing" | "review" | "voicing" | "done" | "failed";
+/** What a dub step (prepare or voice) costs before it runs. */
+export interface DubPrice {
+ engine: Engine;
+ /** What the priced steps cost together (USD); 0 on the open engine. */
+ costUsd: number;
+ /** Models with no listed price (ElevenLabs speech per character, the LLM's tokens): not in costUsd. */
+ unpriced: string[];
+ /** The steps would run as a demo (no key / no GPU): free. */
+ demo: boolean;
+ steps: number;
+}
+
+/** The price as one short line: "≈ $8.13 + ElevenLabs v4", "Demo · free", "Free on your GPU". */
+export function priceLine(p: DubPrice): string {
+ if (p.demo) return "Demo · free";
+ if (p.engine === "open") return "Free on your GPU";
+ const usd = p.costUsd > 0 && p.costUsd < 0.01 ? "< $0.01" : `≈ $${p.costUsd.toFixed(2)}`;
+ return p.unpriced.length ? `${usd} + ${p.unpriced.join(" + ")}` : usd;
+}
+
+/** Characters a voice speaks per second, about (used to flag lines that won't fit before the next one). */
+const SPOKEN_CPS = 16;
+
+/** Takes whose words likely run past the next take's start (it would be cut there): their first line's index. */
+export function crowdedLines(cues: Cue[], duration?: number): number[] {
+ const phrases = dubPhrases(cues, duration);
+ const length = trackLength(phrases, duration);
+ const out: number[] = [];
+ phrases.forEach((p, i) => {
+ const room = (i + 1 < phrases.length ? phrases[i + 1].start : length) - p.start;
+ if (p.text.length / SPOKEN_CPS > room + 0.25) {
+ const first = cues.findIndex((c) => Math.max(0, c.start) === p.start && c.text.trim());
+ if (first >= 0) out.push(first);
+ }
+ });
+ return out;
+}
+
/** A session with its generations, as the studio shows it. */
export interface DubSessionView extends DubSession {
generations: Record<string, Generation>;
diff --git a/src/lib/av/timeline.ts b/src/lib/av/timeline.ts
new file mode 100644
index 00000000..730b9185
--- /dev/null
+++ b/src/lib/av/timeline.ts
@@ -0,0 +1,117 @@
+import type { ComfyWorkflow } from "@/lib/comfy";
+
+/**
+ * A voice track on the video's own timeline: audio clips (one per spoken line) placed at their start
+ * times over silence as long as the video. Each clip plays for at most `duration` seconds (up to the
+ * next line, so two lines never talk over each other) and the track is exactly `length` seconds, so
+ * lip re-sync and the mux keep the whole picture. Plain data, read by both providers:
+ * - ComfyUI (open engine): the audio-timeline workflow, expanded per clip (expandTimelineWorkflow);
+ * - fal (cloud): ffmpeg compose `tracks` (timelineTracks), rendered over a still and read back as audio.
+ */
+export interface TimelineClip {
+ /** Seconds from the start of the video. */
+ start: number;
+ /** How long the clip may play (seconds); its tail past this is cut. */
+ duration: number;
+}
+
+export interface TimelineSpec {
+ /** Length of the track: the video's (seconds). */
+ length: number;
+ clips: TimelineClip[];
+}
+
+const finite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n);
+const round = (n: number) => Math.round(n * 1000) / 1000;
+
+/** A timeline from params.extra.timeline, checked; null when it isn't one. */
+export function readTimeline(v: unknown): TimelineSpec | null {
+ if (!v || typeof v !== "object") return null;
+ const t = v as Partial<TimelineSpec>;
+ if (!finite(t.length) || t.length <= 0 || !Array.isArray(t.clips) || !t.clips.length) return null;
+ const clips = t.clips.map((c) => ({ start: Number((c as TimelineClip)?.start), duration: Number((c as TimelineClip)?.duration) }));
+ if (clips.some((c) => !finite(c.start) || !finite(c.duration) || c.start < 0 || c.duration <= 0 || c.start >= t.length!)) return null;
+ return { length: t.length, clips };
+}
+
+/**
+ * Place clips that start at `starts` on a track `length` seconds long: each may play until the next
+ * one starts (or the end of the track).
+ */
+export function timelineFor(starts: number[], length: number): TimelineSpec {
+ const clips = starts.map((start, i) => {
+ const s = Math.max(0, Math.min(start, length));
+ const next = i + 1 < starts.length ? Math.min(starts[i + 1], length) : length;
+ return { start: round(s), duration: round(Math.max(0.05, next - s)) };
+ });
+ return { length: round(length), clips };
+}
+
+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.
+ */
+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}`);
+ 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) })) },
+ ];
+}
+
+/** ComfyUI handles many hundreds of nodes; a dub is a few dozen lines. */
+export const MAX_TIMELINE_CLIPS = 400;
+
+/**
+ * Rewrite the audio-timeline template (EmptyAudio track → AudioMerge ← AudioConcat(EmptyAudio lead,
+ * TrimAudioDuration(LoadAudio)) → SaveAudio) for every clip: clip i is loaded, cut to its duration,
+ * put after `start` seconds of silence and added onto the track so far. Starts at 0 skip the lead.
+ */
+export function expandTimelineWorkflow(wf: ComfyWorkflow, names: string[], spec: TimelineSpec): ComfyWorkflow {
+ if (names.length !== spec.clips.length) throw new Error(`The timeline places ${spec.clips.length} clip${spec.clips.length === 1 ? "" : "s"} but got ${names.length}`);
+ if (names.length > MAX_TIMELINE_CLIPS) throw new Error(`A timeline takes up to ${MAX_TIMELINE_CLIPS} clips`);
+ const ids = Object.keys(wf);
+ const first = (cls: string) => ids.find((id) => wf[id].class_type === cls);
+ const source = (id: string | undefined, input: string) => {
+ const v = id ? wf[id].inputs[input] : undefined;
+ return Array.isArray(v) && typeof v[0] === "string" ? v[0] : undefined;
+ };
+ const loader = first("LoadAudio");
+ const cut = first("TrimAudioDuration");
+ const concat = first("AudioConcat");
+ const merge = first("AudioMerge");
+ const save = ids.find((id) => /^SaveAudio/.test(wf[id].class_type));
+ // The track is the silence the merge starts from; the lead is the silence put before a line.
+ const trackId = source(merge, "audio1");
+ const leadId = source(concat, "audio1");
+ if (!loader || !cut || !concat || !merge || !save || !trackId || !leadId || wf[trackId]?.class_type !== "EmptyAudio" || wf[leadId]?.class_type !== "EmptyAudio") {
+ throw new Error("Not an audio timeline workflow (needs EmptyAudio → AudioMerge ← AudioConcat(EmptyAudio, TrimAudioDuration(LoadAudio)) → SaveAudio)");
+ }
+ const node = (id: string) => structuredClone(wf[id]);
+ const out: ComfyWorkflow = {};
+ out[trackId] = node(trackId);
+ out[trackId].inputs.duration = spec.length;
+ let last = trackId;
+ spec.clips.forEach((c, i) => {
+ const n = i + 1;
+ const load = `t${n}_load`;
+ out[load] = { ...node(loader), inputs: { ...wf[loader].inputs, audio: names[i] }, _meta: { title: `Line ${n}` } };
+ const trimmed = `t${n}_cut`;
+ out[trimmed] = { ...node(cut), inputs: { ...wf[cut].inputs, audio: [load, 0], start_index: 0, duration: c.duration } };
+ let placed: string = trimmed;
+ if (c.start > 0) {
+ const silence = `t${n}_lead`;
+ out[silence] = { ...node(leadId), inputs: { ...wf[leadId].inputs, duration: c.start } };
+ placed = `t${n}_at`;
+ out[placed] = { ...node(concat), inputs: { ...wf[concat].inputs, audio1: [silence, 0], audio2: [trimmed, 0], direction: "after" } };
+ }
+ const added = `t${n}_add`;
+ out[added] = { ...node(merge), inputs: { ...wf[merge].inputs, audio1: [last, 0], audio2: [placed, 0] }, _meta: { title: `Line ${n} at ${c.start}s` } };
+ last = added;
+ });
+ out[save] = node(save);
+ out[save].inputs.audio = [last, 0];
+ return out;
+}
diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.ts
index b4600084..9931e5bb 100644
--- a/src/lib/catalog/canvas.ts
+++ b/src/lib/catalog/canvas.ts
@@ -610,6 +610,7 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {
audio: "audio",
voiceAudio: "audio",
audio2: "audio",
+ audios: "audio",
prompt: "text",
};
@@ -618,7 +619,7 @@ export function withPlaceholders(req: GenerationRequest): GenerationRequest {
const slots = req.chain ?? [];
const inputs = { ...req.inputs };
let prompt = req.prompt;
- for (const k of ["images", "videos"] as const) {
+ for (const k of ["images", "videos", "audios"] as const) {
const at = (pos: "first" | "last") => slots.filter((s) => s.slot === k && (s.position ?? "last") === pos).map((s) => PLACEHOLDER[SLOT_KIND[s.slot]]);
const first = at("first");
const last = at("last");
@@ -626,7 +627,7 @@ export function withPlaceholders(req: GenerationRequest): GenerationRequest {
}
for (const s of slots) {
if (s.slot === "prompt") prompt = prompt?.includes("{text}") ? prompt.replaceAll("{text}", PLACEHOLDER.text) : PLACEHOLDER.text;
- else if (s.slot !== "images" && s.slot !== "videos") inputs[s.slot] = PLACEHOLDER[SLOT_KIND[s.slot]];
+ else if (s.slot !== "images" && s.slot !== "videos" && s.slot !== "audios") inputs[s.slot] = PLACEHOLDER[SLOT_KIND[s.slot]];
}
return { ...req, prompt, inputs };
}
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index 3c71fdad..92e2ffb2 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -11449,6 +11449,63 @@ export const CLOUD_MODELS: ModelDef[] = [
"usd": 0.0007
}
},
+ {
+ "id": "compose-timeline",
+ "name": "Voice timeline",
+ "vendor": "fal",
+ "family": "utility",
+ "engine": "cloud",
+ "kind": "video",
+ "tagline": "Place audio clips at their start times on a timeline",
+ "routes": [
+ {
+ "op": "timeline",
+ "provider": "fal",
+ "endpoint": "fal-ai/ffmpeg-api/compose",
+ "map": {
+ "prompt": false,
+ "timeline": "tracks"
+ }
+ }
+ ],
+ "options": {
+ "promptless": true
+ },
+ "pricing": {
+ "unit": "second",
+ "usd": 0.0002
+ },
+ "hidden": true
+ },
+ {
+ "id": "extract-soundtrack",
+ "name": "Extract soundtrack",
+ "vendor": "fal",
+ "family": "utility",
+ "engine": "cloud",
+ "kind": "audio",
+ "tagline": "A video's soundtrack as an audio file",
+ "routes": [
+ {
+ "op": "separate-audio",
+ "provider": "fal",
+ "endpoint": "fal-ai/workflow-utilities/extract-audio",
+ "map": {
+ "prompt": false,
+ "video": "video_url"
+ }
+ }
+ ],
+ "options": {
+ "promptless": true
+ },
+ "pricing": {
+ "unit": "second",
+ "usd": 0.0002,
+ "note": "billed by compute time"
+ },
+ "hidden": true
+ },
{
"id": "elevenlabs-voice-isolation",
"name": "ElevenLabs Voice Isolation",
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 31587697..175ea71c 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -1001,6 +1001,17 @@ const open: ModelDef[] = [
routes: [comfy("mux", "video-mux-audio", "one track: video-mux-audio-replace; two: voice + background mix")],
options: { sliders: [{ param: "backgroundVolumeDb", label: "Background level (dB)", min: -30, max: 6, step: 1, default: 0 }] },
}),
+ o({
+ id: "oss-audio-timeline",
+ name: "Voice timeline",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "audio",
+ tagline: "Places spoken lines at their cue times on a silent track as long as the video (dub voices) · CPU",
+ routes: [comfy("timeline", "audio-timeline", "one loader per line, expanded per request")],
+ options: {},
+ hidden: true,
+ }),
// Product 3D, try-on
o({
id: "oss-trellis2",
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 115db910..19f86087 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -1,3 +1,4 @@
+import { readTimeline, timelineTracks } from "@/lib/av/timeline";
import { OPERATION_OUTPUT, type DurationField, type EnumField, type FieldMap, type GenInput, type MediaKind, type Operation } from "./types";
function enumValue(field: string | EnumField, value: string): [string, unknown] {
@@ -109,6 +110,13 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk
if (map.videos && input.videos?.length) out[map.videos] = input.videos;
if (map.audio && input.audio) out[map.audio] = input.audio;
if (map.audios && input.audios?.length) out[map.audios] = input.audios;
+ // A timeline render (fal compose): a still or the video as the picture, the clips at their start times.
+ if (map.timeline) {
+ const spec = readTimeline(input.extra?.timeline);
+ const visual = input.images?.[0] ? { url: input.images[0], type: "image" as const } : input.video ? { url: input.video, type: "video" as const } : null;
+ if (!spec || !visual) throw new Error("A timeline needs the clips' start times and a picture to render over");
+ out[map.timeline] = timelineTracks(spec, visual, input.audios ?? []);
+ }
if (map.aspectRatio && input.aspectRatio) {
const [k, v] = enumValue(map.aspectRatio, input.aspectRatio);
@@ -171,7 +179,7 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk
if (map.numLayers && input.numLayers !== undefined) out[map.numLayers] = input.numLayers;
if (map.palette && input.palette?.length) out[map.palette.key] = paletteValue(map.palette.format, input.palette);
- for (const [k, v] of Object.entries({ ...map.fixed, ...input.extra })) setPath(out, k, v);
+ for (const [k, v] of Object.entries({ ...map.fixed, ...input.extra })) if (!(map.timeline && k === "timeline")) setPath(out, k, v);
// A background colour given as hex goes out in the palette's shape (Recraft wants {r,g,b}).
const bg = map.palette?.background;
if (bg && typeof out[bg] === "string") {
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index b9ab2ca0..d75c3f1a 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -97,6 +97,8 @@ const PROMPTLESS = new Set<Operation>([
"interpolate", "v2a", "face-swap", "motion-transfer", "lipsync", "avatar",
// round 3: tools that work from their inputs (open caption burn-in takes timed lines as its prompt and says so when they're missing)
"trim", "transcribe", "mux", "separate-audio", "layers", "image-to-3d", "captions", "text-layers", "vectorize",
+ // av-tools: the dub voice track (clips placed on the video's timeline)
+ "timeline",
]);
/**
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 5ef2e137..2858af76 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -58,7 +58,8 @@ export type Operation =
| "separate-audio" // audio or video → voice and background stems
| "translate" // text → the same text in params.targetLanguage (LLM)
| "write" // brief → text (LLM: scripts, ad copy, shot lists)
- | "vectorize"; // image → the same picture as an SVG
+ | "vectorize" // image → the same picture as an SVG
+ | "timeline"; // audio clips placed at their start times over silence → one track as long as the video (dub voices)
export const OPERATION_LABELS: Record<Operation, string> = {
t2i: "Text to image",
@@ -106,6 +107,7 @@ export const OPERATION_LABELS: Record<Operation, string> = {
translate: "Translate",
write: "Write",
vectorize: "Vectorize",
+ timeline: "Place on the timeline",
};
export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
@@ -154,6 +156,8 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
translate: "text",
write: "text",
vectorize: "image",
+ // The open engine returns the track; fal's compose renders it as a video (the result follows the model).
+ timeline: "audio",
};
/** "llm" runs text steps (translate, write) on the configured LLM (Claude or Ollama) inside the server. */
@@ -245,6 +249,12 @@ export interface FieldMap {
fixed?: Record<string, unknown>;
/** Array field that receives `inputs.audios` (reference audio clips: Seedance / Cinema Studio reference-to-video). */
audios?: string;
+ /**
+ * Timeline render (fal ffmpeg compose `tracks`): one visual track (inputs.images[0] as a still, else
+ * inputs.video) as long as params.extra.timeline.length, and one audio track with inputs.audios placed
+ * at params.extra.timeline.clips[i].start for .duration seconds (keyframes in milliseconds).
+ */
+ timeline?: string;
/**
* Fields sent unless the request sets them (a canonical field or params.extra wins): Wizper's
* `language: null` (detect instead of assuming English), Mirelo's full-length soundtrack.
@@ -446,8 +456,9 @@ export interface ChainSlot {
* request's prompt, or becomes the prompt when there is no placeholder.
* "voiceAudio" clones the voice of the dependency's audio output.
* "audio2" is the second audio track (the background stem mixed under the new voice, mux).
+ * "audios" is a list of audio clips (the spoken lines a timeline places at their start times).
*/
- slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "audio2" | "prompt";
+ slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "audio2" | "audios" | "prompt";
/** For list slots: put it before or after the request's own items (default last). */
position?: "first" | "last";
/**
diff --git a/src/lib/comfy.ts b/src/lib/comfy.ts
index a9f1b462..1b79c628 100644
--- a/src/lib/comfy.ts
+++ b/src/lib/comfy.ts
@@ -78,8 +78,11 @@ export interface ManifestWorkflow {
autoDownloads?: string[];
/** "isolated": the node pack has process-wide side effects and runs on a separate ComfyUI. */
worker?: "isolated";
- /** The provider rewrites the graph before submitting ("captions": one segment per caption cue). */
- expand?: "captions";
+ /**
+ * The provider rewrites the graph before submitting ("captions": one segment per caption cue;
+ * "timeline": one loader per audio clip, each placed at its start time).
+ */
+ expand?: "captions" | "timeline";
validated: boolean;
notes?: string;
}
diff --git a/src/server/dub.ts b/src/server/dub.ts
index 4f7e0c4f..24127349 100644
--- a/src/server/dub.ts
+++ b/src/server/dub.ts
@@ -1,4 +1,5 @@
import "server-only";
+import fs from "node:fs";
import { nanoid } from "nanoid";
import { z } from "zod";
import type { Cue } from "@/lib/cues";
@@ -11,14 +12,19 @@ import {
reviewCues,
voiceSteps,
type DubSession,
+ type DubStep,
+ type DubPrice,
type DubSessionView,
type OneShotModel,
} from "@/lib/av/dub";
import { normalizeCues } from "@/lib/av/cue-edit";
+import { getModel } from "@/lib/catalog";
import type { Engine, Generation } from "@/lib/catalog/types";
+import { probeMedia } from "@/lib/media-probe";
import { createPipeline } from "./chains";
import { db } from "./db";
-import { createGenerations, getGeneration } from "./generations";
+import { cancelGeneration, createGenerations, getGeneration, previewChained } from "./generations";
+import { absolutePath } from "./storage";
/**
* Translate & dub sessions. A session remembers the source video, the languages and which generations
@@ -86,12 +92,29 @@ export interface CreateDubInput {
source?: string;
targets: string[];
model?: OneShotModel;
+ /** The video's length as the browser measured it (seconds); the file's header wins when it has one. */
+ duration?: number;
+}
+
+/** The source's length: its MP4/MOV header, else what the browser measured. The dubbed voice track is this long. */
+export function videoLength(ref: string, measured?: number): number | undefined {
+ try {
+ if (ref.startsWith("/api/files/")) {
+ const info = probeMedia(fs.readFileSync(absolutePath(decodeURIComponent(ref.slice("/api/files/".length)))));
+ const d = info?.videoDuration ?? info?.duration;
+ if (d && d > 0) return d;
+ }
+ } catch {
+ // An unreadable header (WebM): what the browser measured.
+ }
+ return measured && measured > 0 ? measured : undefined;
}
export function createDubSession(input: CreateDubInput): DubSessionView {
if (input.mode === "oneshot" && input.engine === "open") throw new Error("One-shot dubbing is a cloud service — the open engine dubs step by step");
const now = Date.now();
const title = input.title?.trim().slice(0, 120) || "Dubbed video";
+ const duration = videoLength(input.video, input.duration);
const base: DubSession = {
id: nanoid(10),
title,
@@ -100,6 +123,7 @@ export function createDubSession(input: CreateDubInput): DubSessionView {
video: input.video,
source: input.source || "auto",
targets: [...new Set(input.targets)],
+ ...(duration && { duration }),
batchId: nanoid(10),
createdAt: now,
updatedAt: now,
@@ -134,8 +158,8 @@ export function saveDubDraft(id: string, lang: string, cues: Cue[]): DubSessionV
return dubView(save({ ...s, drafts: { ...s.drafts, [lang]: normalizeCues(cues) } }));
}
-/** Speak the reviewed lines of one language: the voice pipeline. */
-export function voiceDub(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean } = {}): DubSessionView {
+/** The voice pipeline of one language, planned (not started): the steps and the session as it'll be saved. */
+function planVoice(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean }): { s: DubSession; current: DubSession; steps: DubStep[]; lipsync: boolean } {
const s = getDubSession(id);
if (!s) throw new Error("This dub no longer exists");
if (s.mode !== "steps") throw new Error("This dub was made in one go — there's nothing to voice");
@@ -150,15 +174,76 @@ export function voiceDub(id: string, lang: string, opts: { cues?: Cue[]; lipsync
const media = prepareMedia(view);
if (!media.voice) throw new Error("The voice to clone is missing from the first step");
const lipsync = opts.lipsync !== false;
- const steps = voiceSteps({ engine: s.engine, video: s.video, lang, cues, voiceRef: media.voice, background: media.background, lipsync, title: s.title });
+ const steps = voiceSteps({ engine: s.engine, video: s.video, lang, cues, voiceRef: media.voice, background: media.background, lipsync, duration: s.duration ?? videoLength(s.video), title: s.title });
+ return { s, current, steps, lipsync };
+}
+
+/** Speak the reviewed lines of one language: the voice pipeline. */
+export function voiceDub(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean } = {}): DubSessionView {
+ const { s, current, steps, lipsync } = planVoice(id, lang, opts);
const run = createPipeline(steps, { batchId: s.batchId });
const ids = Object.fromEntries(Object.entries(run.byKey).map(([k, g]) => [k, g.id]));
const voices = { ...s.voices, [lang]: [...(s.voices?.[lang] ?? []), { ids, at: Date.now(), lipsync }] };
return dubView(save({ ...current, voices }));
}
+// ---------------------------------------------------------------------------
+// Prices, before anything runs
+
+const asList = (a: string | string[] | undefined) => (a === undefined ? [] : Array.isArray(a) ? a : [a]);
+
+/** Price planned steps; per-second and per-minute steps are priced for the video's length. */
+export function priceSteps(engine: Engine, steps: DubStep[], seconds?: number): DubPrice {
+ let costUsd = 0;
+ let demo = false;
+ const unpriced = new Set<string>();
+ for (const st of steps) {
+ const unit = getModel(st.request.modelId)?.pricing?.unit;
+ const timed = seconds && (unit === "second" || unit === "minute") && st.request.params?.duration === undefined ? { ...st.request, params: { ...st.request.params, duration: seconds } } : st.request;
+ const p = previewChained(st.chain ? { ...timed, chain: st.chain } : timed, asList(st.after).length);
+ demo ||= p.demo;
+ if (p.costUsd === null) unpriced.add(p.model.name);
+ else costUsd += p.costUsd;
+ }
+ return { engine, costUsd: Math.round(costUsd * 1000) / 1000, unpriced: demo || engine === "open" ? [] : [...unpriced], demo, steps: steps.length };
+}
+
+/** What starting this dub would cost (POST /api/dub?preview=1). */
+export function previewDub(input: CreateDubInput): DubPrice {
+ if (input.mode === "oneshot" && input.engine === "open") throw new Error("One-shot dubbing is a cloud service — the open engine dubs step by step");
+ const seconds = videoLength(input.video, input.duration);
+ const targets = [...new Set(input.targets)];
+ if (input.mode === "oneshot") {
+ const jobs = oneShotRequests({ model: input.model ?? "heygen-translate", video: input.video, source: input.source, targets });
+ return priceSteps(input.engine, jobs.map((j, i) => ({ key: `dub:${i}`, request: j.request })), seconds);
+ }
+ return priceSteps(input.engine, prepareSteps({ engine: input.engine, video: input.video, source: input.source, targets }), seconds);
+}
+
+/** What voicing one language would cost (POST /api/dub/[id]/voice?preview=1). */
+export function previewVoiceDub(id: string, lang: string, opts: { cues?: Cue[]; lipsync?: boolean } = {}): DubPrice {
+ const { s, steps } = planVoice(id, lang, opts);
+ return priceSteps(s.engine, steps, s.duration ?? videoLength(s.video));
+}
+
+/** Forget a dub: steps still waiting or running are stopped first (nothing more is spent); finished results stay in the Library. */
export function deleteDubSession(id: string): boolean {
+ const s = getDubSession(id);
+ if (s) stopSteps(sessionIds(s));
return db().prepare("DELETE FROM dub_sessions WHERE id = ?").run(id).changes > 0;
}
+/** Cancel the generations among these that haven't finished. */
+export function stopSteps(ids: string[]): number {
+ let n = 0;
+ for (const gid of ids) {
+ const g = getGeneration(gid);
+ if (g && (g.status === "queued" || g.status === "running")) {
+ void cancelGeneration(gid);
+ n++;
+ }
+ }
+ return n;
+}
+
export { DUB_FEATURE };
diff --git a/src/server/generations.ts b/src/server/generations.ts
index e5034312..e8e486cc 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -263,9 +263,9 @@ export function chooseRoute(candidates: ModelRoute[]): { route: ModelRoute; demo
/** Text steps depend on which LLM the route may use (the open model never calls Claude). */
const routeReady = (r: ModelRoute) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured());
-/** What a run produces: colour matching works on images and videos, so it follows the model. */
+/** What a run produces: colour matching works on images and videos, and fal renders a timeline as a video, so those follow the model. */
export function outputKind(op: Generation["op"], model: { kind: MediaKind }): MediaKind {
- return op === "color-match" ? model.kind : OPERATION_OUTPUT[op];
+ return op === "color-match" || op === "timeline" ? model.kind : OPERATION_OUTPUT[op];
}
// Live updates: every write to the table becomes an event (src/server/live.ts). A trashed row
@@ -410,6 +410,7 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {
audio: "audio",
voiceAudio: "audio",
audio2: "audio",
+ audios: "audio",
prompt: "text",
};
@@ -462,7 +463,7 @@ export function withChainInputs(req: GenerationRequest, urls: string[]): Generat
const inputs = { ...req.inputs };
let prompt = req.prompt;
const slots = slotsFor(req, urls.length);
- for (const k of ["images", "videos"] as const) {
+ for (const k of ["images", "videos", "audios"] as const) {
const at = (pos: "first" | "last") => slots.flatMap((s, i) => (s.slot === k && (s.position ?? "last") === pos ? [urls[i]] : []));
const first = at("first");
const last = at("last");
@@ -470,7 +471,7 @@ export function withChainInputs(req: GenerationRequest, urls: string[]): Generat
}
slots.forEach((s, i) => {
if (s.slot === "prompt") prompt = prompt?.includes("{text}") ? prompt.replaceAll("{text}", urls[i]) : urls[i];
- else if (s.slot !== "images" && s.slot !== "videos") inputs[s.slot] = urls[i];
+ else if (s.slot !== "images" && s.slot !== "videos" && s.slot !== "audios") inputs[s.slot] = urls[i];
});
return { ...req, prompt, inputs };
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 8a3b5793..771b13c6 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -28,6 +28,7 @@ import {
type ManifestOutput,
type ManifestWorkflow,
} from "@/lib/comfy";
+import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";
import { guessKind } from "@/lib/catalog/payload";
import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";
import { probeMedia, type MediaInfo } from "@/lib/media-probe";
@@ -463,6 +464,8 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
values.prompt = (input.dialogue ?? []).filter((l) => l.text.trim()).map((l) => `SPEAKER ${l.voice === "B" ? "B" : "A"}: ${l.text.trim()}`).join("\n");
}
if (ctx.op === "voice-change") values.audio2 = input.voiceAudio;
+ // A voice track on the video's timeline: the clips are the spoken lines (the template binds the first).
+ if (ctx.op === "timeline") values.audio = input.audios?.[0] ?? input.audio;
// Speech workflows read the soundtrack with LoadAudio, which also takes a video upload.
if ((ctx.op === "transcribe" || ctx.op === "separate-audio" || ctx.op === "translate") && b.audio && !b.video) values.audio = input.audio ?? input.video ?? clips[0];
if (b.language && input.targetLanguage) values.language = input.targetLanguage;
@@ -566,6 +569,9 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
const cues = manifest.expand === "captions" ? captionCues(input, extra) : [];
delete extra.cues;
delete extra.wordsPerCaption;
+ const timeline = manifest.expand === "timeline" ? readTimeline(extra.timeline) : null;
+ if (manifest.expand === "timeline" && !timeline) throw new ProviderError("The voice track needs the lines' start times (params.extra.timeline)");
+ delete extra.timeline;
for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;
if (audio2 && ctx.op !== "dialogue" && ctx.op !== "voice-change") values.audio2 = audio2;
// Soundtrack mix: a silent bed as long as the video, so neither track cuts the other short.
@@ -615,6 +621,13 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
throw new ProviderError((e as Error).message);
}
}
+ if (timeline) {
+ try {
+ wf = expandTimelineWorkflow(wf, input.audios?.length ? input.audios : [String(values.audio)], timeline);
+ } catch (e) {
+ throw new ProviderError((e as Error).message);
+ }
+ }
if (input.loras?.length) wf = injectLoras(wf, input.loras);
const metaBatch = Object.values(wf).some((n) => n.class_type === "VHS_BatchManager");
return {
diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.ts
index c73ecb74..3820ad71 100644
--- a/src/server/providers/mock.ts
+++ b/src/server/providers/mock.ts
@@ -233,11 +233,18 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,
return [demoTranslate(brief, String(meta.targetLanguage ?? "Spanish"))];
case "write":
return [demoWrite(brief)];
- case "separate-audio":
- return [
+ case "separate-audio": {
+ const stems: DemoOutput[] = [
{ url: toDataUri(demoWav(3, [220, 330], 3), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: "voice", demo: true } },
{ url: toDataUri(demoWav(3, [110, 165]), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: "background", demo: true } },
];
+ // Workflows that also time the voice stem (the open dub's first step) return its cues too.
+ if (meta.transcript) {
+ const cues = demoCues("");
+ stems.push(textOutput(cueText(cues), cues, { role: "cues", language: meta.sourceLanguage ?? "English", demo: true }));
+ }
+ return stems;
+ }
case "image-to-3d":
return [
{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb" } },
@@ -272,8 +279,8 @@ export const mockProvider: ProviderAdapter = {
meta: {
startedAt: Date.now(),
op: route.op,
- // Colour matching keeps the input's kind (an image or a video).
- kind: route.op === "color-match" ? model.kind : OPERATION_OUTPUT[route.op],
+ // Colour matching keeps the input's kind (an image or a video); a timeline is audio or (fal) a video.
+ kind: route.op === "color-match" || route.op === "timeline" ? model.kind : OPERATION_OUTPUT[route.op],
prompt: input.prompt ?? route.op,
aspectRatio: input.aspectRatio ?? "1:1",
count: Math.max(1, Math.min(4, input.numOutputs ?? 1)),
@@ -282,6 +289,8 @@ export const mockProvider: ProviderAdapter = {
targetLanguage: input.targetLanguage,
sourceLanguage: input.sourceLanguage,
numLayers: input.numLayers,
+ // A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).
+ transcript: route.op === "separate-audio" && route.provider === "comfyui" && route.endpoint.includes("transcribe"),
},
payload: { demo: true, ...input },
};
diff --git a/tests/av-dub.test.ts b/tests/av-dub.test.ts
index 0814d311..8a417253 100644
--- a/tests/av-dub.test.ts
+++ b/tests/av-dub.test.ts
@@ -4,9 +4,10 @@ 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 { languageStage, oneShotRequests, prepareSteps, reviewCues, spokenText, voiceSteps, type DubSessionView } from "@/lib/av/dub";
+import { BLANK_FRAME, dubPhrases, languageStage, oneShotRequests, PHRASE_MAX, prepareSteps, reviewCues, spokenText, voiceSteps, type DubSessionView } from "@/lib/av/dub";
import { DUB_LANGUAGES, supportsTarget } from "@/lib/av/languages";
import { getModel } from "@/lib/catalog";
+import { buildPayload } from "@/lib/catalog/payload";
vi.setConfig({ testTimeout: 120_000 });
@@ -53,18 +54,19 @@ describe("dub languages", () => {
describe("dub pipeline DAGs", () => {
const video = "/api/files/uploads/clip.mp4";
- it("open: stems → transcript of the voice stem → one translation per language", () => {
+ it("open: one job splits the stems and times the voice → one translation per language from its cues", () => {
const steps = prepareSteps({ engine: "open", video, source: "en", targets: ["es", "de"] });
expect(steps.map((s) => [s.key, s.request.modelId, s.request.op, s.after ?? null])).toEqual([
["stems", "oss-voice-separate", "separate-audio", null],
- ["words", "oss-qwen3-asr", "transcribe", "stems"],
- ["translate:es", "oss-text-llm", "translate", "words"],
- ["translate:de", "oss-text-llm", "translate", "words"],
+ ["translate:es", "oss-text-llm", "translate", "stems"],
+ ["translate:de", "oss-text-llm", "translate", "stems"],
]);
- expect(steps[1].chain).toEqual([{ slot: "audio", stem: "voice" }]);
- expect(steps[1].request.params?.sourceLanguage).toBe("en");
- expect(steps[2].chain).toEqual([{ slot: "prompt" }]);
- expect(steps[2].request.params).toEqual({ targetLanguage: "Spanish", sourceLanguage: "English" });
+ // No second, weaker ASR pass: the stems workflow already runs Qwen3-ASR 1.7B + the forced aligner.
+ expect(getModel("oss-voice-separate")!.routes[0].endpoint).toBe("dub-prepare-separate-transcribe");
+ expect(steps[0].request.params?.sourceLanguage).toBe("en");
+ expect(steps[1].chain).toEqual([{ slot: "prompt" }]);
+ expect(steps[1].request.params).toEqual({ targetLanguage: "Spanish", sourceLanguage: "English" });
+ expect(steps[1].request.step).toMatchObject({ index: 1, of: 3 });
expect(() => prepareSteps({ engine: "open", video, targets: ["th"] })).toThrow(/Thai isn't available on the open engine/);
});
@@ -79,37 +81,99 @@ describe("dub pipeline DAGs", () => {
expect(steps[1].request.params).toBeUndefined(); // "auto" = detect
});
+ // Speech starts at 2 s, pauses at 7–12 s and ends at 26 s of a 30 s clip.
const cues = [
- { start: 0, end: 2, text: "Hola a todos" },
- { start: 2.2, end: 4, text: " bienvenidos " },
+ { start: 2, end: 4, text: "Hola a todos" },
+ { start: 4.2, end: 7, text: " bienvenidos " },
+ { start: 12, end: 15, text: "Esto es una prueba" },
+ { start: 24, end: 26, text: "Adiós" },
];
- it("open voice: cloned speech → lip re-sync → mixed over the background", () => {
- const steps = voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav", background: "/bg.wav" });
+ it("phrases: lines a breath apart are one take, pauses split takes, lines past the end are dropped", () => {
+ expect(dubPhrases(cues)).toEqual([
+ { start: 2, end: 7, text: "Hola a todos bienvenidos" },
+ { start: 12, end: 15, text: "Esto es una prueba" },
+ { start: 24, end: 26, text: "Adiós" },
+ ]);
+ // A long run of speech still re-syncs every PHRASE_MAX seconds.
+ const run = Array.from({ length: 10 }, (_, i) => ({ start: i * 2, end: i * 2 + 1.9, text: `line ${i}` }));
+ const takes = dubPhrases(run);
+ expect(takes.length).toBe(2);
+ expect(takes.every((p) => p.end - p.start <= PHRASE_MAX)).toBe(true);
+ expect(dubPhrases([...cues, { start: 31, end: 32, text: "after the end" }, { start: 20, end: 21, text: " " }], 30).map((p) => p.text)).toEqual(["Hola a todos bienvenidos", "Esto es una prueba", "Adiós"]);
+ });
+
+ it("open voice: each take in the cloned voice → placed at its cue on a track as long as the video → lips → over the background", () => {
+ const steps = voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav", background: "/bg.wav", duration: 30 });
expect(steps.map((s) => [s.key, s.request.modelId, s.request.op, s.after ?? null])).toEqual([
- ["speech", "oss-chatterbox", "tts", null],
- ["lips", "oss-infinitetalk-v2v", "lipsync", "speech"],
- ["film", "oss-mux", "mux", ["lips", "speech"]],
+ ["line:0", "oss-chatterbox", "tts", null],
+ ["line:1", "oss-chatterbox", "tts", null],
+ ["line:2", "oss-chatterbox", "tts", null],
+ ["track", "oss-audio-timeline", "timeline", ["line:0", "line:1", "line:2"]],
+ ["lips", "oss-infinitetalk-v2v", "lipsync", "track"],
+ ["film", "oss-mux", "mux", ["lips", "track"]],
]);
- expect(steps[0].request).toMatchObject({ prompt: "Hola a todos\nbienvenidos", inputs: { voiceAudio: "/v.wav" }, params: { targetLanguage: "Spanish (es)" } });
- expect(steps[2].chain).toEqual([{ slot: "video" }, { slot: "audio" }]);
- expect(steps[2].request.inputs).toEqual({ audio2: "/bg.wav" });
+ expect(steps[0].request).toMatchObject({ prompt: "Hola a todos bienvenidos", inputs: { voiceAudio: "/v.wav" }, params: { targetLanguage: "Spanish (es)" } });
+ const track = steps[3];
+ expect(track.chain).toEqual([{ slot: "audios" }, { slot: "audios" }, { slot: "audios" }]);
+ // The voice keeps the source's length and every take starts at its cue (each may play until the next one).
+ expect(track.request.params).toEqual({
+ duration: 30,
+ extra: { timeline: { length: 30, clips: [{ start: 2, duration: 10 }, { start: 12, duration: 12 }, { start: 24, duration: 6 }] } },
+ });
+ // Lip re-sync gets no time span: InfiniteTalk runs as long as its voice, which is now the whole clip.
+ expect(steps[4].request.params).toBeUndefined();
+ expect(steps[5].chain).toEqual([{ slot: "video" }, { slot: "audio" }]);
+ expect(steps[5].request.inputs).toEqual({ audio2: "/bg.wav" });
// Without lip re-sync the new voice goes over the original picture.
- const flat = voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav", background: "/bg.wav", lipsync: false });
- expect(flat.map((s) => s.key)).toEqual(["speech", "film"]);
- expect(flat[1].request.inputs).toEqual({ video, audio2: "/bg.wav" });
+ const flat = voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav", background: "/bg.wav", lipsync: false, duration: 30 });
+ expect(flat.map((s) => s.key)).toEqual(["line:0", "line:1", "line:2", "track", "film"]);
+ expect(flat.at(-1)!.request.inputs).toEqual({ video, audio2: "/bg.wav" });
+ // Unknown length (a WebM the server can't read): a second past the last line.
+ expect(voiceSteps({ engine: "open", video, lang: "es", cues, voiceRef: "/v.wav" })[3].request.params?.duration).toBe(27);
});
- it("cloud voice: ElevenLabs speech → converted to the speaker's voice → Sync lipsync", () => {
- const steps = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3" });
- expect(steps.map((s) => [s.key, s.request.modelId, s.request.op])).toEqual([
- ["speech", "elevenlabs-v4", "tts"],
- ["clone", "chatterbox-vc-cloud", "voice-change"],
- ["film", "sync-lipsync-3", "lipsync"],
+ it("cloud voice: ElevenLabs takes → compose on the timeline → its soundtrack → their voice → Sync lipsync", () => {
+ const steps = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", 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"],
+ ["film", "sync-lipsync-3", "lipsync", "clone"],
]);
- expect(steps[1].request.inputs).toEqual({ voiceAudio: "/v.mp3" });
- expect(voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", lipsync: false })[2].request.modelId).toBe("merge-audio-video");
+ expect(steps[3].request.inputs).toEqual({ images: [BLANK_FRAME] });
+ expect(steps[3].request.params?.extra?.timeline).toEqual({ length: 30, clips: [{ start: 2, duration: 10 }, { start: 12, duration: 12 }, { start: 24, duration: 6 }] });
+ expect(steps[4].chain).toEqual([{ slot: "video" }]);
+ expect(steps[5].request.inputs).toEqual({ voiceAudio: "/v.mp3" });
+ expect(steps[6].request).toMatchObject({ inputs: { video }, params: { duration: 30 } });
+ const flat = voiceSteps({ engine: "cloud", video, lang: "ja", cues, voiceRef: "/v.mp3", lipsync: false, duration: 30 });
+ expect(flat.at(-1)!.request.modelId).toBe("merge-audio-video");
expect(() => voiceSteps({ engine: "cloud", video, lang: "ja", cues: [{ start: 0, end: 1, text: " " }], voiceRef: "/v" })).toThrow(/no lines to speak/);
+ 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("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];
+ const payload = buildPayload(route.map!, { images: ["https://fal.media/still.png"], audios: ["https://a/0.mp3", "https://a/1.mp3", "https://a/2.mp3"], extra: steps[3].request.params?.extra });
+ expect(payload).toEqual({
+ tracks: [
+ { id: "picture", type: "image", keyframes: [{ url: "https://fal.media/still.png", timestamp: 0, duration: 30000 }] },
+ {
+ id: "voice",
+ type: "audio",
+ keyframes: [
+ { url: "https://a/0.mp3", timestamp: 2000, duration: 10000 },
+ { url: "https://a/1.mp3", timestamp: 12000, duration: 12000 },
+ { url: "https://a/2.mp3", timestamp: 24000, duration: 6000 },
+ ],
+ },
+ ],
+ });
+ expect(() => buildPayload(route.map!, { images: ["x"], audios: ["a"], extra: {} })).toThrow(/start times/);
});
it("one shot: HeyGen display names, ElevenLabs codes", () => {
@@ -120,7 +184,7 @@ describe("dub pipeline DAGs", () => {
});
it("spoken text is the reviewed lines, trimmed", () => {
- expect(spokenText(cues)).toBe("Hola a todos\nbienvenidos");
+ expect(spokenText(cues)).toBe("Hola a todos\nbienvenidos\nEsto es una prueba\nAdiós");
});
});
@@ -192,12 +256,16 @@ 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" ? ["speech", "lips", "film"] : ["speech", "clone", "film"]);
- expect(voiced.generations[run.ids.speech].request.prompt).toContain("Hola, esto es una prueba");
+ expect(Object.keys(run.ids)).toEqual(engine === "open" ? ["line:0", "track", "lips", "film"] : ["line:0", "track", "soundtrack", "clone", "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);
+ expect(voiced.generations[run.ids.track].request.params?.duration).toBe(view.duration);
+ expect((voiced.generations[run.ids.track].request.params?.extra?.timeline as { length: number }).length).toBe(view.duration);
if (engine === "open") {
// 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.speech].request.inputs?.voiceAudio).toMatch(/^\/api\/files\//);
+ expect(voiced.generations[run.ids["line:0"]].request.inputs?.voiceAudio).toMatch(/^\/api\/files\//);
}
expect(languageStage(voiced, "es")).toBe("voicing");
expect((await settle(run.ids.film)).status).toBe("succeeded");
@@ -220,4 +288,13 @@ describe("dub sessions (demo mode)", () => {
expect(languageStage(dub.dubView(dub.getDubSession(s.id)!) as DubSessionView, "es")).toBe("done");
expect(dub.listDubSessions().map((x) => x.id)).toContain(s.id);
});
+
+ 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!);
+ expect(dub.deleteDubSession(s.id)).toBe(true);
+ expect(dub.getDubSession(s.id)).toBeNull();
+ for (const id of ids) expect(["canceled", "succeeded"]).toContain((await settle(id)).status);
+ expect(ids.some((id) => gens.getGeneration(id)!.status === "canceled")).toBe(true);
+ });
});
diff --git a/tests/av-workflows.test.ts b/tests/av-workflows.test.ts
index ac4e40ae..f8bcad7d 100644
--- a/tests/av-workflows.test.ts
+++ b/tests/av-workflows.test.ts
@@ -41,6 +41,7 @@ describe("av-tools workflows", () => {
["frame-extract", "oss-extract-frame"],
["v2a-hunyuan-foley", "oss-hunyuan-foley-video"],
["product-shot-qwen-edit-2509", "oss-product-shot"],
+ ["audio-timeline", "oss-audio-timeline"],
]) {
expect(byId.get(id)?.validated, id).toBe(true);
expect(byId.get(id)?.license, id).toBeTruthy();
@@ -72,6 +73,28 @@ describe("av-tools workflows", () => {
for (const n of ["4", "8"]) expect(r.workflow[n].inputs.filename_prefix).toBe("fuobe/gen1");
});
+ it("Voice timeline: every line at its cue on silence as long as the video, cut where the next starts", async () => {
+ const timeline = { length: 30, clips: [{ start: 0, duration: 6 }, { start: 6, duration: 18 }, { start: 24, duration: 6 }] };
+ const r = await prepare("audio-timeline", "timeline", { audios: ["l0.flac", "l1.flac", "l2.flac"], duration: 30, extra: { timeline } });
+ const wf = r.workflow;
+ const of = (cls: string) => Object.entries(wf).filter(([, n]) => n.class_type === cls);
+ // The track: EmptyAudio as long as the video, saved after the last line is added.
+ expect(wf["1"].inputs).toMatchObject({ duration: 30, sample_rate: 44100, channels: 2 });
+ expect(of("LoadAudio").map(([, n]) => n.inputs.audio)).toEqual(["l0.flac", "l1.flac", "l2.flac"]);
+ expect(of("TrimAudioDuration").map(([, n]) => n.inputs.duration)).toEqual([6, 18, 6]);
+ // A line at 0 s needs no lead-in; the others wait their start time in silence.
+ expect(of("EmptyAudio").map(([, n]) => n.inputs.duration)).toEqual([30, 6, 24]);
+ expect(wf.t1_add.inputs).toMatchObject({ audio1: ["1", 0], audio2: ["t1_cut", 0], merge_method: "add" });
+ expect(wf.t2_at.inputs).toMatchObject({ audio1: ["t2_lead", 0], audio2: ["t2_cut", 0], direction: "after" });
+ expect(wf.t2_add.inputs).toMatchObject({ audio1: ["t1_add", 0], audio2: ["t2_at", 0] });
+ expect(wf.t3_add.inputs.audio1).toEqual(["t2_add", 0]);
+ expect(wf["7"].inputs).toMatchObject({ audio: ["t3_add", 0], filename_prefix: "fuobe/gen1" });
+ // Nothing of the template's single line is left over.
+ for (const id of ["2", "3", "4", "5", "6"]) expect(wf[id]).toBeUndefined();
+ await expect(prepare("audio-timeline", "timeline", { audios: ["l0.flac"], duration: 30 })).rejects.toThrow(/start times/);
+ await expect(prepare("audio-timeline", "timeline", { audios: ["l0.flac"], extra: { timeline } })).rejects.toThrow(/places 3 clips but got 1/);
+ });
+
it("Product shot: the photo cut out onto white, the scene after the LoRA's trigger", async () => {
const r = await prepare("product-shot-qwen-edit-2509", "edit", { images: ["bottle.png"], prompt: "on a marble counter, morning light", seed: 3 });
expect(r.workflow["78"].inputs.image).toBe("bottle.png");
diff --git a/tests/pipeline.test.ts b/tests/pipeline.test.ts
index e79095fa..0a767873 100644
--- a/tests/pipeline.test.ts
+++ b/tests/pipeline.test.ts
@@ -139,7 +139,8 @@ describe("stems and the second audio track", () => {
const stems = gens.getGeneration(p.byKey.stems.id)!;
const voice = gens.getGeneration(p.byKey.voice.id)!;
const stem = (name: string) => stems.outputs.find((o) => o.meta?.stem === name)!.url;
- expect(stems.outputs.map((o) => o.meta?.stem)).toEqual(["voice", "background"]);
+ // Two stems, then (like the real dub-prepare workflow) the voice stem's timed transcript.
+ expect(stems.outputs.map((o) => o.meta?.stem ?? o.meta?.role)).toEqual(["voice", "background", "cues"]);
// The voice stem is cloned; the background stem (not the first audio output) goes under the new voice.
expect(voice.request.inputs?.voiceAudio).toBe(stem("voice"));
expect(film.request.inputs).toEqual({ video, audio: voice.outputs[0].url, audio2: stem("background") });
diff --git a/workflows/comfyui/audio-timeline.json b/workflows/comfyui/audio-timeline.json
new file mode 100644
index 00000000..ed92bab5
--- /dev/null
+++ b/workflows/comfyui/audio-timeline.json
@@ -0,0 +1,94 @@
+{
+ "1": {
+ "class_type": "EmptyAudio",
+ "inputs": {
+ "duration": 10,
+ "sample_rate": 44100,
+ "channels": 2
+ },
+ "_meta": {
+ "title": "The track: silence as long as the video (duration)"
+ }
+ },
+ "2": {
+ "class_type": "LoadAudio",
+ "inputs": {
+ "audio": "line.wav"
+ },
+ "_meta": {
+ "title": "A spoken line (audio; the provider adds one per line)"
+ }
+ },
+ "3": {
+ "class_type": "TrimAudioDuration",
+ "inputs": {
+ "audio": [
+ "2",
+ 0
+ ],
+ "start_index": 0,
+ "duration": 600
+ },
+ "_meta": {
+ "title": "Cut where the next line starts"
+ }
+ },
+ "4": {
+ "class_type": "EmptyAudio",
+ "inputs": {
+ "duration": 0.5,
+ "sample_rate": 44100,
+ "channels": 2
+ },
+ "_meta": {
+ "title": "Silence before the line (startTime)"
+ }
+ },
+ "5": {
+ "class_type": "AudioConcat",
+ "inputs": {
+ "audio1": [
+ "4",
+ 0
+ ],
+ "audio2": [
+ "3",
+ 0
+ ],
+ "direction": "after"
+ },
+ "_meta": {
+ "title": "The line at its start time"
+ }
+ },
+ "6": {
+ "class_type": "AudioMerge",
+ "inputs": {
+ "audio1": [
+ "1",
+ 0
+ ],
+ "audio2": [
+ "5",
+ 0
+ ],
+ "merge_method": "add"
+ },
+ "_meta": {
+ "title": "Laid on the track (cut or padded to its length)"
+ }
+ },
+ "7": {
+ "class_type": "SaveAudio",
+ "inputs": {
+ "audio": [
+ "6",
+ 0
+ ],
+ "filename_prefix": "fuobe/audio-timeline"
+ },
+ "_meta": {
+ "title": "Save the track (FLAC, lossless: no encoder delay shifts the lines)"
+ }
+ }
+}
diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.json
index 2366ff7a..c1dbca81 100644
--- a/workflows/comfyui/manifest.json
+++ b/workflows/comfyui/manifest.json
@@ -1,6 +1,6 @@
{
"version": 1,
- "generatedAt": "2026-10-18T11:36:57.338Z",
+ "generatedAt": "2026-10-21T15:15:54.549Z",
"comfyuiCommit": "fc04da91b2ab12f99e4716371a7e4f98ac982597",
"comfyuiVersion": "0.41.0",
"workflowTemplatesVersion": "0.11.86",
@@ -10794,6 +10794,57 @@
"license": "Apache-2.0 (Qwen-Image-Edit-2509, White_to_Scene and Lightning LoRAs); BiRefNet MIT",
"validated": true,
"notes": "relight-qwen-edit-2509 with a cut-out in front: core RemoveBackground (BiRefNet) masks the product, Image Composite Masked puts it on a white backdrop the size of the photo, then Qwen-Image-Edit 2509 + Lightning (4 steps, cfg 1) + dx8152 White_to_Scene LoRA (trigger \"白底图转场景,\" = \"white background to scene\", prefixed by node 1002) places and relights it in the scene the prompt describes. The open route of the Product shot app (Bria Product Shot / Product Photography on the cloud)."
+ },
+ {
+ "id": "audio-timeline",
+ "title": "Voice track on the video's timeline: spoken lines placed at their start times over silence (core audio nodes)",
+ "capability": "timeline",
+ "file": "audio-timeline.json",
+ "source": "hand-built (scripts/comfy/hand-built/audio-timeline.json)",
+ "bindings": {
+ "audio": [
+ {
+ "node": "2",
+ "input": "audio"
+ }
+ ],
+ "duration": [
+ {
+ "node": "1",
+ "input": "duration"
+ }
+ ],
+ "startTime": [
+ {
+ "node": "4",
+ "input": "duration"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "7",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "7",
+ "kind": "audio"
+ }
+ ],
+ "defaults": {
+ "duration": 10,
+ "startTime": 0.5
+ },
+ "limits": {},
+ "models": [],
+ "customNodes": [],
+ "vramGb": 0,
+ "license": "n/a (no model; ComfyUI core audio nodes)",
+ "validated": true,
+ "notes": "The dub voice track, all core nodes. The template places one line: EmptyAudio of the video's length (duration) is the track, the line (audio) is cut where the next line starts (TrimAudioDuration), put after startTime seconds of silence (AudioConcat after EmptyAudio) and added onto the track (AudioMerge add: pads or cuts the line to the track). The provider rewrites the graph per request (expandTimelineWorkflow, src/lib/av/timeline.ts): params.extra.timeline = {length, clips:[{start, duration}]} with one inputs.audios clip per entry, each loaded, cut, led in and added in turn, so the saved track is exactly as long as the video with every line at its cue time (pauses kept). SaveAudio writes FLAC (lossless, no MP3 priming delay). Feeds lip re-sync (InfiniteTalk frames = the track's length = the video's) and video-mux-audio. Runs on CPU.",
+ "expand": "timeline"
}
]
}
diff --git a/workflows/comfyui/object_info.subset.json b/workflows/comfyui/object_info.subset.json
index 2c6db4ff..1b94e41c 100644
--- a/workflows/comfyui/object_info.subset.json
+++ b/workflows/comfyui/object_info.subset.json
@@ -667,6 +667,71 @@
"essentials_category": null,
"has_intermediate_output": false
},
+ "AudioConcat": {
+ "input": {
+ "required": {
+ "audio1": [
+ "AUDIO",
+ {}
+ ],
+ "audio2": [
+ "AUDIO",
+ {}
+ ],
+ "direction": [
+ "COMBO",
+ {
+ "tooltip": "Whether to append audio2 after or before audio1.",
+ "default": "after",
+ "multiselect": false,
+ "options": [
+ "after",
+ "before"
+ ]
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "audio1",
+ "audio2",
+ "direction"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "AUDIO"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "AUDIO"
+ ],
+ "output_tooltips": [
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "AudioConcat",
+ "display_name": "Concatenate Audio",
+ "description": "Concatenates the audio1 to audio2 in the specified direction.",
+ "python_module": "comfy_extras.nodes_audio",
+ "category": "audio",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": [
+ "join audio",
+ "combine audio",
+ "append audio"
+ ],
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
"AudioEncoderEncode": {
"input": {
"required": {
@@ -8919,6 +8984,7 @@
{
"multiselect": false,
"options": [
+ "fuobe_av_frame.mp4",
"fuobe_real.mp4",
"fuobe_real.wav",
"fuobe_validate.mp4",
@@ -9186,6 +9252,7 @@
{
"multiselect": false,
"options": [
+ "fuobe_av_frame.mp4",
"fuobe_real.mp4",
"fuobe_validate.mp4"
],
@@ -15663,6 +15730,74 @@
"essentials_category": null,
"has_intermediate_output": false
},
+ "TrimAudioDuration": {
+ "input": {
+ "required": {
+ "audio": [
+ "AUDIO",
+ {}
+ ],
+ "start_index": [
+ "FLOAT",
+ {
+ "tooltip": "Start time in seconds, can be negative to count from the end (supports sub-seconds).",
+ "default": 0,
+ "min": -18446744073709552000,
+ "max": 18446744073709552000,
+ "step": 0.01
+ }
+ ],
+ "duration": [
+ "FLOAT",
+ {
+ "tooltip": "Duration in seconds",
+ "default": 60,
+ "min": 0,
+ "step": 0.01
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "audio",
+ "start_index",
+ "duration"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "AUDIO"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "AUDIO"
+ ],
+ "output_tooltips": [
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "TrimAudioDuration",
+ "display_name": "Trim Audio Duration",
+ "description": "Trim audio tensor into chosen time range.",
+ "python_module": "comfy_extras.nodes_audio",
+ "category": "audio",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": [
+ "cut audio",
+ "audio clip",
+ "shorten audio"
+ ],
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
"TrimVideoLatent": {
"input": {
"required": {
@@ -16399,6 +16534,7 @@
"required": {
"video": [
[
+ "fuobe_av_frame.mp4",
"fuobe_real.mp4",
"fuobe_validate.mp4"
]