Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): per-clip color grade with Auto, histogram, and export parity [rebuild]

David Le32d807e4219a
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 7cea0c7e..3a55c595 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Bold, Info, RotateCcw, Smile } from "lucide-react";
+import { Bold, ChevronLeft, ChevronRight, Info, RotateCcw, SlidersHorizontal, Smile, Wand2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmojiPicker } from "@/cut/components/EmojiPicker";
import {
@@ -35,6 +35,8 @@ import { writeTextStyle } from "@/cut/lib/textStyle";
import { formatTime } from "@/cut/lib/time";
import {
FONTS,
+ GRADE_HUE_MAX,
+ GRADE_MAX,
LAYOUTS,
rectOf,
regionLabel,
@@ -45,12 +47,15 @@ import {
TRANSITION_STYLE_IDS,
TRANSITION_STYLE_LABELS,
type AudioClip,
+ type ColorGrade,
type FrameRect,
type LayoutId,
type TextOverlay,
type TransitionStyle,
type VideoClip,
} from "@/cut/lib/types";
+import { autoGradeFromImageData, isNeutralGrade, normalizeGrade } from "@/cut/lib/colorGrade";
+import { getPreviewCanvas, sampleClipSource } from "@/cut/lib/previewCanvas";
import { cn } from "@/lib/utils";
const SWATCHES = ["#FFFFFF", "#111114", "#FFD60A", "#FF375F", "#0A84FF", "#30D158"];
@@ -304,6 +309,11 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
const [speedDraft, setSpeedDraft] = useState<number | null>(null);
const [xfadeDraft, setXfadeDraft] = useState<number | null>(null);
const [volumeDraft, setVolumeDraft] = useState<number | null>(null);
+ // The panel can push into the color-grade subview. The subview remembers
+ // which clip opened it, so selecting another clip lands back on the main
+ // view without an effect.
+ const [colorFor, setColorFor] = useState<string | null>(null);
+ const view = colorFor === clip.id ? "color" : "main";
const volume = volumeDraft ?? clip.volume ?? 1;
const speed = speedDraft ?? clip.speed ?? 1;
const xfade = xfadeDraft ?? clip.transition ?? 0;
@@ -311,6 +321,9 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
// Typing can trim out to the source's end but no further; an image has no
// intrinsic duration, so its clip can be any length.
const maxOut = asset && asset.type !== "image" ? asset.duration : Infinity;
+ if (view === "color") {
+ return <ColorPanel clip={clip} onBack={() => setColorFor(null)} />;
+ }
return (
<>
<PanelTitle>Video clip</PanelTitle>
@@ -406,6 +419,22 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
/>
)}
</Row>
+ <Row label="Color">
+ <button
+ type="button"
+ className="clip-color flex h-8 w-[8.5rem] items-center justify-between rounded-md border border-input px-2.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
+ onClick={() => setColorFor(clip.id)}
+ >
+ <span className="flex items-center gap-1.5">
+ <SlidersHorizontal className="size-3.5" />
+ Adjust
+ {!isNeutralGrade(clip.grade) && (
+ <span className="size-1.5 rounded-full bg-violet-500" aria-label="Adjusted" />
+ )}
+ </span>
+ <ChevronRight className="size-3.5" />
+ </button>
+ </Row>
{isFirst && (
<Row label="Fade in">
<Slider
@@ -599,6 +628,189 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
);
}
+const GRADE_FIELDS: { key: keyof ColorGrade; label: string; max: number }[] = [
+ { key: "brightness", label: "Brightness", max: GRADE_MAX },
+ { key: "contrast", label: "Contrast", max: GRADE_MAX },
+ { key: "saturation", label: "Saturation", max: GRADE_MAX },
+ { key: "exposure", label: "Exposure", max: GRADE_MAX },
+ { key: "temperature", label: "Temperature", max: GRADE_MAX },
+ { key: "hue", label: "Hue", max: GRADE_HUE_MAX },
+];
+
+const formatGradeValue = (key: keyof ColorGrade, v: number) =>
+ key === "hue" ? `${Math.round(v)}°` : v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`;
+
+/** The color-grade subview a clip panel pushes into: live histogram over the
+ * adjustment sliders. Slider drags stream through the transient updater under
+ * one history checkpoint, so the preview follows live and ⌘Z undoes the whole
+ * drag. */
+function ColorPanel({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {
+ const ck = useSliderCheckpoint();
+ const updateClip = useEditor((s) => s.updateClip);
+ const setField = (key: keyof ColorGrade, v: number) => {
+ ck.begin();
+ useEditor.getState().updateClipTransient(clip.id, {
+ grade: normalizeGrade({ ...clip.grade, [key]: v }),
+ });
+ };
+ // Fit a starting grade from the clip's raw decoder frame (never the graded
+ // 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.
+ }
+ };
+ return (
+ <>
+ <div className="flex h-10 shrink-0 items-center gap-1 px-2.5 text-sm font-semibold tracking-tight">
+ <button
+ type="button"
+ aria-label="Back"
+ className="clip-color-back grid size-6 place-items-center rounded text-muted-foreground transition-colors hover:text-foreground"
+ onClick={onBack}
+ >
+ <ChevronLeft className="size-4" />
+ </button>
+ Color
+ <button
+ type="button"
+ className="clip-grade-auto ml-auto flex items-center gap-1 rounded-md border border-input px-2 py-0.5 text-[11.5px] font-medium text-muted-foreground transition-colors hover:text-foreground"
+ onClick={autoGrade}
+ >
+ <Wand2 className="size-3" />
+ Auto
+ </button>
+ </div>
+ <div className="flex flex-col gap-1 px-3.5 pb-4">
+ <Histogram />
+ {GRADE_FIELDS.map((f) => {
+ const value = clip.grade?.[f.key] ?? 0;
+ return (
+ <Row key={f.key} label={f.label}>
+ <Slider
+ className={`clip-grade-${f.key} data-horizontal:w-24`}
+ min={-f.max}
+ max={f.max}
+ step={1}
+ value={value}
+ onValueChange={(v) => setField(f.key, Number(v))}
+ onValueCommitted={() => ck.end()}
+ />
+ <ScrubValue
+ label={f.label}
+ className="w-9 text-muted-foreground"
+ value={value}
+ min={-f.max}
+ max={f.max}
+ step={1}
+ format={(v) => formatGradeValue(f.key, v)}
+ parse={parseNumberInput}
+ onScrub={(v) => setField(f.key, v)}
+ onCommit={(v) => {
+ setField(f.key, v);
+ ck.end();
+ }}
+ />
+ {value !== 0 && (
+ <ResetButton
+ title={`Reset ${f.label.toLowerCase()}`}
+ onClick={() => {
+ setField(f.key, 0);
+ ck.end();
+ }}
+ />
+ )}
+ </Row>
+ );
+ })}
+ {!isNeutralGrade(clip.grade) && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="clip-grade-reset mt-2"
+ onClick={() => updateClip(clip.id, { grade: undefined })}
+ >
+ Reset all
+ </Button>
+ )}
+ </div>
+ </>
+ );
+}
+
+/** Live RGB histogram of the composited preview frame: the three channel
+ * curves screen over each other so overlaps read light. Samples a small
+ * downscale of the preview canvas on a short interval while open. */
+function Histogram() {
+ const ref = useRef<HTMLCanvasElement>(null);
+ useEffect(() => {
+ const cv = ref.current;
+ const ctx = cv?.getContext("2d");
+ if (!cv || !ctx) return;
+ const sample = document.createElement("canvas");
+ sample.width = 96;
+ sample.height = 54;
+ const sctx = sample.getContext("2d", { willReadFrequently: true });
+ if (!sctx) return;
+ const BINS = 64;
+ const COLORS = ["#ff453a", "#32d74b", "#0a84ff"];
+ const draw = () => {
+ const src = getPreviewCanvas();
+ if (!src) return;
+ let data: Uint8ClampedArray;
+ try {
+ sctx.drawImage(src, 0, 0, sample.width, sample.height);
+ data = sctx.getImageData(0, 0, sample.width, sample.height).data;
+ } catch {
+ return; // unreadable canvas — keep whatever is drawn
+ }
+ const bins = [new Float64Array(BINS), new Float64Array(BINS), new Float64Array(BINS)];
+ for (let i = 0; i < data.length; i += 4) {
+ bins[0][data[i] >> 2]++;
+ bins[1][data[i + 1] >> 2]++;
+ bins[2][data[i + 2] >> 2]++;
+ }
+ const W = cv.width;
+ const H = cv.height;
+ ctx.globalCompositeOperation = "source-over";
+ ctx.fillStyle = "#101014";
+ ctx.fillRect(0, 0, W, H);
+ const peak = Math.max(1, ...bins.map((b) => Math.max(...b)));
+ ctx.globalCompositeOperation = "screen";
+ bins.forEach((b, ci) => {
+ ctx.fillStyle = COLORS[ci];
+ ctx.beginPath();
+ ctx.moveTo(0, H);
+ for (let i = 0; i < BINS; i++) {
+ // sqrt tames the peaks so midtone shape stays visible.
+ ctx.lineTo((i / (BINS - 1)) * W, H - Math.sqrt(b[i] / peak) * (H - 3));
+ }
+ ctx.lineTo(W, H);
+ ctx.closePath();
+ ctx.fill();
+ });
+ ctx.globalCompositeOperation = "source-over";
+ };
+ draw();
+ const id = setInterval(draw, 150);
+ return () => clearInterval(id);
+ }, []);
+ return <canvas ref={ref} width={256} height={80} className="mb-1.5 h-20 w-full rounded-md" />;
+}
+
/** Per-clip generated-audio block: the voice picker, "Generate audio for clip"
* (which transcribes just this clip when it has no cues yet), and one volume
* slider driving the voiceovers laid over the clip. Shared by every clip
diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsx
index 7e323e3a..fa2c919e 100644
--- a/site/src/cut/components/Preview.tsx
+++ b/site/src/cut/components/Preview.tsx
@@ -5,6 +5,7 @@ import { usePlayback } from "@/cut/hooks/usePlayback";
import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";
import { startDrag } from "@/cut/lib/drag";
import { getClipSpans, useEditor } from "@/cut/lib/store";
+import { setPreviewCanvas } from "@/cut/lib/previewCanvas";
import { FRAME, isFullRect, rectOf, type Aspect, type ClipSpan, type FrameRect, type MediaAsset, type VideoClip } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { OverlayLayer } from "./OverlayLayer";
@@ -42,6 +43,11 @@ export function Preview() {
usePlayback(canvasRef);
+ useEffect(() => {
+ setPreviewCanvas(canvasRef.current);
+ return () => setPreviewCanvas(null);
+ }, []);
+
useEffect(() => {
const wrap = wrapRef.current;
if (!wrap) return;
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index d459b55e..0bda2d5d 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -3,7 +3,9 @@
import { useEffect, type RefObject } from "react";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, useEditor } from "@/cut/lib/store";
import { isFullRect, projectFadeSeconds, rectOf, TRANSITION_ZOOM } from "@/cut/lib/types";
-import type { AudioClip, ClipSpan, FrameRect, MediaAsset, VideoClip } from "@/cut/lib/types";
+import type { AudioClip, ClipSpan, ColorGrade, FrameRect, MediaAsset, VideoClip } from "@/cut/lib/types";
+import { gradeTint, gradeToCssFilter, isNeutralGrade } from "@/cut/lib/colorGrade";
+import { registerSourceSampler } from "@/cut/lib/previewCanvas";
/** The alpha/zoom/gain ramps a transition puts on one upper-track clip at
* `t`. Cross styles blend the incoming clip in over the outgoing one (which
@@ -175,6 +177,11 @@ class Engine {
private raf = 0;
private activeClipId: string | null = null;
private disposed = false;
+ // Scratch surface for per-clip color grades: the source draws here through
+ // ctx.filter (+ a multiply tint), and the graded result is what the
+ // compositor stamps onto the main canvas. One instance suffices — every use
+ // is draw-then-immediately-copy.
+ private gradeCanvas: HTMLCanvasElement | null = null;
// Wall-clock stamp for advancing time where track 0 has nothing playing —
// in a gap or past its end there is no track-0 video element to act as the
// master clock.
@@ -330,7 +337,55 @@ class Engine {
* region and crops the overflow (clipped to the rect); "fit" contains the
* whole picture inside it, centered. `zoom` scales the picture around the
* region's center (zoom transitions), clipping the overflow to the rect. */
- private drawIntoRect(el: MediaEl, rect: FrameRect, fill: boolean, alpha: number, zoom = 1) {
+ /** The clip's raw, ungraded decoder frame for analysis (the color panel's
+ * Auto), or null when no ready decoder exists for the clip. */
+ sourceFor(clipId: string): CanvasImageSource | null {
+ const el = this.videoEls.get(clipId) ?? this.overlayEls.get(clipId);
+ return el && elReady(el) ? el : null;
+ }
+
+ /** The clip's picture with its color grade applied, or the raw element when
+ * there is nothing to grade. Mirrors the export's lutrgb/hue chain: CSS
+ * filter first (gain/contrast/saturate/hue), then the warm tint as a
+ * multiply pass, with source alpha restored so transparent stills keep
+ * their transparency. */
+ private gradedSource(el: MediaEl, grade: ColorGrade | undefined): CanvasImageSource {
+ if (isNeutralGrade(grade)) return el;
+ const scratch = (this.gradeCanvas ??= document.createElement("canvas"));
+ const w = elW(el);
+ const h = elH(el);
+ if (scratch.width !== w) scratch.width = w;
+ if (scratch.height !== h) scratch.height = h;
+ const ctx = scratch.getContext("2d");
+ // Without ctx.filter support, skip the whole grade (never half-apply the
+ // tint); export still renders it.
+ if (!ctx || !("filter" in ctx)) return el;
+ ctx.clearRect(0, 0, w, h);
+ ctx.filter = gradeToCssFilter(grade);
+ ctx.drawImage(el, 0, 0, w, h);
+ ctx.filter = "none";
+ const tint = gradeTint(grade);
+ if (tint) {
+ ctx.globalCompositeOperation = "multiply";
+ ctx.fillStyle = tint;
+ ctx.fillRect(0, 0, w, h);
+ // Multiply painted the transparent areas solid; carve the source's
+ // alpha back in.
+ ctx.globalCompositeOperation = "destination-in";
+ ctx.drawImage(el, 0, 0, w, h);
+ ctx.globalCompositeOperation = "source-over";
+ }
+ return scratch;
+ }
+
+ private drawIntoRect(
+ el: MediaEl,
+ rect: FrameRect,
+ fill: boolean,
+ alpha: number,
+ zoom = 1,
+ grade?: ColorGrade
+ ) {
const ctx = this.canvas.getContext("2d");
if (!ctx) return;
const W = this.canvas.width;
@@ -346,6 +401,7 @@ class Engine {
const dh = vh * sc;
const dx = rx + (rw - dw) / 2;
const dy = ry + (rh - dh) / 2;
+ const src = this.gradedSource(el, grade);
const prevAlpha = ctx.globalAlpha;
ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
if (fill || zoom > 1) {
@@ -353,10 +409,10 @@ class Engine {
ctx.beginPath();
ctx.rect(rx, ry, rw, rh);
ctx.clip();
- ctx.drawImage(el, dx, dy, dw, dh);
+ ctx.drawImage(src, dx, dy, dw, dh);
ctx.restore();
} else {
- ctx.drawImage(el, dx, dy, dw, dh);
+ ctx.drawImage(src, dx, dy, dw, dh);
}
ctx.globalAlpha = prevAlpha;
}
@@ -393,7 +449,7 @@ class Engine {
// black frame; the full-frame path below keeps the pan-crop behavior.
const rect = rectOf(clip ?? {});
if (!isFullRect(rect)) {
- this.drawIntoRect(el, rect, clip?.fit === "fill", alpha, zoom);
+ this.drawIntoRect(el, rect, clip?.fit === "fill", alpha, zoom, clip?.grade);
return;
}
const fill = clip?.fit === "fill";
@@ -413,7 +469,7 @@ class Engine {
}
const prevAlpha = ctx.globalAlpha;
ctx.globalAlpha = Math.max(0, Math.min(1, alpha));
- ctx.drawImage(el, dx, dy, dw, dh);
+ ctx.drawImage(this.gradedSource(el, clip?.grade), dx, dy, dw, dh);
ctx.globalAlpha = prevAlpha;
}
@@ -625,7 +681,7 @@ class Engine {
if (!elReady(el)) continue;
const rect = rectOf(clip);
const cover = clip.fit === "fill" || (clip.fit == null && isFullRect(rect));
- this.drawIntoRect(el, rect, cover, alpha, zoom);
+ this.drawIntoRect(el, rect, cover, alpha, zoom, clip.grade);
}
}
@@ -917,6 +973,10 @@ export function usePlayback(canvasRef: RefObject<HTMLCanvasElement | null>) {
const canvas = canvasRef.current;
if (!canvas) return;
const engine = new Engine(canvas);
- return () => engine.dispose();
+ registerSourceSampler((clipId) => engine.sourceFor(clipId));
+ return () => {
+ registerSourceSampler(null);
+ engine.dispose();
+ };
}, [canvasRef]);
}
diff --git a/site/src/cut/lib/colorGrade.test.ts b/site/src/cut/lib/colorGrade.test.ts
new file mode 100644
index 00000000..2196d8fe
--- /dev/null
+++ b/site/src/cut/lib/colorGrade.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, test } from "bun:test";
+import {
+ autoGradeFromImageData,
+ gradeTint,
+ gradeToCssFilter,
+ gradeToFfmpegFilter,
+ isNeutralGrade,
+ normalizeGrade,
+} from "./colorGrade";
+
+/** RGBA frame from repeating [r,g,b] pixel patterns. */
+function frame(...pixels: [number, number, number][]): Uint8ClampedArray {
+ const per = 64;
+ const data = new Uint8ClampedArray(pixels.length * per * 4);
+ pixels.forEach(([r, g, b], p) => {
+ for (let i = 0; i < per; i++) {
+ const o = (p * per + i) * 4;
+ data[o] = r;
+ data[o + 1] = g;
+ data[o + 2] = b;
+ data[o + 3] = 255;
+ }
+ });
+ return data;
+}
+
+describe("neutrality", () => {
+ test("absent, empty, and all-zero grades are neutral", () => {
+ expect(isNeutralGrade(undefined)).toBe(true);
+ expect(isNeutralGrade({})).toBe(true);
+ expect(isNeutralGrade({ brightness: 0, hue: 0 })).toBe(true);
+ expect(isNeutralGrade({ saturation: -5 })).toBe(false);
+ });
+
+ test("normalize strips zeros and collapses to undefined", () => {
+ expect(normalizeGrade({ brightness: 0, contrast: 0 })).toBeUndefined();
+ expect(normalizeGrade({ brightness: 10, contrast: 0 })).toEqual({ brightness: 10 });
+ });
+
+ test("normalize clamps out-of-range and drops garbage input", () => {
+ expect(normalizeGrade({ brightness: 999, hue: -999 })).toEqual({ brightness: 50, hue: -180 });
+ expect(normalizeGrade({ contrast: Number.NaN, saturation: Infinity })).toBeUndefined();
+ });
+
+ test("neutral grades emit nothing", () => {
+ expect(gradeToCssFilter(undefined)).toBe("");
+ expect(gradeToFfmpegFilter({ brightness: 0 })).toBe("");
+ expect(gradeTint({})).toBe(null);
+ });
+});
+
+describe("css filter", () => {
+ test("brightness and exposure fold into one gain", () => {
+ // (1 + 20/100) · 2^(50/50) = 2.4
+ expect(gradeToCssFilter({ brightness: 20, exposure: 50 })).toBe("brightness(2.400)");
+ });
+
+ test("emits only non-neutral terms, in application order", () => {
+ expect(gradeToCssFilter({ contrast: 25, hue: -90 })).toBe("contrast(1.250) hue-rotate(-90.000deg)");
+ expect(gradeToCssFilter({ saturation: -50 })).toBe("saturate(0.000)");
+ });
+
+ test("warmth keeps luminance: gain rises, tint dims the cool channel", () => {
+ // t=1 → gains (1.25, 1, 0.75), normalized by 1.25.
+ expect(gradeToCssFilter({ temperature: 50 })).toBe("brightness(1.250)");
+ expect(gradeTint({ temperature: 50 })).toBe("rgb(255, 204, 153)");
+ expect(gradeTint({ temperature: -50 })).toBe("rgb(153, 204, 255)");
+ });
+});
+
+describe("auto grade", () => {
+ test("a mid-gray frame needs nearly nothing", () => {
+ const g = autoGradeFromImageData(frame([118, 118, 118]));
+ expect(Math.abs(g?.exposure ?? 0) <= 1).toBe(true);
+ expect(g?.contrast).toBeUndefined(); // flat histogram = no tonal signal
+ expect(g?.temperature).toBeUndefined();
+ });
+
+ test("a dark frame gets pushed up toward middle gray", () => {
+ const g = autoGradeFromImageData(frame([30, 30, 30], [50, 50, 50]));
+ expect((g?.exposure ?? 0) > 10).toBe(true);
+ });
+
+ test("a compressed tonal range gets a contrast stretch", () => {
+ const g = autoGradeFromImageData(frame([100, 100, 100], [150, 150, 150]));
+ expect((g?.contrast ?? 0) > 0).toBe(true);
+ });
+
+ test("gray-world counters color casts both ways, hue and saturation stay", () => {
+ const cool = autoGradeFromImageData(frame([90, 120, 170]));
+ expect((cool?.temperature ?? 0) > 0).toBe(true);
+ const warm = autoGradeFromImageData(frame([170, 120, 90]));
+ expect((warm?.temperature ?? 0) < 0).toBe(true);
+ expect(cool?.saturation).toBeUndefined();
+ expect(cool?.hue).toBeUndefined();
+ });
+
+ test("an empty sample yields no grade", () => {
+ expect(autoGradeFromImageData(new Uint8ClampedArray(0))).toBeUndefined();
+ });
+});
+
+describe("ffmpeg filter", () => {
+ test("gain+contrast ride one lutrgb, trailing comma included", () => {
+ const expr = "clip((clip(val*1.100,0,255)-128)*1.200+128,0,255)";
+ expect(gradeToFfmpegFilter({ brightness: 10, contrast: 20 })).toBe(
+ `lutrgb=r='${expr}':g='${expr}':b='${expr}',`,
+ );
+ });
+
+ test("saturation and hue share the hue filter", () => {
+ expect(gradeToFfmpegFilter({ saturation: 25, hue: 45 })).toBe("hue=h=45.000:s=1.500,");
+ });
+
+ test("temperature emits the gain lut and the tint lut in preview order", () => {
+ expect(gradeToFfmpegFilter({ temperature: 50 })).toBe(
+ "lutrgb=r='clip((clip(val*1.250,0,255)-128)*1.000+128,0,255)'" +
+ ":g='clip((clip(val*1.250,0,255)-128)*1.000+128,0,255)'" +
+ ":b='clip((clip(val*1.250,0,255)-128)*1.000+128,0,255)'," +
+ "lutrgb=r='clip(val*1.000,0,255)':g='clip(val*0.800,0,255)':b='clip(val*0.600,0,255)',",
+ );
+ });
+});
diff --git a/site/src/cut/lib/colorGrade.ts b/site/src/cut/lib/colorGrade.ts
new file mode 100644
index 00000000..910b8e35
--- /dev/null
+++ b/site/src/cut/lib/colorGrade.ts
@@ -0,0 +1,192 @@
+import { GRADE_HUE_MAX, GRADE_MAX } from "./types";
+import type { ColorGrade } from "./types";
+
+/**
+ * One mapping, two renderers. The preview canvas and the export filtergraph
+ * both derive from the numbers computed here, so what the sliders show is what
+ * ffmpeg bakes. Brightness/exposure/contrast/temperature are per-channel
+ * multiplies and a mid-gray pivot — mathematically identical on both sides;
+ * saturation/hue lean on each side's native primitive (CSS saturate/hue-rotate
+ * vs ffmpeg's chroma-plane `hue`), which stay visually indistinguishable over
+ * these ranges.
+ *
+ * Application order everywhere: gain+contrast → saturation+hue → warm tint.
+ */
+
+const FIELDS: [keyof ColorGrade, number][] = [
+ ["brightness", GRADE_MAX],
+ ["contrast", GRADE_MAX],
+ ["saturation", GRADE_MAX],
+ ["exposure", GRADE_MAX],
+ ["temperature", GRADE_MAX],
+ ["hue", GRADE_HUE_MAX],
+];
+
+const clamp = (v: unknown, max: number) => {
+ const n = typeof v === "number" && Number.isFinite(v) ? v : 0;
+ return Math.max(-max, Math.min(max, n));
+};
+
+const fmt = (n: number) => (Math.round(n * 1000) / 1000).toFixed(3);
+
+export function isNeutralGrade(g: ColorGrade | undefined | null): boolean {
+ return !g || FIELDS.every(([k]) => !g[k]);
+}
+
+/** Clamp to slider ranges, drop zeros; an all-neutral grade becomes absent.
+ * Also the sanitizer for grades arriving as client JSON. */
+export function normalizeGrade(g: ColorGrade | undefined | null): ColorGrade | undefined {
+ if (!g) return undefined;
+ const out: ColorGrade = {};
+ for (const [k, max] of FIELDS) {
+ const v = clamp(g[k], max);
+ if (v !== 0) out[k] = v;
+ }
+ return Object.keys(out).length ? out : undefined;
+}
+
+/** The shared numeric model behind both filter strings. */
+function derive(g: ColorGrade) {
+ const b = clamp(g.brightness, GRADE_MAX);
+ const c = clamp(g.contrast, GRADE_MAX);
+ const s = clamp(g.saturation, GRADE_MAX);
+ const e = clamp(g.exposure, GRADE_MAX);
+ const t = clamp(g.temperature, GRADE_MAX) / GRADE_MAX;
+ const H = clamp(g.hue, GRADE_HUE_MAX);
+ // Warm shifts red up and blue down. Gains are normalized to ≤1 (a multiply
+ // tint can only darken); the excess folds into the shared gain so warmth
+ // keeps overall luminance instead of dimming the picture.
+ const gr = 1 + 0.25 * t;
+ const gb = 1 - 0.25 * t;
+ const norm = Math.max(gr, 1, gb);
+ return {
+ gain: (1 + b / 100) * Math.pow(2, e / GRADE_MAX) * norm,
+ contrast: 1 + c / 100,
+ saturate: Math.max(0, 1 + s / GRADE_MAX),
+ hue: H,
+ tint: t === 0 ? null : { r: gr / norm, g: 1 / norm, b: gb / norm },
+ };
+}
+
+/** Canvas 2D `ctx.filter` value; "" when nothing applies. The warm tint is not
+ * expressible as a CSS filter function — apply `gradeTint` as a multiply pass
+ * after drawing with this filter. */
+export function gradeToCssFilter(g: ColorGrade | undefined | null): string {
+ if (isNeutralGrade(g)) return "";
+ const d = derive(g!);
+ const parts: string[] = [];
+ if (d.gain !== 1) parts.push(`brightness(${fmt(d.gain)})`);
+ if (d.contrast !== 1) parts.push(`contrast(${fmt(d.contrast)})`);
+ if (d.saturate !== 1) parts.push(`saturate(${fmt(d.saturate)})`);
+ if (d.hue !== 0) parts.push(`hue-rotate(${fmt(d.hue)}deg)`);
+ return parts.join(" ");
+}
+
+/** CSS color for the multiply tint pass, or null when temperature is neutral. */
+export function gradeTint(g: ColorGrade | undefined | null): string | null {
+ if (isNeutralGrade(g)) return null;
+ const tint = derive(g!).tint;
+ if (!tint) return null;
+ const ch = (v: number) => Math.round(255 * v);
+ return `rgb(${ch(tint.r)}, ${ch(tint.g)}, ${ch(tint.b)})`;
+}
+
+/**
+ * Auto grade from a frame's RGBA pixels, following the classic auto-tone
+ * pipeline rather than invented heuristics:
+ *
+ * 1. Exposure — the photographic auto-exposure convention: map the frame's
+ * log-average (geometric mean) luminance onto 18% middle gray, projected
+ * into this pipeline's gamma-encoded gain.
+ * 2. Contrast — auto-levels: clip 0.5% off each end of the luma histogram
+ * (the common editor default) and stretch what remains toward full range,
+ * projected onto the symmetric mid-gray contrast knob.
+ * 3. Temperature — gray-world white balance: choose the warm/cool gains that
+ * equalize the red and blue channel means.
+ *
+ * Corrections are damped and capped inside the slider range so the result is
+ * a starting point the user refines. Classic auto-tone leaves saturation and
+ * hue alone, and so does this.
+ */
+export function autoGradeFromImageData(data: Uint8ClampedArray): ColorGrade | undefined {
+ const hist = new Float64Array(256);
+ let count = 0;
+ let logSum = 0;
+ let sumR = 0;
+ let sumB = 0;
+ let mids = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i];
+ const g = data[i + 1];
+ const b = data[i + 2];
+ const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ hist[Math.min(255, Math.round(luma))]++;
+ // Approximate linear luminance for the log-average (γ≈2.2 decode).
+ logSum += Math.log(Math.max(1e-4, Math.pow(luma / 255, 2.2)));
+ count++;
+ // Cast statistics from the midtones only — near-black and clipped pixels
+ // carry no reliable illuminant signal.
+ if (luma >= 16 && luma <= 240) {
+ sumR += r;
+ sumB += b;
+ mids++;
+ }
+ }
+ if (!count) return undefined;
+ const percentile = (p: number) => {
+ let acc = 0;
+ for (let v = 0; v < 256; v++) {
+ acc += hist[v];
+ if (acc >= count * p) return v;
+ }
+ return 255;
+ };
+
+ const grade: ColorGrade = {};
+ // EV against 18% gray in linear light; our gain multiplies gamma-encoded
+ // values, so one encoded stop is γ linear stops (slider v: 2^(v/50)).
+ const ev = Math.log2(0.18 / Math.exp(logSum / count));
+ grade.exposure = Math.round((GRADE_MAX * ev * 0.8) / 2.2);
+ // Auto-levels spread after the exposure shift moves it, on encoded values.
+ // A near-flat histogram (solid color, title card) carries no tonal-range
+ // signal — leave contrast alone rather than stretch noise.
+ const gain = Math.pow(2, grade.exposure / GRADE_MAX);
+ const lo = Math.min(255, percentile(0.005) * gain);
+ const hi = Math.min(255, percentile(0.995) * gain);
+ if (hi - lo >= 16) {
+ grade.contrast = Math.max(
+ -10,
+ Math.min(40, Math.round((255 / (hi - lo) - 1) * 100 * 0.6))
+ );
+ }
+ if (mids) {
+ // Gray-world: t such that the temperature gains (1±0.25t) equalize the
+ // red/blue means — a blue cast warms, an orange cast cools.
+ const avgR = sumR / mids;
+ const avgB = sumB / mids;
+ const t = (avgB - avgR) / (0.25 * (avgR + avgB));
+ grade.temperature = Math.max(-40, Math.min(40, Math.round(t * 0.6 * GRADE_MAX)));
+ }
+ return normalizeGrade(grade);
+}
+
+/** ffmpeg filter chain with a trailing comma, ready to sit between the color
+ * conversion and the terminal `format=` of a clip's core chain; "" when
+ * neutral. Uses only `lutrgb` and `hue` — the bundled build has no `eq`. */
+export function gradeToFfmpegFilter(g: ColorGrade | undefined | null): string {
+ if (isNeutralGrade(g)) return "";
+ const d = derive(g!);
+ const parts: string[] = [];
+ if (d.gain !== 1 || d.contrast !== 1) {
+ const expr = `clip((clip(val*${fmt(d.gain)},0,255)-128)*${fmt(d.contrast)}+128,0,255)`;
+ parts.push(`lutrgb=r='${expr}':g='${expr}':b='${expr}'`);
+ }
+ if (d.saturate !== 1 || d.hue !== 0) {
+ parts.push(`hue=h=${fmt(d.hue)}:s=${fmt(d.saturate)}`);
+ }
+ if (d.tint) {
+ const ch = (v: number) => `'clip(val*${fmt(v)},0,255)'`;
+ parts.push(`lutrgb=r=${ch(d.tint.r)}:g=${ch(d.tint.g)}:b=${ch(d.tint.b)}`);
+ }
+ return parts.length ? parts.join(",") + "," : "";
+}
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index ac655926..078272d2 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1,6 +1,7 @@
"use client";
import { apiFetch, apiJson, apiUrl } from "./api";
+import { normalizeGrade } from "./colorGrade";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
import { captionStyle, cueOverlay, cueWordWindows, laneCues, subtitleLaneCount, trackPos } from "./subtitles";
import { renderOverlayPng } from "./textRender";
@@ -182,6 +183,7 @@ async function buildExportForm(
// A still: the server loops the image for the clip's length instead of
// trimming a source span.
image: sp.asset.type === "image",
+ grade: normalizeGrade(sp.clip.grade),
headFade: 0,
tailFade: 0,
headZoom: 0,
@@ -289,6 +291,7 @@ async function buildExportForm(
volume: c.volume,
speed: c.speed,
image: assetById.get(c.assetId)!.type === "image",
+ grade: normalizeGrade(c.grade),
...ramp,
}));
});
diff --git a/site/src/cut/lib/previewCanvas.ts b/site/src/cut/lib/previewCanvas.ts
new file mode 100644
index 00000000..dabb45d9
--- /dev/null
+++ b/site/src/cut/lib/previewCanvas.ts
@@ -0,0 +1,34 @@
+"use client";
+
+/**
+ * The live preview <canvas>, registered by Preview while it is mounted, so
+ * panels can sample the composited frame (the color panel's histogram reads
+ * it). Media decoders load with crossOrigin=anonymous and the engine serves
+ * CORS, so the canvas stays readable.
+ */
+let el: HTMLCanvasElement | null = null;
+
+export function setPreviewCanvas(canvas: HTMLCanvasElement | null) {
+ el = canvas;
+}
+
+export function getPreviewCanvas(): HTMLCanvasElement | null {
+ return el;
+}
+
+/**
+ * A clip's raw decoded frame, straight from the playback engine's decoder
+ * element — before any color grade — so analysis (the color panel's Auto)
+ * never fits corrections on top of its own output. The engine registers the
+ * sampler while mounted; null when the clip has no ready decoder.
+ */
+type SourceSampler = (clipId: string) => CanvasImageSource | null;
+let sampler: SourceSampler | null = null;
+
+export function registerSourceSampler(fn: SourceSampler | null) {
+ sampler = fn;
+}
+
+export function sampleClipSource(clipId: string): CanvasImageSource | null {
+ return sampler?.(clipId) ?? null;
+}
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index d53bd1cf..16756b20 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -149,8 +149,25 @@ export interface VideoClip {
/** Hidden clips stay on the timeline (grayed) but render as black — excluded
* from the played/exported picture without disturbing the layout. */
hidden?: boolean;
+ /** Manual color adjustments; absent when every value is neutral. */
+ grade?: ColorGrade;
}
+/** Per-clip manual color adjustments. Integer sliders, 0 = neutral; the whole
+ * field is absent when every value is 0, so untouched clips carry nothing. */
+export interface ColorGrade {
+ brightness?: number; // -50..50
+ contrast?: number; // -50..50
+ saturation?: number; // -50..50
+ exposure?: number; // -50..50 (±1 EV)
+ temperature?: number; // -50..50, positive = warm
+ hue?: number; // -180..180 degrees
+}
+
+/** Slider range for every grade parameter except hue. */
+export const GRADE_MAX = 50;
+export const GRADE_HUE_MAX = 180;
+
/** Speed slider range. Typed entry and tools may go beyond it; SPEED_FLOOR is
* the only hard bound, keeping rates positive so length math stays finite. */
export const SPEED_MIN = 0.25;
diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.ts
index 85b94e33..7185db31 100644
--- a/site/src/cut/server/jobs.ts
+++ b/site/src/cut/server/jobs.ts
@@ -7,7 +7,8 @@ import { createJobRegistry } from "./jobRegistry";
import { exportsDir, mediaPath, projectDir, readProject } from "./projects";
import { currentCutUser } from "./userScope";
import { atempoChain, hasStream, num, videoColorInfo } from "./util";
-import { projectFadeSeconds, TRANSITION_ZOOM } from "../lib/types";
+import { projectFadeSeconds, TRANSITION_ZOOM, type ColorGrade } from "../lib/types";
+import { gradeToFfmpegFilter } from "../lib/colorGrade";
export interface ExportSpec {
projectId: string;
@@ -51,6 +52,8 @@ export interface ExportSpec {
hidden?: boolean;
/** A still image: looped for the clip's length instead of trimmed. */
image?: boolean;
+ /** Manual color adjustments, baked into this clip's segment. */
+ grade?: ColorGrade;
}[];
/** Video tracks composited over the track-0 `clips`, lowest track first. */
overlayVideos?: {
@@ -78,6 +81,8 @@ export interface ExportSpec {
tailZoom?: number;
/** A still image: looped for the clip's length instead of trimmed. */
image?: boolean;
+ /** Manual color adjustments, baked into this overlay's segment. */
+ grade?: ColorGrade;
}[];
audio: {
file: string;
@@ -712,7 +717,9 @@ async function runExport(job: Job, spec: ExportSpec) {
}
// setpts/speed rescales the clip's duration on the timeline (footage);
// a still just replays its looped input.
- const core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}format=${clipFmt}`;
+ // The grade sits after the color conversion (so it acts on the same
+ // BT.709 values the preview shows) and before the terminal format.
+ const core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeToFfmpegFilter(c.grade)}format=${clipFmt}`;
const fades =
(hf > 0.01 ? `,fade=t=in:st=0:d=${num(hf)}` : "") +
(tf > 0.01 ? `,fade=t=out:st=${num(Math.max(0, dur - tf))}:d=${num(tf)}` : "");
@@ -828,7 +835,7 @@ async function runExport(job: Job, spec: ExportSpec) {
const timebase = oc.image
? `[${idx}:v]setpts=PTS-STARTPTS`
: `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)}`;
- const core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}format=${fmt}`;
+ const core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${fmt}`;
const pre = `ovp${k}`;
pushZoomRamped(core, olen, hz, tz, boxW, boxH, fmt, fades, pre, `o${k}`);
// The zoom slices' concat drops the stream's frame-rate metadata, and