Skip to content

Open source CapCut alternative.

TypeScript

feat(site): Veo 3.1 reference images anchor shot identity

David Le8190b98694e7
diff --git a/docs/README.md b/docs/README.md
index d9eb9378..95a51c86 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -41,6 +41,7 @@ Supported product and engineering guides live in `docs/guides/`. This list is th
- [Frontend and Next.js Guidelines](guides/frontend-nextjs-guidelines.md) — route structure, server/client boundaries, styling, and data access in the site app.
- [Cut](guides/cut/README.md) — the standalone free video editor on the `cut.*` subdomain: what it shares with Donkey (nothing yet), and the local resources it runs on.
- [Cut's AI Assistant](guides/cut/ai-assistant.md) — how a chat turn runs: the providers, the tool bridge into the editor, what the model knows, and the context budgets.
+- [Brief to Video](guides/cut/brief-to-video.md) — the director pipeline's strategy: story planning, the identity ladder that keeps a cast consistent, and where audio goes next.
**Operations**
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index f95f8e2b..d5be3bf5 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -109,4 +109,4 @@ A hidden hermetic test provider exercises the full engine bridge — context, to
The shared catalog (system prompt, tools, skills), the chat route with its provider runners, the browser-tool bridge, and the stdio MCP proxy live with the engine's AI code under the site's Cut folder (`server/ai/`, `server/http/ai.ts`). The page side holds the snapshot builder (`lib/aiContext.ts`), the tool implementations (`lib/aiTools.ts`), the Gemini loop (`lib/geminiChat.ts`), the model catalog (`lib/aiModels.ts`), and the chat panel with threads and transport (`components/AiPanel.tsx`).
-The brief-to-video pipeline is its own subsystem: the orchestrator, coverage invariant, and role interfaces in `lib/genvideo/`, its hosted-model adapters in `lib/genvideo/adapters/`, the browser controller in `lib/genScene.ts`, and the progress card in `components/SceneCard.tsx`.
+The brief-to-video pipeline is its own subsystem: the orchestrator, coverage invariant, and role interfaces in `lib/genvideo/`, its hosted-model adapters in `lib/genvideo/adapters/`, the browser controller in `lib/genScene.ts`, and the progress card in `components/SceneCard.tsx`. Its strategy — story planning, the identity ladder, where audio goes next — is the [Brief to Video](brief-to-video.md) guide.
diff --git a/docs/guides/cut/brief-to-video.md b/docs/guides/cut/brief-to-video.md
new file mode 100644
index 00000000..2f19f01f
--- /dev/null
+++ b/docs/guides/cut/brief-to-video.md
@@ -0,0 +1,86 @@
+# Brief to Video
+
+The brief-to-video pipeline is Cut's director: one request ("make me a video
+about…") becomes a finished cut — script, narration, reference images, shots —
+assembled on the timeline, with subtitles and any other post step one
+assistant tool call away. The benchmark is the current class of
+director-style agents that turn a single prompt into a coherent short film with
+a consistent cast; we match their harness capability first and let model
+quality catch up on its own.
+
+**The one rule: the plan is the product.** Every generation call executes a
+persisted, user-approved plan — never a fresh improvisation. If a shot renders
+wrong, fix the plan (its description, its references, its framing) and
+regenerate that shot; if you're tempted to slip an extra instruction into one
+render call, that knowledge belongs in the plan so every later regeneration
+keeps it.
+
+## How it works
+
+```
+brief
+ │ script — beats with arc, camera framing, dialogue
+ ▼
+style bible — one look + a sheet per character and location
+ │ (reference images minted once, from the user's references)
+ ▼
+voicing — narration spine + music bed; shots rescale to real lengths
+ ▼ (user approves the plan before money is spent)
+keyframes — each shot's opening frame, rendered from the sheets
+ ▼
+shots — video seeded from the keyframe, laddered down on failure
+ ▼
+timeline — clips trimmed to their slice under the narration
+```
+
+The written plan decides *what* every shot is; the render steps decide only
+*how well* it lands.
+
+## Story planning
+
+The script role writes cinema, not a list of captions. Its beats carry a story
+arc (establish, turn, payoff), real camera language varied shot to shot (wide
+establishing, close-up, insert of a telling detail, POV, follow shot), and the
+wardrobe and props the story repeats — named in every beat they appear in, so
+shots rendered independently still match. A character can be introduced late
+(the reveal) but holds one stable id from its first beat.
+
+The grammar is genre-neutral: the same planner writes a travel vlog, a product
+ad, a nature documentary, a stop-motion short, or an explainer that turns the
+model's own knowledge into narrated teaching beats. Text the viewer must read
+is the one exception — video models garble lettering, so the plan keeps
+on-screen text to a word or two and the information rides the narration;
+exact wording belongs in title and subtitle overlays after assembly.
+
+## Visual consistency
+
+Identity lives in images, never in prose. Text describes what happens in a
+shot; what people and places *look like* rides as reference media:
+
+1. **Sheets first.** Each character and location gets one canonical reference
+ image, designed once from the style bible and the user's references. The
+ sheet fixes face, wardrobe, and carried props.
+2. **Keyframes from sheets.** Each shot's opening frame is rendered as an
+ image with the sheets as identity anchors — image models hold identity far
+ better than video models.
+3. **The identity ladder.** Each shot renders from its strongest available
+ anchor and falls one rung on failure: keyframe as the literal first frame →
+ reference-conditioned video from the sheets → text-only, where identity
+ rides the prompt and drifts.
+
+## Where it's going
+
+Audio follows the same principles later: the narration spine generalizes to a
+music-driven spine with sparse on-screen caption beats instead of wall-to-wall
+narration, and pacing cut to the beat. Longer arcs (multi-scene episodes) are
+the same plan data at larger scale — the sheets are what make a cast hold for
+thirty minutes, so they, not the shots, are the durable asset. The assistant
+already controls the whole editor and the bundled ffmpeg, so every post step —
+trims, transitions, titles, subtitles, export — is available to the same agent
+that planned the story.
+
+## Where it lives
+
+The orchestrator, plan types, and coverage invariant live in the site's Cut
+genvideo area; its planning and media roles are the hosted-model adapters
+beside it, and the chat tool that drives it is generate_scene.
diff --git a/site/src/cut/components/SceneCard.tsx b/site/src/cut/components/SceneCard.tsx
index b2193573..339eb79b 100644
--- a/site/src/cut/components/SceneCard.tsx
+++ b/site/src/cut/components/SceneCard.tsx
@@ -4,9 +4,11 @@ import { useEffect, useRef, useState } from "react";
import { Check, ChevronRight, CircleDashed, Clapperboard, TriangleAlert, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { formatDuration, useGenScene, type SceneRun } from "../lib/genScene";
+import { NO_CREDITS_MESSAGE } from "../lib/generate";
import { GEN_FPS } from "../lib/genvideo/editorBridge";
import { useEditor } from "../lib/store";
import type { Shot, ShotStatus } from "../lib/genvideo/types";
+import { HostedErrorText } from "./hostedError";
// The brief-to-video progress card, pinned into the chat while a "generate a
// video" run is planning, waiting for approval, or rendering. The timeline fills
@@ -86,6 +88,10 @@ export function SceneCard() {
const totalFrames = run.shots.length ? Math.max(...run.shots.map((sh) => sh.endFrame)) : 0;
// Shots that couldn't be rendered as video and are holding a still instead.
const stillCount = run.shots.filter((sh) => sh.status === "failed").length;
+ // Any shot stopped by an empty balance: the summary carries the credits link.
+ const creditsOut = run.shots.some(
+ (sh) => sh.status === "failed" && sh.error === NO_CREDITS_MESSAGE
+ );
// Elapsed clock: planning counts from the run start, rendering from approval;
// it stops at the end. Hidden while waiting for the user at the gate.
const clockAnchor = run.status === "planning" ? run.startedAt : run.renderStartedAt ?? run.startedAt;
@@ -160,15 +166,21 @@ export function SceneCard() {
{fmt(sh.startFrame)}–{fmt(sh.endFrame)}
</span>
<span className="text-foreground/90">{describe(sh)}</span>
- {sh.status === "failed" && (
- <span className="mt-0.5 block text-[10px] text-amber-700">
- Couldn&apos;t animate — showing a still
- {sh.error ? `: ${sh.error}` : ""}
- {redoable ? ". Click to retry." : ""}
- </span>
- )}
</span>
</button>
+ {sh.status === "failed" && (
+ // Outside the redo button: an empty-balance error carries
+ // the credits link, and a link can't live inside a button.
+ <span className="mt-0.5 block pl-6 text-[10px] text-amber-700">
+ Couldn&apos;t animate — showing a still
+ {sh.error ? (
+ <>
+ : <HostedErrorText error={sh.error} />
+ </>
+ ) : null}
+ {redoable ? ". Click the shot to retry." : ""}
+ </span>
+ )}
</li>
);
})}
@@ -189,7 +201,9 @@ export function SceneCard() {
{run.error && (
<p className="mt-2 flex items-start gap-1.5 text-amber-700">
<TriangleAlert className="mt-px size-3 shrink-0" />
- {run.error}
+ <span>
+ <HostedErrorText error={run.error} />
+ </span>
</p>
)}
@@ -212,8 +226,16 @@ export function SceneCard() {
{run.status === "done" && stillCount > 0 && (
<span className="flex flex-1 items-start gap-1 text-[10.5px] text-amber-700">
<TriangleAlert className="mt-px size-3 shrink-0" />
- {stillCount} of {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} held a
- still — video generation failed. Click a shot to retry.
+ <span>
+ {stillCount} of {run.shots.length} shot{run.shots.length === 1 ? "" : "s"} held a
+ still —{" "}
+ {creditsOut ? (
+ <HostedErrorText error={NO_CREDITS_MESSAGE} />
+ ) : (
+ "video generation failed"
+ )}
+ . Click a shot to retry.
+ </span>
</span>
)}
{canDismiss && (
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index b90fc40c..36151755 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -84,13 +84,18 @@ export interface VideoGenOptions {
aspect?: "16:9" | "9:16";
resolution?: "720p" | "1080p";
/** Person-safety for the render. Unset, Veo blocks person/face generation, so
- * any shot with a character fails. ALLOW_ADULT is the most image-to-video
- * permits; ALLOW_ALL (needed for minors) only works text-to-video (no image
- * seed). */
+ * any shot with a character fails. ALLOW_ADULT is the most any image input
+ * permits (first-frame seed and reference images alike); ALLOW_ALL (needed
+ * for minors) only works text-to-video. */
personGeneration?: "DONT_ALLOW" | "ALLOW_ADULT" | "ALLOW_ALL";
/** References of any kind — video, image, text file. Veo takes one
* input image, so at most one picture seeds the render. */
refs?: AssetRef[];
+ /** Identity anchors (Veo 3.1 asset references, up to three): the render
+ * keeps these characters/objects/scenes consistent instead of playing one
+ * as the first frame. Mutually exclusive with a `refs` image seed; the
+ * prompt rides as written (no compose rewrite). */
+ referenceImages?: AssetRef[];
/** Rewrite the prompt around the references before rendering (the
* default when refs are present) — see composeGen.ts. Veo plays the
* input image as the literal first frame, so a prompt that transforms
@@ -401,17 +406,23 @@ export const useGenerate = create<GenerateState>((set, get) => {
// The job (and the landed asset's name) keeps the user's own words;
// only the render sees the composed prompt. Veo seeds from a single
// first-frame image, so at most one kept picture rides along.
- const { prompt: sent, images } = await promptAndImages(
- "video",
- prompt,
- opts?.refs ?? [],
- opts?.composeRefs !== false,
- 1
- );
+ // Identity anchors travel separately: with referenceImages set, the
+ // prompt stands as written and no seed image rides (Veo takes one
+ // or the other).
+ const anchors = opts?.referenceImages?.length
+ ? await refsToInlineImages(visualRefs(opts.referenceImages).slice(0, 3))
+ : [];
+ const { prompt: sent, images } = anchors.length
+ ? { prompt, images: [] }
+ : await promptAndImages("video", prompt, opts?.refs ?? [], opts?.composeRefs !== false, 1);
const res = await hostedPost("/api/inference/assets", {
kind: "video",
prompt: sent,
- ...(images.length > 0 ? { inputs: { images } } : {}),
+ ...(anchors.length > 0
+ ? { inputs: { referenceImages: anchors } }
+ : images.length > 0
+ ? { inputs: { images } }
+ : {}),
parameters: {
tier: opts?.tier === "high" ? "high" : "fast",
aspectRatio: opts?.aspect ?? useEditor.getState().aspect,
diff --git a/site/src/cut/lib/genvideo/adapters/media.ts b/site/src/cut/lib/genvideo/adapters/media.ts
index b52cea67..1193e8be 100644
--- a/site/src/cut/lib/genvideo/adapters/media.ts
+++ b/site/src/cut/lib/genvideo/adapters/media.ts
@@ -13,10 +13,14 @@
* model generate whatever audio it wants and handle it locally — the placed
* clip is muted, so its audio never competes — rather than asking the model to
* suppress audio (a knob many models reject, which just fails the render).
- * - Shots render text-to-video with personGeneration ALLOW_ALL — no person-safety
- * ceiling, so any character animates. That rules out a first-frame image seed
- * (Veo caps a seeded render at ALLOW_ADULT and blocks faces it can't clear), so
- * look continuity rides the prompt and style bible, not a keyframe.
+ * - Cast identity is anchored per shot, strongest signal first (see the ladder
+ * in makeVideoRole): the shot's keyframe — already rendered with the cast's
+ * reference images, so it IS the cast — seeds an image-to-video render; if
+ * that's blocked, the character/location reference images condition a
+ * reference-to-video render; only as a last resort does a shot fall back to
+ * text-only, where the cast rides the prompt alone and drifts. The seeded
+ * and referenced modes run at personGeneration ALLOW_ADULT (the most Veo
+ * permits with image inputs); text-only runs ALLOW_ALL.
* - Durations come from the video-model registry (videoGen.ts), never a literal
* here — models render only fixed clip lengths, so we ask for a supported one
* and let the editor trim it to the exact shot.
@@ -24,7 +28,7 @@
import { refFromAsset, type AssetRef } from "../../assetRef";
import { tagChatAsset } from "../../chatAssets";
-import { useGenerate } from "../../generate";
+import { NO_CREDITS_MESSAGE, useGenerate, type VideoGenOptions } from "../../generate";
import { enrichAsset } from "../../media";
import { useEditor } from "../../store";
import { DEFAULT_VOICE, synthesizeSpeech } from "../../tts";
@@ -67,34 +71,80 @@ export function makeImageRole(projectId: string, chatId?: string): ImageRole {
}
const VIDEO_TIER = "fast" as const;
+/** Veo takes at most three asset reference images per render. */
+const MAX_VIDEO_ANCHORS = 3;
export function makeVideoRole(projectId: string, chatId?: string): VideoRole {
return {
// The model isn't given our narration track, so it never lip-syncs to it.
audioNative: false,
async generate(input) {
- // Text-to-video with personGeneration ALLOW_ALL — no person-safety ceiling,
- // so any character animates (children included). That rules out a
- // first-frame image seed: Veo caps a seeded render at ALLOW_ADULT and
- // blocks a face it can't clear, which is what froze shots to a still. Look
- // continuity rides the prompt and the style bible instead of the keyframe.
- const job = await useGenerate.getState().generateVideo(projectId, input.prompt, {
+ // The identity ladder: every rung renders the same prompt, each with a
+ // weaker identity anchor, and a shot takes the first rung that lands.
+ // Veo allows one anchor kind per render (seed OR references), caps both
+ // at ALLOW_ADULT, and renders reference-conditioned clips at 8s only —
+ // so the rungs are distinct requests, not one combined one.
+ const base = {
tier: VIDEO_TIER,
- // A length the model actually renders (registry-driven); the clip is
- // trimmed to the exact slot on placement.
- durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec),
aspect: input.aspect,
- personGeneration: "ALLOW_ALL",
// Chat ownership rides the job from creation, so a shot never touches
// the Video panel — job row, tile, or badge — even when the render
// errors or lands after the user moved on. Once placed on the timeline
// it's protected from thread-deletion by the clip.
...(chatId ? { chatId } : {}),
- }).settled;
- if (job.status !== "done" || !job.assetId) {
- throw new Error(job.error || "Video generation failed.");
+ };
+ const assets = useEditor.getState().assets;
+ const keyframe = input.startKeyframe
+ ? assets.find((a) => a.id === input.startKeyframe)
+ : undefined;
+ // Identity and place anchors only — a user style reference is a look,
+ // not a cast member, and must never ride as an asset to keep consistent.
+ const anchors = refsToAssetRefs(
+ input.refs.filter((r) => r.purpose === "character" || r.purpose === "location")
+ ).slice(0, MAX_VIDEO_ANCHORS);
+ const attempts: VideoGenOptions[] = [
+ // 1. The keyframe as the literal first frame. It was rendered from the
+ // cast's reference images, so it carries identity, wardrobe, setting,
+ // and framing in one anchor — the strongest continuity Veo offers.
+ ...(keyframe
+ ? [{
+ ...base,
+ refs: [refFromAsset(keyframe)],
+ composeRefs: false,
+ personGeneration: "ALLOW_ADULT" as const,
+ durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec),
+ }]
+ : []),
+ // 2. Reference-to-video on the cast sheets themselves — identity holds,
+ // composition is the model's again.
+ ...(anchors.length > 0
+ ? [{
+ ...base,
+ referenceImages: anchors,
+ personGeneration: "ALLOW_ADULT" as const,
+ durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec, {
+ withReferences: true,
+ }),
+ }]
+ : []),
+ // 3. Text-only, ALLOW_ALL — always renders, identity rides the prompt.
+ {
+ ...base,
+ personGeneration: "ALLOW_ALL" as const,
+ durationSeconds: supportedVideoDuration(VIDEO_TIER, input.durationSec),
+ },
+ ];
+ let lastError = "Video generation failed.";
+ for (const opts of attempts) {
+ const job = await useGenerate.getState().generateVideo(projectId, input.prompt, opts)
+ .settled;
+ if (job.status === "done" && job.assetId) return job.assetId;
+ lastError = job.error || lastError;
+ // An empty balance fails every rung (and every orchestrator retry)
+ // identically — stop here so a broke run fails fast, not 9 times.
+ if (lastError === NO_CREDITS_MESSAGE) break;
}
- return job.assetId;
+ throw new Error(lastError);
},
};
}
diff --git a/site/src/cut/lib/genvideo/adapters/text.ts b/site/src/cut/lib/genvideo/adapters/text.ts
index cd3ccd32..625d592b 100644
--- a/site/src/cut/lib/genvideo/adapters/text.ts
+++ b/site/src/cut/lib/genvideo/adapters/text.ts
@@ -72,7 +72,11 @@ Reply with JSON only:
]}
Rules:
- dialogue is the narration/spoken line for that beat (one or two sentences), action is what is shown on screen.
-- Assign each recurring character a stable id "char:1", "char:2", … and each place a stable id "loc:1", "loc:2", …; every beat lists the ids it uses. A beat with no character uses [].
+- Shape the beats as a story, not a list: open by establishing the world, turn on a small surprise or decision, and end on a payoff image that resolves it.
+- framing is real camera language fit to the genre, varied beat to beat — wide establishing, close-up, insert of a telling detail (a sign, hands, an object), POV, follow shot, over-the-shoulder, aerial, macro, low angle, whatever the story calls for. Never the same framing twice in a row, and never treat this list as a quota.
+- action carries continuity: name the wardrobe items and props the story repeats (the book, the earbuds, the bag) in every beat where they appear, so shots rendered independently still match.
+- A shot cannot be trusted to render readable text: no signs, labels, charts, graphic overlays, or lettering beyond a single short word — information the viewer must read goes in the dialogue instead.
+- Assign each recurring character a stable id "char:1", "char:2", … and each place a stable id "loc:1", "loc:2", …; every beat lists the ids it uses. A beat with no character uses []. A character introduced late (the reveal) is still a stable id from its first beat.
- Keep the whole thing near the requested length; each beat is about 4–8 seconds of narration.
- style is a short reusable look for the whole video (medium, lighting, palette, mood), described by its visual traits — never a real brand, franchise, show, or artist name, even one the brief uses (a generator rejects trademarked names).`;
@@ -125,6 +129,7 @@ Reply with JSON only:
Rules:
- start/end are SECONDS on the timeline; the shots must run in order and cover the whole duration with no gaps.
- Each shot is about 4–8 seconds and its action describes what is shown while those words are heard.
+- framing is real camera language, varied shot to shot — wide establishing, close-up, insert of a telling detail, POV, follow shot — and action repeats the wardrobe and props that recur, so independently rendered shots still match.
- Assign stable ids: characters "char:1"…, locations "loc:1"…, reused across shots for continuity. A shot with no character uses [].`;
/** Compact, timed transcript for the model — capped so a long narration stays
@@ -189,7 +194,7 @@ Reply with JSON only:
{"style": string, "characters": [{"id": "char:1", "name": string, "description": string}], "locations": [{"id": "loc:1", "name": string, "description": string}]}
Rules:
- style is one reusable paragraph every shot carries: medium, lighting, palette, camera, mood.
-- Return one entry per id you are asked to define, using those exact ids. description is a concrete visual of that subject/place (appearance, wardrobe, colors) so it stays consistent across shots.
+- Return one entry per id you are asked to define, using those exact ids. description is a concrete visual of that subject/place — appearance, one fixed wardrobe, and the props the story repeats (a bag, a book, earphones) — so every shot renders the same person carrying the same things.
- Never name a real brand, franchise, show, studio, or artist — not even one the brief names. A generator rejects a trademarked name, so translate any such reference into its concrete visual traits: linework, proportions, palette, shading, era. (e.g. a named 1990s TV cartoon → "hand-drawn 2D animation, thick black outlines, flat bright colors, exaggerated rounded features, yellow-toned skin, simple suburban backdrops".)`;
const DEFAULT_STYLE = "Cinematic, natural light, shallow depth of field.";
diff --git a/site/src/cut/lib/videoGen.ts b/site/src/cut/lib/videoGen.ts
index b9f20ac4..44f16f3f 100644
--- a/site/src/cut/lib/videoGen.ts
+++ b/site/src/cut/lib/videoGen.ts
@@ -31,6 +31,9 @@ export interface VideoModelOption {
word: string;
model: string;
durations: number[];
+ /** Clip lengths the model renders when identity reference images ride
+ * along — Veo 3.1 reference-to-video renders 8s only. */
+ referenceDurations: number[];
aspects: VideoAspect[];
resolutions: VideoResolution[];
}
@@ -41,6 +44,7 @@ export const VIDEO_MODELS: VideoModelOption[] = [
word: "Fast",
model: "Veo 3.1 Fast",
durations: [4, 6, 8],
+ referenceDurations: [8],
aspects: ["16:9", "9:16"],
resolutions: ["720p", "1080p"],
},
@@ -49,6 +53,7 @@ export const VIDEO_MODELS: VideoModelOption[] = [
word: "Best",
model: "Veo 3.1",
durations: [4, 6, 8],
+ referenceDurations: [8],
aspects: ["16:9", "9:16"],
resolutions: ["720p", "1080p"],
},
@@ -64,9 +69,17 @@ export function videoModel(tier: "fast" | "high"): VideoModelOption {
/** Snap a desired clip length to one the model actually renders: the shortest
* supported duration that still covers `seconds` (the caller trims down to the
* exact need), or the model's longest. Video models render only a fixed set of
- * lengths and reject anything else, so a caller must never pass a raw duration. */
-export function supportedVideoDuration(tier: "fast" | "high", seconds: number): number {
- const durations = [...videoModel(tier).durations].sort((a, b) => a - b);
+ * lengths and reject anything else, so a caller must never pass a raw duration.
+ * `withReferences` reads the tighter reference-to-video set. */
+export function supportedVideoDuration(
+ tier: "fast" | "high",
+ seconds: number,
+ opts?: { withReferences?: boolean }
+): number {
+ const model = videoModel(tier);
+ const durations = [...(opts?.withReferences ? model.referenceDurations : model.durations)].sort(
+ (a, b) => a - b
+ );
return durations.find((d) => d >= seconds) ?? durations[durations.length - 1];
}
diff --git a/site/src/lib/inference/adapters/gemini-video.ts b/site/src/lib/inference/adapters/gemini-video.ts
index d00d82bf..21455746 100644
--- a/site/src/lib/inference/adapters/gemini-video.ts
+++ b/site/src/lib/inference/adapters/gemini-video.ts
@@ -1,4 +1,8 @@
-import { GenerateVideosOperation, GoogleGenAI } from "@google/genai";
+import {
+ GenerateVideosOperation,
+ GoogleGenAI,
+ VideoGenerationReferenceType,
+} from "@google/genai";
import type {
GenerateVideosConfig,
GenerateVideosParameters,
@@ -103,13 +107,22 @@ export function createGeminiVideoAssetProvider(
const requestParameters = toJsonObject(request.parameters ?? {});
const model = resolveModel(request.model, stringValue(requestParameters.tier));
const prompt = request.prompt?.trim();
- const image = inputImage(toJsonObject(request.inputs ?? {}));
+ const inputs = toJsonObject(request.inputs ?? {});
+ const image = inputImage(inputs);
+ const references = referenceImages(inputs);
if (!prompt && !image) {
throw new InferenceProviderError(
"Video generation requires a prompt or an input image.",
{ statusCode: 400, code: "empty_video_request" },
);
}
+ if (references.length > 0 && image) {
+ // Veo takes a first-frame seed or asset references, never both.
+ throw new InferenceProviderError(
+ "Video generation takes an input image or reference images, not both.",
+ { statusCode: 400, code: "conflicting_video_inputs" },
+ );
+ }
const params: GenerateVideosParameters = {
model,
@@ -117,7 +130,7 @@ export function createGeminiVideoAssetProvider(
...(image
? { image: { imageBytes: image.data, mimeType: image.mimeType } }
: {}),
- config: videoConfig(requestParameters),
+ config: videoConfig(requestParameters, references),
};
const client = clientFactory(clientConfig.options);
@@ -253,9 +266,45 @@ function inputImage(inputs: JsonObject | undefined): InlineImage | undefined {
return undefined;
}
+// Veo 3.1 asset references ("ingredients"): up to three identity anchors — characters, objects,
+// scenes — the render keeps consistent, sent as inputs.referenceImages = [{ data, mimeType }].
+// Distinct from inputs.images: a reference conditions the whole clip, a seed becomes frame one.
+const MAX_REFERENCE_IMAGES = 3;
+
+function referenceImages(inputs: JsonObject | undefined): InlineImage[] {
+ const list = inputs?.referenceImages;
+ if (!Array.isArray(list)) {
+ return [];
+ }
+ const out: InlineImage[] = [];
+ for (const item of list) {
+ if (!isJsonObject(item)) {
+ continue;
+ }
+ const data = stringValue(item.data);
+ if (!data) {
+ continue;
+ }
+ out.push({ data, mimeType: stringValue(item.mimeType) ?? "image/png" });
+ if (out.length === MAX_REFERENCE_IMAGES) {
+ break;
+ }
+ }
+ return out;
+}
+
// Veo knobs the tool may pass through request.parameters; audio defaults on, one video per call.
-function videoConfig(parameters: JsonObject | undefined): GenerateVideosConfig {
+function videoConfig(
+ parameters: JsonObject | undefined,
+ references: InlineImage[] = [],
+): GenerateVideosConfig {
const config: GenerateVideosConfig = { numberOfVideos: 1, generateAudio: true };
+ if (references.length > 0) {
+ config.referenceImages = references.map((ref) => ({
+ image: { imageBytes: ref.data, mimeType: ref.mimeType },
+ referenceType: VideoGenerationReferenceType.ASSET,
+ }));
+ }
if (!parameters) {
return config;
}
@@ -281,8 +330,13 @@ function videoConfig(parameters: JsonObject | undefined): GenerateVideosConfig {
}
// Person-safety: unset, Veo blocks person/face generation (fatal for any shot
// with a character). Callers pass DONT_ALLOW/ALLOW_ADULT/ALLOW_ALL — note Veo
- // caps image-to-video at ALLOW_ADULT (no minors); ALLOW_ALL needs text-to-video.
- const personGeneration = stringValue(parameters.personGeneration);
+ // caps any render with image inputs (first-frame seed or reference images) at
+ // ALLOW_ADULT (no minors); ALLOW_ALL needs text-to-video. Clamp rather than
+ // let the request 400: the reference is the caller's point, the ceiling isn't.
+ let personGeneration = stringValue(parameters.personGeneration);
+ if (personGeneration && references.length > 0 && /allow[_-]?all/i.test(personGeneration)) {
+ personGeneration = "ALLOW_ADULT";
+ }
if (personGeneration) {
config.personGeneration = personGeneration as GenerateVideosConfig["personGeneration"];
}