Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): give ai chat the color grade tool [rebuild]

David Lee0111009d946
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 3a55c595..6457a2f1 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -55,7 +55,7 @@ import {
type VideoClip,
} from "@/cut/lib/types";
import { autoGradeFromImageData, isNeutralGrade, normalizeGrade } from "@/cut/lib/colorGrade";
-import { getPreviewCanvas, sampleClipSource } from "@/cut/lib/previewCanvas";
+import { getPreviewCanvas, sampleClipFrameData } from "@/cut/lib/previewCanvas";
import { cn } from "@/lib/utils";
const SWATCHES = ["#FFFFFF", "#111114", "#FFD60A", "#FF375F", "#0A84FF", "#30D158"];
@@ -657,21 +657,8 @@ function ColorPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {
// preview, which would fold the current grade back into the fit); the
// sliders show the result and stay fully adjustable after.
const autoGrade = () => {
- const src = sampleClipSource(clip.id);
- const scratch = document.createElement("canvas");
- scratch.width = 96;
- scratch.height = 54;
- const ctx = scratch.getContext("2d", { willReadFrequently: true });
- if (!src || !ctx) return;
- try {
- ctx.drawImage(src, 0, 0, scratch.width, scratch.height);
- const grade = autoGradeFromImageData(
- ctx.getImageData(0, 0, scratch.width, scratch.height).data
- );
- updateClip(clip.id, { grade });
- } catch {
- // Unreadable frame — leave the grade as it is.
- }
+ const data = sampleClipFrameData(clip.id);
+ if (data) updateClip(clip.id, { grade: autoGradeFromImageData(data) });
};
return (
<>
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index f0d790f7..9f315205 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -181,6 +181,7 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
...(sp.clip.fit === "fill"
? { panX: r(sp.clip.panX ?? 0), panY: r(sp.clip.panY ?? 0) }
: {}),
+ ...(sp.clip.grade ? { colorGrade: sp.clip.grade } : {}),
})),
// Video layers composited over track 0 in track order (the topmost
// full-frame clip covers the rest). Each track carries its own
@@ -272,6 +273,7 @@ function describeOverlayClip(c: VideoClip, assets: Map<string, { name: string }>
region: { x: r(rect.x), y: r(rect.y), w: r(rect.w), h: r(rect.h) },
fit: c.fit ?? "fit",
...(speed !== 1 ? { speed: r(speed) } : {}),
+ ...(c.grade ? { colorGrade: c.grade } : {}),
};
}
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 20e6c882..6ac91e32 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -26,6 +26,8 @@ import { STOCK_IMAGES } from "./stockManifest";
import { STOCK_VIDEOS } from "./stockVideoManifest";
import { applyOverlayPatchSettled, track0Clips, trackGapAt, getClipSpans, nextFreeStart, overlayLayers, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";
import { buildAiContext } from "./aiContext";
+import { autoGradeFromImageData, normalizeGrade } from "./colorGrade";
+import { sampleClipFrameData } from "./previewCanvas";
import { laneCues, subtitleLaneCount } from "./subtitles";
import { synthesizeMusic } from "./audioGen";
import { composeMusicPrompt } from "./composeGen";
@@ -43,6 +45,7 @@ import {
SPEED_FLOOR,
TRANSITION_STYLE_IDS,
type AudioClip,
+ type ColorGrade,
type FontId,
type MediaAsset,
type Selection,
@@ -52,6 +55,8 @@ import {
const round2 = (n: number) => Math.round(n * 100) / 100;
+const GRADE_KEYS = ["brightness", "contrast", "saturation", "exposure", "temperature", "hue"] as const;
+
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));
const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
@@ -1501,6 +1506,23 @@ export async function runAiTool(
return { id: next.id, speed: next.speed ?? 1 };
}
+ case "set_color_grade": {
+ const clip = requireItem(s.clips, input.clipId, "video clip");
+ let grade: ColorGrade = input.reset === true ? {} : { ...clip.grade };
+ if (input.auto === true) {
+ const data = sampleClipFrameData(clip.id);
+ if (!data)
+ throw new ToolError(
+ "No decoded frame for that clip yet — seek into it so it is on screen, then retry."
+ );
+ grade = { ...autoGradeFromImageData(data) };
+ }
+ for (const k of GRADE_KEYS) if (isNum(input[k])) grade[k] = input[k];
+ s.updateClip(clip.id, { grade: normalizeGrade(grade) });
+ const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
+ return { id: next.id, grade: next.grade ?? "neutral" };
+ }
+
case "set_transition": {
const clip = requireItem(s.clips, input.clipId, "video clip");
// A transition joins a clip to the next one on its own track.
diff --git a/site/src/cut/lib/previewCanvas.ts b/site/src/cut/lib/previewCanvas.ts
index dabb45d9..1e53b69d 100644
--- a/site/src/cut/lib/previewCanvas.ts
+++ b/site/src/cut/lib/previewCanvas.ts
@@ -32,3 +32,21 @@ export function registerSourceSampler(fn: SourceSampler | null) {
export function sampleClipSource(clipId: string): CanvasImageSource | null {
return sampler?.(clipId) ?? null;
}
+
+/** A small RGBA readout of the clip's raw frame, for analysis (auto grade);
+ * null when no decoder is ready or the pixels are unreadable. */
+export function sampleClipFrameData(clipId: string, w = 96, h = 54): Uint8ClampedArray | null {
+ const src = sampleClipSource(clipId);
+ if (!src) return null;
+ const scratch = document.createElement("canvas");
+ scratch.width = w;
+ scratch.height = h;
+ const ctx = scratch.getContext("2d", { willReadFrequently: true });
+ if (!ctx) return null;
+ try {
+ ctx.drawImage(src, 0, 0, w, h);
+ return ctx.getImageData(0, 0, w, h).data;
+ } catch {
+ return null;
+ }
+}
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index fcb7240e..d6252d65 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -638,6 +638,22 @@ export const AI_TOOLS: AiToolDef[] = [
"Set a video clip's playback speed. Faster shortens the clip on the timeline; slower stretches it. Later titles and captions shift to stay in sync.",
inputSchema: obj({ clipId: str("Video clip id"), speed: num("Playback rate (1 = normal, no upper limit)") }, ["clipId", "speed"]),
},
+ {
+ name: "set_color_grade",
+ description:
+ "Color-grade a video clip (any track; stills too). Fields patch the clip's current grade: only the ones you pass change, and every value 0 is neutral. reset:true clears the whole grade first; auto:true fits a starting grade from the clip's decoded frame (auto-tone: exposure to middle gray, contrast stretch, gray-world white balance — needs the clip's frame decoded, so seek into it first if this errors), and explicit fields then override it. Preview, timeline thumbnails, and export all render the same result.",
+ inputSchema: obj({
+ clipId: str("Video clip id"),
+ brightness: num("-50..50, 0 neutral"),
+ contrast: num("-50..50, 0 neutral"),
+ saturation: num("-50..50 (-50 = grayscale), 0 neutral"),
+ exposure: num("-50..50 (±1 stop), 0 neutral"),
+ temperature: num("-50..50, positive = warmer, 0 neutral"),
+ hue: num("Hue rotation in degrees, -180..180"),
+ auto: bool("Fit a starting grade from the clip's current frame"),
+ reset: bool("Clear the existing grade before applying fields"),
+ }, ["clipId"]),
+ },
{
name: "set_transition",
description: