Open source CapCut alternative.
TypeScript
feat(site): brief-to-video generation pipeline (genvideo)
David Le6153f79e3a06
diff --git a/site/src/cut/lib/genvideo/capabilities.ts b/site/src/cut/lib/genvideo/capabilities.tsnew file mode 100644index 00000000..e14dc1b7--- /dev/null+++ b/site/src/cut/lib/genvideo/capabilities.ts@@ -0,0 +1,164 @@+/**+ * Model-agnostic capability roles.+ *+ * The pipeline never names a provider. It asks for a capability by role —+ * "write the script", "generate a video", "sync lips to this audio" — and a+ * `ModelSuite` binds each role to some adapter. Provider names live only inside+ * those adapters (see `registry.ts`); swapping models is swapping which adapter+ * a role resolves to, and evals compare suites that differ by one role. The+ * orchestrator depends on this interface and nothing else model-facing.+ */++import type { RawShot } from "./coverage";+import type { RefAsset, ScriptBeat, ScriptPlan, TranscriptWord, VideoAsset } from "./types";++export type Aspect = "9:16" | "16:9";++export interface ScriptInput {+ brief: string;+ refs: RefAsset[];+ targetSeconds?: number;+}++export interface BreakdownInput {+ /** Present when an audio spine already exists (provided or generated VO). */+ transcript: TranscriptWord[];+ /** Present when the run started from a brief. */+ beats?: ScriptBeat[];+ durationFrames: number;+ fps: number;+}++export interface StyleInput {+ brief?: string;+ refs: RefAsset[];+ beats: { dialogue: string; action: string }[];+}++export interface StyleBible {+ /** The reusable style string every downstream prompt carries. */+ style: string;+ characters: VideoAsset[];+ locations: VideoAsset[];+}++export interface ImageInput {+ prompt: string;+ refs: RefAsset[];+ aspect: Aspect;+}++export interface VideoInput {+ prompt: string;+ refs: RefAsset[];+ startKeyframe?: string;+ endKeyframe?: string;+ /** The audio slice this shot should be spoken over — for audio-native video. */+ audioMediaId?: string;+ audioFromSec?: number;+ audioToSec?: number;+ durationSec: number;+ aspect: Aspect;+}++export interface VoiceInput {+ script: string;+ voice?: string;+ direction?: string;+}++export interface VoiceResult {+ mediaId: string;+ durationSec: number;+}++export interface MusicInput {+ mood: string;+ durationSec: number;+}++export interface LipSyncInput {+ videoMediaId: string;+ audioMediaId: string;+ fromSec?: number;+ toSec?: number;+}++export interface ScriptRole {+ write(input: ScriptInput): Promise<ScriptPlan>;+}+export interface BreakdownRole {+ segment(input: BreakdownInput): Promise<RawShot[]>;+}+export interface StyleRole {+ design(input: StyleInput): Promise<StyleBible>;+}+export interface ImageRole {+ /** Returns the generated project media id. */+ generate(input: ImageInput): Promise<string>;+}+export interface VideoRole {+ /** Returns the generated project media id. */+ generate(input: VideoInput): Promise<string>;+ /** True when this model lip-syncs to provided audio itself (no post-pass). */+ readonly audioNative: boolean;+}+export interface VoiceRole {+ speak(input: VoiceInput): Promise<VoiceResult>;+}+export interface MusicRole {+ /** Returns the generated project media id. */+ compose(input: MusicInput): Promise<string>;+}+export interface LipSyncRole {+ /** Returns a new video media id with mouths aligned to the audio. */+ sync(input: LipSyncInput): Promise<string>;+}+export interface TranscribeRole {+ transcribe(audioMediaId: string): Promise<TranscriptWord[]>;+}++/** One model choice per role — what the orchestrator runs against. */+export interface ModelSuite {+ /** Human label for evals and logs, e.g. "fast-video + hi-res-image". */+ label: string;+ script: ScriptRole;+ breakdown: BreakdownRole;+ style: StyleRole;+ image: ImageRole;+ video: VideoRole;+ voice: VoiceRole;+ music: MusicRole;+ /** Absent when `video.audioNative` — the video does its own lip-sync. */+ lipSync?: LipSyncRole;+ transcribe: TranscribeRole;+}++export type RoleName = keyof Omit<ModelSuite, "label">;++/** The deterministic segmenter — the breakdown fallback and the fake's brain. */+export function segmentByDuration(input: BreakdownInput, maxShotSec: number): RawShot[] {+ const { durationFrames, fps, transcript } = input;+ const maxFrames = Math.round(maxShotSec * fps);+ const count = Math.max(1, Math.ceil(durationFrames / maxFrames));+ const per = Math.floor(durationFrames / count);+ const shots: RawShot[] = [];+ for (let i = 0; i < count; i++) {+ const startFrame = i * per;+ const endFrame = i === count - 1 ? durationFrames : (i + 1) * per;+ shots.push({+ startFrame,+ endFrame,+ audioText: wordsInRange(transcript, startFrame / fps, endFrame / fps),+ action: "",+ characters: ["char:1"],+ location: "loc:1",+ framing: i === 0 ? "wide establishing shot" : "medium shot",+ });+ }+ return shots;+}++function wordsInRange(words: TranscriptWord[], from: number, to: number): string {+ return words.filter((w) => w.t1 > from && w.t0 < to).map((w) => w.w).join(" ");+}diff --git a/site/src/cut/lib/genvideo/coverage.ts b/site/src/cut/lib/genvideo/coverage.tsnew file mode 100644index 00000000..619fe9a3--- /dev/null+++ b/site/src/cut/lib/genvideo/coverage.ts@@ -0,0 +1,239 @@+/**+ * The coverage invariant and the frame/second boundary.+ *+ * Shots must tile the whole audio with no gaps and no overlaps: the first+ * starts at frame 0, the last ends at `durationFrames`, and every shot ends+ * exactly where the next begins. Because frames are integers this holds+ * exactly — the orchestrator re-asserts it after every mutation, and any model+ * output is run through `repairCoverage` before it is trusted. `repairCoverage`+ * is total: it never throws for any input (a model routinely returns+ * overlapping, nested, or out-of-order ranges), and it treats a zero-length+ * timeline as covered by zero shots.+ *+ * Seconds cross this boundary only through `frameToSec`/`secToFrame`, computed+ * once from the project fps. Everything else in the plan is frames.+ */++import type { Shot } from "./types";++/** The video model's clip range, in seconds — shots are tuned to it. */+export const MIN_SHOT_SEC = 4;+export const MAX_SHOT_SEC = 8;++export const secToFrame = (sec: number, fps: number): number =>+ Math.max(0, Math.round(sec * fps));++export const frameToSec = (frame: number, fps: number): number => frame / fps;++export const shotDurationFrames = (shot: Shot): number =>+ shot.endFrame - shot.startFrame;++/** Thrown when the invariant is violated — a bug, not a user-facing error. */+export class CoverageError extends Error {}++/**+ * Assert the invariant. Throws `CoverageError` with the exact break. Call this+ * after every mutation to the shot list.+ */+export function assertCoverage(shots: Shot[], durationFrames: number): void {+ if (shots.length === 0) {+ if (durationFrames <= 0) return;+ throw new CoverageError(`No shots cover ${durationFrames} frames.`);+ }+ if (shots[0].startFrame !== 0)+ throw new CoverageError(`First shot starts at ${shots[0].startFrame}, not 0.`);+ const last = shots[shots.length - 1];+ if (last.endFrame !== durationFrames)+ throw new CoverageError(+ `Last shot ends at ${last.endFrame}, not ${durationFrames}.`+ );+ for (let i = 0; i < shots.length; i++) {+ const s = shots[i];+ if (s.endFrame <= s.startFrame)+ throw new CoverageError(+ `Shot ${s.id} is empty or inverted (${s.startFrame}..${s.endFrame}).`+ );+ if (i > 0 && s.startFrame !== shots[i - 1].endFrame)+ throw new CoverageError(+ `Gap or overlap between shot ${shots[i - 1].id} (ends ${+ shots[i - 1].endFrame+ }) and ${s.id} (starts ${s.startFrame}).`+ );+ }+}++/** A raw shot boundary from a model, before it is trusted. */+export interface RawShot {+ startFrame: number;+ endFrame: number;+ audioText?: string;+ action?: string;+ characters?: string[];+ location?: string;+ framing?: string;+}++/**+ * Force a raw boundary list into a valid, fully-covering, correctly-ordered+ * shot list. Sorts, clamps into range, chains the boundaries into a monotonic+ * contiguous sequence (dropping nested/overlapped ranges rather than inverting+ * them), merges any slice shorter than the minimum clip into a neighbor, and+ * splits any slice longer than the maximum clip. The result always passes+ * `assertCoverage`; a zero-length timeline yields zero shots.+ */+export function repairCoverage(+ raw: RawShot[],+ durationFrames: number,+ fps: number,+ makeId: (i: number) => string+): Shot[] {+ if (durationFrames <= 0) return [];+ const minFrames = Math.round(MIN_SHOT_SEC * fps);+ const maxFrames = Math.round(MAX_SHOT_SEC * fps);++ // Sort by start, drop degenerate, clamp into range.+ const sorted = raw+ .map((r) => ({+ startFrame: clampFrame(r.startFrame, durationFrames),+ endFrame: clampFrame(r.endFrame, durationFrames),+ audioText: r.audioText ?? "",+ action: r.action ?? "",+ characters: r.characters ?? [],+ location: r.location ?? "",+ framing: r.framing ?? "",+ }))+ .filter((r) => r.endFrame > r.startFrame)+ .sort((a, b) => a.startFrame - b.startFrame || a.endFrame - b.endFrame);++ // Chain into a contiguous, monotonic sequence. Walk in start order behind a+ // cursor at the end of the last kept shot: each kept shot starts at the+ // cursor and ends at its own clamped end, and any shot ending at or before+ // the cursor — a nested or fully-overlapped range — is dropped. Non-monotonic+ // model output can never produce a gap or an inverted shot this way.+ const live: Slice[] = [];+ let cursor = 0;+ for (const r of sorted) {+ const end = Math.min(r.endFrame, durationFrames);+ if (end <= cursor) continue; // already covered by an earlier, longer shot+ live.push({ ...r, startFrame: cursor, endFrame: end });+ cursor = end;+ if (cursor >= durationFrames) break;+ }+ if (live.length === 0) {+ live.push({ startFrame: 0, endFrame: durationFrames, audioText: "", action: "", characters: [], location: "", framing: "" });+ }+ live[live.length - 1].endFrame = durationFrames;++ // Merge too-short slices, then split too-long ones (split has the last word —+ // the minimum is half the maximum, so an even division never re-slivers).+ const merged = mergeShort(live, minFrames, durationFrames);+ const normalized = resplitOverMax(merged, maxFrames);++ const shots: Shot[] = normalized.map((r, i) => ({+ id: makeId(i),+ startFrame: r.startFrame,+ endFrame: r.endFrame,+ audioText: r.audioText,+ action: r.action,+ characters: r.characters,+ location: r.location,+ framing: r.framing,+ status: "pending",+ attempts: 0,+ }));++ assertCoverage(shots, durationFrames);+ return shots;+}++type Slice = {+ startFrame: number;+ endFrame: number;+ audioText: string;+ action: string;+ characters: string[];+ location: string;+ framing: string;+};++const unionIds = (a: string[], b: string[]): string[] => Array.from(new Set([...a, ...b]));+const joinText = (a: string, b: string): string => [a, b].filter(Boolean).join(" ").trim();++function mergeShort(slices: Slice[], minFrames: number, durationFrames: number): Slice[] {+ // If the whole thing is shorter than one minimum shot, it is one shot.+ if (durationFrames <= minFrames) {+ const first = slices[0];+ return [{ ...first, startFrame: 0, endFrame: durationFrames }];+ }+ const out: Slice[] = [];+ for (const s of slices) {+ const prev = out[out.length - 1];+ if (s.endFrame - s.startFrame < minFrames && prev) {+ // Absorb the sliver forward, carrying its continuity metadata so a+ // character/location that appears only here isn't lost from the plan.+ prev.endFrame = s.endFrame;+ prev.characters = unionIds(prev.characters, s.characters);+ if (!prev.location) prev.location = s.location;+ if (!prev.action) prev.action = s.action;+ if (!prev.framing) prev.framing = s.framing;+ prev.audioText = joinText(prev.audioText, s.audioText);+ } else {+ out.push({ ...s });+ }+ }+ // A too-short head with no predecessor absorbs its successor instead.+ while (out.length > 1 && out[0].endFrame - out[0].startFrame < minFrames) {+ const head = out[0];+ const next = out[1];+ next.startFrame = head.startFrame;+ next.characters = unionIds(head.characters, next.characters);+ if (!next.location) next.location = head.location;+ if (!next.framing) next.framing = head.framing;+ next.audioText = joinText(head.audioText, next.audioText);+ out.shift();+ }+ out[0].startFrame = 0;+ out[out.length - 1].endFrame = durationFrames;+ return out;+}++function resplitOverMax(slices: Slice[], maxFrames: number): Slice[] {+ const out: Slice[] = [];+ for (const s of slices) {+ const len = s.endFrame - s.startFrame;+ if (len <= maxFrames) {+ out.push(s);+ continue;+ }+ const parts = Math.ceil(len / maxFrames);+ const base = Math.floor(len / parts);+ // Scope the transcript to each sub-part so a sub-clip carries only the words+ // spoken during its slice, not the whole original shot's span.+ const textParts = sliceWords(s.audioText, parts);+ let start = s.startFrame;+ for (let i = 0; i < parts; i++) {+ const end = i === parts - 1 ? s.endFrame : start + base;+ out.push({ ...s, startFrame: start, endFrame: end, audioText: textParts[i] });+ start = end;+ }+ }+ return out;+}++/** Split text into `parts` roughly-equal word chunks (in order). */+function sliceWords(text: string, parts: number): string[] {+ if (parts <= 1) return [text];+ const words = text.split(/\s+/).filter(Boolean);+ const out: string[] = [];+ for (let i = 0; i < parts; i++) {+ const from = Math.floor((i * words.length) / parts);+ const to = Math.floor(((i + 1) * words.length) / parts);+ out.push(words.slice(from, to).join(" "));+ }+ return out;+}++const clampFrame = (v: unknown, durationFrames: number): number => {+ const n = typeof v === "number" && Number.isFinite(v) ? Math.round(v) : 0;+ return Math.max(0, Math.min(durationFrames, n));+};diff --git a/site/src/cut/lib/genvideo/editor.ts b/site/src/cut/lib/genvideo/editor.tsnew file mode 100644index 00000000..a43db44a--- /dev/null+++ b/site/src/cut/lib/genvideo/editor.ts@@ -0,0 +1,142 @@+/**+ * The editor bridge — the typed tool set the orchestrator drives the timeline+ * through. Nothing else touches the editor.+ *+ * Frames, not seconds, cross this boundary: the orchestrator plans in frames+ * and this interface is where the conversion to the editor's seconds happens,+ * once, using the timeline fps. The real bridge (wired later) forwards to Cut's+ * editor store; the fake bridge records placements in memory so a test can+ * assert the track is fully covered and correctly timed.+ */++export interface TimelineInfo {+ fps: number;+ durationFrames: number;+ aspect: "9:16" | "16:9";+}++export interface AudioClipInfo {+ clipId: string;+ assetId: string;+ startFrame: number;+ durationFrames: number;+}++export interface EditorBridge {+ getTimeline(): TimelineInfo;+ getAudioClips(): AudioClipInfo[];+ /** Bring a generated media asset into the project pool; returns its media id. */+ importMedia(mediaId: string): Promise<string>;+ /**+ * Place a video clip on the video track so it exactly fills+ * [startFrame, endFrame). Returns the new timeline clip id.+ */+ placeClip(mediaId: string, startFrame: number, endFrame: number): Promise<string>;+ /** Swap the media under an existing clip (regeneration), keeping its slot. */+ replaceClipMedia(clipId: string, mediaId: string): Promise<void>;+ /** Retime a clip so its footprint is exactly `durationFrames`. */+ retimeClip(clipId: string, durationFrames: number): Promise<void>;+ /** Remove a clip, leaving its slot empty. */+ removeClip(clipId: string): Promise<void>;+ /** Add a transition from a clip into the next, in frames. */+ addTransition(clipId: string, style: string, durationFrames: number): Promise<void>;+ /** Place audio (voiceover or a music bed) on the soundtrack. */+ placeAudio(+ mediaId: string,+ startFrame: number,+ durationFrames: number,+ opts?: { kind?: "voice" | "music"; duck?: number; lane?: number }+ ): Promise<string>;+ /** Remove a soundtrack clip, so voice/music placement stays idempotent. */+ removeAudio(clipId: string): Promise<void>;+}++export interface PlacedAudio {+ clipId: string;+ mediaId: string;+ startFrame: number;+ durationFrames: number;+ kind: "voice" | "music";+}++/** What the fake editor recorded for one placed clip. */+export interface PlacedClip {+ clipId: string;+ mediaId: string;+ startFrame: number;+ endFrame: number;+ transition?: { style: string; durationFrames: number };+}++/** In-memory editor that records placements instead of touching a real store. */+export class FakeEditor implements EditorBridge {+ readonly placed: PlacedClip[] = [];+ readonly placedAudio: PlacedAudio[] = [];+ private seq = 0;++ constructor(private readonly timeline: TimelineInfo, private readonly audio: AudioClipInfo[]) {}++ getTimeline(): TimelineInfo {+ return this.timeline;+ }++ getAudioClips(): AudioClipInfo[] {+ return this.audio;+ }++ async importMedia(mediaId: string): Promise<string> {+ return mediaId;+ }++ async placeClip(mediaId: string, startFrame: number, endFrame: number): Promise<string> {+ const clipId = `clip:${this.seq++}`;+ this.placed.push({ clipId, mediaId, startFrame, endFrame });+ return clipId;+ }++ async replaceClipMedia(clipId: string, mediaId: string): Promise<void> {+ const clip = this.require(clipId);+ clip.mediaId = mediaId;+ }++ async retimeClip(clipId: string, durationFrames: number): Promise<void> {+ const clip = this.require(clipId);+ clip.endFrame = clip.startFrame + durationFrames;+ }++ async removeClip(clipId: string): Promise<void> {+ const i = this.placed.findIndex((c) => c.clipId === clipId);+ if (i >= 0) this.placed.splice(i, 1);+ }++ async addTransition(clipId: string, style: string, durationFrames: number): Promise<void> {+ this.require(clipId).transition = { style, durationFrames };+ }++ async placeAudio(+ mediaId: string,+ startFrame: number,+ durationFrames: number,+ opts?: { kind?: "voice" | "music"; duck?: number; lane?: number }+ ): Promise<string> {+ const clipId = `audio:${this.seq++}`;+ this.placedAudio.push({ clipId, mediaId, startFrame, durationFrames, kind: opts?.kind ?? "voice" });+ return clipId;+ }++ async removeAudio(clipId: string): Promise<void> {+ const i = this.placedAudio.findIndex((c) => c.clipId === clipId);+ if (i >= 0) this.placedAudio.splice(i, 1);+ }++ /** The placed clips sorted by start — the timeline as the fake sees it. */+ timeline_clips(): PlacedClip[] {+ return [...this.placed].sort((a, b) => a.startFrame - b.startFrame);+ }++ private require(clipId: string): PlacedClip {+ const clip = this.placed.find((c) => c.clipId === clipId);+ if (!clip) throw new Error(`no clip ${clipId}`);+ return clip;+ }+}diff --git a/site/src/cut/lib/genvideo/fakes.ts b/site/src/cut/lib/genvideo/fakes.tsnew file mode 100644index 00000000..0f408857--- /dev/null+++ b/site/src/cut/lib/genvideo/fakes.ts@@ -0,0 +1,159 @@+/**+ * A fake studio: every capability role, implemented in memory and instantly.+ *+ * This is how the whole pipeline — coverage, timing, voiceover, music,+ * lip-sync, placement, retry, fallback, model swapping — is exercised without a+ * credit spent or a browser. Each role records its calls so a test can assert+ * what ran, and the studio is configurable per role so an eval can build two+ * suites that differ by one model and compare them.+ */++import { MAX_SHOT_SEC, MIN_SHOT_SEC } from "./coverage";+import {+ segmentByDuration,+ type BreakdownInput,+ type ImageInput,+ type LipSyncInput,+ type ModelSuite,+ type MusicInput,+ type ScriptInput,+ type StyleBible,+ type VideoInput,+ type VoiceInput,+ type VoiceResult,+} from "./capabilities";+import type { RawShot } from "./coverage";+import type { ScriptPlan, TranscriptWord } from "./types";++export interface FakeCall {+ role: string;+ detail: string;+ mediaId?: string;+}++export interface FakeStudioOptions {+ label?: string;+ /** Reject every video whose prompt contains this marker (all attempts). */+ failVideoMarker?: string;+ /** This video model lip-syncs to audio itself — no lip-sync post-pass. */+ audioNative?: boolean;+ /** Tag on generated video ids, so an eval can tell suites apart. */+ videoVariant?: string;+ /** Beats the fake script writes when starting from a brief. */+ scriptBeats?: number;+ /** Force every voiceover to this many seconds (else derived from the line);+ * used to exercise a beat whose VO outruns one clip and spans several shots. */+ voiceSeconds?: number;+ /** Fail every image generation whose prompt contains this marker. */+ failImageMarker?: string;+ /** Make the style/character-design call throw (exercises the default bible). */+ failStyle?: boolean;+ style?: string;+}++/** An in-memory studio; `.suite()` binds it to the orchestrator's roles. */+export class FakeStudio {+ readonly calls: FakeCall[] = [];+ private seq = 0;+ readonly label: string;++ constructor(private readonly opts: FakeStudioOptions = {}) {+ this.label = opts.label ?? "fake";+ }++ private mint(role: string, detail: string): string {+ const mediaId = `fake:${role}:${this.opts.videoVariant ?? "v"}:${this.seq++}`;+ this.calls.push({ role, detail, mediaId });+ return mediaId;+ }++ suite(): ModelSuite {+ const audioNative = !!this.opts.audioNative;+ return {+ label: this.label,+ script: { write: (i) => this.writeScript(i) },+ breakdown: { segment: (i) => this.segment(i) },+ style: { design: () => this.design() },+ image: { generate: (i) => this.image(i) },+ video: { generate: (i) => this.video(i), audioNative },+ voice: { speak: (i) => this.speak(i) },+ music: { compose: (i) => this.music(i) },+ ...(audioNative ? {} : { lipSync: { sync: (i: LipSyncInput) => this.lipSync(i) } }),+ transcribe: { transcribe: (id: string) => this.transcribe(id) },+ };+ }++ private async writeScript(input: ScriptInput): Promise<ScriptPlan> {+ const n = this.opts.scriptBeats ?? Math.max(2, Math.round((input.targetSeconds ?? 30) / 6));+ const beats = Array.from({ length: n }, (_, i) => ({+ dialogue: `Line ${i + 1}: ${input.brief}`.slice(0, 80),+ action: i === 0 ? "establishing the scene" : "the story continues",+ characters: ["char:1"],+ location: "loc:1",+ framing: i === 0 ? "wide establishing shot" : "medium shot",+ approxSeconds: 6,+ }));+ this.calls.push({ role: "script", detail: `${n} beats from brief` });+ return { logline: input.brief, beats, style: this.opts.style };+ }++ private async segment(input: BreakdownInput): Promise<RawShot[]> {+ this.calls.push({ role: "breakdown", detail: `${input.durationFrames} frames` });+ return segmentByDuration(input, MAX_SHOT_SEC);+ }++ private async design(): Promise<StyleBible> {+ if (this.opts.failStyle) throw new Error("fake style design failed");+ this.calls.push({ role: "style", detail: "style bible" });+ return {+ style: this.opts.style ?? "Cinematic, natural light, shallow depth of field.",+ characters: [+ { id: "char:1", kind: "character", name: "the lead", description: "the person from the references" },+ ],+ locations: [{ id: "loc:1", kind: "location", name: "the setting", description: "the place the story lives" }],+ };+ }++ private async image(input: ImageInput): Promise<string> {+ const marker = this.opts.failImageMarker;+ if (marker && input.prompt.includes(marker))+ throw new Error(`fake image failed (marker "${marker}")`);+ return this.mint("image", input.prompt.slice(0, 40));+ }++ private async video(input: VideoInput): Promise<string> {+ const marker = this.opts.failVideoMarker;+ if (marker && input.prompt.includes(marker))+ throw new Error(`fake video failed (marker "${marker}")`);+ return this.mint("video", `${input.durationSec}s${input.audioMediaId ? " +audio" : ""}`);+ }++ private async speak(input: VoiceInput): Promise<VoiceResult> {+ // Length from the line (or forced via voiceSeconds). A line longer than one+ // clip is a real case — the orchestrator spans it across several shots.+ const raw = Math.max(1, input.script.length) * 0.06;+ const durationSec = this.opts.voiceSeconds ?? Math.max(MIN_SHOT_SEC, raw);+ return { mediaId: this.mint("voice", `${durationSec.toFixed(1)}s`), durationSec };+ }++ private async music(input: MusicInput): Promise<string> {+ return this.mint("music", `${input.mood} ${input.durationSec.toFixed(1)}s`);+ }++ private async lipSync(input: LipSyncInput): Promise<string> {+ return this.mint("lipsync", `sync ${input.videoMediaId}`);+ }++ private async transcribe(audioMediaId: string): Promise<TranscriptWord[]> {+ this.calls.push({ role: "transcribe", detail: audioMediaId });+ const words: TranscriptWord[] = [];+ for (let i = 0; i < 60; i++) words.push({ t0: i * 0.5, t1: i * 0.5 + 0.5, w: `word${i}` });+ return words;+ }+}++/** Convenience: a bound suite from options. */+export function fakeSuite(opts: FakeStudioOptions = {}): { suite: ModelSuite; studio: FakeStudio } {+ const studio = new FakeStudio(opts);+ return { suite: studio.suite(), studio };+}diff --git a/site/src/cut/lib/genvideo/orchestrator.ts b/site/src/cut/lib/genvideo/orchestrator.tsnew file mode 100644index 00000000..c2608961--- /dev/null+++ b/site/src/cut/lib/genvideo/orchestrator.ts@@ -0,0 +1,535 @@+/**+ * The brief-to-video orchestrator: a state machine, not a free-form loop.+ *+ * Phases run in order and the run is re-entrant — `run()` advances from+ * whatever phase the persisted project is in, so a restart resumes and a+ * follow-up turn re-enters for a subset of shots. The model is called only at+ * the genuine judgment points (script, breakdown, style); every other step is+ * deterministic. After every shot-list mutation the coverage invariant is+ * re-asserted, and the worker pool fills the track incrementally so the user+ * watches it populate.+ *+ * brief → ingest → breakdown → (confirm) → style → keyframes → generating → polish → done+ *+ * A run has one audio spine — dropped-in audio, or a script the pipeline+ * voices plus a music bed. Shots tile the spine and each shot's video is+ * lip-synced to its slice: an audio-native video model does it inline, else a+ * lip-sync pass follows. Every placement is idempotent (a resume or a+ * regeneration swaps a clip in only once the replacement is ready), so no path+ * double-stacks video, voice, or music, and none leaves a hole in the track.+ */++import { assertCoverage, frameToSec, MAX_SHOT_SEC, MIN_SHOT_SEC, repairCoverage, secToFrame, shotDurationFrames } from "./coverage";+import { fanOut } from "./pool";+import { buildPrompt, buildRefPrompt, refsForAsset, shotRefs } from "./prompt";+import { segmentByDuration, type ModelSuite } from "./capabilities";+import type { EditorBridge } from "./editor";+import type { BeatVoice, RefAsset, Shot, VideoAsset, VideoEmit, VideoPhase, VideoProject } from "./types";++export interface OrchestratorDeps {+ editor: EditorBridge;+ suite: ModelSuite;+ emit: VideoEmit;+ /** Write the plan to disk (rides ProjectDoc.genvideo). */+ persist: (project: VideoProject) => void | Promise<void>;+ /** Workers in flight during generation (tuned to the provider's rate limit). */+ concurrency?: number;+ /** Injected sleep so tests run instantly. */+ sleep?: (ms: number) => Promise<void>;+}++const VIDEO_ATTEMPTS = 3; // the first try plus two retries+const REF_ATTEMPTS = 2; // extra retries for continuity anchors+const BACKOFF_MS = 500;+const VOICE_DUCK = 0.35;++export class VideoOrchestrator {+ private readonly aspect: "9:16" | "16:9";+ /** Serializes persistence so concurrent shot updates never interleave writes. */+ private saveChain: Promise<void> = Promise.resolve();++ constructor(public project: VideoProject, private readonly deps: OrchestratorDeps) {+ this.aspect = deps.editor.getTimeline().aspect;+ }++ private get fps(): number {+ return this.project.fps;+ }+ private get durationFrames(): number {+ return this.project.durationFrames;+ }++ /** Advance the run from its current phase to the next stopping point. */+ async run(): Promise<VideoProject> {+ if (this.project.phase === "failed" || this.project.phase === "done") return this.project;+ await this.brief();+ await this.ingest();+ await this.breakdown();+ if (!this.project.breakdownApproved) return this.project; // wait for confirmation+ await this.style();+ await this.keyframes();+ await this.generateAndPlaceAll();+ await this.polish();+ return this.project;+ }++ /** The user confirmed the shot list — continue the run. */+ async approveBreakdown(): Promise<VideoProject> {+ this.project.breakdownApproved = true;+ await this.save();+ return this.run();+ }++ // ── Phase 0: brief → script → voiced spine + music (generated mode) ───────+ private async brief(): Promise<void> {+ if (this.project.audioMode !== "generated") return;+ if (this.project.shots.length > 0) return; // already planned (resume)+ this.setPhase("brief");+ if (!this.project.script) {+ this.project.script = await this.deps.suite.script.write({+ brief: this.project.brief,+ refs: this.project.references,+ targetSeconds: this.project.targetSeconds,+ });+ await this.save();+ }+ // Voice each beat to get its true length; the voice is one clip per beat,+ // and a beat longer than one video clip spans several shots that each+ // lip-sync to their own slice — so a long line is never cut off.+ const minF = Math.round(MIN_SHOT_SEC * this.fps);+ const maxF = Math.round(MAX_SHOT_SEC * this.fps);+ let cursor = 0;+ const shots: Shot[] = [];+ const beatVoices: BeatVoice[] = [];+ for (const beat of this.project.script.beats) {+ const vo = await this.deps.suite.voice.speak({ script: beat.dialogue });+ const voiceId = await this.deps.editor.importMedia(vo.mediaId);+ const beatFrames = Math.max(minF, secToFrame(vo.durationSec, this.fps));+ const beatStart = cursor;+ beatVoices.push({ voiceAssetId: voiceId, startFrame: beatStart, durationFrames: beatFrames });+ for (const [s, e] of splitBeat(beatStart, beatFrames, maxF)) {+ shots.push({+ id: `shot:${shots.length}`,+ startFrame: s,+ endFrame: e,+ audioText: beat.dialogue,+ dialogue: beat.dialogue,+ action: beat.action,+ characters: beat.characters,+ location: beat.location,+ framing: beat.framing,+ voiceAssetId: voiceId,+ voiceFromSec: frameToSec(s - beatStart, this.fps),+ voiceToSec: frameToSec(e - beatStart, this.fps),+ status: "pending",+ attempts: 0,+ });+ }+ cursor += beatFrames;+ }+ this.project.durationFrames = cursor;+ this.project.shots = shots;+ this.project.beatVoices = beatVoices;+ assertCoverage(this.project.shots, this.durationFrames);+ const music = await this.deps.suite.music.compose({+ mood: this.project.script.style ?? this.project.style ?? "cinematic underscore",+ durationSec: frameToSec(cursor, this.fps),+ });+ this.project.musicAssetId = await this.deps.editor.importMedia(music);+ await this.save();+ }++ // ── Phase A: ingest (provided mode) ──────────────────────────────────────+ private async ingest(): Promise<void> {+ if (this.project.audioMode !== "provided") return;+ if (this.project.transcript.length > 0 || !this.project.audioAssetId) return;+ this.setPhase("ingest");+ this.project.transcript = await this.deps.suite.transcribe.transcribe(this.project.audioAssetId);+ await this.save();+ }++ // ── Phase B: shot breakdown (provided mode) + confirmation gate ───────────+ private async breakdown(): Promise<void> {+ if (this.project.shots.length === 0) {+ this.setPhase("breakdown");+ const input = { transcript: this.project.transcript, durationFrames: this.durationFrames, fps: this.fps };+ const id = (i: number) => `shot:${i}`;+ let shots: Shot[];+ try {+ shots = repairCoverage(await this.deps.suite.breakdown.segment(input), this.durationFrames, this.fps, id);+ } catch {+ shots = repairCoverage(segmentByDuration(input, MAX_SHOT_SEC), this.durationFrames, this.fps, id);+ }+ this.project.shots = shots;+ assertCoverage(this.project.shots, this.durationFrames);+ await this.save();+ }+ this.deps.emit({ type: "breakdown", shots: this.project.shots });+ }++ // ── Phase C: style bible + reference images ──────────────────────────────+ private async style(): Promise<void> {+ this.setPhase("style");+ if (!this.project.style || this.project.characters.length === 0) {+ try {+ const bible = await this.deps.suite.style.design({+ brief: this.project.brief,+ refs: this.project.references,+ beats: this.project.shots.map((s) => ({ dialogue: s.dialogue ?? s.audioText, action: s.action })),+ });+ this.project.style = bible.style;+ this.project.characters = bible.characters;+ this.project.locations = bible.locations;+ } catch {+ // Degrade to a default bible so identity anchors still exist — an empty+ // characters list would silently drop every reference image.+ if (!this.project.style) this.project.style = "Cinematic, natural light.";+ if (this.project.characters.length === 0)+ this.project.characters = [{ id: "char:1", kind: "character", name: "the subject", description: "the main subject, from the references" }];+ if (this.project.locations.length === 0)+ this.project.locations = [{ id: "loc:1", kind: "location", name: "the setting", description: "the scene" }];+ }+ await this.save();+ }+ const needed = this.referencedAssets().filter((a) => !a.mediaId);+ if (needed.length > 0) {+ await fanOut(+ needed,+ async (asset) => {+ const raw = await this.deps.suite.image.generate({+ prompt: buildRefPrompt(asset, this.project.style),+ refs: refsForAsset(asset, this.project),+ aspect: this.aspect,+ });+ asset.mediaId = await this.deps.editor.importMedia(raw);+ this.deps.emit({ type: "log", message: `Designed ${asset.name}.` });+ },+ this.poolOpts(REF_ATTEMPTS)+ );+ const missing = needed.filter((a) => !a.mediaId);+ if (missing.length)+ this.deps.emit({ type: "log", message: `Couldn't design ${missing.map((a) => a.name).join(", ")} — those shots may drift.` });+ await this.save();+ }+ }++ // ── Phase D: keyframes (cheap, run in parallel) ──────────────────────────+ private async keyframes(): Promise<void> {+ this.setPhase("keyframes");+ const need = this.project.shots.filter((s) => !s.startKeyframe && s.status !== "placed");+ if (need.length === 0) return;+ // Failures are fine here — a shot with no keyframe still gets a still sourced+ // in placeFallback, so nothing swallowed leaves a hole.+ await fanOut(need, (shot) => this.makeKeyframes(shot), this.poolOpts(1));+ await this.save();+ }++ private async makeKeyframes(shot: Shot): Promise<void> {+ this.updateShot(shot, { status: "keyframing" });+ const refs = shotRefs(shot, this.project);+ const prompt = buildPrompt(shot, this.project);+ shot.startKeyframe = await this.importedImage(`${prompt} Opening frame.`, refs);+ if (hasMotion(shot)) shot.endKeyframe = await this.importedImage(`${prompt} Closing frame.`, refs);+ this.updateShot(shot, { status: "pending" });+ }++ // ── Phase E + F: generation fans out; each clip places when it lands ──────+ private async generateAndPlaceAll(): Promise<void> {+ this.setPhase("generating");+ await this.placeSpine();+ const pending = this.project.shots.filter((s) => s.status !== "placed");+ await fanOut(pending, (shot) => this.generateAndPlace(shot), this.poolOpts(0));+ this.emitProgress();+ }++ /** Place the generated voiceover, once per beat (idempotent across resumes). */+ private async placeSpine(): Promise<void> {+ if (this.project.audioMode !== "generated" || !this.project.beatVoices) return;+ let changed = false;+ for (const bv of this.project.beatVoices) {+ if (bv.voiceClipId) continue;+ bv.voiceClipId = await this.deps.editor.placeAudio(bv.voiceAssetId, bv.startFrame, bv.durationFrames, {+ kind: "voice",+ duck: VOICE_DUCK,+ });+ changed = true;+ }+ if (changed) await this.save();+ }++ private async generateAndPlace(shot: Shot): Promise<void> {+ this.updateShot(shot, { status: "generating", error: undefined });+ const audio = this.audioForShot(shot);+ const prompt = buildPrompt(shot, this.project);+ const refs = shotRefs(shot, this.project);+ for (let attempt = 1; attempt <= VIDEO_ATTEMPTS; attempt++) {+ shot.attempts = attempt;+ try {+ let clip = await this.deps.suite.video.generate({+ prompt,+ refs,+ startKeyframe: shot.startKeyframe,+ endKeyframe: shot.endKeyframe,+ durationSec: frameToSec(shotDurationFrames(shot), this.fps),+ aspect: this.aspect,+ ...(audio && this.deps.suite.video.audioNative+ ? { audioMediaId: audio.mediaId, audioFromSec: audio.fromSec, audioToSec: audio.toSec }+ : {}),+ });+ clip = await this.deps.editor.importMedia(clip);+ // Lip-sync post-pass when the video model can't do it inline.+ if (audio && !this.deps.suite.video.audioNative && this.deps.suite.lipSync) {+ this.updateShot(shot, { status: "lipsync" });+ const synced = await this.deps.suite.lipSync.sync({+ videoMediaId: clip,+ audioMediaId: audio.mediaId,+ fromSec: audio.fromSec,+ toSec: audio.toSec,+ });+ clip = await this.deps.editor.importMedia(synced);+ shot.lipSynced = true;+ }+ // Swap the new clip in only now that it's ready, replacing any prior+ // placement (a resume's fallback still, a regen's old clip) atomically.+ await this.clearVideoPlacement(shot);+ shot.lastPrompt = prompt;+ shot.clip = clip;+ shot.timelineClipId = await this.deps.editor.placeClip(clip, shot.startFrame, shot.endFrame);+ this.updateShot(shot, { status: "placed", error: undefined });+ this.emitProgress();+ return;+ } catch (e) {+ shot.error = String(e instanceof Error ? e.message : e);+ if (attempt < VIDEO_ATTEMPTS) await this.sleep(BACKOFF_MS * attempt);+ }+ }+ await this.placeFallback(shot); // never leave a hole+ this.emitProgress();+ }++ /** The audio slice a shot should be spoken over. */+ private audioForShot(shot: Shot): { mediaId: string; fromSec: number; toSec: number } | undefined {+ if (this.project.audioMode === "generated") {+ if (!shot.voiceAssetId) return undefined;+ return {+ mediaId: shot.voiceAssetId,+ fromSec: shot.voiceFromSec ?? 0,+ toSec: shot.voiceToSec ?? frameToSec(shotDurationFrames(shot), this.fps),+ };+ }+ if (!this.project.audioAssetId) return undefined;+ return {+ mediaId: this.project.audioAssetId,+ fromSec: frameToSec(shot.startFrame, this.fps),+ toSec: frameToSec(shot.endFrame, this.fps),+ };+ }++ /** Hold a still for a shot whose video couldn't be made — never a black gap. */+ private async placeFallback(shot: Shot): Promise<void> {+ const still = await this.fallbackStill(shot);+ if (still) {+ await this.clearVideoPlacement(shot);+ // `still` is already an imported project media id; placing it directly+ // avoids re-importing an id the pool already holds.+ shot.clip = still;+ shot.timelineClipId = await this.deps.editor.placeClip(still, shot.startFrame, shot.endFrame);+ } else {+ // Nothing to hold — keep whatever was there rather than opening a hole.+ this.deps.emit({ type: "error", message: `Shot ${shot.id} could not be generated or filled.` });+ }+ this.updateShot(shot, { status: "failed" });+ }++ /** Source a still for a fallback: this shot's keyframe, a freshly minted one,+ * or a neighbor's frame — so a keyframe-gen failure never leaves a hole. */+ private async fallbackStill(shot: Shot): Promise<string | undefined> {+ if (shot.startKeyframe) return shot.startKeyframe;+ if (shot.endKeyframe) return shot.endKeyframe;+ try {+ shot.startKeyframe = await this.importedImage(`${buildPrompt(shot, this.project)} Still frame.`, shotRefs(shot, this.project));+ return shot.startKeyframe;+ } catch {+ /* fall through to holding a neighbor's frame */+ }+ const idx = this.project.shots.findIndex((s) => s.id === shot.id);+ for (let i = idx - 1; i >= 0; i--) {+ const prev = this.project.shots[i];+ if (prev.clip) return prev.clip;+ if (prev.startKeyframe) return prev.startKeyframe;+ }+ for (let i = idx + 1; i < this.project.shots.length; i++) {+ const next = this.project.shots[i];+ if (next.clip) return next.clip;+ if (next.startKeyframe) return next.startKeyframe;+ }+ return undefined;+ }++ private async clearVideoPlacement(shot: Shot): Promise<void> {+ if (shot.timelineClipId) {+ await this.deps.editor.removeClip(shot.timelineClipId);+ shot.timelineClipId = undefined;+ }+ }++ // ── Phase H: polish ──────────────────────────────────────────────────────+ private async polish(): Promise<void> {+ this.setPhase("polish");+ if (this.project.musicAssetId) {+ // Idempotent: replace the prior bed instead of stacking a second one.+ if (this.project.musicClipId) await this.deps.editor.removeAudio(this.project.musicClipId);+ this.project.musicClipId = await this.deps.editor.placeAudio(this.project.musicAssetId, 0, this.durationFrames, {+ kind: "music",+ lane: 1,+ });+ }+ const placed = this.project.shots.filter((s) => s.timelineClipId).length;+ const failed = this.project.shots.filter((s) => s.status === "failed").length;+ this.deps.emit({+ type: "log",+ message:+ `Video assembled with ${this.deps.suite.label}: ${placed}/${this.project.shots.length} shots on the track` ++ (failed ? `, ${failed} held as a still to regenerate.` : "."),+ });+ this.setPhase("done");+ await this.save();+ }++ // ── Selective regeneration (review loop + follow-up diffs) ───────────────++ async regenerateShots(ids: string[], mutate?: (shot: Shot) => void): Promise<VideoProject> {+ const targets: Shot[] = [];+ for (const id of ids) {+ const shot = this.project.shots.find((s) => s.id === id);+ if (!shot) continue;+ // Keep timelineClipId/clip so generateAndPlace swaps them once the new+ // clip is ready — clearing them up front would open a hole if the redo+ // fails. The beat voice is untouched, so narration never restacks.+ shot.startKeyframe = undefined;+ shot.endKeyframe = undefined;+ shot.lipSynced = false;+ shot.error = undefined;+ shot.status = "pending";+ mutate?.(shot);+ targets.push(shot);+ }+ await this.save();+ await fanOut(+ targets,+ async (shot) => {+ try {+ await this.makeKeyframes(shot);+ } catch {+ /* placeFallback will source a still */+ }+ await this.generateAndPlace(shot);+ },+ this.poolOpts(0)+ );+ await this.save();+ return this.project;+ }++ /** "Make shot N wider / a close-up" — a framing note, one shot dirtied. */+ async applyShotNote(id: string, note: string): Promise<VideoProject> {+ return this.regenerateShots([id], (shot) => {+ shot.action = shot.action ? `${shot.action} ${note}`.trim() : note;+ });+ }++ /** A style change dirties everything downstream of the style bible. */+ async changeStyle(style: string): Promise<VideoProject> {+ this.project.style = style;+ for (const a of [...this.project.characters, ...this.project.locations]) a.mediaId = undefined;+ await this.save();+ await this.style();+ await this.regenerateShots(this.project.shots.map((s) => s.id));+ // Restore the terminal phase so a later resume doesn't re-run polish (which+ // would otherwise re-place the music bed).+ this.setPhase("done");+ await this.save();+ return this.project;+ }++ shotIdByNumber(n: number): string | undefined {+ return this.project.shots[n - 1]?.id;+ }++ // ── helpers ──────────────────────────────────────────────────────────────++ private referencedAssets(): VideoAsset[] {+ const usedChars = new Set(this.project.shots.flatMap((s) => s.characters));+ const usedLocs = new Set(this.project.shots.map((s) => s.location));+ return [+ ...this.project.characters.filter((c) => usedChars.has(c.id)),+ ...this.project.locations.filter((l) => usedLocs.has(l.id)),+ ];+ }++ private async importedImage(prompt: string, refs: RefAsset[]): Promise<string> {+ const raw = await this.deps.suite.image.generate({ prompt, refs, aspect: this.aspect });+ return this.deps.editor.importMedia(raw);+ }++ private emitProgress(): void {+ const placed = this.project.shots.filter((s) => s.timelineClipId).length;+ this.deps.emit({ type: "progress", placed, total: this.project.shots.length });+ }++ private setPhase(phase: VideoPhase, note?: string): void {+ this.project.phase = phase;+ this.deps.emit({ type: "phase", phase, note });+ }++ private updateShot(shot: Shot, patch: Partial<Shot>): void {+ Object.assign(shot, patch);+ void this.save();+ this.deps.emit({ type: "shot:update", shot });+ }++ private poolOpts(retries: number) {+ return {+ concurrency: this.deps.concurrency ?? 6,+ retries,+ backoffMs: BACKOFF_MS,+ ...(this.deps.sleep ? { sleep: this.deps.sleep } : {}),+ };+ }++ private sleep(ms: number): Promise<void> {+ return this.deps.sleep ? this.deps.sleep(ms) : new Promise((r) => setTimeout(r, ms));+ }++ /** Persist, serialized so concurrent updates never interleave writes. */+ private save(): Promise<void> {+ this.project.updatedAt = this.project.updatedAt + 1; // monotonic without Date in tests+ this.saveChain = this.saveChain.then(() => this.deps.persist(this.project)).catch(() => {});+ return this.saveChain;+ }+}++/** Whether a shot has enough motion to warrant a distinct closing keyframe. */+function hasMotion(shot: Shot): boolean {+ return /\b(runs?|walks?|jumps?|flies|fly|turns?|moves?|falls?|rises?|spins?|races?|drives?|dances?|zoom)/i.test(+ shot.action+ );+}++/** Split one beat's span into contiguous shots each no longer than `maxFrames`,+ * distributing the remainder so the pieces stay as even as possible. */+function splitBeat(start: number, frames: number, maxFrames: number): [number, number][] {+ const parts = Math.max(1, Math.ceil(frames / maxFrames));+ const base = Math.floor(frames / parts);+ let rem = frames - base * parts;+ const out: [number, number][] = [];+ let s = start;+ for (let i = 0; i < parts; i++) {+ const size = base + (rem > 0 ? 1 : 0);+ if (rem > 0) rem--;+ const e = i === parts - 1 ? start + frames : s + size;+ out.push([s, e]);+ s = e;+ }+ return out;+}diff --git a/site/src/cut/lib/genvideo/pool.ts b/site/src/cut/lib/genvideo/pool.tsnew file mode 100644index 00000000..5d20519a--- /dev/null+++ b/site/src/cut/lib/genvideo/pool.ts@@ -0,0 +1,74 @@+/**+ * A bounded worker pool — the fan-out for video generation.+ *+ * Mirrors the deterministic-orchestrator `fanOut` primitive: N items run+ * through a worker at most `concurrency` in flight, one item's failure never+ * sinks the others, and each item retries with backoff before it is given up+ * on. The pool owns scheduling only; what a worker does on final failure+ * (hold a still, mark the shot) is the caller's business.+ */++export interface PoolOptions {+ /** Max workers in flight (tuned to the provider's rate limit). */+ concurrency: number;+ /** Extra attempts after the first, per item. */+ retries: number;+ /** Base backoff between attempts, ms (grows linearly with the attempt). */+ backoffMs: number;+ /** Injected sleep so tests run instantly; defaults to a real timer. */+ sleep?: (ms: number) => Promise<void>;+}++export interface PoolResult<T> {+ /** Per-item outcome in submission order: the value, or null if it gave up. */+ results: (T | null)[];+ /** Indices that exhausted their retries. */+ failures: number[];+}++const realSleep = (ms: number) =>+ new Promise<void>((r) => setTimeout(r, ms));++/**+ * Run `worker` over every item with bounded concurrency and per-item retry.+ * The returned promise never rejects — a worker that throws through all its+ * attempts lands as `null` in `results` and its index in `failures`.+ */+export async function fanOut<I, T>(+ items: I[],+ worker: (item: I, index: number) => Promise<T>,+ opts: PoolOptions+): Promise<PoolResult<T>> {+ const sleep = opts.sleep ?? realSleep;+ const concurrency = Math.max(1, Math.floor(opts.concurrency));+ const results: (T | null)[] = new Array(items.length).fill(null);+ const failures: number[] = [];+ let next = 0;++ async function runOne(index: number): Promise<void> {+ const item = items[index];+ for (let attempt = 0; attempt <= opts.retries; attempt++) {+ try {+ results[index] = await worker(item, index);+ return;+ } catch {+ if (attempt < opts.retries) await sleep(opts.backoffMs * (attempt + 1));+ }+ }+ failures.push(index);+ }++ async function drain(): Promise<void> {+ while (true) {+ const index = next++;+ if (index >= items.length) return;+ await runOne(index);+ }+ }++ const lanes = Array.from({ length: Math.min(concurrency, items.length) }, () =>+ drain()+ );+ await Promise.all(lanes);+ return { results, failures };+}diff --git a/site/src/cut/lib/genvideo/prompt.ts b/site/src/cut/lib/genvideo/prompt.tsnew file mode 100644index 00000000..059155cd--- /dev/null+++ b/site/src/cut/lib/genvideo/prompt.ts@@ -0,0 +1,55 @@+/**+ * One prompt builder, so every generation call is consistent.+ *+ * Text describes what happens; references (character and location images, plus+ * whatever the user brought) carry what things look like and are passed as+ * media, never described here. Keeping that split clean is what holds identity+ * and style continuous across shots.+ */++import type { RefAsset, Shot, VideoAsset, VideoProject } from "./types";++/** The text half of a shot's generation prompt. */+export function buildPrompt(shot: Shot, project: VideoProject): string {+ const parts = [shot.action.trim()];+ const location = findAsset(project.locations, shot.location);+ if (location) parts.push(`Setting, ${location.name}.`);+ else if (shot.location) parts.push(`Setting, ${shot.location}.`);+ if (shot.framing) parts.push(`Framing, ${shot.framing}.`);+ if (project.style) parts.push(project.style);+ return parts.filter(Boolean).join(" ").trim();+}++/** The reference media a shot's generation draws from: its characters, its+ * location, and every reference the user brought (identity, style, motion). */+export function shotRefs(shot: Shot, project: VideoProject): RefAsset[] {+ const refs: RefAsset[] = [];+ for (const id of shot.characters) {+ const asset = findAsset(project.characters, id);+ if (asset?.mediaId) refs.push({ mediaId: asset.mediaId, kind: "image", purpose: "character", name: asset.name });+ }+ const location = findAsset(project.locations, shot.location);+ if (location?.mediaId) refs.push({ mediaId: location.mediaId, kind: "image", purpose: "location", name: location.name });+ refs.push(...project.references);+ return refs;+}++/** The prompt that mints one reference image for a character or location. */+export function buildRefPrompt(asset: VideoAsset, style: string): string {+ const subject =+ asset.kind === "character"+ ? `Character reference: ${asset.name}. ${asset.description}`+ : `Location reference: ${asset.name}. ${asset.description}`;+ return [subject, style].filter(Boolean).join(" ").trim();+}++/** The user references that anchor a character/location reference image. */+export function refsForAsset(asset: VideoAsset, project: VideoProject): RefAsset[] {+ const want = asset.kind === "character" ? "character" : "location";+ return project.references.filter((r) => r.purpose === want || r.purpose === "style");+}++function findAsset(list: VideoAsset[], id: string): VideoAsset | undefined {+ if (!id) return undefined;+ return list.find((a) => a.id === id);+}diff --git a/site/src/cut/lib/genvideo/registry.ts b/site/src/cut/lib/genvideo/registry.tsnew file mode 100644index 00000000..0c659283--- /dev/null+++ b/site/src/cut/lib/genvideo/registry.ts@@ -0,0 +1,131 @@+/**+ * The model registry — how models are swapped in and out.+ *+ * Each capability role has a slot; adapters register themselves into it under a+ * stable id. A `ModelSuite` is then a selection of one id per role, and+ * `buildSuite` resolves that selection to live adapters. Swapping a model is+ * passing a different id; an eval compares two selections that differ by one+ * role. Role names stay provider-neutral — the provider name lives only on the+ * registered adapter (its `id`, `label`, `provider`), never in a role.+ *+ * Real adapters (for video, image, speech, music, lip-sync, transcribe)+ * register here the same way the fakes below do — the provider name lives on+ * the adapter's id/label/provider; nothing else in the pipeline changes when+ * they land. Model ids are code, not env (config is code).+ */++import { FakeStudio } from "./fakes";+import type {+ BreakdownRole,+ ImageRole,+ LipSyncRole,+ ModelSuite,+ MusicRole,+ RoleName,+ ScriptRole,+ StyleRole,+ TranscribeRole,+ VideoRole,+ VoiceRole,+} from "./capabilities";++export interface ModelOption {+ id: string;+ label: string;+ provider: string;+}++interface Registered<T> extends ModelOption {+ make: () => T;+}++class Slot<T> {+ private readonly options = new Map<string, Registered<T>>();+ private defaultId: string | undefined;++ register(entry: Registered<T>, isDefault = false): this {+ this.options.set(entry.id, entry);+ if (isDefault || this.defaultId === undefined) this.defaultId = entry.id;+ return this;+ }++ list(): ModelOption[] {+ return [...this.options.values()].map(({ id, label, provider }) => ({ id, label, provider }));+ }++ resolve(id?: string): T {+ const chosen = this.options.get(id ?? this.defaultId ?? "");+ if (!chosen) throw new Error(`no model registered${id ? ` with id "${id}"` : ""} for this role`);+ return chosen.make();+ }+}++export class ModelRegistry {+ readonly script = new Slot<ScriptRole>();+ readonly breakdown = new Slot<BreakdownRole>();+ readonly style = new Slot<StyleRole>();+ readonly image = new Slot<ImageRole>();+ readonly video = new Slot<VideoRole>();+ readonly voice = new Slot<VoiceRole>();+ readonly music = new Slot<MusicRole>();+ readonly lipSync = new Slot<LipSyncRole>();+ readonly transcribe = new Slot<TranscribeRole>();++ /** The models registered for one role — what a picker or an eval iterates. */+ options(role: RoleName): ModelOption[] {+ return (this[role] as Slot<unknown>).list();+ }++ /** Resolve a per-role selection into a runnable suite. */+ buildSuite(selection: Partial<Record<RoleName, string>>, label: string): ModelSuite {+ const video = this.video.resolve(selection.video);+ return {+ label,+ script: this.script.resolve(selection.script),+ breakdown: this.breakdown.resolve(selection.breakdown),+ style: this.style.resolve(selection.style),+ image: this.image.resolve(selection.image),+ video,+ voice: this.voice.resolve(selection.voice),+ music: this.music.resolve(selection.music),+ // A lip-sync model is only needed when the video model isn't audio-native.+ ...(video.audioNative ? {} : { lipSync: this.lipSync.resolve(selection.lipSync) }),+ transcribe: this.transcribe.resolve(selection.transcribe),+ };+ }+}++/**+ * A registry wired entirely to fakes, with two video variants so the swap+ * mechanism and the comparison eval are demonstrable end to end. Replace each+ * `make` with a real adapter to bring a model online.+ */+export function fakeRegistry(): ModelRegistry {+ const r = new ModelRegistry();+ const base = new FakeStudio({ label: "fake" }).suite();+ r.script.register({ id: "fake", label: "Fake script", provider: "fake", make: () => base.script });+ r.breakdown.register({ id: "fake", label: "Fake breakdown", provider: "fake", make: () => base.breakdown });+ r.style.register({ id: "fake", label: "Fake style", provider: "fake", make: () => base.style });+ r.image.register({ id: "fake", label: "Fake image", provider: "fake", make: () => base.image });+ r.voice.register({ id: "fake", label: "Fake voice", provider: "fake", make: () => base.voice });+ r.music.register({ id: "fake", label: "Fake music", provider: "fake", make: () => base.music });+ r.transcribe.register({ id: "fake", label: "Fake transcribe", provider: "fake", make: () => base.transcribe });+ r.lipSync.register({+ id: "fake",+ label: "Fake lip-sync",+ provider: "fake",+ make: () => new FakeStudio().suite().lipSync!,+ });+ // Two swappable video models to compare.+ r.video.register(+ { id: "fake-fast", label: "Fake video (fast)", provider: "fake", make: () => new FakeStudio({ videoVariant: "fast" }).suite().video },+ true+ );+ r.video.register({+ id: "fake-pro",+ label: "Fake video (pro, audio-native)",+ provider: "fake",+ make: () => new FakeStudio({ videoVariant: "pro", audioNative: true }).suite().video,+ });+ return r;+}diff --git a/site/src/cut/lib/genvideo/types.ts b/site/src/cut/lib/genvideo/types.tsnew file mode 100644index 00000000..86081a2e--- /dev/null+++ b/site/src/cut/lib/genvideo/types.ts@@ -0,0 +1,174 @@+/**+ * Brief-to-video: the persisted plan.+ *+ * One `VideoProject` is the single source of truth for a run — it survives+ * restarts (it rides `ProjectDoc.genvideo`) and drives resume and selective+ * regeneration. Everything here is data; the orchestrator (`orchestrator.ts`)+ * is the only thing that mutates it, and it re-asserts the coverage invariant+ * (`coverage.ts`) after every mutation.+ *+ * A run has one audio spine — either audio the user dropped in, or audio the+ * pipeline generates from a brief (a spoken script plus a music bed). Shots+ * tile that spine, and each shot's video is lip-synced to its slice, so the+ * two entry points ("animate this audio" and "make me a video of X") share the+ * same machinery.+ *+ * Units: the plan reasons in whole frames, never seconds. Frame boundaries are+ * integers, so "shot i ends exactly where shot i+1 begins" holds by+ * construction. Seconds appear only at the editor boundary (see coverage.ts).+ */++/** A reference the user brought, passed to generation as media not text. */+export interface RefAsset {+ mediaId: string;+ kind: "image" | "video" | "audio";+ /** What this reference anchors — identity, place, look, or motion. */+ purpose?: "character" | "location" | "style" | "motion";+ name?: string;+}++/** One beat of a generated script — a shot's worth of screen time. */+export interface ScriptBeat {+ dialogue: string; // spoken line (drives the voiceover and the lip-sync)+ action: string; // what happens on screen+ characters: string[];+ location: string;+ framing: string;+ approxSeconds: number;+}++export interface ScriptPlan {+ logline: string;+ beats: ScriptBeat[];+ style?: string;+}++/** A reference image the whole run carries — a character or a location. */+export interface VideoAsset {+ /** Stable id referenced by shots (e.g. "char:nova", "loc:kitchen"). */+ id: string;+ kind: "character" | "location";+ name: string;+ description: string;+ /** The generated (or user-provided) reference image, once resolved. */+ mediaId?: string;+}++export type ShotStatus =+ | "pending"+ | "keyframing"+ | "generating"+ | "lipsync"+ | "placed"+ | "failed";++/** One contiguous slice of the audio spine, and the shot that covers it. */+export interface Shot {+ id: string;+ /** Inclusive start frame; `endFrame` is exclusive. */+ startFrame: number;+ endFrame: number;+ /** What is heard across this slice (from the transcript or the script). */+ audioText: string;+ /** The spoken line, when the run wrote its own script. */+ dialogue?: string;+ /** What happens on screen — the motion, the beat. Text, never refs. */+ action: string;+ characters: string[]; // character asset ids+ location: string; // location asset id ("" = unspecified)+ framing: string;+ startKeyframe?: string; // media asset id+ endKeyframe?: string; // media asset id+ /** The beat voiceover this shot lip-syncs to (generated mode). The voice is+ * placed once per beat; a shot spans a slice of it (voiceFromSec..voiceToSec,+ * relative to the beat start), so a line longer than one clip is never cut. */+ voiceAssetId?: string;+ voiceFromSec?: number;+ voiceToSec?: number;+ clip?: string; // generated video, media asset id+ timelineClipId?: string; // the clip placed on the timeline+ lipSynced?: boolean;+ status: ShotStatus;+ attempts: number;+ lastPrompt?: string;+ error?: string;+}++/** One beat's voiceover placed on the soundtrack — the unit the spine is+ * placed in, so a video regeneration never restacks narration. */+export interface BeatVoice {+ voiceAssetId: string;+ startFrame: number;+ durationFrames: number;+ /** The placed soundtrack clip id, once on the timeline (idempotent placement). */+ voiceClipId?: string;+}++export type AudioMode = "provided" | "generated";++/** The whole run. Persisted to disk as `ProjectDoc.genvideo`. */+export interface VideoProject {+ id: string;+ /** The free-text request when the run started from a brief. */+ brief: string;+ /** User-supplied references (images, video, audio) — may be empty. */+ references: RefAsset[];+ /** Where the audio spine comes from. */+ audioMode: AudioMode;+ /** Provided mode: the dropped audio clip + its asset. */+ audioClipId?: string;+ audioAssetId?: string;+ /** Generated mode: the written script, the voiced spine, and the music bed. */+ script?: ScriptPlan;+ beatVoices?: BeatVoice[];+ musicAssetId?: string;+ /** The placed music-bed clip id, once on the timeline (idempotent placement). */+ musicClipId?: string;+ /** Target length when generating from a brief (seconds). */+ targetSeconds?: number;+ fps: number;+ durationFrames: number;+ /** Word-level transcript of the spine (provided mode, or generated VO). */+ transcript: TranscriptWord[];+ /** Reusable style string every downstream prompt carries. */+ style: string;+ /** The suite label the run was produced with (for provenance and evals). */+ suiteLabel: string;+ characters: VideoAsset[];+ locations: VideoAsset[];+ shots: Shot[];+ phase: VideoPhase;+ breakdownApproved: boolean;+ createdAt: number;+ updatedAt: number;+}++export type VideoPhase =+ | "brief"+ | "ingest"+ | "breakdown"+ | "style"+ | "keyframes"+ | "generating"+ | "review"+ | "polish"+ | "done"+ | "failed";++/** A transcribed word with timeline timing (seconds, as the engine returns). */+export interface TranscriptWord {+ t0: number;+ t1: number;+ w: string;+}++/** A progress event the chat panel and timeline both listen to. */+export type VideoEvent =+ | { type: "phase"; phase: VideoPhase; note?: string }+ | { type: "shot:update"; shot: Shot }+ | { type: "breakdown"; shots: Shot[] }+ | { type: "progress"; placed: number; total: number }+ | { type: "log"; message: string }+ | { type: "error"; message: string };++export type VideoEmit = (event: VideoEvent) => void;