Open source CapCut alternative.
TypeScript
feat(cut): let generate_music match attached media references [rebuild] (#11)
David Le1bf734e77079
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.mdindex 57735c77..036d4fa8 100644--- a/docs/guides/cut/ai-assistant.md+++ b/docs/guides/cut/ai-assistant.md@@ -74,7 +74,7 @@ Tool calls execute in the open tab against the same store the user is editing## Generating a whole video-Most generation tools make one asset — an image, a video clip, a voiceover, or an instrumental music bed (`generate_music`, scene-aware enough to score a whole video). `generate_scene` makes a whole cut: it writes a script, breaks it into shots, and — once the user approves — renders each shot and lays them on the timeline. The video model speaks each shot's line, so the clips carry their own narration; a music bed sits under them. It is genre-agnostic; the look comes from the brief and any references. It can also animate audio the project already has (`from_audio_asset_id`), tiling shots over that spine instead of writing a script.+Most generation tools make one asset — an image, a video clip, a voiceover, or an instrumental music bed (`generate_music`, scene-aware enough to score a whole video, and able to match a track to a reference the user attaches — an audio clip to emulate or a video whose tone it should carry, since the music model reads only text a multimodal pass turns the reference into the sound description it renders from). `generate_scene` makes a whole cut: it writes a script, breaks it into shots, and — once the user approves — renders each shot and lays them on the timeline. The video model speaks each shot's line, so the clips carry their own narration; a music bed sits under them. It is genre-agnostic; the look comes from the brief and any references. It can also animate audio the project already has (`from_audio_asset_id`), tiling shots over that spine instead of writing a script.Because a scene renders many paid shots, the tool plans and then stops. `generate_scene` returns a shot list and waits; `approve_scene` starts the renders; `regenerate_shot` and `restyle_scene` revise afterward; `cancel_scene` kills the active run. The plan the user approves is the plan that renders: voicing runs after the gate and only rescales the approved shots to the real voice lengths (a line longer than one clip splits its shot). The run is browser-side like every generation here, held in a small store beside the panels (`lib/genScene.ts`) so switching tabs never orphans it; leaving the project pauses it, its persisted plan (`ProjectDoc.genvideo`) resumes on the next open, and a run that dies persists as failed so a reload never resumes it. Nothing runs behind the user's back: cancelling, dismissing an unrendered plan, or deleting the chat thread that asked all stop the run and clear its plan — clips already placed stay on the timeline. Progress shows on a card in the chat while the timeline fills on its own. The shots ride under one consistent AI voice with the video model's own audio off; this version has no talking-head lip-sync.diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex e901e17b..7781f425 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -27,6 +27,7 @@ import { baseClips, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX,import { buildAiContext } from "./aiContext";import { laneCues, subtitleLaneCount } from "./subtitles";import { synthesizeMusic } from "./audioGen";+import { composeMusicPrompt } from "./composeGen";import { stockAssetInDoc } from "./genvideo/docWriter";import { resolveVoice, synthesizeSpeech, SPEECH_VOICES } from "./tts";import { DUCK_DEFAULT, generateSubtitlesReadout } from "./voiceover";@@ -1278,10 +1279,25 @@ export async function runAiTool(const variant = input.length === "song" ? "song" : "clip";// Default to a vocal-free bed; the model opts into a sung song explicitly.const instrumental = input.instrumental !== false;+ // References ("match this audio", "the tone of this video"): the music+ // model reads only text, so a multimodal pass listens to/looks at each+ // reference and folds a description of its sound into the prompt. A failed+ // compose falls back to the raw prompt so the render still happens. Keep+ // the user's own words as the track name — the composed prompt is verbose.+ const refs = resolveMusicRefs(input.reference_asset_ids);+ let sent = prompt;+ if (refs.length > 0) {+ const composed = await composeMusicPrompt(prompt, refs);+ if (composed) sent = composed;+ }// Captured before synthesis: the track files under the chat that asked,// even if the user switches threads while it renders.const chatId = chatOwner();- const asset = await synthesizeMusic(projectId, prompt, { variant, instrumental });+ const asset = await synthesizeMusic(projectId, sent, {+ variant,+ instrumental,+ ...(sent !== prompt ? { name: prompt } : {}),+ });const cur = useEditor.getState();// The render can outlast the open project: if the user switched away while// it ran, save it into the project it was made for — never the one now on@@ -1686,6 +1702,20 @@ function resolveRefAssets(ids: unknown): AssetRef[] {});}+/** Map music-reference ids to project asset refs. Music takes any media as a+ * style reference — an audio track to match, or video/images for tone — so+ * unlike the visual generators, audio resolves here too. */+function resolveMusicRefs(ids: unknown): AssetRef[] {+ if (ids === undefined || ids === null) return [];+ const s = useEditor.getState();+ return (Array.isArray(ids) ? ids : [ids]).map((raw) => {+ const asset = s.assets.find((a) => a.id === String(raw));+ if (!asset)+ throw new ToolError(`No project asset with id ${String(raw)} — see media in the editor state.`);+ return refFromAsset(asset);+ });+}+/** An overlay clip's frame patch for a layout preset name. */const OVERLAY_LAYOUT_KEYS = {full: "full",diff --git a/site/src/cut/lib/audioGen.ts b/site/src/cut/lib/audioGen.tsindex 606236fb..bf86cc96 100644--- a/site/src/cut/lib/audioGen.ts+++ b/site/src/cut/lib/audioGen.ts@@ -88,7 +88,9 @@ export async function synthesizeMusic(};const out = gen.outputs?.find((o) => o.dataBase64) ?? gen.outputs?.find((o) => o.url);- const label = opts?.name?.trim() || musicName(prompt);+ // Cap whatever the label comes from — a caller-supplied name (the user's own+ // words when the prompt was composed from references) or the prompt itself.+ const label = musicName(opts?.name?.trim() || prompt);const fileName = `ai-${slug(label)}.mp3`;let file: File;if (out?.dataBase64) {diff --git a/site/src/cut/lib/composeGen.ts b/site/src/cut/lib/composeGen.tsindex a087a88e..ca24e913 100644--- a/site/src/cut/lib/composeGen.ts+++ b/site/src/cut/lib/composeGen.ts@@ -27,6 +27,11 @@ Reply with JSON {"prompt": string, "keepImages": number[]}:- keepImages lists the image numbers the model should receive: keep the ones the request edits, combines, or borrows a subject or style from; drop ones whose contribution is better said in words.- prompt must stand alone given only the kept images: refer to them by their content, and fold in whatever matters from the dropped references and any script or text from attached files, with the requested changes applied.`;+const MUSIC_INSTRUCTIONS = `You prepare prompts for a text-to-music model that generates a track from a text description alone — it never hears or sees the references. The attachments are what the user wants the music to match: an audio track to emulate, or video/images whose mood the score should carry. Their request comes last.+Reply with JSON {"prompt": string}:+- prompt must fully describe the SOUND to generate so a new track can match the reference: genre, instrumentation, vocal style and gender (or that it is instrumental), mood, energy, tempo, and production feel. For an audio reference, describe what you actually hear — groove, arrangement, key feel — closely enough to recreate it; for visual references, translate their tone and pacing into music. Keep any language the lyrics should be in.+- Describe everything by its musical traits. Never name a real artist, band, song, album, or brand — the model rejects those; state the characteristics instead.`;+export interface ComposedGen {prompt: string;/** The reference pictures the generator should receive, in kept order. */@@ -69,6 +74,35 @@ export async function composeGenPrompt(}}+/** Compose a music-generation prompt from the user's request and their media+ * references. The music model reads only text, so a multimodal pass listens to+ * each audio reference and looks at each visual one, then folds a description+ * of the target sound into a stand-alone prompt. Null on any failure (or when+ * no ref contributes anything) — the caller falls back to the raw prompt. */+export async function composeMusicPrompt(+ prompt: string,+ refs: AssetRef[]+): Promise<string | null> {+ try {+ const { parts } = await refsToParts(refs);+ if (parts.length === 0) return null;+ const res = await hostedPost("/api/inference/responses", {+ donkeyProvider: "gemini",+ model: geminiModelRoles.chat,+ instructions: MUSIC_INSTRUCTIONS,+ response_format: { type: "json_object" },+ input: [{ role: "user", content: [...parts, { text: `Request: ${prompt}` }] }],+ });+ if (!res.ok) return null;+ const body = (await res.json()) as { output_text?: string };+ const parsed = JSON.parse(body.output_text ?? "") as { prompt?: unknown };+ if (typeof parsed.prompt !== "string" || !parsed.prompt.trim()) return null;+ return parsed.prompt.trim();+ } catch {+ return null;+ }+}+/** Fallback text folding for when the compose call fails: append each text* ref's contents to the prompt so a dropped script still reaches the* generator. Unreadable files are skipped. */diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 9ae6a8f1..31611bc0 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -527,11 +527,16 @@ export const AI_TOOLS: AiToolDef[] = [{name: "generate_music",description:- "Generate a music track from a text prompt (Donkey's hosted music model, Gemini/Lyria) — a full song with sung vocals, or an instrumental bed. Describe mood, genre, instruments, and tempo. By default it renders an instrumental bed (instrumental:true); pass instrumental:false for a full song, where the model writes and sings its own lyrics — or include your own with [Verse]/[Chorus] tags and a singer description in the prompt. length \"clip\" is ~30s (default), \"song\" a longer ~2-minute track. When the user asks you to write or refine the lyrics or brief itself, put it in chat and wait for them to ask for the music. It RETURNS once the track has landed and previews as a playable card in this chat; pass add_to_timeline:true (or a `start`) to drop it on the soundtrack when the user asked for it in the cut. For \"background music for this video\", read the timeline (videoTrack, project duration) to fit the mood and length, keep it instrumental so any speech stays on top, and set those clips' `duck` so the bed dips under them. This is SUNG music — a spoken narration is voiceover_generate. Needs the user signed in to Donkey (spends their credits).",+ "Generate a music track from a text prompt (Donkey's hosted music model, Gemini/Lyria) — a full song with sung vocals, or an instrumental bed. Describe mood, genre, instruments, and tempo. By default it renders an instrumental bed (instrumental:true); pass instrumental:false for a full song, where the model writes and sings its own lyrics — or include your own with [Verse]/[Chorus] tags and a singer description in the prompt. length \"clip\" is ~30s (default), \"song\" a longer ~2-minute track. reference_asset_ids matches a track to the user's own media (\"a song that matches this audio\", \"score the tone of this video\"): pass the project asset ids — an audio track to emulate, or video/images whose mood to carry — and a multimodal pass folds a description of that sound into the prompt (the model itself never hears the audio, so always pass the reference rather than describing it yourself). When you match an audio reference that has singing, pass instrumental:false so the new track sings too. When the user asks you to write or refine the lyrics or brief itself, put it in chat and wait for them to ask for the music. It RETURNS once the track has landed and previews as a playable card in this chat; pass add_to_timeline:true (or a `start`) to drop it on the soundtrack when the user asked for it in the cut. For \"background music for this video\", read the timeline (videoTrack, project duration) to fit the mood and length, keep it instrumental so any speech stays on top, and set those clips' `duck` so the bed dips under them. This is SUNG music — a spoken narration is voiceover_generate. Needs the user signed in to Donkey (spends their credits).",inputSchema: obj({prompt: str("The music to generate — mood, genre, instruments, tempo; for a song, the theme to sing about, or your own [Verse]/[Chorus] lyrics"),instrumental: bool("Vocal-free background bed (default true). Pass false to let the model write and sing a full song"),length: { type: "string", enum: ["clip", "song"], description: "clip = ~30s (default), song = ~2-minute track" },+ reference_asset_ids: {+ type: "array",+ items: { type: "string" },+ description: "Project asset ids to match the sound of — an audio track to emulate, or video/images whose mood the score should carry",+ },volume: num("Bed volume 0..1.5 when placed (default 0.4 so it sits under speech)"),add_to_timeline: bool("Place it on the soundtrack (default false — it stays on its chat card until the user asks)"),start: num("Timeline start in seconds (passing it implies add_to_timeline; default when placed: the playhead)"),@@ -754,7 +759,7 @@ Generation:- generate_video(prompt, aspect?, reference_asset_id?, add_to_timeline?, index?): the hosted video model renders a short clip with audio in one pass — 720p, up to ~10s, the model picks the length (no duration knob; the user trims the clip on the timeline). With reference_asset_id it stages: the image model designs the opening frame from the reference first (that still previews in the chat), then the video model animates that exact frame. The render takes a minute or two, so the tool returns once it's started and the clip previews in the chat when it finishes (on the timeline only when asked) — tell the user it's rendering. Don't call it again for the same shot while one is in flight.- Every render's live status is \`renders\` in editor_state (running with elapsed seconds, done with its asset id, failed with the error) — report render progress from there, never from memory. When the user's ask depends on a running render ("assemble the clips", "add it when it's done"), call wait_for_renders and finish the job in the same turn — never hand the waiting to the user.- generate_character_video(character_id, line, …): a stock talking character delivers a line to camera, same async render as generate_video. Characters come from stock_search kind:"character" — each has a persona; you write the line (chat deliverable rules apply: asked for "a script", write it in chat first).-References: users attach images/clips to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. Images draw from any number of references; video stages one reference into a designed opening frame and animates it. When the user says "use this clip/image", pass the reference — don't just describe it in the prompt.+References: users attach media to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. Images draw from any number of references; video stages one reference into a designed opening frame and animates it; generate_music matches the sound of an audio reference or the mood of a video/image one. When the user says "use this clip/image/song" or "match this", pass the reference — don't just describe it in the prompt.If generation fails with a sign-in or credits message, relay that plainly — generation needs a Donkey sign-in with credits. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out. A narrated multi-shot production is generate_scene — read the scene-productions skill before planning one, especially from an audio file or in a named style.`,"scene-productions": `# Scene productions (generate_scene)