Open source CapCut alternative.
TypeScript
feat(site): let the Cut assistant listen to video assets' audio [rebuild]
David Lefca8e07181d6
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 7781f425..cbd92b2a 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -19,7 +19,7 @@ import {saveAssetToLibrary,} from "./library";import { enrichAsset, ensurePeaks, importImage, importStockVideo, importUrlMedia } from "./media";-import { refToInlineAudio } from "./refMedia";+import { blobToInlineAudio, refToInlineAudio, type InlineImage } from "./refMedia";import { characterPrompt, stockTitle } from "./stock";import { STOCK_IMAGES } from "./stockManifest";import { STOCK_VIDEOS } from "./stockVideoManifest";@@ -89,7 +89,7 @@ export async function runAiTool(case "watch_video": {const { projectId, asset, clip, speed, from, to } = resolveWatchRange(s, input);if (asset.type === "audio")- throw new ToolError(`"${asset.name}" is audio — detect_silence and subtitles_generate are the listening tools.`);+ throw new ToolError(`"${asset.name}" is audio — listen_audio hears it, detect_silence finds its dead air.`);interface WatchBody {sheets: { image: string; frames: { t: number; scene?: number }[] }[];layout: { grid: number; margin: number; padding: number };@@ -217,17 +217,28 @@ export async function runAiTool(}case "listen_audio": {- const asset = requireItem(s.assets, input.asset_id, "project asset");- if (asset.type !== "audio")- throw new ToolError("listen_audio is for audio assets — watch_video covers video and images.");- const inline = await refToInlineAudio(refFromAsset(asset));+ const { projectId, asset, clip, from, to } = resolveWatchRange(s, input);+ if (asset.type === "image")+ throw new ToolError(`"${asset.name}" is an image — it has no sound. watch_video shows it.`);+ // A whole audio asset rides its own file bytes. A video, or any trimmed+ // range, gets its audio track pulled off by the engine first — so the+ // muxed video never travels and a long source still fits the inline cap.+ const wholeAudio = asset.type === "audio" && !clip && !isNum(input.from) && !isNum(input.to);+ const inline = wholeAudio+ ? await refToInlineAudio(refFromAsset(asset))+ : await listenToSource(projectId, asset.fileName, from, to);if (!inline)- throw new ToolError("That audio file is too large to listen to inline (≈12MB cap).");+ throw new ToolError(+ "That stretch is too long to listen to inline (≈12MB cap) — pass a narrower from/to."+ );// The `audio` data URL leaves the JSON in geminiChat and rides to the// model as an input_audio part, the way attachments do.return {name: asset.name,duration: round2(asset.duration),+ ...(clip ? { clipId: clip.id } : {}),+ ...(from > 0 ? { from: round2(from) } : {}),+ ...(to !== undefined ? { to: round2(to) } : {}),audio: `data:${inline.mimeType};base64,${inline.data}`,};}@@ -1667,6 +1678,26 @@ function resolveWatchRange(return { projectId, asset, clip, speed, from, to };}+/** Pull a source's audio track off the engine (video and audio alike) and+ * inline it for the model; null when the range clears the inline cap. */+async function listenToSource(+ projectId: string,+ fileName: string,+ from: number,+ to: number | undefined,+): Promise<InlineImage | null> {+ const res = await apiFetch(`/api/cut/projects/${projectId}/audio`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ file: fileName, from, ...(to !== undefined ? { to } : {}) }),+ });+ if (!res.ok) {+ const body = await apiJson<{ error?: string }>(res).catch(() => ({ error: undefined }));+ throw new ToolError(body.error ?? "Could not read the audio.");+ }+ return blobToInlineAudio(await res.blob());+}+function requireItem<T extends { id: string }>(pool: T[], id: unknown, label: string): T {const item = pool.find((x) => x.id === String(id ?? ""));if (!item) throw new ToolError(`No ${label} with id ${String(id)}. Call get_state for current ids.`);diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.tsindex 37f8af20..f28a29ab 100644--- a/site/src/cut/lib/refMedia.ts+++ b/site/src/cut/lib/refMedia.ts@@ -71,6 +71,20 @@ export async function blobToInline(blob: Blob): Promise<InlineImage> {return splitDataUrl(await blobToDataUrl(blob));}+/** A media blob's bytes as an inline audio part, mime from the blob's own type+ * (the engine's extractor hands back audio/aac). Null when it clears the inline+ * cap — a longer stretch than the model can take at once. */+export async function blobToInlineAudio(blob: Blob): Promise<InlineImage | null> {+ if (blob.size > MAX_AUDIO_BYTES) return null;+ const dataUrl = await blobToDataUrl(blob);+ const comma = dataUrl.indexOf(",");+ const labelled = dataUrl.slice(5, comma).split(";")[0];+ return {+ data: dataUrl.slice(comma + 1),+ mimeType: labelled.startsWith("audio/") ? labelled : "audio/aac",+ };+}+/** Video models take input images only as JPEG or PNG — the render rejects anything* else by format, killing the render after it was billed. Re-encode any other* picture (webp saved off the web is the common case) to PNG; jpeg and pngdiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 31611bc0..3994c47c 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -70,8 +70,13 @@ export const AI_TOOLS: AiToolDef[] = [{name: "listen_audio",description:- "Listen to a project audio asset with your own ears: its actual sound rides back inline (≈12MB cap) so you can answer what it says or how it sounds. Audio attached to the user's message already plays in it — this is for assets from `media`. For a clip's speech as text, subtitles_generate transcribes the cut.",- inputSchema: obj({ asset_id: str("Project audio asset id from `media`") }, ["asset_id"]),+ "Listen with your own ears to a project asset's sound — an audio asset, or the audio track of a video (its speech, music, burned-in narration) — so you can answer what it says or how it sounds. The sound rides back inline (≈12MB cap). Pass clip_id for a timeline clip's source (scopes to its trim) or asset_id for the whole source; add from/to (source seconds) to hear one stretch of a long file. Audio the user attached to their message already plays in it. To WRITE a caption track, use subtitles_generate.",+ inputSchema: obj({+ clip_id: str("Clip id — video or soundtrack (defaults from/to to its trimmed in/out)"),+ asset_id: str("Project asset id (audio or video) — listen to the whole source"),+ from: num("Source start s (default: the clip's in, else 0)"),+ to: num("Source end s (default: the clip's out, else the source's end)"),+ }),},{name: "seek",@@ -772,7 +777,7 @@ After renders land: spot-check with capture_frame or watch_video (aspect, style,"media-and-library": `# Media, Library & organizingProject media (\`media\` in editor_state) is every file in the open project. The Media panel shows the user's own imports — assets with no origin tag; created media (origin generated, voiceover, stock, chat, freeze, recording) lives where it was made until filed away.-- add_clip / add_overlay_video place a project asset on the timeline; listen_audio plays an audio asset to you; watch_video is the visual sibling.+- add_clip / add_overlay_video place a project asset on the timeline; listen_audio plays an asset's sound to you — an audio asset, or a video/clip's own track; watch_video is the visual sibling.- file_asset moves a created asset into Media (to:"media", clears its origin) or copies any asset into the Library (to:"library").- delete_asset removes an asset from the project plus its timeline clips; the media does not come back with undo, so only on an explicit ask, and say what went with it.The Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.@@ -801,7 +806,7 @@ Rules:- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud / generate_music make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the shot list — confirm with the user, then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after).-- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen; listen_audio plays a project audio asset; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;+- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen; listen_audio plays a source's audio — an audio asset or a video/clip's own track; detect_silence finds dead air; capture_frame shows the one rendered frame at the playhead. The watching-and-cutting skill has the flow.`;}export const AI_SKILL_INDEX = Object.keys(AI_SKILLS);diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.tsindex 07b3fc77..e884acaa 100644--- a/site/src/cut/server/frames.ts+++ b/site/src/cut/server/frames.ts@@ -385,3 +385,49 @@ export async function detectSilence(silences.push({ start: round(open), end: round(to), duration: round(to - open) });return silences;}++/** Pull a media file's audio track off as a small mono AAC stream so the+ * assistant can hear it inline. Works for audio and video sources alike — the+ * video image never travels, and 32 kbps keeps ~50 min under the model's+ * inline cap. Times are absolute source seconds; an empty `to` runs to the end. */+export function extractAudio(+ projectId: string,+ sourceFile: string,+ opts: { from: number; to?: number },+): Promise<Buffer> {+ const { from, to } = opts;+ return new Promise((resolve, reject) => {+ const p = spawn("ffmpeg", [+ "-hide_banner", "-nostats", "-loglevel", "error",+ ...(from > 0 ? ["-ss", num(from)] : []),+ ...(to !== undefined ? ["-t", num(to - from)] : []),+ "-i", mediaPath(projectId, sourceFile),+ "-vn", "-sn", "-dn",+ "-ac", "1", "-ar", "24000", "-c:a", "aac", "-b:a", "32k",+ "-f", "adts", "-",+ ]);+ const chunks: Buffer[] = [];+ let err = "";+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ reject(new Error("Reading the audio timed out — try a shorter from/to range."));+ }, 120_000);+ timer.unref();+ p.stdout.on("data", (d: Buffer) => chunks.push(d));+ p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-4000)));+ p.on("error", (e) =>+ reject(+ e.message.includes("ENOENT")+ ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")+ : e,+ ),+ );+ p.on("close", (code) => {+ clearTimeout(timer);+ if (code === 0 && chunks.length > 0) return resolve(Buffer.concat(chunks));+ if (/does not contain any stream|matches no streams|Cannot find a matching stream/i.test(err))+ return reject(new Error("This file has no audio track."));+ reject(new Error(errTail(err) || "Could not read the audio."));+ });+ });+}diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.tsindex d70bdc15..7f0863d8 100644--- a/site/src/cut/server/http/projects.ts+++ b/site/src/cut/server/http/projects.ts@@ -1,6 +1,6 @@import { execFile } from "node:child_process";import type { ProjectDoc } from "@/cut/lib/types";-import { detectSilence, makeContactSheets, makeFreezeFrame, probeDims, probeDuration } from "../frames";+import { detectSilence, extractAudio, makeContactSheets, makeFreezeFrame, probeDims, probeDuration } from "../frames";import {createProject,createProjectFolder,@@ -438,4 +438,23 @@ export const projectsApi = {return caught(e, "Could not scan for silence.");}},++ /** Extract a media file's audio track so the assistant can hear it (video and+ * audio alike). Returns raw AAC bytes; the caller inlines them for the model. */+ async audio(req: Request, { id }: { id: string }) {+ try {+ if (!(await readProject(id))) return err("Project not found.", 404);+ const body = (await req.json()) as { file?: string; from?: number; to?: number };+ if (!body.file) return err("file is required.", 400);+ const from = Math.max(0, typeof body.from === "number" ? body.from : 0);+ const to = typeof body.to === "number" ? body.to : undefined;+ if (to !== undefined && !(to > from)) return err("from/to describe an empty range.", 400);+ const audio = await extractAudio(id, body.file, { from, to });+ return new Response(new Uint8Array(audio), {+ headers: { "Content-Type": "audio/aac", "Content-Length": String(audio.length) },+ });+ } catch (e) {+ return caught(e, "Could not read the audio.");+ }+ },};diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex de7a590f..92bc0fe3 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -49,6 +49,7 @@ export const CUT_ROUTES: CutRoute[] = [{ method: "POST", path: "/api/cut/projects/:id/freeze", handler: (req, p) => projectsApi.freeze(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/watch", handler: (req, p) => projectsApi.watch(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/silence", handler: (req, p) => projectsApi.silence(req, { id: p.id }) },+ { method: "POST", path: "/api/cut/projects/:id/audio", handler: (req, p) => projectsApi.audio(req, { id: p.id }) },{ method: "POST", path: "/api/cut/projects/:id/duplicate", handler: (req, p) => projectsApi.duplicate(req, { id: p.id }) },{ method: "GET", path: "/api/cut/projects/:id/preview", handler: (req, p) => projectsApi.servePreview(req, { id: p.id }) },{ method: "GET", path: "/api/cut/projects/:id/export-jobs", handler: (req, p) => exportApi.activeForProject(req, { id: p.id }) },