The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Catalog: round-4 operations, canonical params, structured outputs and demo outputs
Clauded221be90c848
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 62e0ca47..789d35d5 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -4,6 +4,9 @@ import { createGenerations, listGenerations } from "@/server/generations";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { SignatureSchema } from "@/server/palettes";+/** A point on a picture as fractions of its width and height. */+const Focus = z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) });+const RequestSchema = z.object({feature: z.string().min(1),presetId: z.string().optional(),@@ -25,6 +28,8 @@ const RequestSchema = z.object({videos: z.array(z.string()).max(24).optional(),// Reference audio clips for reference-to-video (Seedance 2.5 / Cinema Studio take up to 10).audios: z.array(z.string()).max(10).optional(),+ // A .glb to rig.+ model3d: z.string().optional(),}).optional(),params: z@@ -50,6 +55,24 @@ const RequestSchema = z.object({styleId: z.string().max(200).optional(),sourceLanguage: z.string().max(80).optional(),numLayers: z.number().int().min(1).max(20).optional(),+ // Round 4: clicked points, keyframe times, output formats, Ken Burns moves, crossfades, retiming, overlays, rigging.+ points: z.array(z.object({ x: z.number(), y: z.number(), label: z.enum(["positive", "negative"]).optional() })).max(64).optional(),+ keyframeTimes: z.array(z.number().min(0).max(600)).max(10).optional(),+ format: z.enum(["h264", "h265_10bit", "prores_422_hq", "prores_4444", "ffv1", "exr"]).optional(),+ zoomFrom: z.number().min(0.1).max(10).optional(),+ zoomTo: z.number().min(0.1).max(10).optional(),+ panFrom: Focus.optional(),+ panTo: Focus.optional(),+ easing: z.enum(["linear", "ease-in-out"]).optional(),+ crossfade: z.number().min(0).max(30).optional(),+ sourceDuration: z.number().positive().max(36_000).optional(),+ frameInterval: z.number().int().min(1).max(10_000).optional(),+ targetFps: z.number().positive().max(240).optional(),+ slowdown: z.number().min(1).max(8).optional(),+ colormap: z.string().max(40).optional(),+ position: Focus.optional(),+ scale: z.number().positive().max(10).optional(),+ animation: z.union([z.string().max(200), z.number()]).optional(),extra: z.record(z.string(), z.unknown()).optional(),}).optional(),diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex fe8f7f8c..1e09e908 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -236,9 +236,9 @@ export function Composer({ docked }: { docked: boolean }) {}}if (signed.blocker) planError = signed.blocker;- // Models that take no prompt (try-on, 3D, transcription, upscalers) never ask for one.+ // Models that take no prompt (try-on, 3D, transcription, upscalers), or can run without one, never ask for one.const promptMissing =- !config.promptOptional && !opts.promptless && preset?.userPrompt !== "none" && preset?.userPrompt !== "optional" && !draft.prompt.trim() && !draft.params.shots?.some((s) => s.prompt.trim());+ !config.promptOptional && !opts.promptless && !opts.promptOptional && preset?.userPrompt !== "none" && preset?.userPrompt !== "optional" && !draft.prompt.trim() && !draft.params.shots?.some((s) => s.prompt.trim());const blocker = blockerFor({loading: !catalog.ready ? "Loading models…" : presetLoading ? "Loading presets…" : null,model: !!model,diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex 9931e5bb..5c3f972c 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -611,6 +611,7 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {voiceAudio: "audio",audio2: "audio",audios: "audio",+ model3d: "model3d",prompt: "text",};diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex 3fe71e27..dc7abc9f 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -1,5 +1,6 @@import { CLOUD_MODELS } from "./cloud-models.generated";import { HIGGSFIELD_MODELS, HIGGSFIELD_ROUTES } from "./higgsfield-models.generated";+import { pricingAt } from "./plan";import { LAST_FRAME_CHAIN, type ModelDef, type ModelRoute, type Operation } from "./types";/*@@ -1207,9 +1208,14 @@ const AI_INFLUENCER: ModelDef = {pricing: { unit: "image", usd: 0.05 },};+/** A launch price while it lasts, the list price after (FLUX 3 Max); read once, when the catalog loads. */+const withCurrentPrice = (m: ModelDef): ModelDef => (m.pricing?.promo ? { ...m, pricing: pricingAt(m.pricing) } : m);+/** Cloud models with their Higgsfield routes attached, plus the models only Higgsfield hosts. */const cloud: ModelDef[] = [- ...CLOUD_MODELS.map((m) => (HIGGSFIELD_ROUTES[m.id] ? { ...m, routes: [...m.routes, ...HIGGSFIELD_ROUTES[m.id]] } : m)).map(withLastFrameExtend),+ ...CLOUD_MODELS.map((m) => (HIGGSFIELD_ROUTES[m.id] ? { ...m, routes: [...m.routes, ...HIGGSFIELD_ROUTES[m.id]] } : m))+ .map(withLastFrameExtend)+ .map(withCurrentPrice),...HIGGSFIELD_MODELS,AI_INFLUENCER,...cloudTools,diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.tsindex 71677609..0e1e5492 100644--- a/src/lib/catalog/payload.ts+++ b/src/lib/catalog/payload.ts@@ -1,5 +1,5 @@import { readTimeline, timelineTracks } from "@/lib/av/timeline";-import { OPERATION_OUTPUT, type DurationField, type EnumField, type FieldMap, type GenInput, type MediaKind, type Operation } from "./types";+import { OPERATION_OUTPUT, type DurationField, type EnumField, type FieldMap, type GenInput, type MediaKind, type Operation, type PixelPoint } from "./types";function enumValue(field: string | EnumField, value: string): [string, unknown] {if (typeof field === "string") return [field, value];@@ -91,6 +91,65 @@ export function languageValue(values: string[], lang: string): string | undefinereturn values.find((x) => x.toLowerCase().startsWith(`${code}-`));}+const round3 = (n: number) => Math.round(n * 1000) / 1000;++/**+ * Clicked points in the API's own shape: Bria's eraser takes strings ("{'x':100, 'y':100, 'type':'positive'}"),+ * SAM 3 takes {x, y, label} with 1 = this thing, 0 = not this. Pixels, rounded.+ */+export function pointsValue(format: NonNullable<FieldMap["points"]>["format"], points: PixelPoint[]): unknown[] {+ return points.map((p) => {+ const x = Math.round(p.x);+ const y = Math.round(p.y);+ const positive = p.label !== "negative";+ return format === "bria" ? `{'x':${x}, 'y':${y}, 'type':'${positive ? "positive" : "negative"}'}` : { x, y, label: positive ? 1 : 0 };+ });+}++/**+ * Keyframes pinned to frame indexes at the API's frame rate: each image at its time, or spread evenly over+ * the clip when no times are given. Indexes stay inside the clip and strictly increase (APIs want them unique).+ */+export function keyframesValue(k: NonNullable<FieldMap["keyframes"]>, images: string[], times: number[] | undefined, duration: number | undefined) {+ const last = duration !== undefined ? Math.round(duration * k.fps) : undefined;+ const span = last ?? (images.length - 1) * k.fps;+ const frames: number[] = [];+ images.forEach((_, i) => {+ const t = times?.[i];+ let f = t !== undefined && Number.isFinite(t) ? Math.round(t * k.fps) : images.length > 1 ? Math.round((i * span) / (images.length - 1)) : 0;+ f = Math.max(0, last !== undefined ? Math.min(f, last) : f);+ frames.push(i > 0 ? Math.max(f, frames[i - 1] + 1) : f);+ });+ return images.map((url, i) => ({ [k.image]: url, [k.frame]: frames[i] }));+}++/**+ * A Ken Burns move as one zoom (fal's zoompan zooms from the whole picture toward a focal point, or back+ * out): the factor is the larger zoom over the smaller, the focal point is the pan point at the zoomed-in+ * end. Nothing is sent when the request says nothing about the move (the API's defaults apply).+ */+function zoomValue(z: NonNullable<FieldMap["zoom"]>, input: GenInput): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ const said = input.zoomFrom !== undefined || input.zoomTo !== undefined || input.panFrom || input.panTo;+ if (said) {+ const from = input.zoomFrom ?? 1;+ const to = input.zoomTo ?? from;+ const zoomIn = to >= from;+ const factor = Math.max(from, to) / Math.max(0.01, Math.min(from, to));+ out[z.factor] = round3(z.max ? Math.min(z.max, factor) : factor);+ if (z.direction) out[z.direction.key] = zoomIn ? z.direction.in : z.direction.out;+ const focus = zoomIn ? (input.panTo ?? input.panFrom) : (input.panFrom ?? input.panTo);+ const k = z.percent ? 100 : 1;+ if (focus && z.x) out[z.x] = round3(focus.x * k);+ if (focus && z.y) out[z.y] = round3(focus.y * k);+ }+ if (z.easing && input.easing) {+ const [k, v] = enumValue(z.easing, input.easing);+ out[k] = v;+ }+ return out;+}+/** Build a provider payload from canonical input using a route's {@link FieldMap}. Pure + unit-tested. */export function buildPayload(map: FieldMap, input: GenInput): Record<string, unknown> {const out: Record<string, unknown> = {};@@ -185,6 +244,40 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unkif (map.numLayers && input.numLayers !== undefined) out[map.numLayers] = input.numLayers;if (map.palette && input.palette?.length) out[map.palette.key] = paletteValue(map.palette.format, input.palette);+ // Round 4: clicked points, keyframes, formats, Ken Burns, overlays, retiming, frames and 3D (research part 4).+ if (map.points && input.points?.length) out[map.points.key] = pointsValue(map.points.format, input.points);+ if (map.keyframes && images.length) out[map.keyframes.key] = keyframesValue(map.keyframes, images, input.keyframeTimes, input.duration);+ if (map.format && input.format) {+ const v = map.format.values[input.format];+ if (v !== undefined) out[map.format.key] = v;+ }+ if (map.crossfade && input.crossfade !== undefined) out[map.crossfade] = input.crossfade;+ if (map.zoom) Object.assign(out, zoomValue(map.zoom, input));+ if (map.position && input.position) {+ const k = map.position.percent ? 100 : 1;+ out[map.position.x] = round3(input.position.x * k);+ out[map.position.y] = round3(input.position.y * k);+ }+ if (map.scale && input.scale !== undefined) out[map.scale.key] = round3(input.scale * (map.scale.multiplier ?? 1));+ if (map.targetFps && input.targetFps !== undefined) out[map.targetFps] = input.targetFps;+ if (map.slowdown && input.slowdown !== undefined) out[map.slowdown] = input.slowdown;+ if (map.frameInterval && input.frameInterval !== undefined) out[map.frameInterval] = input.frameInterval;+ if (map.colormap && input.colormap) {+ const [k, v] = enumValue(map.colormap, input.colormap);+ out[k] = v;+ }+ if (map.frames && images.length) out[map.frames.key] = images.map((url) => ({ [map.frames!.url]: url, [map.frames!.frames]: 1 }));+ if (map.loop && input.audio) {+ const want = input.duration && input.sourceDuration ? Math.ceil(input.duration / input.sourceDuration) : map.loop.max;+ out[map.loop.key] = Array.from({ length: Math.max(2, Math.min(map.loop.max, want)) }, () => input.audio);+ }+ if (map.model3d && input.model3d) out[map.model3d] = input.model3d;+ if (map.animation && input.animation !== undefined && input.animation !== "") {+ const n = typeof input.animation === "number" ? input.animation : Number(input.animation);+ out[map.animation.key] = Number.isFinite(n) && String(input.animation).trim() !== "" ? n : input.animation;+ if (map.animation.flag) out[map.animation.flag] = true;+ }+for (const [k, v] of Object.entries({ ...map.fixed, ...input.extra })) if (!(map.timeline && k === "timeline")) setPath(out, k, v);// A background colour given as hex goes out in the palette's shape (Recraft wants {r,g,b}).const bg = map.palette?.background;@@ -483,7 +576,8 @@ function model3dOutputs(response: unknown): ExtractedOutput[] {const urls = isObj(r.model_urls) ? r.model_urls : {};const glb = fileOf(r.model_glb) ?? fileOf(urls.glb) ?? fileOf(r.model_mesh) ?? fileOf(r.mesh) ?? fileOf(r.model_file);if (glb) {- const formats = compact(Object.fromEntries(Object.entries(urls).map(([k, v]) => [k, fileOf(v)?.url])));+ // SAM 3D Objects also returns the scene as a Gaussian splat.+ const formats = compact({ ...Object.fromEntries(Object.entries(urls).map(([k, v]) => [k, fileOf(v)?.url])), splat: fileOf(r.gaussian_splat)?.url });const preview = fileOf(r.thumbnail)?.url ?? fileOf(r.rendered_image)?.url ?? fileOf(r.preview)?.url;// A GLB was asked for; generic or missing types are labelled as one so it is stored as .glb.const contentType = !glb.contentType || glb.contentType === "application/octet-stream" || MODEL3D_EXT.test(glb.url) ? "model/gltf-binary" : glb.contentType;@@ -495,6 +589,88 @@ function model3dOutputs(response: unknown): ExtractedOutput[] {return mesh ? [{ url: mesh.url, kind: "model3d", contentType: MODEL3D_EXT.test(mesh.url) ? "model/gltf-binary" : mesh.contentType }] : [];}+/**+ * Gaussian splats (TripoSplat's model_mesh, a .ply unless it says .spz) with meta.format; the cut-out the+ * model actually saw is the preview.+ */+function splatOutputs(response: unknown): ExtractedOutput[] {+ const r = body(response);+ const f = isObj(r) ? (fileOf(r.model_mesh) ?? fileOf(r.splat) ?? fileOf(r.gaussian_splat)) : undefined;+ if (!f) return model3dOutputs(response);+ const format = /\.spz(\?|$)/i.test(f.url) || f.contentType?.includes("spz") ? "spz" : "ply";+ const preview = isObj(r) ? fileOf(r.preprocessed_image)?.url : undefined;+ return [{ url: f.url, kind: "model3d", contentType: format === "spz" ? "model/x-spz" : "model/ply", meta: compact({ format, preview }) }];+}++/**+ * Rigging (Meshy): the animated GLB when an animation preset was asked for, else the rigged character;+ * the FBX files and the walking / running clips ride along in meta.formats.+ */+function rigOutputs(response: unknown): ExtractedOutput[] {+ const r = body(response);+ const animated = isObj(r) ? fileOf(r.animation_glb) : undefined;+ const main = animated ?? (isObj(r) ? fileOf(r.rigged_character_glb) : undefined);+ if (!isObj(r) || !main) return model3dOutputs(response);+ const basic = isObj(r.basic_animations) ? r.basic_animations : {};+ const formats = compact({+ fbx: fileOf(animated ? r.animation_fbx : r.rigged_character_fbx)?.url,+ rigged: animated ? fileOf(r.rigged_character_glb)?.url : undefined,+ walking: fileOf(basic.walking_glb)?.url,+ running: fileOf(basic.running_glb)?.url,+ });+ return [{ url: main.url, kind: "model3d", contentType: "model/gltf-binary", meta: compact({ rigged: true, animated: !!animated || undefined, formats: Object.keys(formats).length ? formats : undefined }) }];+}++/**+ * OCR: Florence-2's results.quad_boxes [{x, y, w, h, label}] (x, y = top left, in the pixels of the image+ * it read) become one text output: the lines joined by newlines, and meta.lines [{text, bbox}] with+ * bbox = [x, y, w, h] as fractions of the image (pixels in bboxPx when the response gives no size).+ * A list that is already normalized ({lines: [{text, bbox}]}) passes through; an image without text+ * gives an empty text with no lines.+ */+function ocrOutputs(response: unknown): ExtractedOutput[] {+ const r = body(response);+ const res = isObj(r) && isObj(r.results) ? r.results : r;+ const boxes = isObj(res) && Array.isArray(res.quad_boxes) ? res.quad_boxes : isObj(r) && Array.isArray(r.lines) ? r.lines : undefined;+ if (!isObj(r) || !boxes) return transcriptOutputs(response);+ const img = isObj(r.image) ? r.image : undefined;+ const w = num(img?.width);+ const h = num(img?.height);+ const r4 = (n: number) => Math.round(n * 10000) / 10000;+ const lines = boxes.flatMap((b) => {+ if (!isObj(b)) return [];+ const text = (str(b.label) ?? str(b.text))?.trim();+ if (!text) return [];+ if (Array.isArray(b.bbox) && b.bbox.length === 4 && b.bbox.every((n) => typeof n === "number")) return [{ text, bbox: b.bbox as number[] }];+ const box = [num(b.x), num(b.y), num(b.w), num(b.h)];+ if (box.some((n) => n === undefined)) return [{ text }];+ const [x, y, bw, bh] = box as number[];+ return [w && h ? { text, bbox: [r4(x / w), r4(y / h), r4(bw / w), r4(bh / h)] } : { text, bboxPx: [x, y, bw, bh] }];+ });+ const text = lines.map((l) => l.text).join("\n");+ return [{ url: textDataUri(text), kind: "text", contentType: "text/plain", text, meta: compact({ lines, size: w && h ? [w, h] : undefined }) }];+}++/** Extracted frames in order, each with meta.index (its place in the sequence: source frame = index × frameInterval). */+function frameOutputs(response: unknown): ExtractedOutput[] {+ return extractMedia(response)+ .filter((o) => o.kind === "image")+ .map((o, index) => ({ ...o, meta: { index } }));+}++/**+ * SDR to HDR: a playable HDR file (Topaz) is the result. LTX-2.3 HDR answers with a ZIP of 16-bit EXR+ * frames and an SDR preview: the preview is the result and the EXR archive rides along as a link+ * (meta.artifacts.exr), as Higgsfield's extra files do.+ */+function hdrOutputs(response: unknown): ExtractedOutput[] {+ const r = body(response);+ const exr = isObj(r) ? fileOf(r.exr_frames_url) : undefined;+ if (!isObj(r) || !exr) return extractMedia(response);+ const preview = fileOf(r.preview_video);+ return preview ? [{ url: preview.url, kind: "video", contentType: preview.contentType, meta: { preview: "sdr", artifacts: { exr: exr.url } } }] : [];+}+const STEM_ORDER = ["vocals", "voice", "speech", "target", "drums", "bass", "guitar", "piano", "other", "residual", "accompaniment", "instrumental"];/** Demucs: {vocals, drums, bass, other, guitar, piano} files; SAM Audio: {target, residual}. Voice first. */@@ -528,8 +704,25 @@ export function extractOutputs(response: unknown, op?: Operation): ExtractedOutpout = transcriptOutputs(response);break;case "image-to-3d":+ case "text-to-3d":+ case "scene-3d":out = model3dOutputs(response);break;+ case "splat":+ out = splatOutputs(response);+ break;+ case "rig-3d":+ out = rigOutputs(response);+ break;+ case "ocr":+ out = ocrOutputs(response);+ break;+ case "extract-frames":+ out = frameOutputs(response);+ break;+ case "sdr-to-hdr":+ out = hdrOutputs(response);+ break;case "separate-audio":out = stemOutputs(response);break;diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.tsindex 608548d0..8aa20adc 100644--- a/src/lib/catalog/plan.ts+++ b/src/lib/catalog/plan.ts@@ -8,10 +8,11 @@ import type {Operation,Preset,PresetRoute,+ Pricing,} from "./types";/** Infer the operation from what the user attached. */-export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "op" | "inputs">): Operation {+export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "op" | "inputs" | "params">): Operation {if (req.op) return req.op;const ops = new Set(model.routes.map((r) => r.op));const imgs = req.inputs?.images?.length ?? 0;@@ -24,7 +25,12 @@ export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "opif (req.inputs?.video && imgs && has("motion-transfer")) return "motion-transfer";if (req.inputs?.video && has("v2v")) return "v2v";if (req.inputs?.video && has("extend")) return "extend";+ // Video erasers and swappers (a general video editor above takes these as plain edits unless asked).+ if (req.inputs?.video && imgs && has("video-swap")) return "video-swap";+ if (req.inputs?.video && has("remove-object")) return "remove-object";if (imgs && req.inputs?.endImage && has("flf2v")) return "flf2v";+ // Several stills are keyframes when they have times, or when the model takes no references.+ if (imgs > 1 && has("keyframes") && (req.params?.keyframeTimes?.length || !has("ref2v"))) return "keyframes";if ((imgs > 1 || clipRefs > 0) && has("ref2v")) return "ref2v";if (imgs && has("i2v")) return "i2v";if (has("t2v")) return "t2v";@@ -34,6 +40,15 @@ export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "opif (imgs && has("edit")) return "edit";if (has("t2i")) return "t2i";}+ if (model.kind === "audio") {+ if ((req.inputs?.audios?.length ?? 0) > 1 && has("audio-join")) return "audio-join";+ if (req.inputs?.audio && has("audio-loop")) return "audio-loop";+ }+ if (model.kind === "model3d") {+ if (req.inputs?.model3d && has("rig-3d")) return "rig-3d";+ if (imgs && has("image-to-3d")) return "image-to-3d";+ if (!imgs && has("text-to-3d")) return "text-to-3d";+ }return model.routes[0].op;}@@ -99,6 +114,8 @@ const PROMPTLESS = new Set<Operation>(["trim", "transcribe", "mux", "separate-audio", "layers", "image-to-3d", "captions", "text-layers", "vectorize", "level",// av-tools: the dub voice track (clips placed on the video's timeline)"timeline",+ // round 4: tools that work from their inputs (removing an object needs a prompt only on models that read one)+ "sdr-to-hdr", "export-video", "ocr", "still-motion", "audio-loop", "audio-join", "scene-3d", "splat", "rig-3d", "extract-frames", "images-to-video", "overlay",]);/**@@ -107,11 +124,23 @@ const PROMPTLESS = new Set<Operation>([* routes for this operation sends one.*/export function promptOptional(model: ModelDef, op: Operation): boolean {- if (PROMPTLESS.has(op) || model.options.promptless) return true;+ if (PROMPTLESS.has(op) || model.options.promptless || model.options.promptOptional) return true;const routes = routesFor(model, op);return routes.length > 0 && routes.every((r) => r.map?.prompt === false);}+/**+ * Removing an object: what to erase is named (the prompt), painted (inputs.mask) or clicked (params.points).+ * A mask or points stand in for the words when a route reads them (unknown on the client, whose catalog+ * has no field maps, and on ComfyUI routes, whose workflows bind them).+ */+function markedTarget(model: ModelDef, op: Operation, req: GenerationRequest, params: GenParams): boolean {+ if (op !== "remove-object") return false;+ const routes = routesFor(model, op);+ const reads = (k: "mask" | "points") => routes.some((r) => !r.map || !!r.map[k]);+ return (!!req.inputs?.mask && reads("mask")) || (!!params.points?.length && reads("points"));+}+export function planGeneration(req: GenerationRequest,getModel: (id: string) => ModelDef | undefined,@@ -200,11 +229,14 @@ export function planGeneration(throw new Error(op === "tts" ? "Pick or record the voice to speak with" : "Pick or record the voice to change into");}if (op === "dub" && !req.inputs?.video && !req.inputs?.audio) throw new Error("Add the video to translate");+ if (op === "keyframes") checkKeyframes(model, req.inputs?.images?.length ?? 0, params);const requires = model.options.requires;if (requires?.images && (req.inputs?.images?.length ?? 0) < requires.images) throw new Error(requires.msg);if (requires?.prompt && !prompt) throw new Error(requires.msg);- if (!prompt && !promptOptional(model, op)) {- throw new Error("Write a prompt first");+ if (requires?.mask && !req.inputs?.mask) throw new Error(requires.msg);+ if (requires?.points && !params.points?.length) throw new Error(requires.msg);+ if (!prompt && !promptOptional(model, op) && !markedTarget(model, op, req, params)) {+ throw new Error(op === "remove-object" ? "Say what to remove, e.g. “the coffee cup in her hand”" : "Write a prompt first");}const missing = missingInputs(op, req) ?? unreadInputs(model, op, req) ?? missingImages(model, req);@@ -219,10 +251,26 @@ export function planGeneration(return { model, op, prompt, params: { ...params, numOutputs: perJobOutputs }, loras, jobs, perJobOutputs };}+/** Keyframes: one time per image, from 0 up, inside the clip, no more than the model takes. */+function checkKeyframes(model: ModelDef, n: number, params: GenParams) {+ const max = model.options.maxImages;+ if (max && n > max) throw new Error(`${model.name} takes up to ${max} keyframes`);+ const times = params.keyframeTimes;+ if (!times?.length) return;+ if (times.length !== n) throw new Error(`Give each of the ${n} keyframes a time`);+ if (times.some((t, i) => !Number.isFinite(t) || t < 0 || (i > 0 && t <= times[i - 1]))) throw new Error("Keyframe times start at 0 or later and go up");+ const duration = params.duration ?? model.defaults?.duration;+ const last = times[times.length - 1];+ if (duration !== undefined && last > duration) throw new Error(`The last keyframe is at ${last}s — make the clip at least that long`);+}+type InputKey = keyof NonNullable<GenerationRequest["inputs"]>;const NEEDS: Partial<- Record<Operation, { images?: number; video?: boolean; videos?: number; audio?: boolean; endImage?: boolean; mask?: boolean; oneOf?: InputKey[]; msg: string }>+ Record<+ Operation,+ { images?: number; video?: boolean; videos?: number; audio?: boolean; audios?: number; endImage?: boolean; mask?: boolean; model3d?: boolean; oneOf?: InputKey[]; msg: string }+ >> = {edit: { images: 1, msg: "Add an image to edit" },inpaint: { images: 1, mask: true, msg: "Add an image and paint the area to change" },@@ -261,6 +309,23 @@ const NEEDS: Partial<transcribe: { oneOf: ["audio", "video"], msg: "Add the audio or video to transcribe" },"separate-audio": { oneOf: ["audio", "video"], msg: "Add the audio or video to split" },level: { audio: true, msg: "Add the audio to level" },+ // round 4+ "remove-object": { video: true, msg: "Add the video to remove something from" },+ "video-swap": { video: true, images: 1, msg: "Add the video and a picture of what goes in" },+ "video-insert": { video: true, images: 1, msg: "Add the video and a picture of what to add" },+ keyframes: { images: 1, msg: "Add the keyframes, in order" },+ "sdr-to-hdr": { video: true, msg: "Add the video to convert" },+ "export-video": { video: true, msg: "Add the video to export" },+ ocr: { images: 1, msg: "Add the image to read" },+ "still-motion": { images: 1, msg: "Add the still to move over" },+ "audio-loop": { audio: true, msg: "Add the audio to loop" },+ "audio-join": { audios: 2, msg: "Add at least two audio clips to join" },+ "scene-3d": { images: 1, msg: "Add the image to build the scene from" },+ splat: { images: 1, msg: "Add a photo of the subject" },+ "rig-3d": { model3d: true, msg: "Add the 3D model to rig" },+ "extract-frames": { video: true, msg: "Add the video to take frames from" },+ "images-to-video": { images: 1, msg: "Add the images, in order" },+ overlay: { images: 2, msg: "Add the picture and the overlay to put on it" },};const given = (v: unknown) => (Array.isArray(v) ? v.length > 0 : !!v);@@ -274,8 +339,10 @@ export function missingInputs(op: Operation, req: Pick<GenerationRequest, "inputif (n.video && !i.video) return n.msg;if (n.videos && (i.videos?.length ?? 0) < n.videos) return n.msg;if (n.audio && !i.audio) return n.msg;+ if (n.audios && (i.audios?.length ?? 0) < n.audios) return n.msg;if (n.endImage && !i.endImage) return n.msg;if (n.mask && !i.mask) return n.msg;+ if (n.model3d && !i.model3d) return n.msg;if (n.oneOf && !n.oneOf.some((k) => given(i[k]))) return n.msg;return null;}@@ -320,6 +387,14 @@ function missingImages(model: ModelDef, req: Pick<GenerationRequest, "inputs">):return labels?.length === min ? `Add the ${labels.join(" and the ")}` : `${model.name} needs ${min} images`;}+/** The price that holds at `now`: a launch promo to the end of its last day (UTC), then the list price. */+export function pricingAt(p: Pricing, now = Date.now()): Pricing {+ if (!p.promo) return p;+ const { promo, ...list } = p;+ if (!(now <= Date.parse(`${promo.until}T23:59:59.999Z`))) return list;+ return { ...list, usd: promo.usd, ...(promo.byResolution ? { byResolution: promo.byResolution } : {}) };+}+/** Rough USD estimate for a plan (BYO-key cloud runs). Open-source runs are free. */export function estimateCost(model: ModelDef, params: GenParams, jobs = 1): number | null {if (model.engine === "open" || !model.pricing) return model.engine === "open" ? 0 : null;diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 6f77b271..3be61032 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -61,7 +61,25 @@ export type Operation =| "write" // brief → text (LLM: scripts, ad copy, shot lists)| "vectorize" // image → the same picture as an SVG| "level" // audio → the same audio at a set loudness (a music bed under a voice-over)- | "timeline"; // audio clips placed at their start times over silence → one track as long as the video (dub voices)+ | "timeline" // audio clips placed at their start times over silence → one track as long as the video (dub voices)+ // round 4+ | "remove-object" // video + (prompt naming it | mask: first-frame mask, white = erase | params.points) → the same video without it+ | "video-swap" // video + reference image(s) + prompt (optional mask / points) → the object or person replaced by the reference+ | "video-insert" // video + reference image + prompt (where it goes) → the object added+ | "keyframes" // images (1–10, in order) + params.keyframeTimes → one video through every keyframe+ | "sdr-to-hdr" // video → HDR video (params.format)+ | "export-video" // video → the same video in params.format+ | "ocr" // image → its text lines (OutputFile.text, OutputFile.meta.lines [{text, bbox}])+ | "still-motion" // image → a camera move over it (Ken Burns: zoomFrom/zoomTo, panFrom/panTo, easing)+ | "audio-loop" // audio → the same audio extended to params.duration (params.crossfade at each seam)+ | "audio-join" // audio clips in order → one track (params.crossfade between them)+ | "scene-3d" // image → a whole-scene 3D model (GLB) for camera recomposition+ | "splat" // image → a Gaussian splat of the subject (meta.format "ply" | "spz")+ | "text-to-3d" // prompt → 3D model+ | "rig-3d" // 3D model (+ params.animation) → rigged / animated model+ | "extract-frames" // video → an image every params.frameInterval frames (meta.index)+ | "images-to-video" // images in order → a video at params.fps+ | "overlay"; // image + a second image (logo) → composited (params.position, params.scale)export const OPERATION_LABELS: Record<Operation, string> = {t2i: "Text to image",@@ -111,6 +129,23 @@ export const OPERATION_LABELS: Record<Operation, string> = {vectorize: "Vectorize",level: "Level audio",timeline: "Place on the timeline",+ "remove-object": "Remove object",+ "video-swap": "Swap object",+ "video-insert": "Add object",+ keyframes: "Keyframes to video",+ "sdr-to-hdr": "SDR to HDR",+ "export-video": "Export video",+ ocr: "Read text",+ "still-motion": "Ken Burns",+ "audio-loop": "Loop audio",+ "audio-join": "Join audio",+ "scene-3d": "3D scene",+ splat: "Gaussian splat",+ "text-to-3d": "Text to 3D",+ "rig-3d": "Rig 3D model",+ "extract-frames": "Extract frames",+ "images-to-video": "Images to video",+ overlay: "Overlay image",};export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {@@ -162,8 +197,44 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {level: "audio",// The open engine returns the track; fal's compose renders it as a video (the result follows the model).timeline: "audio",+ "remove-object": "video",+ "video-swap": "video",+ "video-insert": "video",+ keyframes: "video",+ "sdr-to-hdr": "video",+ "export-video": "video",+ ocr: "text",+ "still-motion": "video",+ "audio-loop": "audio",+ "audio-join": "audio",+ "scene-3d": "model3d",+ splat: "model3d",+ "text-to-3d": "model3d",+ "rig-3d": "model3d",+ "extract-frames": "image",+ "images-to-video": "video",+ overlay: "image",};+/**+ * Video codecs and containers an export or HDR job can write (params.format): H.264 MP4, 10-bit H.265+ * MP4, ProRes 422 HQ or 4444 in a .mov, lossless FFV1 in a .mkv, or a 16-bit EXR frame sequence.+ */+export type VideoFormat = "h264" | "h265_10bit" | "prores_422_hq" | "prores_4444" | "ffv1" | "exr";++/** A point on a picture in its own pixels (the first frame of a video). Negative points mark what to keep. */+export interface PixelPoint {+ x: number;+ y: number;+ label?: "positive" | "negative";+}++/** A position on a picture as fractions of its width and height (0–1 from the top left). */+export interface FocusPoint {+ x: number;+ y: number;+}+/** "llm" runs text steps (translate, write) on the configured LLM (Claude or Ollama) inside the server. */export type ProviderId = "fal" | "replicate" | "higgsfield" | "openai" | "google" | "comfyui" | "mock" | "local" | "llm";@@ -269,6 +340,49 @@ export interface FieldMap {* and one for `audio2` (a background bed), each placed at 0 and as long as `duration` (seconds).*/tracks?: string;+ // Round 4 (research part 4).+ /**+ * Points clicked on the first frame (params.points, pixels) in the API's shape: "bria" = strings like+ * "{'x':100, 'y':100, 'type':'positive'}", "sam" = objects {x, y, label: 1 | 0}.+ */+ points?: { key: string; format: "bria" | "sam" };+ /**+ * Keyframes (inputs.images in order at params.keyframeTimes seconds) as [{[image]: url, [frame]: index}],+ * the frame index counted at the API's `fps`. Without times the keyframes are spread over the clip.+ */+ keyframes?: { key: string; image: string; frame: string; fps: number };+ /** Output codec / container (params.format) as the API's own value; a format the API can't write is left out. */+ format?: { key: string; values: Partial<Record<VideoFormat, string>> };+ /** Seconds of crossfade at each join or loop seam (params.crossfade). */+ crossfade?: string;+ /**+ * A Ken Burns move sent as one zoom toward a focal point (fal's zoompan): `factor` = the larger of+ * params.zoomFrom / zoomTo over the smaller (at most `max`), `direction` in or out, the focal point = the pan point at+ * the zoomed-in end (0–1, or percent), `easing` from params.easing.+ */+ zoom?: { factor: string; max?: number; direction?: { key: string; in: string; out: string }; x?: string; y?: string; easing?: EnumField; percent?: boolean };+ /** Where an overlay's centre goes (params.position, 0–1 of the background; or percent). */+ position?: { x: string; y: string; percent?: boolean };+ /** An overlay's size (params.scale, 1 = its own size) times `multiplier` (100 for percent). */+ scale?: { key: string; multiplier?: number };+ /** Frame interpolation: the output frame rate (params.targetFps) and slow-motion factor (params.slowdown). */+ targetFps?: string;+ slowdown?: string;+ /** Every Nth frame (params.frameInterval). */+ frameInterval?: string;+ /** Depth map colours (params.colormap: grayscale, turbo, inferno, magma, viridis). */+ colormap?: string | EnumField;+ /** Images held as video frames: [{[url]: image, [frames]: 1}] in order (images to video at params.fps). */+ frames?: { key: string; url: string; frames: string };+ /**+ * A loop by repetition: inputs.audio listed as many times as params.duration / params.sourceDuration+ * needs (2 to `max` plays; `max` when either is unknown).+ */+ loop?: { key: string; max: number };+ /** The 3D model to work on (inputs.model3d: rig-3d). */+ model3d?: string;+ /** An animation preset (params.animation); `flag` is the API's switch that turns animation on. */+ animation?: { key: string; flag?: string };}export interface ModelRoute {@@ -322,6 +436,8 @@ export interface ModelOptions {imageLabels?: string[];/** None of its routes takes a prompt (try-on, 3D, transcription): the composer can hide the prompt box. */promptless?: boolean;+ /** The prompt box shows, but the model also runs without words (P-Video Replace, Genjutsu Lite object swap). */+ promptOptional?: boolean;/** Max reference videos / audio clips it accepts (reference-to-video: inputs.videos / inputs.audios). */maxVideos?: number;maxAudios?: number;@@ -330,9 +446,11 @@ export interface ModelOptions {/*** What this model needs beyond its operation's own inputs, checked before a job is created (the* composer shows `msg` inline): reference images for a style-reference t2i model, a prompt for a- * model whose operation is otherwise promptless.+ * model whose operation is otherwise promptless, a painted mask or clicked points (video erasers).*/- requires?: { images?: number; prompt?: boolean; msg: string };+ requires?: { images?: number; prompt?: boolean; mask?: boolean; points?: boolean; msg: string };+ /** Output formats it can write (params.format: SDR to HDR, export). */+ formats?: VideoFormat[];}export interface Pricing {@@ -343,6 +461,11 @@ export interface Pricing {byResolution?: Record<string, number>;/** Billed on the input clip's seconds as well as the output's (Happy Horse video edit): a restyle costs about twice the clip's length. */inputSeconds?: boolean;+ /**+ * A launch price that runs to the end of `until` (UTC, YYYY-MM-DD); `usd` / `byResolution` are the list+ * prices after it. The catalog applies whichever holds when it loads (FLUX 3 Max: $0.0425/s until 2026-11-07, then $0.17/s).+ */+ promo?: { until: string; usd: number; byResolution?: Record<string, number> };}export interface ModelDef {@@ -399,6 +522,35 @@ export interface GenParams {sourceLanguage?: string;/** Layer decomposition: how many layers to ask for. */numLayers?: number;+ // Round 4.+ /** Points clicked on the first frame, in its pixels (remove-object, video-swap, 3D objects). */+ points?: PixelPoint[];+ /** Keyframes: when each image is reached, in seconds (one per image, ascending). */+ keyframeTimes?: number[];+ /** Codec / container to write (export-video, sdr-to-hdr). */+ format?: VideoFormat;+ /** Ken Burns: zoom at the start and end (1 = the whole picture, 1.25 = 25% closer), where it looks (0–1) and how it moves. */+ zoomFrom?: number;+ zoomTo?: number;+ panFrom?: FocusPoint;+ panTo?: FocusPoint;+ easing?: "linear" | "ease-in-out";+ /** Seconds of crossfade at each seam (audio-loop, audio-join). */+ crossfade?: number;+ /** The input clip's length in seconds, when the caller knows it (how many plays a cloud loop needs). */+ sourceDuration?: number;+ /** Extract every Nth frame. */+ frameInterval?: number;+ /** Frame interpolation: the frame rate to reach, and a slow-motion factor (1–8; 2 = twice as long). */+ targetFps?: number;+ slowdown?: number;+ /** Depth map colours: grayscale, turbo, inferno, magma or viridis. */+ colormap?: string;+ /** Overlay: where its centre goes (0–1 of the background) and its size (1 = its own size). */+ position?: FocusPoint;+ scale?: number;+ /** An animation preset for a rigged model (the provider's preset id). */+ animation?: string | number;/** Free-form advanced params forwarded to the provider payload. */extra?: Record<string, unknown>;}@@ -439,6 +591,8 @@ export interface GenerationRequest {videos?: string[];/** Reference audio clips (reference-to-video: voices, music or sound the clip should follow). */audios?: string[];+ /** A 3D model file (.glb) to work on (rig-3d). */+ model3d?: string;};params?: GenParams;/** Values for preset option pickers (apps). */@@ -476,8 +630,9 @@ export interface ChainSlot {* "voiceAudio" clones the voice of the dependency's audio output.* "audio2" is the second audio track (the background stem mixed under the new voice, mux).* "audios" is a list of audio clips (the spoken lines a timeline places at their start times).+ * "model3d" is a 3D model (a mesh to rig).*/- slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "audio2" | "audios" | "prompt";+ slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "audio2" | "audios" | "model3d" | "prompt";/** For list slots: put it before or after the request's own items (default last). */position?: "first" | "last";/**@@ -503,6 +658,7 @@ export interface GenInput extends GenParams {voiceAudio2?: string;videos?: string[];audios?: string[];+ model3d?: string;loras?: LoraRef[];}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 672b29db..0d9f673a 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -429,6 +429,7 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {voiceAudio: "audio",audio2: "audio",audios: "audio",+ model3d: "model3d",prompt: "text",};@@ -458,6 +459,7 @@ const slotNoun = (s: ChainSlot) => (s.stem ? `${s.stem} stem` : SLOT_KIND[s.slotfunction placeholderFor(s: ChainSlot): string {const kind = SLOT_KIND[s.slot];if (kind === "text") return "Placeholder text from an earlier step";+ if (kind === "model3d") return "/api/files/placeholder.glb";return kind === "image" ? "/api/files/placeholder.png" : kind === "video" ? "/api/files/placeholder.mp4" : "/api/files/placeholder.wav";}@@ -633,6 +635,7 @@ async function submit(voiceAudio2: await prep(req.inputs?.voiceAudio2),videos: (await Promise.all((req.inputs?.videos ?? []).map(prep))).filter(Boolean) as string[],audios: (await Promise.all((req.inputs?.audios ?? []).map(prep))).filter(Boolean) as string[],+ model3d: await prep(req.inputs?.model3d),loras: plan.loras,// Vary seeds across a batch so N jobs don't return N identical results.seed: plan.params.seed !== undefined && plan.params.seed >= 0 ? plan.params.seed + index : undefined,diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.tsindex 2567700c..2f547810 100644--- a/src/server/providers/mock.ts+++ b/src/server/providers/mock.ts@@ -10,7 +10,8 @@ import { toDataUri } from "../storage";* Demo provider: lets anyone click through the whole product with no API keys or GPU.* Produces abstract placeholder art (SVG) for images, a bundled sample clip for video, a short* tone for audio, labelled text for transcripts/translations/scripts and a sample .glb for 3D,- * with the structured extras real providers return (layer boxes, cues, text blocks, stems).+ * with the structured extras real providers return (layer boxes, cues, text blocks, stems, OCR lines with boxes,+ * numbered frames).* Clearly labelled as demo output.*/@@ -217,6 +218,18 @@ function demoWrite(brief: string): DemoOutput {const sampleClip = (ar: string) => (ar === "9:16" || ar === "3:4" || ar === "2:3" ? "demo-portrait.mp4" : ar === "1:1" ? "demo-square.mp4" : "demo-landscape.mp4");+/** OCR: a few lines with their boxes (x, y, w, h as fractions of the picture), as a real reader returns them. */+function demoOcr(brief: string): DemoOutput {+ const lines = [+ { text: "DEMO TEXT", bbox: [0.08, 0.1, 0.52, 0.09] },+ { text: brief ? brief.slice(0, 60) : "Every line comes with its box", bbox: [0.08, 0.24, 0.7, 0.05] },+ { text: "Connect fal or start ComfyUI to read the real text", bbox: [0.08, 0.84, 0.78, 0.04] },+ ];+ return textOutput(lines.map((l) => l.text).join("\n"), null, { lines, demo: true });+}++const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Number.isFinite(n) ? n : lo));+function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string, ar: string, meta: Record<string, unknown>): DemoOutput[] {// The prompt falls back to the op name when a step has none.const brief = prompt === op ? "" : prompt;@@ -246,10 +259,39 @@ function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string,return stems;}case "image-to-3d":+ case "text-to-3d":return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb" } },{ url: "sample:demo-turntable.mp4", kind: "video", contentType: "video/mp4", meta: { demo: true, turntable: true } },];+ // Round 4. A scene, a splat and a rig all come back as the demo mesh (a real splat is a .ply or .spz).+ case "scene-3d":+ return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", scene: true } }];+ case "splat":+ return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", splat: true } }];+ case "rig-3d":+ return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb", rigged: true } }];+ case "ocr":+ return [demoOcr(brief)];+ case "extract-frames":+ return Array.from({ length: 4 }, (_, index) => ({ url: svgUri(demoSvg(`frame ${index + 1}`, ar, index)), kind: "image" as const, contentType: "image/svg+xml", meta: { index, demo: true } }));+ case "overlay":+ return [{ url: svgUri(demoSvg(brief || "overlay", ar, 5)), kind: "image", contentType: "image/svg+xml", meta: { demo: true } }];+ // The same tone, as long as the loop was asked to be (or the clips joined end to end).+ case "audio-loop":+ return [{ url: toDataUri(demoWav(clamp(Math.round(Number(meta.duration ?? 12)), 4, 30)), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { demo: true } }];+ case "audio-join":+ return [{ url: toDataUri(demoWav(clamp(3 * Number(meta.clips ?? 2), 4, 30), [330, 495]), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { demo: true } }];+ case "remove-object":+ case "video-swap":+ case "video-insert":+ case "keyframes":+ case "still-motion":+ case "images-to-video":+ return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } }];+ case "sdr-to-hdr":+ case "export-video":+ return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true, ...(meta.format ? { format: meta.format } : {}) } }];case "trim":case "captions":case "mux":@@ -293,6 +335,9 @@ export const mockProvider: ProviderAdapter = {targetLanguage: input.targetLanguage,sourceLanguage: input.sourceLanguage,numLayers: input.numLayers,+ duration: input.duration,+ format: input.format,+ clips: input.audios?.length,// Workflows whose second output is the cut's first frame (video-segment-resample).firstFrame: route.provider === "comfyui" && route.endpoint === "video-segment-resample",// A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).diff --git a/src/server/storage.ts b/src/server/storage.tsindex 92af7cf8..6ea1c9db 100644--- a/src/server/storage.ts+++ b/src/server/storage.ts@@ -31,6 +31,9 @@ const EXT_BY_TYPE: Record<string, string> = {"application/json": "json","model/gltf-binary": "glb","model/gltf+json": "gltf",+ // Gaussian splats (TripoSplat on fal writes .ply; the open TripoSplat graph writes .spz).+ "model/ply": "ply",+ "model/x-spz": "spz",};const TYPE_BY_EXT: Record<string, string> = {@@ -55,6 +58,8 @@ const TYPE_BY_EXT: Record<string, string> = {json: "application/json",glb: "model/gltf-binary",gltf: "model/gltf+json",+ ply: "model/ply",+ spz: "model/x-spz",};export function contentTypeFor(fileName: string, fallback = "application/octet-stream"): string {diff --git a/tests/demo-ops.test.ts b/tests/demo-ops.test.tsindex 30754c14..0322380a 100644--- a/tests/demo-ops.test.ts+++ b/tests/demo-ops.test.ts@@ -7,7 +7,9 @@ import type { Generation, GenerationRequest } from "@/lib/catalog/types";vi.mock("@/lib/catalog", async (importOriginal) => {const mod = await importOriginal<typeof import("@/lib/catalog")>();const { ROUND3_FIXTURES } = await import("./fixtures/round3-models");- return { ...mod, MODELS: [...mod.MODELS, ...ROUND3_FIXTURES], getModel: (id: string) => ROUND3_FIXTURES.find((m) => m.id === id) ?? mod.getModel(id) };+ const { ROUND4_FIXTURES } = await import("./fixtures/round4-models");+ const fixtures = [...ROUND3_FIXTURES, ...ROUND4_FIXTURES];+ return { ...mod, MODELS: [...mod.MODELS, ...fixtures], getModel: (id: string) => fixtures.find((m) => m.id === id) ?? mod.getModel(id) };});vi.setConfig({ testTimeout: 60_000 });@@ -143,3 +145,80 @@ describe("demo outputs for every new operation", () => {checkGlb(Buffer.from(await res.arrayBuffer()));});});++describe("demo outputs for the round-4 operations", () => {+ it("gives clips, OCR lines, longer tones, meshes and numbered frames", async () => {+ const image = saveFile({ data: png, contentType: "image/png", source: "upload" }).url;+ const image2 = saveFile({ data: png, contentType: "image/png", source: "upload" }).url;+ const video = saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-square.mp4")), contentType: "video/mp4", source: "upload" }).url;+ const audio = saveFile({ data: Buffer.from("RIFF0000WAVEfmt "), contentType: "audio/wav", source: "upload" }).url;+ const glb = saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-model.glb")), contentType: "model/gltf-binary", source: "upload" }).url;+ const req = (op: string, r: Omit<GenerationRequest, "feature" | "modelId">): GenerationRequest => ({ feature: "tools", modelId: `test4-${op}`, ...r });+ const reqs: Record<string, GenerationRequest> = {+ "remove-object": req("remove-object", { prompt: "the coffee cup", inputs: { video } }),+ "video-swap": req("video-swap", { prompt: "swap the car for the red one", inputs: { video, images: [image] } }),+ "video-insert": req("video-insert", { prompt: "put the lamp on the table", inputs: { video, images: [image] } }),+ keyframes: req("keyframes", { prompt: "she puts on the hat", inputs: { images: [image, image2] }, params: { keyframeTimes: [0, 4], duration: 5 } }),+ "sdr-to-hdr": req("sdr-to-hdr", { inputs: { video }, params: { format: "h265_10bit" } }),+ "export-video": req("export-video", { inputs: { video }, params: { format: "prores_422_hq" } }),+ ocr: req("ocr", { inputs: { images: [image] } }),+ "still-motion": req("still-motion", { inputs: { images: [image] }, params: { zoomFrom: 1, zoomTo: 1.2, duration: 5 } }),+ "audio-loop": req("audio-loop", { inputs: { audio }, params: { duration: 20, crossfade: 1 } }),+ "audio-join": req("audio-join", { inputs: { audios: [audio, audio, audio] }, params: { crossfade: 0.5 } }),+ "scene-3d": req("scene-3d", { inputs: { images: [image] } }),+ splat: req("splat", { inputs: { images: [image] } }),+ "text-to-3d": req("text-to-3d", { prompt: "a brass lantern" }),+ "rig-3d": req("rig-3d", { inputs: { model3d: glb }, params: { animation: 12 } }),+ "extract-frames": req("extract-frames", { inputs: { video }, params: { frameInterval: 2 } }),+ "images-to-video": req("images-to-video", { inputs: { images: [image, image2] }, params: { fps: 12 } }),+ overlay: req("overlay", { inputs: { images: [image, image2] }, params: { position: { x: 0.5, y: 0.8 }, scale: 0.5 } }),+ };+ const started = Object.fromEntries(Object.entries(reqs).map(([k, r]) => [k, gens.createGenerations(r)[0]]));+ expect(started.ocr.kind).toBe("text");+ expect(started.splat.kind).toBe("model3d");+ expect(started["extract-frames"].kind).toBe("image");+ const done = Object.fromEntries(await Promise.all(Object.entries(started).map(async ([k, g]) => [k, await settle(g.id)] as const)));+ for (const [k, g] of Object.entries(done)) {+ expect(g.status, `${k}: ${g.error}`).toBe("succeeded");+ expect(g.op, k).toBe(k);+ }++ for (const k of ["remove-object", "video-swap", "video-insert", "keyframes", "sdr-to-hdr", "export-video", "still-motion", "images-to-video"]) {+ expect(done[k].outputs, k).toHaveLength(1);+ expect(done[k].outputs[0], k).toMatchObject({ kind: "video", contentType: "video/mp4", meta: { demo: true } });+ }+ expect(done["sdr-to-hdr"].outputs[0].meta?.format).toBe("h265_10bit");+ expect(done["export-video"].outputs[0].meta?.format).toBe("prores_422_hq");++ const ocr = done.ocr.outputs[0];+ expect(ocr).toMatchObject({ kind: "text", contentType: "text/plain" });+ const lines = ocr.meta?.lines as { text: string; bbox: number[] }[];+ expect(lines.length).toBeGreaterThanOrEqual(2);+ expect(ocr.text).toBe(lines.map((l) => l.text).join("\n"));+ for (const l of lines) {+ expect(l.bbox).toHaveLength(4);+ for (const n of l.bbox) expect(n >= 0 && n <= 1).toBe(true);+ }++ // The loop is as long as asked (20 s), longer than the 3 s demo tone; a join is a track too.+ const wavSeconds = async (url: string) => {+ const buf = Buffer.from(await (await serve(url)).arrayBuffer());+ return buf.readUInt32LE(40) / buf.readUInt32LE(28);+ };+ expect(done["audio-loop"].outputs[0]).toMatchObject({ kind: "audio", contentType: "audio/wav" });+ expect(await wavSeconds(done["audio-loop"].outputs[0].url)).toBeCloseTo(20, 1);+ expect(await wavSeconds(done["audio-join"].outputs[0].url)).toBeCloseTo(9, 1);++ for (const k of ["scene-3d", "splat", "text-to-3d", "rig-3d"]) {+ const m = done[k].outputs.find((o) => o.kind === "model3d");+ expect(m, k).toMatchObject({ contentType: "model/gltf-binary" });+ expect(m!.url, k).toMatch(/\.glb$/);+ }+ expect(done["rig-3d"].outputs[0].meta?.rigged).toBe(true);+ checkGlb(Buffer.from(await (await serve(done.splat.outputs[0].url)).arrayBuffer()));++ const frames = done["extract-frames"].outputs;+ expect(frames.map((f) => [f.kind, f.meta?.index])).toEqual([0, 1, 2, 3].map((i) => ["image", i]));+ expect(done.overlay.outputs).toEqual([expect.objectContaining({ kind: "image", contentType: "image/svg+xml" })]);+ });+});diff --git a/tests/fixtures/round4-models.ts b/tests/fixtures/round4-models.tsnew file mode 100644index 00000000..d9d45ad4--- /dev/null+++ b/tests/fixtures/round4-models.ts@@ -0,0 +1,39 @@+import type { ModelDef, Operation } from "@/lib/catalog/types";++/**+ * Stand-in cloud models for the round-4 operations (some have no cloud model at all: scene-3d and+ * export-video run on the open engine). They route to fal, which tests never configure, so they run+ * on the demo provider.+ */+const fixture = (op: Operation, kind: ModelDef["kind"]): ModelDef => ({+ id: `test4-${op}`,+ name: `Test ${op}`,+ vendor: "Test",+ family: "test",+ engine: "cloud",+ kind,+ tagline: `Fixture for ${op}`,+ routes: [{ op, provider: "fal", endpoint: `test/${op}` }],+ options: { aspectRatios: ["1:1", "16:9", "9:16"], maxImages: 10 },+ pricing: { unit: "request", usd: 0.01 },+});++export const ROUND4_FIXTURES: ModelDef[] = [+ fixture("remove-object", "video"),+ fixture("video-swap", "video"),+ fixture("video-insert", "video"),+ fixture("keyframes", "video"),+ fixture("sdr-to-hdr", "video"),+ fixture("export-video", "video"),+ fixture("ocr", "text"),+ fixture("still-motion", "video"),+ fixture("audio-loop", "audio"),+ fixture("audio-join", "audio"),+ fixture("scene-3d", "model3d"),+ fixture("splat", "model3d"),+ fixture("text-to-3d", "model3d"),+ fixture("rig-3d", "model3d"),+ fixture("extract-frames", "image"),+ fixture("images-to-video", "video"),+ fixture("overlay", "image"),+];diff --git a/tests/outputs.test.ts b/tests/outputs.test.tsindex ee0be9fe..da40cba5 100644--- a/tests/outputs.test.ts+++ b/tests/outputs.test.ts@@ -228,3 +228,86 @@ describe("3D models, stems and other extras", () => {]);});});++// Round 4: response fixtures follow docs/research/paid-model-apis-4.json → outputShape / outputFields.+describe("round-4 structured outputs", () => {+ it("Florence-2 OCR: the lines joined as text, each line's box as fractions of the picture", () => {+ const res = {+ results: {+ quad_boxes: [+ { x: 100, y: 50, w: 400, h: 60, label: "SUMMER SALE" },+ { x: 100, y: 130, w: 300, h: 30, label: " 50% off everything " },+ { x: 0, y: 0, w: 10, h: 10, label: "" },+ ],+ },+ image: { ...file("https://v3.fal.media/files/annotated.png", "image/png"), width: 1000, height: 500 },+ };+ const [out] = extractOutputs(res, "ocr");+ expect(out).toMatchObject({ kind: "text", contentType: "text/plain", text: "SUMMER SALE\n50% off everything" });+ expect(decode(out.url)).toBe("SUMMER SALE\n50% off everything");+ expect(out.meta).toEqual({+ lines: [+ { text: "SUMMER SALE", bbox: [0.1, 0.1, 0.4, 0.12] },+ { text: "50% off everything", bbox: [0.1, 0.26, 0.3, 0.06] },+ ],+ size: [1000, 500],+ });+ // No size in the answer: the boxes stay in pixels (bboxPx) for the caller to scale.+ expect(extractOutputs({ results: { quad_boxes: [{ x: 1, y: 2, w: 3, h: 4, label: "Hi" }] } }, "ocr")[0].meta).toEqual({ lines: [{ text: "Hi", bboxPx: [1, 2, 3, 4] }] });+ // Lines that are already normalized pass through; a picture without text is an empty text.+ expect(extractOutputs({ lines: [{ text: "Hello", bbox: [0.1, 0.2, 0.3, 0.05] }] }, "ocr")[0].meta).toEqual({ lines: [{ text: "Hello", bbox: [0.1, 0.2, 0.3, 0.05] }] });+ expect(extractOutputs({ results: { quad_boxes: [] }, image: { width: 10, height: 10 } }, "ocr")[0]).toMatchObject({ text: "", meta: { lines: [] } });+ });++ it("TripoSplat: the splat as a model3d .ply with meta.format, the cut-out it saw as the preview", () => {+ const res = {+ model_mesh: file("https://v3.fal.media/files/splat.ply", "application/octet-stream"),+ preprocessed_image: { ...file("https://v3.fal.media/files/cut.png", "image/png"), width: 512, height: 512 },+ seed: 1,+ num_gaussians: 262144,+ };+ expect(extractOutputs(res, "splat")).toEqual([+ { url: "https://v3.fal.media/files/splat.ply", kind: "model3d", contentType: "model/ply", meta: { format: "ply", preview: "https://v3.fal.media/files/cut.png" } },+ ]);+ expect(extractOutputs({ model_mesh: file("https://x/scene.spz") }, "splat")[0]).toMatchObject({ contentType: "model/x-spz", meta: { format: "spz" } });+ });++ it("SAM 3D Objects: the combined GLB, with the whole splat among its formats", () => {+ const res = {+ model_glb: file("https://v3.fal.media/files/objects.glb", "model/gltf-binary"),+ gaussian_splat: file("https://v3.fal.media/files/objects.ply"),+ individual_splats: [file("https://v3.fal.media/files/o1.ply")],+ metadata: [{ object_index: 0 }],+ };+ expect(extractOutputs(res, "image-to-3d")).toEqual([+ { url: "https://v3.fal.media/files/objects.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { formats: { splat: "https://v3.fal.media/files/objects.ply" } } },+ ]);+ });++ it("Meshy rigging: the animated GLB when a preset was asked for, the rig and walk / run cycles in meta.formats", () => {+ const basic = { walking_glb: file("https://x/walk.glb"), running_glb: file("https://x/run.glb"), walking_fbx: file("https://x/walk.fbx") };+ const rigged = { rigged_character_glb: file("https://x/rig.glb"), rigged_character_fbx: file("https://x/rig.fbx"), basic_animations: basic, rig_task_id: "r1" };+ expect(extractOutputs(rigged, "rig-3d")).toEqual([+ { url: "https://x/rig.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { rigged: true, formats: { fbx: "https://x/rig.fbx", walking: "https://x/walk.glb", running: "https://x/run.glb" } } },+ ]);+ const animated = extractOutputs({ ...rigged, animation_glb: file("https://x/dance.glb"), animation_fbx: file("https://x/dance.fbx") }, "rig-3d");+ expect(animated[0]).toMatchObject({ url: "https://x/dance.glb", meta: { rigged: true, animated: true, formats: { fbx: "https://x/dance.fbx", rigged: "https://x/rig.glb" } } });+ // Text to 3D (Tripo H3.1) reads like image to 3D.+ expect(extractOutputs({ model_mesh: file("https://x/lantern.glb"), rendered_image: file("https://x/r.webp") }, "text-to-3d")[0]).toMatchObject({ kind: "model3d", meta: { preview: "https://x/r.webp" } });+ });++ it("SDR to HDR: Topaz's HDR file is the result; LTX's EXR frames ride along on the SDR preview", () => {+ expect(extractOutputs({ video: file("https://x/hdr.mp4", "video/mp4") }, "sdr-to-hdr")).toEqual([{ url: "https://x/hdr.mp4", kind: "video", contentType: "video/mp4" }]);+ const ltx = { exr_frames_url: file("https://x/frames.zip", "application/zip"), preview_video: file("https://x/preview.mp4", "video/mp4"), prompt: "p", seed: 2 };+ expect(extractOutputs(ltx, "sdr-to-hdr")).toEqual([{ url: "https://x/preview.mp4", kind: "video", contentType: "video/mp4", meta: { preview: "sdr", artifacts: { exr: "https://x/frames.zip" } } }]);+ });++ it("extract frames: the images in order, each with meta.index", () => {+ const res = { images: [file("https://x/f0.png", "image/png"), file("https://x/f1.png", "image/png"), file("https://x/f2.png", "image/png")], frame_count: 3 };+ expect(extractOutputs(res, "extract-frames").map((o) => [o.url, o.meta?.index])).toEqual([+ ["https://x/f0.png", 0],+ ["https://x/f1.png", 1],+ ["https://x/f2.png", 2],+ ]);+ });+});