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.

Mixed Media: the cloud engine redraws the clip frame by frame like Higgsfield, with Fast kept for one video-to-video pass

Claude749a38e4462e
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index 7caa8ea2..b41bf9fc 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -84,7 +84,8 @@ model("nano-banana-pro", "Nano Banana Pro", "Google", "gemini-image", "image",
model("nano-banana-2", "Nano Banana 2", "Google", "gemini-image", "image",
"Newest Gemini image model — sharper detail, 0.5K–4K, up to 14 references",
[("t2i", "fal-ai/nano-banana-2"), ("edit", "fal-ai/nano-banana-2/edit")],
- badges=["new", "4k"], pricing=("image", 0.08, "2K 1.5x, 4K 2x"), defaults={"aspectRatio": "1:1", "resolution": "1K"})
+ badges=["new", "4k"], pricing=("image", 0.08, "2K 1.5x, 4K 2x, 0.5K 0.75x", {"byResolution": {"0.5K": 0.06, "1K": 0.08, "2K": 0.12, "4K": 0.16}}),
+ defaults={"aspectRatio": "1:1", "resolution": "1K"})
model("nano-banana-2-1", "Nano Banana 2.1", "Google", "gemini-image", "image",
"Gemini 2.1 image with thinking — strongest instruction following",
[("t2i", "google/nano-banana-2.1"), ("edit", "google/nano-banana-2.1/edit")],
@@ -102,6 +103,10 @@ model("seedream-5-lite", "Seedream 5.0 Lite", "ByteDance", "seedream", "image",
"Fast, affordable Seedream 5",
[("t2i", "bytedance/seedream/v5/lite/text-to-image"), ("edit", "bytedance/seedream/v5/lite/edit")],
badges=["fast"], defaults={"aspectRatio": "3:4"})
+model("seedream-5-flash", "Seedream 5.0 Flash", "ByteDance", "seedream", "image",
+ "The fastest, cheapest Seedream 5 — quick edits in bulk",
+ [("t2i", "bytedance/seedream/v5/flash/text-to-image"), ("edit", "bytedance/seedream/v5/flash/edit")],
+ badges=["fast"], defaults={"aspectRatio": "3:4"})
model("seedream-4-5", "Seedream 4.5", "ByteDance", "seedream", "image",
"Photoreal 4K generation and multi-image editing",
[("t2i", "fal-ai/bytedance/seedream/v4.5/text-to-image"), ("edit", "fal-ai/bytedance/seedream/v4.5/edit")],
diff --git a/src/app/api/mixed-media/route.ts b/src/app/api/mixed-media/route.ts
index 1c2759fa..1b02db46 100644
--- a/src/app/api/mixed-media/route.ts
+++ b/src/app/api/mixed-media/route.ts
@@ -1,12 +1,12 @@
import { createMixed } from "@/server/mixed-media";
import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";
-/** Render a Mixed Media video (open: per frame; cloud: cut → restyle → original sound). */
+/** Render a Mixed Media video (open: per frame; cloud: cut → frames or restyle → original sound). `items` leaves out the per-frame edits (`frames` counts them). */
export async function POST(request: Request) {
return handle(async () => {
const input = await body(request, MixedBodySchema, "Pick a preset, upload a clip and choose up to 10 seconds");
// A repeated requestId (a second click on Generate video) gets the render the first one started.
- const { final, items } = await once("mixed-render", input.requestId, () => createMixed(input));
- return Response.json({ final, items }, { status: 201 });
+ const { final, items, frames } = await once("mixed-render", input.requestId, () => createMixed(input));
+ return Response.json({ final, items, frames }, { status: 201 });
});
}
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index a505b272..8345bf2d 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -166,7 +166,13 @@ export const CLOUD_MODELS: ModelDef[] = [
"pricing": {
"unit": "image",
"usd": 0.08,
- "note": "2K 1.5x, 4K 2x"
+ "note": "2K 1.5x, 4K 2x, 0.5K 0.75x",
+ "byResolution": {
+ "0.5K": 0.06,
+ "1K": 0.08,
+ "2K": 0.12,
+ "4K": 0.16
+ }
}
},
{
@@ -490,6 +496,90 @@ export const CLOUD_MODELS: ModelDef[] = [
"usd": 0.035
}
},
+ {
+ "id": "seedream-5-flash",
+ "name": "Seedream 5.0 Flash",
+ "vendor": "ByteDance",
+ "family": "seedream",
+ "engine": "cloud",
+ "kind": "image",
+ "tagline": "The fastest, cheapest Seedream 5 \u2014 quick edits in bulk",
+ "routes": [
+ {
+ "op": "t2i",
+ "provider": "fal",
+ "endpoint": "bytedance/seedream/v5/flash/text-to-image",
+ "map": {
+ "numOutputs": "num_images",
+ "aspectRatio": {
+ "key": "image_size",
+ "values": {
+ "1:1": "square_hd",
+ "4:3": "landscape_4_3",
+ "3:4": "portrait_4_3",
+ "16:9": "landscape_16_9",
+ "9:16": "portrait_16_9",
+ "3:2": "landscape_4_3",
+ "2:3": "portrait_4_3",
+ "21:9": "landscape_16_9",
+ "5:4": "landscape_4_3",
+ "4:5": "portrait_4_3"
+ }
+ }
+ }
+ },
+ {
+ "op": "edit",
+ "provider": "fal",
+ "endpoint": "bytedance/seedream/v5/flash/edit",
+ "map": {
+ "images": "image_urls",
+ "numOutputs": "num_images",
+ "aspectRatio": {
+ "key": "image_size",
+ "values": {
+ "1:1": "square_hd",
+ "4:3": "landscape_4_3",
+ "3:4": "portrait_4_3",
+ "16:9": "landscape_16_9",
+ "9:16": "portrait_16_9",
+ "3:2": "landscape_4_3",
+ "2:3": "portrait_4_3",
+ "21:9": "landscape_16_9",
+ "5:4": "landscape_4_3",
+ "4:5": "portrait_4_3"
+ }
+ }
+ }
+ }
+ ],
+ "options": {
+ "aspectRatios": [
+ "1:1",
+ "4:3",
+ "3:4",
+ "16:9",
+ "9:16",
+ "3:2",
+ "2:3",
+ "21:9",
+ "5:4",
+ "4:5"
+ ],
+ "maxOutputs": 4,
+ "maxImages": 10
+ },
+ "badges": [
+ "fast"
+ ],
+ "defaults": {
+ "aspectRatio": "3:4"
+ },
+ "pricing": {
+ "unit": "image",
+ "usd": 0.027
+ }
+ },
{
"id": "seedream-4-5",
"name": "Seedream 4.5",
diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.ts
index f974a354..3f3dec9f 100644
--- a/src/lib/catalog/mixed-media.ts
+++ b/src/lib/catalog/mixed-media.ts
@@ -1,9 +1,11 @@
/**
* Mixed Media (Higgsfield's /mixed-media): turn a 1–10 s clip into mixed-media art (sketch, comic,
* paper, neon…) with per-preset settings. Higgsfield samples frames at 4–24 fps and stylises each
- * one, priced per output frame; the open engine does the same (Z-Image per frame, oss-mixed-media),
- * the cloud route runs a video-to-video restyle model on the trimmed clip, anchored on the preview
- * frame when the model takes one (LTX 2.3 reference restyle).
+ * one, priced per output frame; the open engine does the same (Z-Image per frame, oss-mixed-media).
+ * The cloud engine does it too by default ("Per frame": cut → frames → an image edit per frame, each
+ * looking at the frame styled before it → frames back to video → the cut's own sound); "Fast" runs a
+ * video-to-video restyle model on the trimmed clip instead, anchored on the preview frame when the
+ * model takes one (LTX 2.3 reference restyle).
*
* Pure module, shared by the page, src/server/mixed-media.ts and the tests.
* Research: docs/research/higgsfield-studios.md §3.
@@ -31,6 +33,8 @@ export const MIXED_FEATURE = "mixed-media";
/** Helper steps (the cut, the render before the soundtrack) and preview frames stay out of History. */
export const MIXED_STEP_FEATURE = "mixed-media-step";
export const MIXED_PREVIEW_FEATURE = "mixed-media-preview";
+/** Cloud Per frame: one edit per frame. A helper step too ("-step"), kept apart so History and the render view don't load hundreds of them. */
+export const MIXED_FRAME_FEATURE = "mixed-media-frame-step";
/** Cloud restyle models (the first is the default) and the open per-frame model. */
export const MIXED_MODELS: Record<Engine, string[]> = {
@@ -38,10 +42,25 @@ export const MIXED_MODELS: Record<Engine, string[]> = {
open: ["oss-mixed-media"],
};
export const MIXED_TOOLS = {
- cloud: { cut: "trim-video", mux: "merge-audio-video", preview: "nano-banana-2" },
+ cloud: { cut: "trim-video", mux: "merge-audio-video", preview: "nano-banana-2", frames: "extract-frames", assemble: "images-to-video", join: "join-clips" },
open: { preview: "oss-mixed-media" },
} as const;
+/** How the cloud engine restyles: frame by frame like Higgsfield (the default), or one video-to-video pass. */
+export type MixedMode = "frames" | "fast";
+/** Cloud image editors that redraw each frame (the first is the default): Nano Banana 2 takes a seed, Seedream 5.0 Flash is the cheapest. */
+export const MIXED_FRAME_MODELS = ["nano-banana-2", "seedream-5-flash"] as const;
+
+/**
+ * Cloud per-frame limits: fal's extract-nth-frame returns up to 500 frames a call and images-to-video
+ * takes up to 200 images. Frames are styled in lanes of `lane`: each frame looks at the one styled before
+ * it, and each lane's first frame at the approved preview (else the first styled frame), so lanes run side
+ * by side and a 240-frame clip takes the time of about 13 edits, not 240.
+ */
+export const FRAME_LIMITS = { perExtract: 500, perClip: 200, lane: 12, maxInterval: 300 } as const;
+/** The seed every frame is redrawn with when the request names none (the same seed keeps frames alike). */
+export const FRAME_SEED = 424242;
+
// ---------------------------------------------------------------------------
// Settings (Higgsfield's per-preset param_configs: colour pickers, dropdowns with a custom option, text)
@@ -408,13 +427,18 @@ export function mixedLook(p: Pick<MixedPreset, "look" | "settings">, values: Mix
const cap = (s: string) => s[0].toUpperCase() + s.slice(1);
-/** Prompts per step: the video restyle (cloud), each frame (open, img2img), and the preview still (cloud edit). */
+/**
+ * Prompts per step: the video restyle (cloud Fast), each frame (open, img2img), the preview still (cloud
+ * edit), and a cloud frame redrawn next to a styled one (the frame before it, or the approved preview).
+ */
export function mixedPrompts(p: Pick<MixedPreset, "look" | "settings">, values: MixedValues) {
const look = mixedLook(p, values);
+ const still = `Redraw this image as ${look}. Keep the composition, framing, people and poses exactly.`;
return {
video: `Restyle this video as ${look}. Keep the people, poses, motion, timing and camera exactly as they are; change only the look.`,
frame: `${cap(look)}. Same composition and subject as the source frame, highly detailed mixed-media artwork.`,
- still: `Redraw this image as ${look}. Keep the composition, framing, people and poses exactly.`,
+ still,
+ framePair: `Redraw the first image as ${look}. Keep its composition, framing, people and poses exactly. The second image is an earlier frame of the same clip already redrawn: match its style, colours, textures and line work exactly so the frames play as one animation.`,
};
}
@@ -476,6 +500,33 @@ export function nearestResolution(choices: string[] | undefined, want: MixedReso
return [...choices].filter((c) => c !== "auto").sort((a, b) => Math.abs(rank(a) - t) - Math.abs(rank(b) - t) || rank(b) - rank(a))[0];
}
+/**
+ * Cloud per-frame sampling: the extractor takes every `interval`-th frame of the clip, so the frame rate
+ * is the clip's own divided by a whole number — the one closest to the rate asked for (fewer frames on a
+ * tie), never below 4 FPS. 8 FPS from a 30 FPS clip is every 4th frame, 7.5 FPS; 24 from 25 is every
+ * frame. `frames` counts as Higgsfield does, floor(seconds × fps).
+ */
+export function frameSampling(seconds: number, fps: number, sourceFps: number): { interval: number; fps: number; frames: number } {
+ let interval = 1;
+ for (let k = 2; k <= FRAME_LIMITS.maxInterval && sourceFps / k >= MIXED.manualFps.min - 1e-9; k++) {
+ if (Math.abs(sourceFps / k - fps) <= Math.abs(sourceFps / interval - fps) + 1e-9) interval = k;
+ if (sourceFps / k < fps) break;
+ }
+ const rate = sourceFps / interval;
+ return { interval, fps: Math.round(rate * 1000) / 1000, frames: mixedFrames(seconds, rate) };
+}
+
+/** Consecutive runs of at most `size` frames: the extractor's calls (500) or the clips frames go back into (200). */
+export function frameChunks(frames: number, size: number): { from: number; count: number }[] {
+ return Array.from({ length: Math.ceil(frames / size) }, (_, i) => ({ from: i * size, count: Math.min(size, frames - i * size) }));
+}
+
+/** What the cloud frame editor is asked for: Nano Banana 2 keeps the frame's shape at 1K/2K/4K, Seedream 5.0 Flash at auto 1K/2K. */
+export function frameEditParams(modelId: string, resolution: MixedResolution, seed: number): { aspectRatio?: string; resolution?: string; seed?: number; extra?: Record<string, unknown> } {
+ if (modelId === "seedream-5-flash") return { extra: { image_size: resolution === "1K" ? "auto_1K" : "auto_2K" } };
+ return { aspectRatio: "auto", resolution, seed };
+}
+
// ---------------------------------------------------------------------------
// Pipelines
@@ -488,8 +539,12 @@ export interface MixedPlanInput {
range: { start: number; end: number };
fps: number;
resolution: MixedResolution;
- /** The restyle model (cloud) or oss-mixed-media (open). */
+ /** The restyle model (cloud Fast), the frame editor (cloud Per frame: MIXED_FRAME_MODELS) or oss-mixed-media (open). */
modelId: string;
+ /** Cloud: frame by frame (default) or one video-to-video pass. */
+ mode?: MixedMode;
+ /** Cloud Per frame: the clip's own frame rate (frames are every Nth one of it). */
+ sourceFps?: number;
/** Cloud: the approved preview still, sent when the model takes an image (LTX: the first frame; Kling, Happy Horse: a style reference). */
anchor?: string;
/** Cloud: what to ask the model for (its nearest resolution). */
@@ -499,8 +554,9 @@ export interface MixedPlanInput {
seed?: number;
}
-/** The full render. Open: one per-frame job. Cloud: cut the selection, restyle it, put its own sound back. */
+/** The full render. Open: one per-frame job. Cloud: cut the selection, restyle it (frame by frame, or Fast), put its own sound back. */
export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: string } {
+ if (input.engine === "cloud" && (input.mode ?? "frames") === "frames") return planMixedFrames(input);
const prompts = mixedPrompts(input.preset, input.values);
const base = { batchTitle: input.title };
const seed = input.seed !== undefined ? { seed: input.seed } : {};
@@ -575,6 +631,112 @@ export function planMixed(input: MixedPlanInput): { steps: PlanStep[]; final: st
return { steps, final: "final" };
}
+/**
+ * Cloud, frame by frame (Higgsfield's Mixed Media): cut the selection → take every Nth frame (500 a call;
+ * a longer run is cut into windows) → redraw each frame with the frame editor, a fixed seed and the frame
+ * styled before it as a second picture (lanes of FRAME_LIMITS.lane; a lane starts from the approved preview,
+ * else the first styled frame) → the styled frames back into clips of up to 200 at the sampled frame rate
+ * (joined when there are several) → the cut's own sound.
+ */
+export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; final: string } {
+ const t = MIXED_TOOLS.cloud;
+ const prompts = mixedPrompts(input.preset, input.values);
+ const len = Math.round((input.range.end - input.range.start) * 1000) / 1000;
+ if (!input.sourceFps) throw new Error("Couldn't read this clip's frame rate — pick Fast to restyle it as video");
+ const sampling = frameSampling(len, input.fps, input.sourceFps);
+ const n = sampling.frames;
+ if (n < 1) throw new Error("Select a longer part of the clip");
+ const windows = frameChunks(n, FRAME_LIMITS.perExtract);
+ const clips = frameChunks(n, FRAME_LIMITS.perClip);
+ const sound = !!input.source.hasAudio;
+ const joined = clips.length > 1;
+ const total = 1 + (windows.length > 1 ? windows.length : 0) + windows.length + n + clips.length + (joined ? 1 : 0) + (sound ? 1 : 0);
+ const steps: PlanStep[] = [];
+ const add = (label: string, s: PlanStep) => steps.push({ ...s, request: { ...s.request, step: { label, index: steps.length, of: total } } });
+ const base = { batchTitle: input.title };
+ const helper = { ...base, feature: MIXED_STEP_FEATURE };
+ const seed = input.seed ?? FRAME_SEED;
+ const edit = frameEditParams(input.modelId, input.resolution, seed);
+ // The whole selection: its sound goes back under the result, and with one window its frames come from it.
+ add("Cut", { key: "cut", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end } } });
+ const secondsPerWindow = (FRAME_LIMITS.perExtract * sampling.interval) / input.sourceFps;
+ windows.forEach((w, i) => {
+ let source = "cut";
+ if (windows.length > 1) {
+ source = `cut${i + 1}`;
+ const start = Math.round((input.range.start + i * secondsPerWindow) * 1000) / 1000;
+ const end = Math.min(input.range.end, Math.round((start + secondsPerWindow) * 1000) / 1000);
+ add(`Cut ${i + 1} of ${windows.length}`, { key: source, request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: start, endTime: end } } });
+ }
+ add(windows.length > 1 ? `Frames ${w.from + 1}–${w.from + w.count}` : `${n} frames`, {
+ key: `frames${i + 1}`,
+ request: {
+ ...helper,
+ modelId: t.frames,
+ op: "extract-frames",
+ params: { frameInterval: sampling.interval, extra: { max_frames: w.count } },
+ },
+ after: [source],
+ chain: [{ slot: "video" }],
+ });
+ });
+ const lane = FRAME_LIMITS.lane;
+ for (let i = 0; i < n; i++) {
+ const w = Math.floor(i / FRAME_LIMITS.perExtract);
+ const frame = { slot: "images" as const, index: i - w * FRAME_LIMITS.perExtract, position: "first" as const };
+ // The styled picture it matches: the frame before it in its lane, else the approved preview, else the first styled frame.
+ const ref = i % lane ? `f${i - 1}` : input.anchor ? null : i ? "f0" : null;
+ add(`Frame ${i + 1} of ${n}`, {
+ key: `f${i}`,
+ request: {
+ ...base,
+ feature: MIXED_FRAME_FEATURE,
+ modelId: input.modelId,
+ op: "edit",
+ prompt: ref || input.anchor ? prompts.framePair : prompts.still,
+ ...(input.anchor && !ref ? { inputs: { images: [input.anchor] } } : {}),
+ params: { ...edit, numOutputs: 1 },
+ },
+ after: ref ? [`frames${w + 1}`, ref] : [`frames${w + 1}`],
+ chain: ref ? [frame, { slot: "images" }] : [frame],
+ });
+ }
+ clips.forEach((c, i) => {
+ const keys = Array.from({ length: c.count }, (_, j) => `f${c.from + j}`);
+ const last = !joined && !sound;
+ add(joined ? `Clip ${i + 1} of ${clips.length}` : "Frames to video", {
+ key: `clip${i + 1}`,
+ request: {
+ ...(last ? { ...base, feature: MIXED_FEATURE, title: input.title } : helper),
+ modelId: t.assemble,
+ op: "images-to-video",
+ params: { fps: sampling.fps },
+ },
+ after: keys,
+ chain: keys.map(() => ({ slot: "images" as const })),
+ });
+ });
+ let picture = "clip1";
+ if (joined) {
+ picture = "film";
+ add("Joining the clips", {
+ key: "film",
+ request: { ...(sound ? helper : { ...base, feature: MIXED_FEATURE, title: input.title }), modelId: t.join, op: "concat", prompt: input.title },
+ after: clips.map((_, i) => `clip${i + 1}`),
+ chain: clips.map(() => ({ slot: "videos" as const })),
+ });
+ }
+ if (!sound) return { steps, final: picture };
+ add("Original sound", {
+ key: "final",
+ request: { ...base, feature: MIXED_FEATURE, title: input.title, modelId: t.mux, op: "mux" },
+ after: [picture, "cut"],
+ // The cut is a clip: the mux takes its soundtrack.
+ chain: [{ slot: "video" }, { slot: "audio" }],
+ });
+ return { steps, final: "final" };
+}
+
/** One frame with the current settings. Open: the per-frame model on one frame; cloud: an image edit of the frame the browser grabbed. */
export function planMixedPreview(input: MixedPlanInput & { frameUrl?: string }): PlanStep {
const prompts = mixedPrompts(input.preset, input.values);
@@ -593,16 +755,22 @@ export function planMixedPreview(input: MixedPlanInput & { frameUrl?: string }):
},
};
}
+ // Per frame: the frame editor itself with the render's settings, so the approved preview is what the first frame looks like.
+ const frames = (input.mode ?? "frames") === "frames" && (MIXED_FRAME_MODELS as readonly string[]).includes(input.modelId);
return {
key: "preview",
request: {
feature: MIXED_PREVIEW_FEATURE,
title,
- modelId: MIXED_TOOLS.cloud.preview,
+ modelId: frames ? input.modelId : MIXED_TOOLS.cloud.preview,
op: "edit",
prompt: prompts.still,
inputs: { images: input.frameUrl ? [input.frameUrl] : [] },
- ...(input.seed !== undefined ? { params: { seed: input.seed } } : {}),
+ ...(frames
+ ? { params: { ...frameEditParams(input.modelId, input.resolution, input.seed ?? FRAME_SEED), numOutputs: 1 } }
+ : input.seed !== undefined
+ ? { params: { seed: input.seed } }
+ : {}),
},
};
}
diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.ts
index 3d115eb1..99c34bdd 100644
--- a/src/server/mixed-media.ts
+++ b/src/server/mixed-media.ts
@@ -3,8 +3,11 @@ import { getModel } from "@/lib/catalog";
import {
clampFps,
cleanValues,
+ frameSampling,
getMixedPreset,
MIXED_FEATURE,
+ MIXED_FRAME_FEATURE,
+ MIXED_FRAME_MODELS,
MIXED_MODELS,
MIXED_STEP_FEATURE,
mixedFrames,
@@ -12,6 +15,7 @@ import {
nearestResolution,
planMixed,
planMixedPreview,
+ type MixedMode,
type MixedPlanInput,
type MixedResolution,
} from "@/lib/catalog/mixed-media";
@@ -20,7 +24,7 @@ import { sourceSeconds, takesImage } from "@/lib/catalog/shorts-models";
import type { Engine, Generation } from "@/lib/catalog/types";
import { createPipeline } from "./chains";
import { db } from "./db";
-import { getGeneration, previewChained } from "./generations";
+import { getGeneration, previewChained, unfilledRequest } from "./generations";
import { engineMode } from "./settings";
import { probeSource, ShortsError } from "./shorts";
@@ -40,18 +44,23 @@ export interface MixedBody {
range: { start: number; end: number };
fps: number;
resolution: MixedResolution;
+ /** Cloud Fast: the restyle model; cloud Per frame: the frame editor (MIXED_FRAME_MODELS). */
modelId?: string;
- /** Cloud: the approved preview still (anchors the render when the model takes an image). */
+ /** Cloud: frame by frame (default) or Fast (one video-to-video pass). */
+ mode?: MixedMode;
+ /** Cloud: the approved preview still (anchors the render: Per frame always, Fast when the model takes an image). */
anchor?: string;
/** Cloud preview: the frame the browser grabbed at the start of the selection. */
frameUrl?: string;
seed?: number;
}
-async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ input: MixedPlanInput; frames: number; notes: string[] }> {
- const mode = engineMode();
- if (mode !== "both" && mode !== body.engine) {
- throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);
+const ordinal = (n: number) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : (["th", "st", "nd", "rd"][n % 10] ?? "th")}`;
+
+async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ input: MixedPlanInput; frames: number; fps: number; notes: string[] }> {
+ const engines = engineMode();
+ if (engines !== "both" && engines !== body.engine) {
+ throw new ShortsError(engines === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);
}
const preset = getMixedPreset(body.presetId);
if (!preset) throw new ShortsError("Pick a preset");
@@ -61,26 +70,41 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i
const problem = mixedRangeProblem(body.range, duration, sourceFps);
if (problem) throw new ShortsError(problem);
const fps = clampFps(body.fps, sourceFps);
- const modelId = body.modelId && MIXED_MODELS[body.engine].includes(body.modelId) ? body.modelId : MIXED_MODELS[body.engine][0];
+ const mode: MixedMode | undefined = body.engine === "cloud" ? (body.mode ?? "frames") : undefined;
+ const choices: readonly string[] = mode === "frames" ? MIXED_FRAME_MODELS : MIXED_MODELS[body.engine];
+ const modelId = body.modelId && choices.includes(body.modelId) ? body.modelId : choices[0];
const model = getModel(modelId);
- // A cut the model won't take is paid for, then refused: say so before anything runs.
const len = body.range.end - body.range.start;
- const fits = (id: string) => clipLengthProblem({ name: getModel(id)?.name ?? id, minSeconds: sourceSeconds(id).min, maxSeconds: sourceSeconds(id).max }, len);
- const tooShort = body.engine === "cloud" ? fits(modelId) : null;
- if (tooShort) {
- const other = MIXED_MODELS.cloud.find((id) => !fits(id));
- const more = (sourceSeconds(modelId).min ?? 0) > len;
- throw new ShortsError(`${tooShort} — select ${more ? "more" : "less"}${other ? `, or pick ${getModel(other)?.name ?? other}` : ""}`);
- }
const notes: string[] = [];
- const anchor = body.engine === "cloud" && body.anchor && takesImage(modelId) ? body.anchor : undefined;
- if (body.engine === "cloud") {
+ let frames = mixedFrames(len, fps);
+ let rate = fps;
+ if (mode === "frames") {
+ // Frames are every Nth frame of the clip: say so when that isn't the rate picked.
+ if (!sourceFps) throw new ShortsError("Couldn't read this clip's frame rate — pick Fast to restyle it as video", 422);
+ const s = frameSampling(len, fps, sourceFps);
+ frames = s.frames;
+ rate = s.fps;
+ if (Math.abs(s.fps - fps) > 0.01) notes.push(`Frames are every ${s.interval === 1 ? "" : `${ordinal(s.interval)} `}frame of this ${+sourceFps.toFixed(2)} FPS clip: ${+s.fps.toFixed(2)} FPS, ${frames} frames`);
+ if (modelId === "seedream-5-flash") notes.push(`Seedream 5.0 Flash takes no seed, so frames vary a little more than with Nano Banana 2${body.resolution === "4K" ? "; it draws up to 2K" : ""}`);
+ } else if (mode === "fast") {
+ // A cut the model won't take is paid for, then refused: say so before anything runs.
+ const fits = (id: string) => clipLengthProblem({ name: getModel(id)?.name ?? id, minSeconds: sourceSeconds(id).min, maxSeconds: sourceSeconds(id).max }, len);
+ const tooShort = fits(modelId);
+ if (tooShort) {
+ const other = MIXED_MODELS.cloud.find((id) => !fits(id));
+ const more = (sourceSeconds(modelId).min ?? 0) > len;
+ throw new ShortsError(`${tooShort} — select ${more ? "more" : "less"}${other ? `, or pick ${getModel(other)?.name ?? other}` : ""}`);
+ }
+ }
+ const anchor = mode === "frames" ? body.anchor : mode === "fast" && body.anchor && takesImage(modelId) ? body.anchor : undefined;
+ if (mode === "fast") {
if (body.anchor && !anchor) notes.push(`${model?.name} restyles from words only — the preview frame isn't sent`);
- notes.push(`${model?.name} restyles the clip as smooth video — the open engine restyles it frame by frame at 4–24 FPS`);
- } else if (body.resolution !== "1K") notes.push("The open engine renders up to 1536 px on the long side");
+ notes.push(`${model?.name} restyles the clip as smooth video in one pass — Per frame redraws every frame like Higgsfield`);
+ } else if (!mode && body.resolution !== "1K") notes.push("The open engine renders up to 1536 px on the long side");
const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);
return {
- frames: mixedFrames(body.range.end - body.range.start, fps),
+ frames,
+ fps: rate,
notes,
input: {
engine: body.engine,
@@ -93,8 +117,10 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i
fps,
resolution: body.resolution,
modelId,
+ mode,
+ sourceFps,
anchor,
- modelResolution: body.engine === "cloud" ? nearestResolution(model?.options.resolutions, body.resolution) : undefined,
+ modelResolution: mode === "fast" ? nearestResolution(model?.options.resolutions, body.resolution) : undefined,
// LTX follows the clip's outlines, like the open engine's canny ControlNet.
extra: modelId === "ltx-2-3-restyle" ? { preprocessor: "canny" } : undefined,
...(body.seed !== undefined ? { seed: body.seed } : {}),
@@ -104,11 +130,16 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i
const withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });
+/** Every step validated and priced; steps alike but for their place in the chain (a frame each) are previewed once. */
function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {
let cost: number | null = 0;
let demo = false;
+ const seen = new Map<string, ReturnType<typeof previewChained>>();
for (const s of steps) {
- const p = previewChained(withChain(s), s.after?.length ?? 0);
+ const req = withChain(s);
+ const key = JSON.stringify([req.modelId, req.op, req.prompt, req.inputs, req.params, req.chain?.map((c) => c.slot), s.after?.length ?? 0]);
+ const p = seen.get(key) ?? previewChained(req, s.after?.length ?? 0);
+ seen.set(key, p);
demo ||= p.demo;
cost = cost === null || p.costUsd === null ? null : cost + p.costUsd;
}
@@ -120,15 +151,23 @@ export interface MixedEstimate {
previewUsd: number | null;
demo: boolean;
frames: number;
+ /** The frame rate the frames are taken at (cloud Per frame: the clip's own over a whole number). */
fps: number;
+ /** Cloud: how it restyles. */
+ mode?: MixedMode;
+ /** Cloud Per frame: the price of redrawing one frame (Higgsfield's 2 credits a frame). */
+ perFrameUsd?: number | null;
notes: string[];
}
export async function estimateMixed(body: MixedBody): Promise<MixedEstimate> {
- const { input, frames, notes } = await planInput(body, { probe: false });
- const full = price(planMixed(input).steps);
+ const { input, frames, fps, notes } = await planInput(body, { probe: false });
+ const plan = planMixed(input);
+ const full = price(plan.steps);
const preview = price([planMixedPreview({ ...input, frameUrl: body.frameUrl ?? "/api/files/placeholder.png" })]);
- return { ...full, previewUsd: preview.costUsd, frames, fps: input.fps, notes };
+ const frame = input.mode === "frames" ? plan.steps.find((s) => s.key === "f0") : undefined;
+ const perFrameUsd = frame ? previewChained(withChain(frame), frame.after?.length ?? 0).costUsd : undefined;
+ return { ...full, previewUsd: preview.costUsd, frames, fps, notes, ...(input.mode && { mode: input.mode }), ...(perFrameUsd !== undefined && { perFrameUsd }) };
}
function run(steps: PlanStep[]): { batchId: string; items: Generation[]; byKey: Record<string, Generation> } {
@@ -139,19 +178,22 @@ function run(steps: PlanStep[]): { batchId: string; items: Generation[]; byKey:
}
}
+/** What the page follows of a render: every step but the per-frame edits (their count instead). */
+const followed = (p: { items: Generation[] }) => ({ items: p.items.filter((g) => g.feature !== MIXED_FRAME_FEATURE), frames: p.items.filter((g) => g.feature === MIXED_FRAME_FEATURE).length });
+
/** Start the full render; returns the finished video's generation (the others wait for it). */
-export async function createMixed(body: MixedBody): Promise<{ final: Generation; items: Generation[] }> {
+export async function createMixed(body: MixedBody): Promise<{ final: Generation; items: Generation[]; frames: number }> {
const { input } = await planInput(body, { probe: true });
const plan = planMixed(input);
const p = run(plan.steps);
- return { final: p.byKey[plan.final], items: p.items };
+ return { final: p.byKey[plan.final], ...followed(p) };
}
/**
* Run a render again with the same settings (History's "Try again" after a failed step): its steps
* are made anew from their stored requests, waiting on each other as before.
*/
-export function retryMixed(id: string): { final: Generation; items: Generation[] } {
+export function retryMixed(id: string): { final: Generation; items: Generation[]; frames: number } {
const final = getGeneration(id);
if (!final || final.feature !== MIXED_FEATURE || !final.batchId) throw new ShortsError("This render no longer exists", 404);
const mode = engineMode();
@@ -159,21 +201,21 @@ export function retryMixed(id: string): { final: Generation; items: Generation[]
throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);
}
const rows = db()
- .prepare("SELECT id, depends_on FROM generations WHERE batch_id = ? AND feature IN (?, ?) ORDER BY created_at ASC, id ASC")
- .all(final.batchId, MIXED_FEATURE, MIXED_STEP_FEATURE) as { id: string; depends_on: string | null }[];
+ .prepare("SELECT id, depends_on FROM generations WHERE batch_id = ? AND feature IN (?, ?, ?) ORDER BY created_at ASC, id ASC")
+ .all(final.batchId, MIXED_FEATURE, MIXED_STEP_FEATURE, MIXED_FRAME_FEATURE) as { id: string; depends_on: string | null }[];
const deps = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);
const steps: PlanStep[] = rows.map((r) => {
const g = getGeneration(r.id);
if (!g) throw new ShortsError("Part of this render was deleted — make it again from the editor", 409);
- const { chain, ...request } = g.request;
const after = deps(r.depends_on);
// Chained inputs were filled in when the step ran: the new run fills them from the new steps.
+ const { chain, ...request } = unfilledRequest(g.request, after.length);
const inputs = { ...request.inputs };
- for (const c of chain ?? []) if (c.slot !== "images" && c.slot !== "videos" && c.slot !== "prompt") delete inputs[c.slot];
+ for (const c of chain ?? []) if (c.slot !== "images" && c.slot !== "videos" && c.slot !== "audios" && c.slot !== "prompt") delete inputs[c.slot];
return { key: r.id, request: { ...request, inputs: Object.keys(inputs).length ? inputs : undefined }, ...(after.length ? { after, chain } : {}) };
});
const p = run(steps);
- return { final: p.byKey[id], items: p.items };
+ return { final: p.byKey[id], ...followed(p) };
}
/** One frame with the current settings. */
diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.ts
index e270f2af..3dc32d7f 100644
--- a/src/server/shorts-schemas.ts
+++ b/src/server/shorts-schemas.ts
@@ -51,6 +51,8 @@ export const MixedBodySchema = z.object({
fps: z.number().finite().min(MIXED.manualFps.min).max(MIXED.manualFps.max).default(MIXED.defaultFps),
resolution: z.enum(MIXED.resolutions).default("1K"),
modelId: z.string().max(80).optional(),
+ /** Cloud: "frames" (frame by frame, the default) or "fast" (one video-to-video pass). */
+ mode: z.enum(["frames", "fast"]).optional(),
anchor: fileUrl.optional(),
frameUrl: fileUrl.optional(),
seed: z.number().int().min(0).max(2 ** 48).optional(),
diff --git a/tests/mixed-media.test.ts b/tests/mixed-media.test.ts
index df6d4d25..fa98d796 100644
--- a/tests/mixed-media.test.ts
+++ b/tests/mixed-media.test.ts
@@ -6,10 +6,16 @@ import {
colorName,
defaultValues,
denoiseFor,
+ FRAME_LIMITS,
+ FRAME_SEED,
+ frameChunks,
+ frameEditParams,
+ frameSampling,
fpsChoices,
framesCost,
getMixedPreset,
MIXED,
+ MIXED_FRAME_MODELS,
MIXED_MODELS,
MIXED_PRESETS,
MIXED_TOOLS,
@@ -19,6 +25,7 @@ import {
mixedRangeProblem,
nearestResolution,
planMixed,
+ planMixedFrames,
planMixedPreview,
settingWords,
type MixedPlanInput,
@@ -58,7 +65,11 @@ describe("Mixed Media presets", () => {
});
it("uses real models", () => {
- for (const id of [...MIXED_MODELS.cloud, ...MIXED_MODELS.open, ...Object.values(MIXED_TOOLS.cloud), ...Object.values(MIXED_TOOLS.open)]) expect(getModel(id), id).toBeDefined();
+ for (const id of [...MIXED_MODELS.cloud, ...MIXED_MODELS.open, ...MIXED_FRAME_MODELS, ...Object.values(MIXED_TOOLS.cloud), ...Object.values(MIXED_TOOLS.open)]) expect(getModel(id), id).toBeDefined();
+ // Per frame redraws each frame with an image editor; the helpers are fal's FFmpeg tools.
+ for (const id of MIXED_FRAME_MODELS) expect(getModel(id)!.routes.some((r) => r.op === "edit")).toBe(true);
+ expect(getModel("nano-banana-2")!.pricing?.byResolution).toMatchObject({ "1K": 0.08, "2K": 0.12, "4K": 0.16 });
+ expect(getModel("seedream-5-flash")!.pricing?.usd).toBe(0.027);
});
it("cleans saved settings: bad colours and unknown options go back to the default, words are kept", () => {
@@ -159,8 +170,8 @@ describe("Mixed Media pipeline shape", () => {
});
});
- it("cloud: cut → restyle (anchored on the preview) → the cut's own sound", () => {
- const plan = planMixed(input({ engine: "cloud", modelId: "ltx-2-3-restyle", anchor: "/api/files/outputs/still.png", extra: { preprocessor: "canny" } }));
+ it("cloud Fast: cut → restyle (anchored on the preview) → the cut's own sound", () => {
+ const plan = planMixed(input({ engine: "cloud", mode: "fast", modelId: "ltx-2-3-restyle", anchor: "/api/files/outputs/still.png", extra: { preprocessor: "canny" } }));
const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));
expect(Object.keys(by)).toEqual(["cut", "render", "final"]);
expect(by.cut.request).toMatchObject({ feature: "mixed-media-step", modelId: "trim-video", op: "trim", params: { startTime: 2, endTime: 7 } });
@@ -170,7 +181,7 @@ describe("Mixed Media pipeline shape", () => {
request: { feature: "mixed-media-step", modelId: "ltx-2-3-restyle", inputs: { images: ["/api/files/outputs/still.png"] }, params: { generateAudio: false, extra: { preprocessor: "canny" } } },
});
expect(by.final).toMatchObject({ after: ["render", "cut"], chain: [{ slot: "video" }, { slot: "audio" }], request: { feature: "mixed-media", modelId: "merge-audio-video", op: "mux" } });
- const silent = planMixed(input({ engine: "cloud", modelId: "lucy-edit-pro", source: { url: "/api/files/x.mp4", hasAudio: false } }));
+ const silent = planMixed(input({ engine: "cloud", mode: "fast", modelId: "lucy-edit-pro", source: { url: "/api/files/x.mp4", hasAudio: false } }));
expect(silent.final).toBe("render");
expect(silent.steps[1].request).toMatchObject({ feature: "mixed-media", title: "Sketch · skate" });
expect(silent.steps[1].request.inputs).toBeUndefined();
@@ -179,8 +190,114 @@ describe("Mixed Media pipeline shape", () => {
it("preview: one frame (open: the per-frame model; cloud: an edit of the grabbed frame)", () => {
const open = planMixedPreview(input());
expect(open.request).toMatchObject({ feature: "mixed-media-preview", modelId: "oss-mixed-media", params: { startTime: 2, fps: 8, extra: { frames: 1 } } });
- const cloud = planMixedPreview({ ...input({ engine: "cloud", modelId: "ltx-2-3-restyle" }), frameUrl: "/api/files/uploads/frame.png" });
+ const cloud = planMixedPreview({ ...input({ engine: "cloud", mode: "fast", modelId: "ltx-2-3-restyle" }), frameUrl: "/api/files/uploads/frame.png" });
expect(cloud.request).toMatchObject({ modelId: "nano-banana-2", op: "edit", inputs: { images: ["/api/files/uploads/frame.png"] } });
expect(cloud.request.prompt).toMatch(/^Redraw this image as hand-drawn/);
});
});
+
+describe("Mixed Media per frame on the cloud", () => {
+ const frames = (over: Partial<MixedPlanInput> = {}) =>
+ input({ engine: "cloud", modelId: "nano-banana-2", sourceFps: 24, range: { start: 2, end: 7 }, fps: 8, ...over });
+
+ it("takes every Nth frame of the clip, the N closest to the rate asked for", () => {
+ expect(frameSampling(5, 8, 24)).toEqual({ interval: 3, fps: 8, frames: 40 });
+ // 30 FPS has no whole step to 8: every 4th frame, 7.5 FPS (fewer frames on a tie).
+ expect(frameSampling(10, 8, 30)).toEqual({ interval: 4, fps: 7.5, frames: 75 });
+ expect(frameSampling(10, 12, 30)).toEqual({ interval: 3, fps: 10, frames: 100 });
+ // 24 from 25 or 30: every frame.
+ expect(frameSampling(10, 24, 25)).toEqual({ interval: 1, fps: 25, frames: 250 });
+ expect(frameSampling(10, 24, 30).interval).toBe(1);
+ expect(frameSampling(4, 4, 29.97)).toEqual({ interval: 7, fps: 4.281, frames: 17 });
+ expect(frameSampling(2, 4, 240).interval).toBe(60);
+ });
+
+ it("splits frames into the extractor's 500 and the assembler's 200", () => {
+ expect(frameChunks(240, FRAME_LIMITS.perClip)).toEqual([
+ { from: 0, count: 200 },
+ { from: 200, count: 40 },
+ ]);
+ expect(frameChunks(1100, FRAME_LIMITS.perExtract)).toEqual([
+ { from: 0, count: 500 },
+ { from: 500, count: 500 },
+ { from: 1000, count: 100 },
+ ]);
+ expect(frameChunks(40, 200)).toEqual([{ from: 0, count: 40 }]);
+ });
+
+ it("asks each editor for the frame's own shape, with a fixed seed where it takes one", () => {
+ expect(frameEditParams("nano-banana-2", "2K", 9)).toEqual({ aspectRatio: "auto", resolution: "2K", seed: 9 });
+ expect(frameEditParams("seedream-5-flash", "1K", 9)).toEqual({ extra: { image_size: "auto_1K" } });
+ expect(frameEditParams("seedream-5-flash", "4K", 9)).toEqual({ extra: { image_size: "auto_2K" } });
+ });
+
+ it("is the cloud default: cut → frames → one edit per frame → frames to video → the cut's sound", () => {
+ const plan = planMixed(frames());
+ expect(plan).toEqual(planMixedFrames(frames()));
+ expect(plan.final).toBe("final");
+ const keys = plan.steps.map((s) => s.key);
+ expect(keys).toEqual(["cut", "frames1", ...Array.from({ length: 40 }, (_, i) => `f${i}`), "clip1", "final"]);
+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));
+ expect(by.cut.request).toMatchObject({ feature: "mixed-media-step", modelId: "trim-video", op: "trim", params: { startTime: 2, endTime: 7 } });
+ expect(by.frames1).toMatchObject({ after: ["cut"], chain: [{ slot: "video" }], request: { modelId: "extract-frames", op: "extract-frames", params: { frameInterval: 3, extra: { max_frames: 40 } } } });
+ // Frame 0 alone; then each frame with the one styled before it (lanes of 12: frame 12 looks at frame 0).
+ expect(by.f0).toMatchObject({ after: ["frames1"], chain: [{ slot: "images", index: 0, position: "first" }] });
+ expect(by.f0.request).toMatchObject({ feature: "mixed-media-frame-step", modelId: "nano-banana-2", op: "edit", params: { aspectRatio: "auto", resolution: "1K", seed: FRAME_SEED, numOutputs: 1 } });
+ expect(by.f0.request.prompt).toMatch(/^Redraw this image as hand-drawn/);
+ expect(by.f1).toMatchObject({ after: ["frames1", "f0"], chain: [{ slot: "images", index: 1, position: "first" }, { slot: "images" }] });
+ expect(by.f1.request.prompt).toMatch(/^Redraw the first image as .*The second image is an earlier frame of the same clip already redrawn/);
+ expect(by.f12.after).toEqual(["frames1", "f0"]);
+ expect(by.f13.after).toEqual(["frames1", "f12"]);
+ expect(by.f39.request.step).toMatchObject({ label: "Frame 40 of 40" });
+ expect(by.clip1).toMatchObject({ after: keys.filter((k) => /^f\d/.test(k)), request: { modelId: "images-to-video", op: "images-to-video", params: { fps: 8 } } });
+ expect(by.clip1.chain).toHaveLength(40);
+ expect(by.final).toMatchObject({ after: ["clip1", "cut"], chain: [{ slot: "video" }, { slot: "audio" }], request: { feature: "mixed-media", title: "Sketch · skate", modelId: "merge-audio-video", op: "mux" } });
+ // Every step knows its place.
+ expect(plan.steps.map((s) => s.request.step?.index)).toEqual(plan.steps.map((_, i) => i));
+ expect(new Set(plan.steps.map((s) => s.request.step?.of))).toEqual(new Set([plan.steps.length]));
+ });
+
+ it("starts every lane from the approved preview when there is one", () => {
+ const plan = planMixed(frames({ anchor: "/api/files/outputs/preview.png", seed: 5 }));
+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));
+ for (const k of ["f0", "f12", "f24", "f36"]) {
+ expect(by[k]).toMatchObject({ after: ["frames1"], request: { inputs: { images: ["/api/files/outputs/preview.png"] }, params: { seed: 5 } } });
+ expect(by[k].request.prompt).toMatch(/^Redraw the first image/);
+ }
+ expect(by.f1.request.inputs).toBeUndefined();
+ });
+
+ it("makes clips of up to 200 frames and joins them; a silent clip ends on the picture", () => {
+ const plan = planMixed(frames({ range: { start: 0, end: 10 }, fps: 24, source: { url: "/api/files/x.mp4", hasAudio: false } }));
+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));
+ expect(plan.steps.filter((s) => s.request.op === "edit")).toHaveLength(240);
+ expect(by.clip1.after).toHaveLength(200);
+ expect(by.clip2.after).toEqual(Array.from({ length: 40 }, (_, i) => `f${200 + i}`));
+ expect(by.film).toMatchObject({ after: ["clip1", "clip2"], chain: [{ slot: "videos" }, { slot: "videos" }], request: { feature: "mixed-media", title: "Sketch · skate", modelId: "join-clips", op: "concat" } });
+ expect(plan.final).toBe("film");
+ expect(by.final).toBeUndefined();
+ });
+
+ it("cuts a run of more than 500 frames into windows for the extractor", () => {
+ // 25 s at 24 FPS from a 24 FPS clip: 600 frames, two windows of 500 and 100.
+ const plan = planMixedFrames(frames({ range: { start: 1, end: 26 }, fps: 24 }));
+ const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));
+ expect(by.cut1.request.params).toEqual({ startTime: 1, endTime: 21.833 });
+ expect(by.cut2.request.params).toEqual({ startTime: 21.833, endTime: 26 });
+ expect(by.frames2).toMatchObject({ after: ["cut2"], request: { params: { frameInterval: 1, extra: { max_frames: 100 } } } });
+ // Frame 503 is the 4th of the second window.
+ expect(by.f503).toMatchObject({ after: ["frames2", "f502"], chain: [{ slot: "images", index: 3, position: "first" }, { slot: "images" }] });
+ expect(by.final.after).toEqual(["film", "cut"]);
+ });
+
+ it("uses Seedream 5.0 Flash at auto size, and needs the clip's frame rate", () => {
+ const plan = planMixed(frames({ modelId: "seedream-5-flash", resolution: "2K" }));
+ expect(plan.steps.find((s) => s.key === "f3")!.request).toMatchObject({ modelId: "seedream-5-flash", params: { extra: { image_size: "auto_2K" }, numOutputs: 1 } });
+ expect(() => planMixed(frames({ sourceFps: undefined }))).toThrow(/Couldn't read this clip's frame rate — pick Fast/);
+ });
+
+ it("previews with the frame editor itself, so the approved frame is what the render starts from", () => {
+ const p = planMixedPreview({ ...frames({ modelId: "seedream-5-flash" }), frameUrl: "/api/files/uploads/frame.png" });
+ expect(p.request).toMatchObject({ modelId: "seedream-5-flash", op: "edit", inputs: { images: ["/api/files/uploads/frame.png"] }, params: { extra: { image_size: "auto_1K" } } });
+ });
+});
diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.ts
index 74da97df..43c1ce25 100644
--- a/tests/shorts-api.test.ts
+++ b/tests/shorts-api.test.ts
@@ -354,12 +354,12 @@ describe("Mixed Media renders", () => {
expect(await settle(final.id)).toMatchObject({ status: "succeeded" });
});
- it("renders on the cloud: cut → restyle anchored on the preview still → the cut's sound", async () => {
+ it("renders on the cloud (Fast): cut → restyle anchored on the preview still → the cut's sound", async () => {
const preview = await (await mixedPreviewRoute.POST(json("POST", mm({ engine: "cloud", frameUrl: png })))).json();
expect(preview).toMatchObject({ modelId: "nano-banana-2", op: "edit", feature: "mixed-media-preview" });
const still = await settle(preview.id);
const anchor = still.outputs[0].url;
- const { final, items } = await mixed.createMixed(mm({ engine: "cloud", anchor }) as never);
+ const { final, items } = await mixed.createMixed(mm({ engine: "cloud", mode: "fast", anchor }) as never);
expect(items.map((g) => g.modelId)).toEqual(["trim-video", "ltx-2-3-restyle", "merge-audio-video"]);
expect(items[1].request.inputs?.images).toEqual([anchor]);
expect(items[1].request.params?.extra).toEqual({ preprocessor: "canny" });
@@ -368,7 +368,7 @@ describe("Mixed Media renders", () => {
});
it("tries a failed render again with the same settings, from its first step", async () => {
- const { final, items } = await mixed.createMixed(mm({ engine: "cloud", range: { start: 1, end: 4 } }) as never);
+ const { final, items } = await mixed.createMixed(mm({ engine: "cloud", mode: "fast", range: { start: 1, end: 4 } }) as never);
// The restyle stops: the soundtrack step then fails with the generic "An earlier step didn't finish".
await gens.cancelGeneration(items[1].id);
expect(await settle(final.id)).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });
@@ -396,11 +396,11 @@ describe("Mixed Media renders", () => {
});
it("refuses a cut the cloud model won't take, before anything is paid for", async () => {
- const res = await mixedRoute.POST(json("POST", mm({ engine: "cloud", modelId: "kling-o3-4k-edit", range: { start: 2, end: 3.4 } })));
+ const res = await mixedRoute.POST(json("POST", mm({ engine: "cloud", mode: "fast", modelId: "kling-o3-4k-edit", range: { start: 2, end: 3.4 } })));
expect(res.status).toBe(400);
expect((await res.json()).error).toBe("Kling O3 4K Edit needs at least 3 s — select more, or pick LTX 2.3 Reference Restyle");
// LTX takes it.
- const est = await mixed.estimateMixed(mm({ engine: "cloud", range: { start: 2, end: 3.4 } }) as never);
+ const est = await mixed.estimateMixed(mm({ engine: "cloud", mode: "fast", range: { start: 2, end: 3.4 } }) as never);
expect(est.costUsd).toBe(0);
});
@@ -409,4 +409,59 @@ describe("Mixed Media renders", () => {
expect(res.status).toBe(400);
expect((await res.json()).error).toMatch(/Couldn't grab a frame/);
});
+
+ it("prices the cloud per-frame render from the editor's price per frame", async () => {
+ setSetting("falKey", "fal-test-key");
+ try {
+ const est = await mixed.estimateMixed(mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 30 }, range: { start: 0, end: 10 }, fps: 8 }) as never);
+ expect(est).toMatchObject({ mode: "frames", frames: 75, fps: 7.5, perFrameUsd: 0.08, demo: false, previewUsd: 0.08 });
+ expect(est.notes).toContain("Frames are every 4th frame of this 30 FPS clip: 7.5 FPS, 75 frames");
+ // 75 frames × $0.08, plus the cut, the extraction and the assembly (fal compute, about free).
+ expect(est.costUsd).toBeGreaterThanOrEqual(6);
+ expect(est.costUsd).toBeLessThan(6.01);
+ const big = await mixed.estimateMixed(mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 10 }, fps: 24, resolution: "4K" }) as never);
+ expect(big).toMatchObject({ frames: 240, fps: 24, perFrameUsd: 0.16 });
+ expect(big.costUsd).toBeGreaterThanOrEqual(38.4);
+ const flash = await mixed.estimateMixed(mm({ engine: "cloud", modelId: "seedream-5-flash", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 5 }, fps: 8 }) as never);
+ expect(flash).toMatchObject({ frames: 40, perFrameUsd: 0.027 });
+ expect(flash.notes.join(" ")).toMatch(/Seedream 5\.0 Flash takes no seed/);
+ // Fast keeps the video-to-video price, and says what it skips.
+ const fast = await mixed.estimateMixed(mm({ engine: "cloud", mode: "fast", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 5 } }) as never);
+ expect(fast.mode).toBe("fast");
+ expect(fast.perFrameUsd).toBeUndefined();
+ expect(fast.notes.join(" ")).toMatch(/Per frame redraws every frame/);
+ // No frame rate, no per-frame plan.
+ const res = await mixedEstimateRoute.POST(json("POST", mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12 } })));
+ expect(res.status).toBe(422);
+ expect((await res.json()).error).toMatch(/pick Fast/);
+ } finally {
+ setSetting("falKey", "");
+ }
+ });
+
+ it("renders on the cloud frame by frame (demo) and tries it again from new frames", async () => {
+ const res = await mixedRoute.POST(json("POST", mm({ engine: "cloud", range: { start: 1, end: 2 }, fps: 4, requestId: "mm-frames-0001" })));
+ expect(res.status).toBe(201);
+ const { final, items, frames } = await res.json();
+ // The page follows the main steps; the per-frame edits are counted.
+ expect(frames).toBe(4);
+ expect(items.map((g: Generation) => g.op)).toEqual(["trim", "extract-frames", "images-to-video", "mux"]);
+ const done = await settle(final.id);
+ expect(done).toMatchObject({ status: "succeeded", feature: "mixed-media" });
+ const edits = gens.listGenerations({ batchId: final.batchId, features: ["mixed-media-frame-step"], limit: 50 }).sort((a, b) => a.request.step!.index - b.request.step!.index);
+ expect(edits.map((g) => g.request.step?.label)).toEqual(["Frame 1 of 4", "Frame 2 of 4", "Frame 3 of 4", "Frame 4 of 4"]);
+ const extracted = gens.getGeneration(items[1].id)!.outputs;
+ expect(edits[0].request.inputs?.images).toEqual([extracted[0].url]);
+ expect(edits[2].request.inputs?.images).toEqual([extracted[2].url, edits[1].outputs[0].url]);
+ expect(gens.getGeneration(items[2].id)!.request.inputs?.images).toEqual(edits.map((g) => g.outputs[0].url));
+
+ const again = await (await mixedRetryRoute.POST(json("POST", { id: final.id, requestId: "mm-frames-retry1" }))).json();
+ expect(again.frames).toBe(4);
+ const redo = gens.listGenerations({ batchId: again.final.batchId, features: ["mixed-media-frame-step"], limit: 50 }).sort((a, b) => a.request.step!.index - b.request.step!.index);
+ // Rebuilt from the stored steps without the old frames in them.
+ expect(redo.map((g) => g.request.inputs)).toEqual([undefined, undefined, undefined, undefined]);
+ expect(redo.map((g) => g.request.chainFilled)).toEqual([undefined, undefined, undefined, undefined]);
+ expect(await settle(again.final.id)).toMatchObject({ status: "succeeded" });
+ expect(gens.getGeneration(redo[3].id)!.request.inputs?.images).toHaveLength(2);
+ });
});
diff --git a/tests/shorts-pricing.test.ts b/tests/shorts-pricing.test.ts
index ad43518c..98d73b30 100644
--- a/tests/shorts-pricing.test.ts
+++ b/tests/shorts-pricing.test.ts
@@ -80,7 +80,7 @@ describe("restyled segments stay in sync with the original sound", () => {
modelId: "wan-2-7",
...over,
});
- const cloud = planMixed(mm({}));
+ const cloud = planMixed(mm({ mode: "fast" }));
expect(cloud.steps.find((s) => s.key === "render")!.request.params!.duration).toBe(1.4);
const open = planMixed(mm({ engine: "open", modelId: "oss-mixed-media", range: { start: 0, end: 10 } }));
expect(open.steps[0].request.params!.extra).toMatchObject({ frames: 80 });