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.

Clean the voice first: transcripts and lip syncs can run on the speech alone, with a lip re-sync's music and effects put back on your GPU

Claudee9bd13d421ab
diff --git a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts
index 01681252..b8882db6 100644
--- a/src/app/api/swap-studio/projects/[id]/transcribe/route.ts
+++ b/src/app/api/swap-studio/projects/[id]/transcribe/route.ts
@@ -2,12 +2,13 @@ import { z } from "zod";
import { body, handle } from "@/server/shorts-schemas";
import { transcribe } from "@/server/swap-studio";
-const Transcribe = z.object({ clipId: z.string().min(1).max(80) });
+const Transcribe = z.object({ clipId: z.string().min(1).max(80), voiceFirst: z.boolean().optional() });
-/** The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU). */
+/** The clip's words, with who speaks when (Scribe v2 on the cloud, Qwen3-ASR on your GPU), from the speech alone with voiceFirst. */
export async function POST(request: Request, ctx: RouteContext<"/api/swap-studio/projects/[id]/transcribe">) {
return handle(async () => {
const { id } = await ctx.params;
- return Response.json(transcribe(id, (await body(request, Transcribe, "Pick a clip")).clipId));
+ const b = await body(request, Transcribe, "Pick a clip");
+ return Response.json(transcribe(id, b.clipId, b.voiceFirst));
}, request);
}
diff --git a/src/lib/av/voice-first.ts b/src/lib/av/voice-first.ts
new file mode 100644
index 00000000..5d6125a3
--- /dev/null
+++ b/src/lib/av/voice-first.ts
@@ -0,0 +1,232 @@
+import { estimateCost } from "@/lib/catalog/plan";
+import type { ChainSlot, Engine, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";
+import type { ToolStep } from "./audio-tools";
+import { durationWords, splitTime, SPLIT_MODEL, type SplitQuality } from "./split";
+
+/**
+ * "Clean the voice first" (DBS D6, docs/research/dbs-separation-7.md §8 and §9 D6): wherever speech feeds a model
+ * (Transcribe, Captions, Lipsync & avatars, Genjutsu's "What's said", Character Swap Studio's transcript), the speech is
+ * taken out from under the music and sound effects first, so the transcript and the lip sync follow the voice alone.
+ * Pure: the composer, the studios and the server (src/server/voice-first.ts) share it.
+ *
+ * - Open engine (ComfyUI + ComfyUI-DBS, CPU or GPU): a DBS step (oss-dbs-separate, graph separate-soundtrack-dbs)
+ * before Qwen3-ASR, InfiniteTalk or LatentSync, which take its `voice` stem. Lip re-sync on a video: the clip's own
+ * soundtrack is split too, and after the lip sync the stream-copy mux (oss-mux → video-mux-audio) puts the clean
+ * voice back over the clip's music and effects (`background` stem, 0 dB), the picture copied as made.
+ * - Cloud: ElevenLabs Voice Isolation (fal, $0.10 a minute) before Scribe v2 or the lip sync model. DBS is hosted
+ * nowhere, and SAM Audio in its place is the owner's call, not taken (docs/handoff/owner-decisions.json
+ * samAudioCloud: false), so the music and effects don't go back under a cloud lip sync, and the switch says so.
+ *
+ * Default on for a video (a soundtrack usually has music or effects under the speech), off for an audio upload (usually
+ * speech alone): a guess until the separation evaluation (D4) measures transcripts with and without it.
+ */
+
+export const VOICE_FIRST_LABEL = "Clean the voice first";
+
+/** The step that cleans the voice, per engine. */
+export const VOICE_FIRST_MODELS: Record<Engine, string> = {
+ open: SPLIT_MODEL,
+ cloud: "elevenlabs-voice-isolation",
+};
+/** The mux that puts the clip's music and effects back under a lip re-sync (open engine). */
+export const BED_MUX_MODEL = "oss-mux";
+/** The level the music and effects go back at (dB): as they were. */
+export const BED_DB = 0;
+
+/** The operations whose speech can be cleaned first. */
+export const VOICE_FIRST_OPS: ReadonlySet<Operation> = new Set<Operation>(["transcribe", "lipsync", "avatar"]);
+
+/** One line under the switch, per engine. */
+export const VOICE_FIRST_HINTS: Record<Engine, string> = {
+ open: "Takes the music and sound effects out from under the speech first",
+ cloud: "ElevenLabs isolates the voice first: music and noise are taken out",
+};
+
+/** What a lip re-sync on a video does with the clip's own music and effects, per engine. */
+export const BED_NOTES: Record<Engine, string> = {
+ open: "The clip's music and effects go back under the new lip movement.",
+ cloud: "In the cloud the result keeps the clean voice only: the clip's music and effects go back under it on your GPU (open source).",
+};
+
+/** Whether the request is one a clean voice helps (an operation that listens to speech, with the speech attached). */
+export function voiceFirstApplies(req: Pick<GenerationRequest, "inputs">, op: Operation | undefined): boolean {
+ return !!op && VOICE_FIRST_OPS.has(op) && !!voiceSource(req, op);
+}
+
+/** The file whose speech is cleaned and where it sits: a transcript's recording or video, a lip sync's voice. */
+export function voiceSource(req: Pick<GenerationRequest, "inputs">, op: Operation | undefined): { slot: "audio" | "video"; url: string } | null {
+ const i = req.inputs ?? {};
+ if (op === "transcribe") return i.audio ? { slot: "audio", url: i.audio } : i.video ? { slot: "video", url: i.video } : null;
+ if (op === "lipsync" || op === "avatar") return i.audio ? { slot: "audio", url: i.audio } : null;
+ return null;
+}
+
+/**
+ * The switch's default: on when the speech comes with a picture (a video to transcribe, a clip to re-sync), off for an
+ * audio upload, which is usually speech alone.
+ */
+export function voiceFirstDefault(req: Pick<GenerationRequest, "inputs">, op: Operation | undefined): boolean {
+ const src = voiceSource(req, op);
+ if (!src) return false;
+ if (op === "transcribe") return src.slot === "video";
+ return op === "lipsync" && !!req.inputs?.video;
+}
+
+/** Whether a run puts the clip's music and effects back after the lip sync (open engine, a clip with sound). */
+export function putsBedBack(req: Pick<GenerationRequest, "inputs">, op: Operation | undefined, engine: Engine, clipHasSound?: boolean): boolean {
+ return engine === "open" && op === "lipsync" && !!req.inputs?.video && !!req.inputs?.audio && clipHasSound !== false;
+}
+
+export interface VoiceFirstInput {
+ /** The request as the studio sends it, its operation resolved. */
+ request: GenerationRequest;
+ op: Operation;
+ engine: Engine;
+ /** Seconds the speech runs, when known (prices the cloud step, times the open one). */
+ seconds?: number;
+ /** The speech file's channel count (a file with more than 2 is split in mono). */
+ channels?: number;
+ /** False when the lip re-synced clip's header says it has no sound (nothing to put back). */
+ clipHasSound?: boolean;
+ /** The clip's channel count. */
+ clipChannels?: number;
+}
+
+export interface VoiceFirstPlan {
+ steps: ToolStep[];
+ /** The step whose result is the run's result (the transcript, the lip sync, or the lip sync with its music back). */
+ result: string;
+ /** Whether the clip's music and effects go back after the lip sync. */
+ bed: boolean;
+}
+
+const round3 = (s: number | undefined) => (s && s > 0 ? Math.round(s * 1000) / 1000 : undefined);
+
+/** A DBS split of `url` (mono, as Remove dialogue: the background is the original minus the speech). */
+function dbsStep(key: string, base: Pick<GenerationRequest, "feature" | "batchTitle">, slot: "audio" | "video", url: string, seconds: number | undefined, channels: number | undefined, label: string, title: string): ToolStep {
+ const extra: Record<string, unknown> = { channels: "mono" };
+ if (channels && channels > 0) extra.sourceChannels = Math.round(channels);
+ return {
+ key,
+ request: {
+ ...base,
+ modelId: SPLIT_MODEL,
+ op: "separate-audio",
+ title,
+ inputs: { [slot]: url },
+ params: { extra, ...(seconds && { sourceDuration: seconds }) },
+ step: { label, index: 0, of: 1 },
+ },
+ };
+}
+
+/**
+ * The steps of a run with its voice cleaned first, in one batch: the clean voice, the run on it, and on the open engine
+ * for a lip re-sync of a clip with sound, the clip's split and the mux that puts its music and effects back. Throws
+ * what's in the way (in words the studio shows).
+ */
+export function planVoiceFirst(i: VoiceFirstInput): VoiceFirstPlan {
+ const { request: req, op, engine } = i;
+ const src = voiceSource(req, op);
+ if (!VOICE_FIRST_OPS.has(op) || !src) throw new Error(op === "transcribe" ? "Add the recording or video to transcribe" : "Add the voice first");
+ const seconds = round3(i.seconds ?? req.params?.sourceDuration);
+ const name = req.title?.trim() || req.batchTitle?.trim();
+ const base: Pick<GenerationRequest, "feature" | "batchTitle"> = {
+ feature: req.feature,
+ ...(req.batchTitle && { batchTitle: req.batchTitle }),
+ };
+ const bed = putsBedBack(req, op, engine, i.clipHasSound);
+ const n = bed ? 4 : 2;
+ const voiceTitle = `Clean voice${name ? ` · ${name}` : ""}`;
+ const voice: ToolStep =
+ engine === "open"
+ ? dbsStep("voice", base, src.slot, src.url, seconds, i.channels, "Clean voice", voiceTitle)
+ : {
+ key: "voice",
+ request: {
+ ...base,
+ modelId: VOICE_FIRST_MODELS.cloud,
+ op: "separate-audio",
+ title: voiceTitle,
+ inputs: { [src.slot]: src.url },
+ ...(seconds && { params: { sourceDuration: seconds } }),
+ step: { label: "Clean voice", index: 0, of: 1 },
+ },
+ };
+ voice.request.step = { label: "Clean voice", index: 0, of: n };
+ // The run takes the clean voice in place of the file it was given (a transcript of a video then reads the voice alone).
+ const inputs = { ...req.inputs };
+ delete inputs.audio;
+ if (op === "transcribe") delete inputs.video;
+ const { voiceFirst: _off, ...rest } = req;
+ void _off;
+ const slot: ChainSlot = engine === "open" ? { slot: "audio", stem: "voice" } : { slot: "audio" };
+ const own = req.step;
+ const main: ToolStep = {
+ key: "main",
+ after: ["voice"],
+ chain: [slot],
+ request: {
+ ...rest,
+ inputs,
+ ...(seconds && { params: { ...req.params, sourceDuration: req.params?.sourceDuration ?? seconds } }),
+ step: { label: own?.label ?? (op === "transcribe" ? "Words from the clean voice" : "Lip sync on the clean voice"), index: 1, of: n },
+ },
+ };
+ if (!bed) return { steps: [voice, main], result: "main", bed: false };
+ const clip = req.inputs!.video!;
+ const split = dbsStep("bed", base, "video", clip, undefined, i.clipChannels, "The clip's music and effects", `Music & effects${name ? ` · ${name}` : ""}`);
+ split.request.step = { label: "The clip's music and effects", index: 2, of: n };
+ const film: ToolStep = {
+ key: "film",
+ // The lip sync's picture, the clean voice, and the clip's music and effects at their own level.
+ after: ["main", "voice", "bed"],
+ chain: [{ slot: "video" }, { slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }],
+ request: {
+ ...base,
+ modelId: BED_MUX_MODEL,
+ op: "mux",
+ ...(req.title && { title: req.title }),
+ params: { extra: { backgroundVolumeDb: BED_DB } },
+ step: { label: "Music and effects back under the voice · picture copied", index: 3, of: n },
+ },
+ };
+ return { steps: [voice, main, split, film], result: "film", bed: true };
+}
+
+// ---------------------------------------------------------------------------
+// What the switch says: the time it adds on the open engine, the price in the cloud
+
+/** The price the clean voice adds in the cloud (USD; ElevenLabs Voice Isolation per minute of speech), 0 on the open engine. */
+export function voiceFirstCost(engine: Engine, seconds: number | undefined, getModel: (id: string) => ModelDef | undefined): number {
+ if (engine === "open") return 0;
+ const m = getModel(VOICE_FIRST_MODELS.cloud);
+ if (!m) return 0;
+ return estimateCost(m, seconds && seconds > 0 ? { sourceDuration: seconds } : {}, 1, "separate-audio") ?? 0;
+}
+
+/**
+ * About how long the clean voice adds on the open engine (a range in seconds): one DBS pass over the speech (Fast,
+ * mono), and for a lip re-sync with its music put back, a second over the clip and the mux.
+ */
+export function voiceFirstTime(o: { seconds: number; device?: string | null; bed?: boolean }): { low: number; high: number } {
+ // The host's own pick (DBS-TIGER on CUDA, DBS-BSRNN otherwise), in mono: one pass whatever the channels.
+ const quality: SplitQuality = o.device === "cuda" ? "best" : "fast";
+ const one = splitTime({ seconds: o.seconds, quality, mode: "mono", device: o.device });
+ return o.bed ? { low: one.low * 2 + 2, high: one.high * 2 + 4 } : one;
+}
+
+/** The switch's time or price line: "Free · adds about 1–2 min", "+$0.05", "+$0.10 a minute". */
+export function voiceFirstLine(o: { engine: Engine; seconds?: number; device?: string | null; bed?: boolean; getModel: (id: string) => ModelDef | undefined }): string {
+ if (o.engine === "open") {
+ if (!o.seconds || o.seconds <= 0) return "Free · adds a little time";
+ const t = voiceFirstTime({ seconds: o.seconds, device: o.device, bed: o.bed });
+ return `Free · adds ${t.high < 60 ? "under a minute" : durationWords(t)}`;
+ }
+ if (!o.seconds || o.seconds <= 0) {
+ const per = voiceFirstCost("cloud", 60, o.getModel);
+ return per > 0 ? `+$${per.toFixed(2)} a minute` : "Priced by the minute";
+ }
+ const usd = voiceFirstCost("cloud", o.seconds, o.getModel);
+ return `+$${usd < 0.01 ? usd.toFixed(3) : usd.toFixed(2)}`;
+}
diff --git a/src/lib/catalog/swap-studio-plan.ts b/src/lib/catalog/swap-studio-plan.ts
index 1018b4d1..8a33d804 100644
--- a/src/lib/catalog/swap-studio-plan.ts
+++ b/src/lib/catalog/swap-studio-plan.ts
@@ -122,7 +122,8 @@ export function planPreview(clip: SwapClip): PlanStep[] | null {
// ---------------------------------------------------------------------------
// Transcript
-export function planTranscribe(clip: SwapClip, engine: Engine): PlanStep[] {
+/** The clip's words; with `voiceFirst`, read from the speech alone ("Clean the voice first", src/lib/av/voice-first.ts). */
+export function planTranscribe(clip: SwapClip, engine: Engine, voiceFirst = false): PlanStep[] {
const s = clip.source.duration;
return [
{
@@ -134,6 +135,7 @@ export function planTranscribe(clip: SwapClip, engine: Engine): PlanStep[] {
op: "transcribe",
inputs: { video: workingClip(clip, engine) },
params: { duration: s, sourceDuration: s },
+ ...(voiceFirst && { voiceFirst: true }),
step: { label: "The clip's words", index: 0, of: 1 },
},
},
diff --git a/src/lib/catalog/swap-studio.ts b/src/lib/catalog/swap-studio.ts
index 6583c01d..c1083a3a 100644
--- a/src/lib/catalog/swap-studio.ts
+++ b/src/lib/catalog/swap-studio.ts
@@ -1137,6 +1137,8 @@ export interface StudioEstimate {
project: { costUsd: number | null; segments: number };
assembly: Record<string, number | null>;
transcribe: Record<string, number | null>;
+ /** What "Clean the voice first" adds to a clip's transcript (null: unknown). */
+ cleanVoice: Record<string, number | null>;
/** Tracking a whole shot's mask. */
mask: Record<string, number | null>;
/**
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 06f1d0f4..85c08997 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1147,6 +1147,12 @@ export interface GenerationRequest {
* steps, src/server/turnaround.ts; a character trained with it carries its training's time). Stripped from API input.
*/
consentAt?: number;
+ /**
+ * "Clean the voice first" (src/lib/av/voice-first.ts): a transcript or a lip sync runs on the speech taken out from
+ * under the music and effects (DBS on your GPU, ElevenLabs Voice Isolation in the cloud), and a lip re-sync on your GPU
+ * gets the clip's music and effects back after it. The server expands it into steps (src/server/voice-first.ts).
+ */
+ voiceFirst?: boolean;
}
export interface ChainSlot {
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 441b1755..d3a29bf2 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -59,7 +59,7 @@ export function assertOneMode(steps: ModeStep[]): void {
* the result (src/server/recipe-builder.ts) rebuilds that one request, not the rows it expanded into, whose number
* changes with the input (a film of 3 shots is 4 rows, of 5 shots 6).
*/
-function withAsked(made: Generation[], asked: GenerationRequest, engine: Engine): Generation[] {
+export function withAsked(made: Generation[], asked: GenerationRequest, engine: Engine): Generation[] {
const [first, ...rest] = made;
if (!first) return made;
// A Fuobe Original keeps the engine it ran on, as a plain row's request does (createGenerations).
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 863a3da6..b59e004d 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -57,6 +57,8 @@ import { BLOCKED_CARD_MESSAGE, looksBlocked } from "./safety-card";
import { pollTrainings } from "./training";
import { createEndFrameClip, createExtendChain, createKeyframeFilm, createMosaicRun, createRelitClip, createShotFilm, createStillTo3d, joinClips } from "./chains";
import { createRegenerateRun } from "./regenerate";
+import { createVoiceFirstRun, voiceFirstPlanFor } from "./voice-first";
+import { BED_NOTES, VOICE_FIRST_LABEL } from "@/lib/av/voice-first";
import { REGEN_MODEL, regenerateGraphLoras } from "@/lib/catalog/regenerate";
import { enhancePrompt, enhanceSoulWords, ideogramCaption } from "./enhance";
import { carriesLayout } from "@/lib/layout-prompt";
@@ -843,7 +845,13 @@ export function previewGeneration(asked: GenerationRequest) {
dropped: [...switchedOff, ...unreachable.map((l) => ({ file: l.file, reason: "it downloads from civitai, which needs your civitai key (Settings → LoRAs)" })), ...fitted.dropped],
};
// PixeletedFace pixelates each picture's faces afterwards (createMosaicRun): fal's SAM 3.1 per picture in the cloud.
- const post = demo || moved.request.postMade ? 0 : postStepCost(plan.model.id, moved.request.presetId, plan.model.engine, plan.jobs * plan.perJobOutputs, getModel);
+ let post = demo || moved.request.postMade ? 0 : postStepCost(plan.model.id, moved.request.presetId, plan.model.engine, plan.jobs * plan.perJobOutputs, getModel);
+ // "Clean the voice first" (voice-first.ts): its other steps are checked as the run checks them, and priced in.
+ const voiced = moved.request.voiceFirst ? voiceFirstExtra(moved.request, plan.model) : null;
+ if (voiced) {
+ post = cost === null || voiced.costUsd === null ? post : post + voiced.costUsd;
+ notes.push(...voiced.notes);
+ }
return {
model: plan.model,
op: plan.op,
@@ -865,6 +873,26 @@ export function previewGeneration(asked: GenerationRequest) {
};
}
+/** The steps "Clean the voice first" adds to a run (all but the run itself), checked and priced as the run makes them. */
+function voiceFirstExtra(req: GenerationRequest, model: ModelDef): { costUsd: number | null; notes: string[] } | null {
+ const vf = voiceFirstPlanFor(req, model);
+ if (!vf) return null;
+ let costUsd: number | null = 0;
+ for (const s of vf.steps) {
+ if (s.key === "main") continue;
+ let p: ReturnType<typeof previewChained>;
+ try {
+ p = previewChained(s.chain ? { ...s.request, chain: s.chain } : s.request, s.after?.length ?? 0);
+ } catch (e) {
+ throw new Error(`${VOICE_FIRST_LABEL} can't run: ${(e as Error).message}. Turn it off to run without it`);
+ }
+ costUsd = costUsd === null || p.costUsd === null ? null : costUsd + p.costUsd;
+ }
+ const op = inferOperation(model, req);
+ const notes = op === "lipsync" && req.inputs?.video ? [vf.bed ? BED_NOTES.open : model.engine === "cloud" ? BED_NOTES.cloud : null].filter((x): x is string => !!x) : [];
+ return { costUsd: costUsd === null ? null : Math.round(costUsd * 10000) / 10000, notes };
+}
+
/** Preview a step that will wait for `deps` earlier steps: validated with placeholders in its chain slots, as createGenerations does. */
export function previewChained(req: GenerationRequest, deps: number) {
if (!deps) return previewGeneration(req);
@@ -949,6 +977,11 @@ export function createGenerations(given: GenerationRequest, opts: CreateOptions
const waitsFor = opts.dependsOn === undefined ? undefined : Array.isArray(opts.dependsOn) ? opts.dependsOn : [opts.dependsOn];
return createMosaicRun(original, shotModel, { batchId: opts.batchId, dependsOn: waitsFor });
}
+ // "Clean the voice first": the clean voice, then the transcript or lip sync on it (and a lip re-sync's music back after).
+ if (!opts.dependsOn && original.voiceFirst && shotModel) {
+ const run = createVoiceFirstRun(original, shotModel, { batchId: opts.batchId });
+ if (run) return run;
+ }
// Open-H3 Regenerate: the draft preset from the clip's maker, and a clip over 15 s in 15 s parts joined (regenerate.ts).
if (shotModel?.id === REGEN_MODEL) {
const run = createRegenerateRun(original, shotModel, opts, createGenerations, joinClips, (id) => void cancelGeneration(id));
diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.ts
index 01860897..0e05ffc9 100644
--- a/src/server/genjutsu.ts
+++ b/src/server/genjutsu.ts
@@ -582,6 +582,8 @@ export const TRANSCRIBERS: Record<Engine, string> = { cloud: "scribe-v2", open:
export const TranscribeSchema = z.object({
engine: z.enum(["cloud", "open"]),
source: z.object({ url: z.string().startsWith("/api/files/").max(500), duration: z.number().finite().positive().max(3600).optional() }),
+ // "Clean the voice first" (src/lib/av/voice-first.ts): the words are read from the speech alone.
+ voiceFirst: z.boolean().optional(),
});
/**
@@ -601,6 +603,7 @@ export function transcribeClip(body: z.infer<typeof TranscribeSchema>): { id: st
op: "transcribe",
inputs: { video: body.source.url },
...(seconds ? { params: { duration: seconds, sourceDuration: seconds } } : {}),
+ ...(body.voiceFirst && { voiceFirst: true }),
step: { label: "The clip's words", index: 0, of: 1 },
});
return { id: g.id, modelId };
diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.ts
index 411121be..dfff2490 100644
--- a/src/server/recipe-builder.ts
+++ b/src/server/recipe-builder.ts
@@ -88,7 +88,7 @@ function mosaicShape(req: GenerationRequest): string {
}
/** Request fields a step keeps (GenerationRequestSchema's, less the server's own): everything else is dropped. */
-const KEEP: (keyof GenerationRequest)[] = ["feature", "presetId", "modelId", "op", "prompt", "negativePrompt", "inputs", "params", "presetOptions", "presetStrength", "mix", "loras", "engine", "signature"];
+const KEEP: (keyof GenerationRequest)[] = ["feature", "presetId", "modelId", "op", "prompt", "negativePrompt", "inputs", "params", "presetOptions", "presetStrength", "mix", "loras", "engine", "signature", "voiceFirst"];
function stepRequest(req: GenerationRequest): Record<string, unknown> {
const out = Object.fromEntries(KEEP.flatMap((k) => (req[k] === undefined ? [] : [[k, JSON.parse(JSON.stringify(req[k]))]]))) as Record<string, unknown> & GenerationRequest;
diff --git a/src/server/request-schema.ts b/src/server/request-schema.ts
index 2126fd48..2fbf74c7 100644
--- a/src/server/request-schema.ts
+++ b/src/server/request-schema.ts
@@ -146,4 +146,6 @@ export const GenerationRequestSchema = z.object({
// What a tool calls its result (Trim · 0:01.0–0:02.5, Captions · Karaoke), shown instead of the prompt.
title: z.string().max(200).optional(),
batchTitle: z.string().max(200).optional(),
+ // "Clean the voice first" (src/lib/av/voice-first.ts): a transcript or lip sync runs on the speech alone.
+ voiceFirst: z.boolean().optional(),
});
diff --git a/src/server/swap-studio.ts b/src/server/swap-studio.ts
index 6ea0a918..97d0a32d 100644
--- a/src/server/swap-studio.ts
+++ b/src/server/swap-studio.ts
@@ -728,7 +728,7 @@ function prepareClipQuietly(projectId: string, clipId: string): void {
// ---------------------------------------------------------------------------
// Transcript
-export function transcribe(projectId: string, clipId: string): SwapProject {
+export function transcribe(projectId: string, clipId: string, voiceFirst = false): SwapProject {
const p = advanceProject(projectId);
mustMatchMode(p.engine);
const clip = mustClip(p, clipId);
@@ -737,7 +737,7 @@ export function transcribe(projectId: string, clipId: string): SwapProject {
mustOffer(modelId, p.engine, "type each shot's words instead");
const busy = look1(clip.transcript?.genId);
if (busy && ACTIVE.has(busy.status)) throw new ShortsError("The clip is being transcribed", 409);
- const pipe = run(planTranscribe(clip, p.engine));
+ const pipe = run(planTranscribe(clip, p.engine, voiceFirst));
const genId = pipe.byKey.transcribe.id;
return mutate(projectId, (cur) => mapClip(cur, clipId, (c) => ({ ...c, transcript: { genId, modelId, cues: null, voices: c.transcript?.voices ?? {} } })));
}
@@ -1219,7 +1219,7 @@ export function estimateProject(projectId: string): StudioEstimate {
const p = advanceProject(projectId);
const look = lookup();
const engine = p.engine;
- const out: StudioEstimate = { engine, demo: false, free: engine === "open", segments: {}, problems: {}, shots: {}, project: { costUsd: 0, segments: 0 }, assembly: {}, transcribe: {}, mask: {}, sharpen: {}, anchors: [], notes: [] };
+ const out: StudioEstimate = { engine, demo: false, free: engine === "open", segments: {}, problems: {}, shots: {}, project: { costUsd: 0, segments: 0 }, assembly: {}, transcribe: {}, cleanVoice: {}, mask: {}, sharpen: {}, anchors: [], notes: [] };
const track = (r: { demo: boolean }) => {
if (r.demo) out.demo = true;
};
@@ -1231,6 +1231,9 @@ export function estimateProject(projectId: string): StudioEstimate {
const t = price(planTranscribe(working, engine));
track(t);
out.transcribe[clip.id] = t.costUsd;
+ // "Clean the voice first": what it adds (ElevenLabs Voice Isolation in the cloud; free on your GPU).
+ const c = price(planTranscribe(working, engine, true));
+ out.cleanVoice[clip.id] = c.costUsd === null || t.costUsd === null ? null : Math.round((c.costUsd - t.costUsd) * 10000) / 10000;
}
for (const [si, shot] of clip.shots.entries()) {
if (shot.mode !== "generate") continue;
diff --git a/src/server/voice-first.ts b/src/server/voice-first.ts
new file mode 100644
index 00000000..45d1b5e2
--- /dev/null
+++ b/src/server/voice-first.ts
@@ -0,0 +1,73 @@
+import "server-only";
+import { inferOperation } from "@/lib/catalog/plan";
+import type { Generation, GenerationRequest, ModelDef } from "@/lib/catalog/types";
+import { planVoiceFirst, voiceFirstApplies, voiceSource, VOICE_FIRST_LABEL, VOICE_FIRST_MODELS, type VoiceFirstPlan } from "@/lib/av/voice-first";
+import { getModel } from "@/lib/catalog";
+import { createPipeline, withAsked } from "./chains";
+import { storedMedia } from "./storage";
+
+/**
+ * "Clean the voice first" on the server (src/lib/av/voice-first.ts plans it): a request with `voiceFirst` becomes one
+ * batch of steps, the clean voice before the transcript or lip sync and, for a lip re-sync on your GPU, the clip's music
+ * and effects put back after it. Every studio that sends a transcript or a lip sync through createGenerations gets it
+ * (Transcribe, Captions, Lipsync & avatars, Genjutsu's "What's said", Character Swap Studio's transcript).
+ *
+ * The files read are the request's own (the route checked them for an account, account-inputs.ts), and their headers are
+ * read through storedMedia, which inside an account's run sees only the account's files.
+ */
+
+/** A file's length, channels and sound from its header (null when nothing reads it). */
+function facts(url: string | undefined): { duration?: number; channels?: number; hasAudio?: boolean } | null {
+ if (!url) return null;
+ const info = storedMedia(url, { allContainers: true })?.info;
+ if (!info) return null;
+ return { ...(info.duration && info.duration > 0 && { duration: info.duration }), ...(info.channels && { channels: info.channels }), hasAudio: info.hasAudio };
+}
+
+/** The steps a request with "Clean the voice first" runs as, or null when it doesn't apply (no speech attached, another operation). */
+export function voiceFirstPlanFor(req: GenerationRequest, model: ModelDef): VoiceFirstPlan | null {
+ if (!req.voiceFirst) return null;
+ const op = inferOperation(model, req);
+ if (!voiceFirstApplies(req, op)) return null;
+ const src = voiceSource(req, op)!;
+ const heard = facts(src.url);
+ // A recording with no sound in it: nothing to clean, and the run itself says what's wrong.
+ if (heard?.hasAudio === false) return null;
+ const clip = op === "lipsync" && req.inputs?.video ? facts(req.inputs.video) : null;
+ return planVoiceFirst({
+ request: { ...req, op },
+ op,
+ engine: model.engine,
+ seconds: req.params?.sourceDuration ?? heard?.duration,
+ channels: heard?.channels,
+ clipHasSound: clip ? clip.hasAudio : undefined,
+ clipChannels: clip?.channels,
+ });
+}
+
+/** Why the clean voice can't run, in the studio's words (its model switched off, the other engine only…). */
+function refused(e: unknown, plan: VoiceFirstPlan): Error {
+ const msg = (e as Error).message ?? String(e);
+ const step = /^Step “(\w+)”: (.*)$/s.exec(msg);
+ if (!step || step[1] === "main") return new Error(step ? step[2] : msg);
+ const model = getModel(plan.steps.find((s) => s.key === step[1])?.request.modelId ?? VOICE_FIRST_MODELS.open);
+ return new Error(`${VOICE_FIRST_LABEL} can't run${model ? ` (${model.name})` : ""}: ${step[2]}. Turn it off to run without it`);
+}
+
+/**
+ * The run as steps (one batch), its result first, as createMosaicRun returns it: a caller that takes the first row (a
+ * studio's card, Genjutsu's transcript id) gets the transcript or the lip sync. Null when the switch doesn't apply.
+ */
+export function createVoiceFirstRun(req: GenerationRequest, model: ModelDef, opts: { batchId?: string } = {}): Generation[] | null {
+ const plan = voiceFirstPlanFor(req, model);
+ if (!plan) return null;
+ let made: ReturnType<typeof createPipeline>;
+ try {
+ made = createPipeline(plan.steps, { ...(opts.batchId && { batchId: opts.batchId }) });
+ } catch (e) {
+ throw refused(e, plan);
+ }
+ const result = made.byKey[plan.result];
+ // The result keeps the request as asked (the switch on, the file given), so Reuse and a skill run it the same way.
+ return withAsked([result, ...made.items.filter((g) => g.id !== result.id)], req, model.engine);
+}
diff --git a/tests/voice-first.test.ts b/tests/voice-first.test.ts
new file mode 100644
index 00000000..981cbb24
--- /dev/null
+++ b/tests/voice-first.test.ts
@@ -0,0 +1,339 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import {
+ BED_DB,
+ BED_NOTES,
+ planVoiceFirst,
+ putsBedBack,
+ VOICE_FIRST_MODELS,
+ voiceFirstApplies,
+ voiceFirstCost,
+ voiceFirstDefault,
+ voiceFirstLine,
+ voiceFirstTime,
+ voiceSource,
+} from "@/lib/av/voice-first";
+import { splitTime } from "@/lib/av/split";
+import { getModel } from "@/lib/catalog";
+import type { GenerationRequest } from "@/lib/catalog/types";
+
+// "Clean the voice first" (DBS D6): the plan per engine and studio, the chain's stems, the put-back after a lip re-sync,
+// the prices and times, and the server's expansion in demo mode (createGenerations, previewGeneration, Genjutsu's
+// "What's said", Character Swap Studio's transcript).
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-voice-first-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: the open models run on the demo provider.
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { saveFile } = await import("@/server/storage");
+const gens = await import("@/server/generations");
+const { createPipeline } = await import("@/server/chains");
+const { transcribeClip } = await import("@/server/genjutsu");
+const { changeAccess } = await import("@/server/model-access");
+const { planTranscribe } = await import("@/lib/catalog/swap-studio-plan");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const AUDIO = "/api/files/uploads/2026-11-02/voice.wav";
+const VIDEO = "/api/files/uploads/2026-11-02/clip.mp4";
+
+const transcript = (inputs: GenerationRequest["inputs"], modelId = "oss-qwen3-asr"): GenerationRequest => ({ feature: "transcribe", modelId, op: "transcribe", inputs, params: { sourceLanguage: "en" } });
+const lipsync = (inputs: GenerationRequest["inputs"], modelId = "oss-infinitetalk-v2v"): GenerationRequest => ({ feature: "lipsync", modelId, op: "lipsync", inputs, title: "Re-sync" });
+
+describe("where it applies, and its default", () => {
+ it("cleans a transcript's recording or video and a lip sync's voice; nothing else", () => {
+ expect(voiceSource({ inputs: { audio: AUDIO } }, "transcribe")).toEqual({ slot: "audio", url: AUDIO });
+ expect(voiceSource({ inputs: { video: VIDEO } }, "transcribe")).toEqual({ slot: "video", url: VIDEO });
+ expect(voiceSource({ inputs: { video: VIDEO, audio: AUDIO } }, "lipsync")).toEqual({ slot: "audio", url: AUDIO });
+ expect(voiceSource({ inputs: { images: ["/api/files/a.png"], audio: AUDIO } }, "avatar")).toEqual({ slot: "audio", url: AUDIO });
+ // A lip sync's video is the picture, not the speech.
+ expect(voiceSource({ inputs: { video: VIDEO } }, "lipsync")).toBeNull();
+ expect(voiceFirstApplies({ inputs: { audio: AUDIO } }, "tts")).toBe(false);
+ expect(voiceFirstApplies({ inputs: {} }, "transcribe")).toBe(false);
+ });
+
+ it("is on for a video and off for an audio upload", () => {
+ expect(voiceFirstDefault({ inputs: { video: VIDEO } }, "transcribe")).toBe(true);
+ expect(voiceFirstDefault({ inputs: { audio: AUDIO } }, "transcribe")).toBe(false);
+ expect(voiceFirstDefault({ inputs: { video: VIDEO, audio: AUDIO } }, "lipsync")).toBe(true);
+ expect(voiceFirstDefault({ inputs: { images: ["/api/files/a.png"], audio: AUDIO } }, "avatar")).toBe(false);
+ });
+
+ it("puts the music and effects back only after a lip re-sync on your GPU of a clip with sound", () => {
+ const req = { inputs: { video: VIDEO, audio: AUDIO } };
+ expect(putsBedBack(req, "lipsync", "open")).toBe(true);
+ expect(putsBedBack(req, "lipsync", "open", false)).toBe(false);
+ expect(putsBedBack(req, "lipsync", "cloud")).toBe(false);
+ expect(putsBedBack({ inputs: { images: ["/api/files/a.png"], audio: AUDIO } }, "avatar", "open")).toBe(false);
+ });
+});
+
+describe("the plan per engine", () => {
+ it("Transcribe on your GPU: DBS on the video, then Qwen3-ASR on its voice stem (the video no longer goes in)", () => {
+ const p = planVoiceFirst({ request: { ...transcript({ video: VIDEO }), voiceFirst: true }, op: "transcribe", engine: "open", seconds: 12.3456 });
+ expect(p.result).toBe("main");
+ expect(p.bed).toBe(false);
+ expect(p.steps.map((s) => [s.key, s.request.modelId, s.request.op])).toEqual([
+ ["voice", "oss-dbs-separate", "separate-audio"],
+ ["main", "oss-qwen3-asr", "transcribe"],
+ ]);
+ expect(p.steps[0].request.inputs).toEqual({ video: VIDEO });
+ expect(p.steps[0].request.params).toEqual({ extra: { channels: "mono" }, sourceDuration: 12.346 });
+ const main = p.steps[1];
+ expect(main.after).toEqual(["voice"]);
+ expect(main.chain).toEqual([{ slot: "audio", stem: "voice" }]);
+ expect(main.request.inputs).toEqual({});
+ expect(main.request.voiceFirst).toBeUndefined();
+ expect(main.request.params).toMatchObject({ sourceLanguage: "en", sourceDuration: 12.346 });
+ expect(p.steps.map((s) => s.request.step)).toEqual([
+ { label: "Clean voice", index: 0, of: 2 },
+ { label: "Words from the clean voice", index: 1, of: 2 },
+ ]);
+ });
+
+ it("Transcribe in the cloud: ElevenLabs Voice Isolation before Scribe v2, its one output taken whole", () => {
+ const p = planVoiceFirst({ request: transcript({ audio: AUDIO }, "scribe-v2"), op: "transcribe", engine: "cloud" });
+ expect(p.steps.map((s) => s.request.modelId)).toEqual([VOICE_FIRST_MODELS.cloud, "scribe-v2"]);
+ expect(p.steps[0].request.inputs).toEqual({ audio: AUDIO });
+ expect(p.steps[1].chain).toEqual([{ slot: "audio" }]);
+ });
+
+ it("Lipsync on your GPU of a clip: the voice cleaned, the clip split, and its music and effects back under the clean voice at 0 dB", () => {
+ const p = planVoiceFirst({ request: lipsync({ video: VIDEO, audio: AUDIO }), op: "lipsync", engine: "open", seconds: 8, clipChannels: 6 });
+ expect(p.result).toBe("film");
+ expect(p.bed).toBe(true);
+ expect(p.steps.map((s) => [s.key, s.request.modelId, s.request.op])).toEqual([
+ ["voice", "oss-dbs-separate", "separate-audio"],
+ ["main", "oss-infinitetalk-v2v", "lipsync"],
+ ["bed", "oss-dbs-separate", "separate-audio"],
+ ["film", "oss-mux", "mux"],
+ ]);
+ // The lip sync keeps its picture and takes the clean voice.
+ expect(p.steps[1].request.inputs).toEqual({ video: VIDEO });
+ expect(p.steps[1].chain).toEqual([{ slot: "audio", stem: "voice" }]);
+ // The clip's split reads its soundtrack (a surround file is split in mono, with its channel count).
+ expect(p.steps[2].request.inputs).toEqual({ video: VIDEO });
+ expect(p.steps[2].request.params?.extra).toEqual({ channels: "mono", sourceChannels: 6 });
+ const film = p.steps[3];
+ expect(film.after).toEqual(["main", "voice", "bed"]);
+ expect(film.chain).toEqual([{ slot: "video" }, { slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }]);
+ expect(film.request.params?.extra).toEqual({ backgroundVolumeDb: BED_DB });
+ expect(BED_DB).toBe(0);
+ expect(film.request.title).toBe("Re-sync");
+ expect(p.steps.map((s) => s.request.step?.index)).toEqual([0, 1, 2, 3]);
+ expect(p.steps.every((s) => s.request.step?.of === 4)).toBe(true);
+ });
+
+ it("Lipsync of a silent clip, a talking avatar, or in the cloud: no put-back", () => {
+ expect(planVoiceFirst({ request: lipsync({ video: VIDEO, audio: AUDIO }), op: "lipsync", engine: "open", clipHasSound: false }).steps.map((s) => s.key)).toEqual(["voice", "main"]);
+ const avatar = planVoiceFirst({ request: { feature: "lipsync", modelId: "oss-infinitetalk", op: "avatar", inputs: { images: ["/api/files/a.png"], audio: AUDIO } }, op: "avatar", engine: "open" });
+ expect(avatar.steps.map((s) => s.key)).toEqual(["voice", "main"]);
+ expect(avatar.steps[1].request.inputs).toEqual({ images: ["/api/files/a.png"] });
+ const cloud = planVoiceFirst({ request: lipsync({ video: VIDEO, audio: AUDIO }, "sync-lipsync-3"), op: "lipsync", engine: "cloud" });
+ expect(cloud.steps.map((s) => s.request.modelId)).toEqual(["elevenlabs-voice-isolation", "sync-lipsync-3"]);
+ expect(cloud.steps[0].request.inputs).toEqual({ audio: AUDIO });
+ });
+
+ it("says what's missing", () => {
+ expect(() => planVoiceFirst({ request: transcript({}), op: "transcribe", engine: "open" })).toThrow("Add the recording or video to transcribe");
+ expect(() => planVoiceFirst({ request: lipsync({ video: VIDEO }), op: "lipsync", engine: "open" })).toThrow("Add the voice first");
+ });
+});
+
+describe("what the switch says", () => {
+ it("prices the cloud step at ElevenLabs' $0.10 a minute of speech; free on your GPU", () => {
+ expect(getModel("elevenlabs-voice-isolation")?.pricing).toMatchObject({ unit: "minute", usd: 0.1 });
+ expect(voiceFirstCost("cloud", 30, getModel)).toBeCloseTo(0.05, 6);
+ expect(voiceFirstCost("cloud", 120, getModel)).toBeCloseTo(0.2, 6);
+ expect(voiceFirstCost("open", 120, getModel)).toBe(0);
+ expect(voiceFirstLine({ engine: "cloud", seconds: 30, getModel })).toBe("+$0.05");
+ expect(voiceFirstLine({ engine: "cloud", getModel })).toBe("+$0.10 a minute");
+ });
+
+ it("times the open step as one Fast mono split (two and the mux with the put-back)", () => {
+ const one = splitTime({ seconds: 60, quality: "fast", mode: "mono" });
+ expect(voiceFirstTime({ seconds: 60 })).toEqual(one);
+ expect(voiceFirstTime({ seconds: 60, bed: true })).toEqual({ low: one.low * 2 + 2, high: one.high * 2 + 4 });
+ expect(voiceFirstTime({ seconds: 60, device: "cuda" })).toEqual(splitTime({ seconds: 60, quality: "best", mode: "mono", device: "cuda" }));
+ expect(voiceFirstLine({ engine: "open", seconds: 60, getModel })).toMatch(/^Free · adds about \d+(–\d+)? min$/);
+ expect(voiceFirstLine({ engine: "open", seconds: 5, device: "cuda", getModel })).toBe("Free · adds under a minute");
+ expect(voiceFirstLine({ engine: "open", getModel })).toBe("Free · adds a little time");
+ });
+
+ it("says plainly what each engine does with a clip's music and effects", () => {
+ expect(BED_NOTES.open).toMatch(/go back under the new lip movement/);
+ expect(BED_NOTES.cloud).toMatch(/your GPU \(open source\)/);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The server, in demo mode
+
+/** A small MP4: a video track and, unless `sound` is false, a stereo AAC track (2 s each). */
+function mp4(sound = true): Buffer {
+ const u32 = (...v: number[]) => Buffer.concat(v.map((n) => Buffer.from([n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255])));
+ const box = (type: string, ...parts: Buffer[]) => {
+ const body = Buffer.concat(parts);
+ return Buffer.concat([u32(8 + body.length), Buffer.from(type), body]);
+ };
+ const trak = (handler: string, ...stbl: Buffer[]) =>
+ box("trak", box("mdia", box("mdhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(4)), box("hdlr", u32(0, 0), Buffer.from(handler), Buffer.alloc(12)), box("minf", box("stbl", ...stbl))));
+ const entry = Buffer.alloc(28);
+ entry.writeUInt16BE(1, 6);
+ entry.writeUInt16BE(2, 16);
+ entry.writeUInt16BE(16, 18);
+ return Buffer.concat([
+ box("ftyp", Buffer.from("isom"), u32(0)),
+ box("moov", box("mvhd", u32(0, 0, 0, 1000, 2000), Buffer.alloc(80)), trak("vide", box("stts", u32(0, 1, 50, 40))), ...(sound ? [trak("soun", box("stsd", u32(0, 1), box("mp4a", entry)))] : [])),
+ ]);
+}
+const clip = (sound = true) => saveFile({ data: mp4(sound), contentType: "video/mp4", name: sound ? "clip.mp4" : "silent.mp4", source: "upload" }).url;
+
+/** A 1 s mono 16 kHz WAV. */
+function wav(): Buffer {
+ const frames = 16000;
+ const b = Buffer.alloc(44 + frames * 2);
+ b.write("RIFF", 0);
+ b.writeUInt32LE(36 + frames * 2, 4);
+ b.write("WAVE", 8);
+ b.write("fmt ", 12);
+ b.writeUInt32LE(16, 16);
+ b.writeUInt16LE(1, 20);
+ b.writeUInt16LE(1, 22);
+ b.writeUInt32LE(16000, 24);
+ b.writeUInt32LE(32000, 28);
+ b.writeUInt16LE(2, 32);
+ b.writeUInt16LE(16, 34);
+ b.write("data", 36);
+ b.writeUInt32LE(frames * 2, 40);
+ return b;
+}
+const voice = () => saveFile({ data: wav(), contentType: "audio/wav", name: "voice.wav", source: "upload" }).url;
+
+async function finished(id: string, ms = 15_000) {
+ const deadline = Date.now() + ms;
+ let g = gens.getGeneration(id)!;
+ while (g.status !== "succeeded" && g.status !== "failed" && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 200));
+ g = gens.getGeneration(id)!;
+ }
+ return g;
+}
+
+describe("createGenerations with voiceFirst (demo mode)", () => {
+ it("transcribes a video's clean voice on your GPU: the transcript first, both in one batch", async () => {
+ const video = clip();
+ const made = gens.createGenerations({ ...transcript({ video }), voiceFirst: true });
+ expect(made.map((g) => [g.modelId, g.op])).toEqual([
+ ["oss-qwen3-asr", "transcribe"],
+ ["oss-dbs-separate", "separate-audio"],
+ ]);
+ expect(new Set(made.map((g) => g.batchId)).size).toBe(1);
+ // The transcript keeps the request as asked: Reuse runs it again with the switch on.
+ expect(made[0].request.asked).toMatchObject({ voiceFirst: true, inputs: { video } });
+ expect(made[0].request.chain).toEqual([{ slot: "audio", stem: "voice" }]);
+ const split = await finished(made[1].id);
+ expect(split.status).toBe("succeeded");
+ const words = await finished(made[0].id);
+ expect(words.status).toBe("succeeded");
+ // It ran on the voice stem, not the video.
+ const voiceStem = split.outputs.find((o) => o.meta?.stem === "voice")!;
+ const ran = gens.getGeneration(made[0].id)!.request;
+ expect(ran.inputs?.audio).toBe(voiceStem.url);
+ expect(ran.inputs?.video).toBeUndefined();
+ }, 30_000);
+
+ it("re-syncs a clip on your GPU with its music and effects put back: the mux first, four steps", async () => {
+ const video = clip();
+ const audio = voice();
+ const made = gens.createGenerations({ ...lipsync({ video, audio }), voiceFirst: true });
+ expect(made.map((g) => [g.modelId, g.op])).toEqual([
+ ["oss-mux", "mux"],
+ ["oss-dbs-separate", "separate-audio"],
+ ["oss-dbs-separate", "separate-audio"],
+ ["oss-infinitetalk-v2v", "lipsync"],
+ ]);
+ expect(made[0].request.chain).toEqual([{ slot: "video" }, { slot: "audio", stem: "voice" }, { slot: "audio2", stem: "background" }]);
+ expect(made[0].request.params?.extra).toEqual({ backgroundVolumeDb: 0 });
+ // The voice is split from the voice upload, the bed from the clip.
+ expect(made.filter((g) => g.op === "separate-audio").map((g) => g.request.inputs)).toEqual([{ audio }, { video }]);
+ // The demo's placeholder mux takes a while after the three steps it waits for.
+ const film = await finished(made[0].id, 50_000);
+ expect(film.status).toBe("succeeded");
+ expect(film.outputs[0].kind).toBe("video");
+ }, 60_000);
+
+ it("leaves the put-back out for a clip with no sound", () => {
+ const made = gens.createGenerations({ ...lipsync({ video: clip(false), audio: voice() }), voiceFirst: true });
+ expect(made.map((g) => g.modelId)).toEqual(["oss-infinitetalk-v2v", "oss-dbs-separate"]);
+ });
+
+ it("cleans with ElevenLabs before a cloud model, without the put-back", () => {
+ const made = gens.createGenerations({ ...lipsync({ video: clip(), audio: voice() }, "sync-lipsync-3"), voiceFirst: true });
+ expect(made.map((g) => g.modelId)).toEqual(["sync-lipsync-3", "elevenlabs-voice-isolation"]);
+ expect(made[0].request.chain).toEqual([{ slot: "audio" }]);
+ });
+
+ it("runs as asked without the switch, or where it doesn't apply", () => {
+ expect(gens.createGenerations(transcript({ video: clip() })).map((g) => g.modelId)).toEqual(["oss-qwen3-asr"]);
+ expect(gens.createGenerations({ feature: "image", modelId: "oss-qwen-image-21", op: "t2i", prompt: "A koi pond at night", voiceFirst: true }).map((g) => g.modelId)).toEqual(["oss-qwen-image-21"]);
+ });
+
+ it("works as a pipeline step: the step's result is the transcript", () => {
+ const { byKey, items } = createPipeline([{ key: "words", request: { ...transcript({ video: clip() }), voiceFirst: true } }]);
+ expect(byKey.words.modelId).toBe("oss-qwen3-asr");
+ expect(items.map((g) => g.modelId)).toEqual(["oss-qwen3-asr", "oss-dbs-separate"]);
+ });
+
+ it("names the switch when its step can't run (its model switched off)", () => {
+ changeAccess([{ kind: "model", id: "oss-dbs-separate", on: false }]);
+ try {
+ expect(() => gens.createGenerations({ ...transcript({ video: clip() }), voiceFirst: true })).toThrow(/^Clean the voice first can't run \(DBS \(dialogue, music, effects\)\): .*Turn it off to run without it$/s);
+ expect(() => gens.previewGeneration({ ...transcript({ video: clip() }), voiceFirst: true })).toThrow(/^Clean the voice first can't run: /);
+ } finally {
+ changeAccess([{ kind: "reset" }]);
+ }
+ });
+});
+
+describe("previewGeneration with voiceFirst", () => {
+ it("adds ElevenLabs' price in the cloud and nothing on your GPU", () => {
+ const audio = voice();
+ const plain = gens.previewGeneration(transcript({ audio }, "scribe-v2"));
+ const clean = gens.previewGeneration({ ...transcript({ audio }, "scribe-v2"), voiceFirst: true });
+ // Demo mode prices the run as it would be paid (the demo is free, the price says what it would cost).
+ if (plain.costUsd !== null && clean.costUsd !== null) expect(clean.costUsd).toBeGreaterThanOrEqual(plain.costUsd);
+ const open = gens.previewGeneration({ ...transcript({ audio }), voiceFirst: true });
+ expect(open.model.id).toBe("oss-qwen3-asr");
+ expect(open.costUsd).toBe(0);
+ });
+
+ it("says what a lip re-sync does with the clip's music and effects on each engine", () => {
+ const req = (modelId: string) => ({ ...lipsync({ video: clip(), audio: voice() }, modelId), voiceFirst: true });
+ expect(gens.previewGeneration(req("oss-infinitetalk-v2v")).notes).toContain(BED_NOTES.open);
+ expect(gens.previewGeneration(req("sync-lipsync-3")).notes).toContain(BED_NOTES.cloud);
+ });
+});
+
+describe("the studios that transcribe a clip", () => {
+ it("Genjutsu's “What's said” cleans the voice when asked, and returns the transcript's id", () => {
+ const video = clip();
+ const on = transcribeClip({ engine: "open", source: { url: video, duration: 2 }, voiceFirst: true });
+ const g = gens.getGeneration(on.id)!;
+ expect(g.op).toBe("transcribe");
+ expect(g.request.chain).toEqual([{ slot: "audio", stem: "voice" }]);
+ const off = transcribeClip({ engine: "open", source: { url: video, duration: 2 } });
+ expect(gens.getGeneration(off.id)!.request.chain).toBeUndefined();
+ });
+
+ it("Character Swap Studio's transcript carries the switch on its step", () => {
+ const c = { name: "Take 1", source: { url: VIDEO, duration: 4, hasAudio: true }, normalized: { url: VIDEO } } as unknown as Parameters<typeof planTranscribe>[0];
+ expect(planTranscribe(c, "open")[0].request.voiceFirst).toBeUndefined();
+ expect(planTranscribe(c, "open", true)[0].request.voiceFirst).toBe(true);
+ expect(planTranscribe(c, "cloud", true)[0].request).toMatchObject({ modelId: "scribe-v2", voiceFirst: true });
+ });
+});