Open source CapCut alternative.
TypeScript
feat(site): color grade engine — presets, curves, wheels, HSL [rebuild]
David Lebc6135b5117f
diff --git a/site/packages/effects-kit/src/colorGrade.ts b/site/packages/effects-kit/src/colorGrade.tsindex b23a4be4..1b0e2ef8 100644--- a/site/packages/effects-kit/src/colorGrade.ts+++ b/site/packages/effects-kit/src/colorGrade.ts@@ -1,37 +1,142 @@-/** Per-clip manual color adjustments. Integer sliders, 0 = neutral; the whole- * field is absent when every value is 0, so untouched clips carry nothing. */+/** A tone-curve control point: [input, output], both 0..255. */+export type CurvePoint = [number, number];++/** Per-channel tone curves; an absent channel is identity. */+export interface GradeCurves {+ m?: CurvePoint[];+ r?: CurvePoint[];+ g?: CurvePoint[];+ b?: CurvePoint[];+}++/** A color wheel's state: [dx, dy, luma], each -50..50. dx/dy is the puck's+ * position on the wheel (a chroma offset direction and strength); luma is the+ * per-range brightness trim. */+export type WheelTuple = [number, number, number];++/** Shadows / midtones / highlights color wheels; an absent wheel is neutral. */+export interface GradeWheels {+ s?: WheelTuple;+ m?: WheelTuple;+ h?: WheelTuple;+}++export type HslBand =+ | "red"+ | "orange"+ | "yellow"+ | "green"+ | "aqua"+ | "blue"+ | "purple"+ | "magenta";++/** A hue band's adjustments: [hueShift, saturation, luminance], each -50..50.+ * hueShift spans about ±30 degrees at full range. */+export type HslTuple = [number, number, number];++/** A preset layered under the manual adjustments. `amount` 0..1 scales the+ * preset toward neutral (default 1); `skin` keeps the preset's color shifts+ * off skin tones. Unknown ids render as neutral, so docs can carry presets+ * from newer catalogs without breaking. */+export interface GradePresetRef {+ id: string;+ amount?: number;+ skin?: boolean;+}++/** Per-clip color adjustments. Integer sliders, 0 = neutral; every field is+ * absent when neutral, so untouched clips carry nothing. */export interface ColorGrade {brightness?: number; // -50..50contrast?: number; // -50..50saturation?: number; // -50..50exposure?: number; // -50..50 (±1 EV)temperature?: number; // -50..50, positive = warm+ tint?: number; // -50..50, negative = green, positive = magentahue?: number; // -180..180 degrees+ highlights?: number; // -50..50, luma-masked highlight trim+ shadows?: number; // -50..50, luma-masked shadow lift/crush+ vibrance?: number; // -50..50, low-saturation-weighted saturation+ curves?: GradeCurves;+ wheels?: GradeWheels;+ hsl?: Partial<Record<HslBand, HslTuple>>;+ preset?: GradePresetRef;}/** Slider range for every grade parameter except hue. */export const GRADE_MAX = 50;export const GRADE_HUE_MAX = 180;+/** The Basic tool's slider rows; the UI and the AI tool schema both derive+ * from this list. Legacy `brightness` and `hue` stay in the model and render+ * everywhere, surfaced by the UI only when a stored grade carries them. */+export const GRADE_BASIC_FIELDS: {+ key: "exposure" | "contrast" | "highlights" | "shadows" | "temperature" | "tint" | "saturation" | "vibrance";+ label: string;+ group: "light" | "color";+}[] = [+ { key: "exposure", label: "Exposure", group: "light" },+ { key: "contrast", label: "Contrast", group: "light" },+ { key: "highlights", label: "Highlights", group: "light" },+ { key: "shadows", label: "Shadows", group: "light" },+ { key: "temperature", label: "Temperature", group: "color" },+ { key: "tint", label: "Tint", group: "color" },+ { key: "saturation", label: "Saturation", group: "color" },+ { key: "vibrance", label: "Vibrance", group: "color" },+];++/** The HSL tool's hue bands: chip swatch plus the band's center hue used by+ * the renderer's feathered band weights. */+export const HSL_BANDS: { id: HslBand; label: string; center: number; swatch: string }[] = [+ { id: "red", label: "Red", center: 0, swatch: "hsl(0 70% 55%)" },+ { id: "orange", label: "Orange", center: 30, swatch: "hsl(30 70% 55%)" },+ { id: "yellow", label: "Yellow", center: 60, swatch: "hsl(55 70% 55%)" },+ { id: "green", label: "Green", center: 120, swatch: "hsl(110 60% 45%)" },+ { id: "aqua", label: "Aqua", center: 180, swatch: "hsl(178 60% 50%)" },+ { id: "blue", label: "Blue", center: 240, swatch: "hsl(222 70% 55%)" },+ { id: "purple", label: "Purple", center: 285, swatch: "hsl(275 60% 55%)" },+ { id: "magenta", label: "Magenta", center: 330, swatch: "hsl(320 65% 55%)" },+];+/**- * 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.+ * One mapping, every renderer. Scalar-only grades (the fast path) derive both+ * filter strings from the numbers computed here, so what the sliders show is+ * what ffmpeg bakes: gain/contrast 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`), visually indistinguishable over these ranges.*- * Application order everywhere: gain+contrast → saturation+hue → warm tint.+ * Fast-path application order everywhere: gain+contrast → saturation+hue →+ * cast tint. Grades that use curves, wheels, per-hue HSL, highlights/shadows,+ * vibrance, or a preset render through one shared 3D LUT instead — built in+ * gradeLut.ts from the transform in gradeMath.ts — applied by ffmpeg's lut3d,+ * the preview's WebGL pass, and the headless CPU pass alike.*/-const FIELDS: [keyof ColorGrade, number][] = [+type ScalarKey =+ | "brightness"+ | "contrast"+ | "saturation"+ | "exposure"+ | "temperature"+ | "tint"+ | "hue"+ | "highlights"+ | "shadows"+ | "vibrance";++const FIELDS: [ScalarKey, number][] = [["brightness", GRADE_MAX],["contrast", GRADE_MAX],["saturation", GRADE_MAX],["exposure", GRADE_MAX],["temperature", GRADE_MAX],+ ["tint", GRADE_MAX],["hue", GRADE_HUE_MAX],+ ["highlights", GRADE_MAX],+ ["shadows", GRADE_MAX],+ ["vibrance", GRADE_MAX],];const clamp = (v: unknown, max: number) => {@@ -41,12 +146,74 @@ const clamp = (v: unknown, max: number) => {const fmt = (n: number) => (Math.round(n * 1000) / 1000).toFixed(3);+const CURVE_CHANNELS = ["m", "r", "g", "b"] as const;+const WHEEL_ZONES = ["s", "m", "h"] as const;++/** Clamp a stored curve into shape: integer points inside 0..255, sorted by+ * input, one point per input; identity or degenerate curves become absent. */+function normalizeCurve(pts: unknown): CurvePoint[] | undefined {+ if (!Array.isArray(pts)) return undefined;+ const byInput = new Map<number, number>();+ for (const p of pts) {+ if (!Array.isArray(p) || p.length < 2) continue;+ const x = Math.max(0, Math.min(255, Math.round(Number(p[0]) || 0)));+ const y = Math.max(0, Math.min(255, Math.round(Number(p[1]) || 0)));+ byInput.set(x, y);+ }+ const out = [...byInput.entries()].sort((a, b) => a[0] - b[0]).map(([x, y]) => [x, y] as CurvePoint);+ if (out.length < 2) return undefined;+ if (out.every(([x, y]) => x === y)) return undefined;+ return out;+}++function normalizeTuple(t: unknown, max = GRADE_MAX): [number, number, number] | undefined {+ if (!Array.isArray(t)) return undefined;+ const out: [number, number, number] = [+ Math.round(clamp(t[0], max)),+ Math.round(clamp(t[1], max)),+ Math.round(clamp(t[2], max)),+ ];+ return out.some((v) => v !== 0) ? out : undefined;+}+export function isNeutralGrade(g: ColorGrade | undefined | null): boolean {- return !g || FIELDS.every(([k]) => !g[k]);+ return !g || normalizeGrade(g) === undefined;+}++/** True when the grade uses primitives beyond the cheap ctx.filter path —+ * those render through the shared 3D LUT. Every legacy scalar-only grade+ * stays false and keeps the original render path byte for byte. */+export function gradeNeedsLut(g: ColorGrade | undefined | null): boolean {+ if (!g) return false;+ return !!(+ g.highlights ||+ g.shadows ||+ g.vibrance ||+ g.curves ||+ g.wheels ||+ g.hsl ||+ (g.preset?.id && (g.preset.amount ?? 1) > 0)+ );+}++/** True when the given Adjust tool holds a non-neutral value; drives the+ * panel's per-tool dirty dots. */+export function gradeToolDirty(+ g: ColorGrade | undefined | null,+ tool: "basic" | "curves" | "wheels" | "hsl"+): boolean {+ const n = normalizeGrade(g);+ if (!n) return false;+ if (tool === "curves") return !!n.curves;+ if (tool === "wheels") return !!n.wheels;+ if (tool === "hsl") return !!n.hsl;+ return FIELDS.some(([k]) => n[k]);}-/** Clamp to slider ranges, drop zeros; an all-neutral grade becomes absent.- * Also the sanitizer for grades arriving as client JSON. */+/** Clamp to slider ranges, drop zeros and identity shapes; an all-neutral+ * grade becomes absent. Also the sanitizer for grades arriving as client+ * JSON. Preset ids are kept structurally — an id the running catalog does not+ * know renders as neutral instead of being stripped from the doc. */export function normalizeGrade(g: ColorGrade | undefined | null): ColorGrade | undefined {if (!g) return undefined;const out: ColorGrade = {};@@ -54,29 +221,70 @@ export function normalizeGrade(g: ColorGrade | undefined | null): ColorGrade | uconst v = clamp(g[k], max);if (v !== 0) out[k] = v;}+ if (g.curves && typeof g.curves === "object") {+ const curves: GradeCurves = {};+ for (const ch of CURVE_CHANNELS) {+ const c = normalizeCurve(g.curves[ch]);+ if (c) curves[ch] = c;+ }+ if (Object.keys(curves).length) out.curves = curves;+ }+ if (g.wheels && typeof g.wheels === "object") {+ const wheels: GradeWheels = {};+ for (const z of WHEEL_ZONES) {+ const w = normalizeTuple(g.wheels[z]);+ if (w) wheels[z] = w;+ }+ if (Object.keys(wheels).length) out.wheels = wheels;+ }+ if (g.hsl && typeof g.hsl === "object") {+ const hsl: Partial<Record<HslBand, HslTuple>> = {};+ for (const band of HSL_BANDS) {+ const t = normalizeTuple((g.hsl as Record<string, unknown>)[band.id]);+ if (t) hsl[band.id] = t;+ }+ if (Object.keys(hsl).length) out.hsl = hsl;+ }+ if (g.preset && typeof g.preset.id === "string" && g.preset.id) {+ const amount = Math.max(+ 0,+ Math.min(1, typeof g.preset.amount === "number" && Number.isFinite(g.preset.amount) ? g.preset.amount : 1)+ );+ // Amount 0 is a preset turned all the way down, still applied — the tile+ // stays picked and the intensity slider can ride back up.+ out.preset = {+ id: g.preset.id,+ ...(amount !== 1 ? { amount } : {}),+ ...(g.preset.skin ? { skin: true } : {}),+ };+ }return Object.keys(out).length ? out : undefined;}/** The shared numeric model behind both filter strings. */-function derive(g: ColorGrade) {+export function deriveGrade(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 m = clamp(g.tint, 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.+ // Warm shifts red up and blue down; magenta lowers green, green raises it.+ // Gains are normalized to ≤1 (a multiply tint can only darken); the excess+ // folds into the shared gain so a cast shift keeps overall luminance+ // instead of dimming the picture.const gr = 1 + 0.25 * t;+ const gg = 1 - 0.2 * m;const gb = 1 - 0.25 * t;- const norm = Math.max(gr, 1, gb);+ const norm = Math.max(gr, gg, gb, 1);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 },+ tint:+ t === 0 && m === 0 ? null : { r: gr / norm, g: gg / norm, b: gb / norm },};}@@ -85,7 +293,7 @@ function derive(g: ColorGrade) {* after drawing with this filter. */export function gradeToCssFilter(g: ColorGrade | undefined | null): string {if (isNeutralGrade(g)) return "";- const d = derive(g!);+ const d = deriveGrade(g!);const parts: string[] = [];if (d.gain !== 1) parts.push(`brightness(${fmt(d.gain)})`);if (d.contrast !== 1) parts.push(`contrast(${fmt(d.contrast)})`);@@ -97,7 +305,7 @@ export function gradeToCssFilter(g: ColorGrade | undefined | null): string {/** 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;+ const tint = deriveGrade(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)})`;@@ -187,7 +395,7 @@ export function autoGradeFromImageData(data: Uint8ClampedArray): ColorGrade | un* 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 d = deriveGrade(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)`;diff --git a/site/packages/effects-kit/src/gradeLut.test.ts b/site/packages/effects-kit/src/gradeLut.test.tsnew file mode 100644index 00000000..12e810b9--- /dev/null+++ b/site/packages/effects-kit/src/gradeLut.test.ts@@ -0,0 +1,187 @@+import { describe, expect, test } from "bun:test";+import type { ColorGrade } from "./colorGrade";+import { gradeNeedsLut, normalizeGrade } from "./colorGrade";+import { applyLutToImageData, buildGradeLut, gradeKey, lutToCube } from "./gradeLut";+import { createGradeTransform, curveLut, scaleGradeToward, skinWeight } from "./gradeMath";++const px = (...rgb: [number, number, number][]): Uint8ClampedArray => {+ const data = new Uint8ClampedArray(rgb.length * 4);+ rgb.forEach(([r, g, b], i) => {+ data[i * 4] = r;+ data[i * 4 + 1] = g;+ data[i * 4 + 2] = b;+ data[i * 4 + 3] = 255;+ });+ return data;+};++describe("gradeKey", () => {+ test("neutral is empty, key order is stable", () => {+ expect(gradeKey(undefined)).toBe("");+ expect(gradeKey({ contrast: 0 })).toBe("");+ expect(gradeKey({ contrast: 10, exposure: 5 })).toBe(gradeKey({ exposure: 5, contrast: 10 }));+ });++ test("distinct grades get distinct keys", () => {+ expect(gradeKey({ contrast: 10 })).not.toBe(gradeKey({ contrast: 11 }));+ expect(gradeKey({ preset: { id: "mono" } })).not.toBe(gradeKey({ preset: { id: "silver" } }));+ });+});++describe("buildGradeLut", () => {+ test("neutral grade builds no LUT", () => {+ expect(buildGradeLut(undefined)).toBe(null);+ expect(buildGradeLut({ contrast: 0 })).toBe(null);+ });++ test("an identity-adjacent grade stays near identity through the LUT", () => {+ const lut = buildGradeLut({ curves: { m: [[0, 1], [128, 128], [255, 255]] } })!;+ const data = px([0, 0, 0], [128, 128, 128], [255, 255, 255], [200, 40, 90]);+ const before = [...data];+ applyLutToImageData(data, lut);+ for (let i = 0; i < data.length; i++) {+ expect(Math.abs(data[i] - before[i])).toBeLessThanOrEqual(3);+ }+ });++ test("LUT application agrees with the direct transform", () => {+ const grade: ColorGrade = {+ contrast: 20,+ exposure: 8,+ shadows: 12,+ curves: { m: [[0, 20], [128, 118], [255, 250]] },+ hsl: { blue: [10, 20, -8] },+ };+ const lut = buildGradeLut(grade)!;+ const transform = createGradeTransform(grade)!;+ const samples: [number, number, number][] = [+ [12, 40, 200],+ [128, 128, 128],+ [240, 180, 60],+ [70, 160, 90],+ ];+ const data = px(...samples);+ applyLutToImageData(data, lut);+ samples.forEach(([r, g, b], i) => {+ const direct = transform(r / 255, g / 255, b / 255);+ for (let c = 0; c < 3; c++) {+ // Tetrahedral interpolation over a 33³ lattice of a smooth transform+ // lands within a few 8-bit steps of the exact evaluation.+ expect(Math.abs(data[i * 4 + c] - direct[c] * 255)).toBeLessThanOrEqual(4);+ }+ });+ });++ test("fast-path scalar fields match the LUT within quantization", () => {+ // gain + contrast are the exact fast-path formulas; a LUT-only render of+ // them must agree with the direct math.+ const grade: ColorGrade = { exposure: 10, contrast: 15, brightness: 5 };+ const transform = createGradeTransform(grade)!;+ const gain = (1 + 5 / 100) * Math.pow(2, 10 / 50);+ const c = 1 + 15 / 100;+ for (const v of [0.1, 0.4, 0.7]) {+ const expected = Math.min(1, Math.max(0, (Math.min(1, v * gain) - 0.5) * c + 0.5));+ const got = transform(v, v, v);+ for (let ch = 0; ch < 3; ch++) expect(Math.abs(got[ch] - expected)).toBeLessThan(1e-6);+ }+ });+});++describe("lutToCube", () => {+ test("serializes header and every node", () => {+ const lut = buildGradeLut({ contrast: 20 }, 5)!;+ const cube = lutToCube(lut);+ expect(cube).toContain("LUT_3D_SIZE 5");+ const rows = cube.trim().split("\n").filter((l) => /^[0-9]/.test(l));+ expect(rows.length).toBe(125);+ expect(rows[0].split(" ").length).toBe(3);+ });+});++describe("intensity", () => {+ test("scaling toward neutral is monotone", () => {+ const grade: ColorGrade = {+ contrast: 30,+ temperature: 20,+ curves: { m: [[0, 40], [255, 255]] },+ wheels: { s: [20, 10, 5] },+ hsl: { red: [10, 20, 0] },+ };+ const v: [number, number, number] = [0.3, 0.5, 0.6];+ const full = createGradeTransform(grade)!(...v);+ const half = createGradeTransform(scaleGradeToward(grade, 0.5))!(...v);+ const zeroish = createGradeTransform(scaleGradeToward(grade, 0.001));+ for (let c = 0; c < 3; c++) {+ const dFull = Math.abs(full[c] - v[c]);+ const dHalf = Math.abs(half[c] - v[c]);+ expect(dHalf).toBeLessThanOrEqual(dFull + 1e-6);+ }+ if (zeroish) {+ const out = zeroish(...v);+ for (let c = 0; c < 3; c++) expect(Math.abs(out[c] - v[c])).toBeLessThan(0.01);+ }+ });+});++describe("skin protection", () => {+ test("skin weight peaks on warm skin hues and dies on gray and neon", () => {+ expect(skinWeight(25, 0.3)).toBeGreaterThan(0.9);+ expect(skinWeight(25, 0.01)).toBe(0);+ expect(skinWeight(25, 0.95)).toBe(0);+ expect(skinWeight(220, 0.3)).toBe(0);+ });++ test("a skin-flagged preset damps color shifts on skin but grades the rest", () => {+ const grade: ColorGrade = { preset: { id: "teal-orange", skin: true } };+ const plain: ColorGrade = { preset: { id: "teal-orange" } };+ // A skin tone: warm orange, mid saturation.+ const skin: [number, number, number] = [0.8, 0.55, 0.42];+ const sky: [number, number, number] = [0.4, 0.6, 0.85];+ const withSkin = createGradeTransform(grade)!(...skin);+ const noSkin = createGradeTransform(plain)!(...skin);+ const dWith = Math.hypot(withSkin[0] - skin[0], withSkin[1] - skin[1], withSkin[2] - skin[2]);+ const dWithout = Math.hypot(noSkin[0] - skin[0], noSkin[1] - skin[1], noSkin[2] - skin[2]);+ expect(dWith).toBeLessThan(dWithout);+ // Non-skin pixels still take the full grade.+ const skySkin = createGradeTransform(grade)!(...sky);+ const skyPlain = createGradeTransform(plain)!(...sky);+ for (let c = 0; c < 3; c++) expect(Math.abs(skySkin[c] - skyPlain[c])).toBeLessThan(0.02);+ });+});++describe("gradeNeedsLut", () => {+ test("legacy scalar grades keep the fast path", () => {+ expect(gradeNeedsLut({ brightness: 10, contrast: -5, hue: 90, temperature: 20 })).toBe(false);+ expect(gradeNeedsLut({ tint: 10 })).toBe(false);+ });++ test("new primitives take the LUT path", () => {+ expect(gradeNeedsLut({ highlights: 5 })).toBe(true);+ expect(gradeNeedsLut({ curves: { m: [[0, 10], [255, 255]] } })).toBe(true);+ expect(gradeNeedsLut({ preset: { id: "mono" } })).toBe(true);+ });++ test("a preset turned all the way down stays applied and renders neutral", () => {+ // Intensity 0 keeps the pick (the tile stays selected, the slider can ride+ // back up) while costing the renderer nothing.+ const g = normalizeGrade({ preset: { id: "mono", amount: 0 } })!;+ expect(g.preset).toEqual({ id: "mono", amount: 0 });+ expect(gradeNeedsLut(g)).toBe(false);+ expect(buildGradeLut(g)).toBe(null);+ });+});++describe("curveLut", () => {+ test("monotone through control points without overshoot", () => {+ const lut = curveLut([+ [0, 0],+ [64, 32],+ [192, 224],+ [255, 255],+ ]);+ expect(lut[0]).toBeCloseTo(0, 3);+ expect(lut[64]).toBeCloseTo(32 / 255, 2);+ expect(lut[255]).toBeCloseTo(1, 3);+ for (let i = 1; i < 256; i++) expect(lut[i]).toBeGreaterThanOrEqual(lut[i - 1] - 1e-6);+ });+});diff --git a/site/packages/effects-kit/src/gradeLut.ts b/site/packages/effects-kit/src/gradeLut.tsnew file mode 100644index 00000000..5459d923--- /dev/null+++ b/site/packages/effects-kit/src/gradeLut.ts@@ -0,0 +1,143 @@+/**+ * The 3D LUT every renderer shares. buildGradeLut samples gradeMath's+ * transform onto a cubic lattice; ffmpeg consumes it as a .cube file+ * (lut3d, tetrahedral), the preview's WebGL pass uploads it as a 3D+ * texture, and headless export applies it on the CPU. All three+ * interpolate tetrahedrally so they agree to within 8-bit quantization.+ */++import type { ColorGrade } from "./colorGrade";+import { normalizeGrade } from "./colorGrade";+import { createGradeTransform } from "./gradeMath";++export interface GradeLut {+ /** Lattice nodes per axis. */+ size: number;+ /** RGB triples, red axis fastest: index = ((b*size + g)*size + r) * 3. */+ data: Float32Array;+}++export const GRADE_LUT_SIZE = 33;++/** A stable identity for a grade's rendered result: normalized, key-sorted+ * JSON. Two grades with the same key produce the same LUT. */+export function gradeKey(g: ColorGrade | undefined | null): string {+ const n = normalizeGrade(g);+ if (!n) return "";+ const sort = (v: unknown): unknown => {+ if (Array.isArray(v)) return v.map(sort);+ if (v && typeof v === "object") {+ const out: Record<string, unknown> = {};+ for (const k of Object.keys(v).sort()) out[k] = sort((v as Record<string, unknown>)[k]);+ return out;+ }+ return v;+ };+ return JSON.stringify(sort(n));+}++/** Sample the grade's transform onto the lattice. Returns null for a grade+ * that resolves to neutral. */+export function buildGradeLut(+ g: ColorGrade | undefined | null,+ size = GRADE_LUT_SIZE+): GradeLut | null {+ const transform = createGradeTransform(g);+ if (!transform) return null;+ const data = new Float32Array(size * size * size * 3);+ const step = 1 / (size - 1);+ let i = 0;+ for (let b = 0; b < size; b++) {+ for (let gg = 0; gg < size; gg++) {+ for (let r = 0; r < size; r++) {+ const out = transform(r * step, gg * step, b * step);+ data[i++] = out[0];+ data[i++] = out[1];+ data[i++] = out[2];+ }+ }+ }+ return { size, data };+}++/** Serialize to the .cube text ffmpeg's lut3d reads. */+export function lutToCube(lut: GradeLut, title = "Donkey Cut grade"): string {+ const lines: string[] = [`TITLE "${title}"`, `LUT_3D_SIZE ${lut.size}`, ""];+ const n = lut.size * lut.size * lut.size;+ for (let i = 0; i < n; i++) {+ const o = i * 3;+ lines.push(+ `${lut.data[o].toFixed(6)} ${lut.data[o + 1].toFixed(6)} ${lut.data[o + 2].toFixed(6)}`+ );+ }+ return lines.join("\n") + "\n";+}++/**+ * Apply the LUT to RGBA pixels in place with tetrahedral interpolation —+ * the same scheme ffmpeg's lut3d defaults to. Alpha passes through.+ */+export function applyLutToImageData(px: Uint8ClampedArray, lut: GradeLut): void {+ const { size, data } = lut;+ const scale = (size - 1) / 255;+ const s2 = size * size;+ for (let i = 0; i < px.length; i += 4) {+ const rf = px[i] * scale;+ const gf = px[i + 1] * scale;+ const bf = px[i + 2] * scale;+ let r0 = Math.floor(rf);+ let g0 = Math.floor(gf);+ let b0 = Math.floor(bf);+ if (r0 >= size - 1) r0 = size - 2;+ if (g0 >= size - 1) g0 = size - 2;+ if (b0 >= size - 1) b0 = size - 2;+ const dr = rf - r0;+ const dg = gf - g0;+ const db = bf - b0;+ const base = (b0 * s2 + g0 * size + r0) * 3;+ const R = 3;+ const G = size * 3;+ const B = s2 * 3;+ // Tetrahedral: pick the tetrahedron of the unit cube containing (dr,dg,db)+ // and blend its four lattice corners.+ const c0 = base;+ let w1: number;+ let w2: number;+ let w3: number;+ let o1: number;+ let o2: number;+ let o3: number;+ if (dr >= dg) {+ if (dg >= db) {+ w1 = dr - dg; w2 = dg - db; w3 = db;+ o1 = R; o2 = R + G; o3 = R + G + B;+ } else if (dr >= db) {+ w1 = dr - db; w2 = db - dg; w3 = dg;+ o1 = R; o2 = R + B; o3 = R + G + B;+ } else {+ w1 = db - dr; w2 = dr - dg; w3 = dg;+ o1 = B; o2 = R + B; o3 = R + G + B;+ }+ } else {+ if (db >= dg) {+ w1 = db - dg; w2 = dg - dr; w3 = dr;+ o1 = B; o2 = G + B; o3 = R + G + B;+ } else if (db >= dr) {+ w1 = dg - db; w2 = db - dr; w3 = dr;+ o1 = G; o2 = G + B; o3 = R + G + B;+ } else {+ w1 = dg - dr; w2 = dr - db; w3 = db;+ o1 = G; o2 = R + G; o3 = R + G + B;+ }+ }+ const w0 = 1 - w1 - w2 - w3;+ for (let c = 0; c < 3; c++) {+ const v =+ w0 * data[c0 + c] ++ w1 * data[c0 + o1 + c] ++ w2 * data[c0 + o2 + c] ++ w3 * data[c0 + o3 + c];+ px[i + c] = Math.max(0, Math.min(255, Math.round(v * 255)));+ }+ }+}diff --git a/site/packages/effects-kit/src/gradeMatch.test.ts b/site/packages/effects-kit/src/gradeMatch.test.tsnew file mode 100644index 00000000..d908cfd8--- /dev/null+++ b/site/packages/effects-kit/src/gradeMatch.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from "bun:test";+import { createGradeTransform } from "./gradeMath";+import { colorStatsFromImageData, matchGrade } from "./gradeMatch";++/** A synthetic frame with tonal and color variety. */+function testFrame(): Uint8ClampedArray {+ const w = 64;+ const h = 64;+ const data = new Uint8ClampedArray(w * h * 4);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const o = (y * w + x) * 4;+ data[o] = Math.round((x / (w - 1)) * 255);+ data[o + 1] = Math.round((y / (h - 1)) * 255);+ data[o + 2] = Math.round(((x + y) / (w + h - 2)) * 200 + 20);+ data[o + 3] = 255;+ }+ }+ return data;+}++function graded(data: Uint8ClampedArray, f: (v: number, c: number) => number): Uint8ClampedArray {+ const out = new Uint8ClampedArray(data.length);+ for (let i = 0; i < data.length; i += 4) {+ for (let c = 0; c < 3; c++) out[i + c] = Math.max(0, Math.min(255, Math.round(f(data[i + c], c))));+ out[i + 3] = data[i + 3];+ }+ return out;+}++describe("matchGrade", () => {+ test("a frame matched to itself is neutral", () => {+ const stats = colorStatsFromImageData(testFrame())!;+ expect(matchGrade(stats, stats)).toBeUndefined();+ });++ test("recovers a known channel shift within tolerance", () => {+ const src = testFrame();+ // Warm the reference: red up, blue down — a temperature-like cast.+ const ref = graded(src, (v, c) => (c === 0 ? v * 1.18 : c === 2 ? v * 0.85 : v));+ const srcStats = colorStatsFromImageData(src)!;+ const refStats = colorStatsFromImageData(ref)!;+ const grade = matchGrade(srcStats, refStats);+ expect(grade !== undefined).toBe(true);+ const transform = createGradeTransform(grade)!;+ // Apply the match and compare channel means against the reference.+ let mr = 0;+ let mg = 0;+ let mb = 0;+ let n = 0;+ for (let i = 0; i < src.length; i += 4) {+ const [r, g, b] = transform(src[i] / 255, src[i + 1] / 255, src[i + 2] / 255);+ mr += r * 255;+ mg += g * 255;+ mb += b * 255;+ n++;+ }+ mr /= n;+ mg /= n;+ mb /= n;+ expect(Math.abs(mr - refStats.meanR)).toBeLessThan(10);+ expect(Math.abs(mg - refStats.meanG)).toBeLessThan(10);+ expect(Math.abs(mb - refStats.meanB)).toBeLessThan(10);+ });++ test("matched curves reach both ends of the range", () => {+ const src = testFrame();+ const ref = graded(src, (v, c) => (c === 0 ? v * 1.18 : c === 2 ? v * 0.85 : v));+ const grade = matchGrade(colorStatsFromImageData(src)!, colorStatsFromImageData(ref)!)!;+ // The spline holds flat past its end points, so a curve stopping at the+ // p2/p98 probes would flatten the darkest and brightest pixels.+ for (const ch of ["r", "g", "b"] as const) {+ const pts = grade.curves?.[ch];+ if (!pts) continue;+ expect(pts[0][0]).toBe(0);+ expect(pts[pts.length - 1][0]).toBe(255);+ for (let i = 1; i < pts.length; i++) {+ expect(pts[i][0]).toBeGreaterThan(pts[i - 1][0]);+ expect(pts[i][1]).toBeGreaterThanOrEqual(pts[i - 1][1]);+ }+ }+ });++ test("stats expose warmth and saturation for the assistant", () => {+ const stats = colorStatsFromImageData(testFrame())!;+ expect(stats.meanSat).toBeGreaterThan(0);+ expect(stats.warmth).toBeGreaterThan(0);+ expect(stats.luma.length).toBe(7);+ });+});diff --git a/site/packages/effects-kit/src/gradeMatch.ts b/site/packages/effects-kit/src/gradeMatch.tsnew file mode 100644index 00000000..cb204378--- /dev/null+++ b/site/packages/effects-kit/src/gradeMatch.ts@@ -0,0 +1,143 @@+/**+ * Reference matching: read color statistics off two frames and compute the+ * grade that carries one onto the other. The match is per-channel quantile+ * mapping compiled into tone-curve control points — the same curves the+ * panel edits — plus a saturation delta, so the result is an ordinary+ * ColorGrade the user (or the assistant) can refine afterward.+ */++import { type ColorGrade, type CurvePoint, GRADE_MAX, normalizeGrade } from "./colorGrade";++/** Quantile probes used by stats and matching. */+export const STAT_QUANTILES = [0.02, 0.1, 0.25, 0.5, 0.75, 0.9, 0.98] as const;++export interface ColorStats {+ /** Per-channel values 0..255 at each STAT_QUANTILES probe. */+ r: number[];+ g: number[];+ b: number[];+ luma: number[];+ /** Channel means 0..255. */+ meanR: number;+ meanG: number;+ meanB: number;+ /** Mean HSL saturation 0..1. */+ meanSat: number;+ /** Red/blue mean ratio in the midtones; >1 reads warm, <1 reads cool. */+ warmth: number;+}++export function colorStatsFromImageData(data: Uint8ClampedArray): ColorStats | undefined {+ const hist = [new Float64Array(256), new Float64Array(256), new Float64Array(256), new Float64Array(256)];+ let count = 0;+ let sumR = 0;+ let sumG = 0;+ let sumB = 0;+ let sumSat = 0;+ let midR = 0;+ let midB = 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[0][r]++;+ hist[1][g]++;+ hist[2][b]++;+ hist[3][Math.min(255, Math.round(luma))]++;+ sumR += r;+ sumG += g;+ sumB += b;+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l2 = max + min;+ sumSat += max === min ? 0 : (max - min) / (l2 <= 255 ? l2 : 510 - l2);+ if (luma >= 16 && luma <= 240) {+ midR += r;+ midB += b;+ mids++;+ }+ count++;+ }+ if (!count) return undefined;+ const quantiles = (h: Float64Array) =>+ STAT_QUANTILES.map((p) => {+ let acc = 0;+ for (let v = 0; v < 256; v++) {+ acc += h[v];+ if (acc >= count * p) return v;+ }+ return 255;+ });+ return {+ r: quantiles(hist[0]),+ g: quantiles(hist[1]),+ b: quantiles(hist[2]),+ luma: quantiles(hist[3]),+ meanR: sumR / count,+ meanG: sumG / count,+ meanB: sumB / count,+ meanSat: sumSat / count,+ warmth: mids ? midR / Math.max(1, midB) : 1,+ };+}++function quantileCurve(src: number[], ref: number[]): CurvePoint[] | undefined {+ const pts: CurvePoint[] = [];+ let lastX = -1;+ for (let i = 0; i < src.length; i++) {+ const x = Math.round(src[i]);+ const y = Math.round(ref[i]);+ if (x <= lastX) continue;+ pts.push([x, y]);+ lastX = x;+ }+ // Monotone outputs keep the compiled spline monotone.+ for (let i = 1; i < pts.length; i++) {+ if (pts[i][1] < pts[i - 1][1]) pts[i][1] = pts[i - 1][1];+ }+ if (pts.length < 2 || pts.every(([x, y]) => Math.abs(x - y) <= 2)) return undefined;+ // The spline holds flat outside its end points, so a curve that stops at the+ // p2/p98 probes would crush everything darker and brighter into those two+ // values. Carry the end segments' slopes out to 0 and 255 instead, keeping+ // the shadow and specular separation the reference has.+ const [x0, y0] = pts[0];+ const [x1, y1] = pts[1];+ const [xa, ya] = pts[pts.length - 2];+ const [xb, yb] = pts[pts.length - 1];+ if (xb < 255) {+ const slope = (yb - ya) / Math.max(1, xb - xa);+ pts.push([255, Math.round(Math.min(255, Math.max(yb, yb + slope * (255 - xb))))]);+ }+ if (x0 > 0) {+ const slope = (y1 - y0) / Math.max(1, x1 - x0);+ pts.unshift([0, Math.round(Math.max(0, Math.min(y0, y0 - slope * x0)))]);+ }+ return pts;+}++/**+ * Compute the grade that moves `source` toward `reference`: per-channel+ * quantile curves plus a saturation delta. Returns undefined when the frames+ * already agree.+ */+export function matchGrade(source: ColorStats, reference: ColorStats): ColorGrade | undefined {+ const grade: ColorGrade = {};+ const r = quantileCurve(source.r, reference.r);+ const g = quantileCurve(source.g, reference.g);+ const b = quantileCurve(source.b, reference.b);+ if (r || g || b) {+ grade.curves = {};+ if (r) grade.curves.r = r;+ if (g) grade.curves.g = g;+ if (b) grade.curves.b = b;+ }+ if (source.meanSat > 0.01) {+ const delta = Math.round((reference.meanSat / source.meanSat - 1) * GRADE_MAX);+ if (Math.abs(delta) >= 2) {+ grade.saturation = Math.max(-GRADE_MAX, Math.min(GRADE_MAX, delta));+ }+ }+ return normalizeGrade(grade);+}diff --git a/site/packages/effects-kit/src/gradeMath.ts b/site/packages/effects-kit/src/gradeMath.tsnew file mode 100644index 00000000..dff739e1--- /dev/null+++ b/site/packages/effects-kit/src/gradeMath.ts@@ -0,0 +1,509 @@+/**+ * The extended grade's pixel math: one pure transform [0,1]³ → [0,1]³ that+ * every renderer consumes through the 3D LUT in gradeLut.ts. A grade resolves+ * to at most two layers — the preset (scaled by its amount, optionally kept+ * off skin tones) and the manual adjustments on top — and each layer applies+ * its stages in one canonical order:+ *+ * gain → contrast → wheels → highlights/shadows → curves → cast tint →+ * HSL (global hue/saturation, vibrance, feathered hue bands) → clamp+ *+ * The tonal stages reuse the exact fast-path formulas from colorGrade.ts, so+ * a scalar grade evaluated through the LUT lands on the fast path's result to+ * within quantization.+ */++import {+ type ColorGrade,+ type CurvePoint,+ type GradePresetRef,+ type HslBand,+ GRADE_MAX,+ HSL_BANDS,+ deriveGrade,+ gradeTint,+ gradeToCssFilter,+ isNeutralGrade,+ normalizeGrade,+} from "./colorGrade";+import { GRADE_PRESETS } from "./gradePresets";++const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);+const luma = (r: number, g: number, b: number) => 0.2126 * r + 0.7152 * g + 0.0722 * b;++/* ------------------------------------------------------------------ */+/* Monotone tone curves */+/* ------------------------------------------------------------------ */++/**+ * Sample a control-point curve into a 256-entry LUT over [0,1] using the+ * Fritsch–Carlson monotone cubic — smooth through every point, no overshoot.+ * The curve holds flat outside its first and last points.+ */+export function curveLut(points: CurvePoint[]): Float32Array {+ const n = points.length;+ const xs = points.map((p) => p[0] / 255);+ const ys = points.map((p) => p[1] / 255);+ const out = new Float32Array(256);+ if (n === 1) {+ out.fill(clamp01(ys[0] ?? 0));+ return out;+ }+ const h: number[] = [];+ const d: number[] = [];+ for (let i = 0; i < n - 1; i++) {+ const dx = Math.max(1e-6, xs[i + 1] - xs[i]);+ h.push(dx);+ d.push((ys[i + 1] - ys[i]) / dx);+ }+ const m: number[] = [d[0]];+ for (let i = 1; i < n - 1; i++) {+ m.push(d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2);+ }+ m.push(d[n - 2]);+ for (let i = 0; i < n - 1; i++) {+ if (d[i] === 0) {+ m[i] = 0;+ m[i + 1] = 0;+ continue;+ }+ const a = m[i] / d[i];+ const b = m[i + 1] / d[i];+ const s = a * a + b * b;+ if (s > 9) {+ const t = 3 / Math.sqrt(s);+ m[i] = t * a * d[i];+ m[i + 1] = t * b * d[i];+ }+ }+ for (let s = 0; s < 256; s++) {+ const x = s / 255;+ if (x <= xs[0]) {+ out[s] = clamp01(ys[0]);+ continue;+ }+ if (x >= xs[n - 1]) {+ out[s] = clamp01(ys[n - 1]);+ continue;+ }+ let i = 0;+ while (i < n - 2 && x > xs[i + 1]) i++;+ const t = (x - xs[i]) / h[i];+ const t2 = t * t;+ const t3 = t2 * t;+ out[s] =+ clamp01(+ ys[i] * (2 * t3 - 3 * t2 + 1) ++ h[i] * m[i] * (t3 - 2 * t2 + t) ++ ys[i + 1] * (-2 * t3 + 3 * t2) ++ h[i] * m[i + 1] * (t3 - t2)+ );+ }+ return out;+}++const sampleCurve = (lut: Float32Array, v: number) => {+ const x = clamp01(v) * 255;+ const i = Math.floor(x);+ const f = x - i;+ return i >= 255 ? lut[255] : lut[i] * (1 - f) + lut[i + 1] * f;+};++/* ------------------------------------------------------------------ */+/* Semantic curve helpers (chat tools compile to real control points) */+/* ------------------------------------------------------------------ */++/**+ * Build master-curve control points from two semantic knobs: `contrast`+ * (-50..50, an s-curve around mid-gray) and `fade` (0..50, lifted blacks).+ * Returns undefined when both are neutral.+ */+export function semanticMasterCurve(contrast: number, fade: number): CurvePoint[] | undefined {+ const c = Math.max(-GRADE_MAX, Math.min(GRADE_MAX, contrast || 0)) / GRADE_MAX;+ const f = Math.max(0, Math.min(GRADE_MAX, fade || 0)) / GRADE_MAX;+ if (!c && !f) return undefined;+ const bend = Math.round(c * 28);+ const lift = Math.round(f * 56);+ const pts: CurvePoint[] = [+ [0, lift],+ [64, Math.max(0, Math.min(255, 64 - bend + Math.round(lift * 0.4)))],+ [192, Math.max(0, Math.min(255, 192 + bend))],+ [255, 255],+ ];+ return pts;+}++/* ------------------------------------------------------------------ */+/* Color space */+/* ------------------------------------------------------------------ */++function rgbToHsl(r: number, g: number, b: number): [number, number, number] {+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ const d = max - min;+ if (d < 1e-6) return [0, 0, l];+ const s = d / (1 - Math.abs(2 * l - 1) || 1e-6);+ let h: number;+ if (max === r) h = ((g - b) / d) % 6;+ else if (max === g) h = (b - r) / d + 2;+ else h = (r - g) / d + 4;+ h *= 60;+ if (h < 0) h += 360;+ return [h, Math.min(1, s), l];+}++function hslToRgb(h: number, s: number, l: number): [number, number, number] {+ const c = (1 - Math.abs(2 * l - 1)) * s;+ const hp = (((h % 360) + 360) % 360) / 60;+ const x = c * (1 - Math.abs((hp % 2) - 1));+ let r = 0;+ let g = 0;+ let b = 0;+ if (hp < 1) [r, g, b] = [c, x, 0];+ else if (hp < 2) [r, g, b] = [x, c, 0];+ else if (hp < 3) [r, g, b] = [0, c, x];+ else if (hp < 4) [r, g, b] = [0, x, c];+ else if (hp < 5) [r, g, b] = [x, 0, c];+ else [r, g, b] = [c, 0, x];+ const m = l - c / 2;+ return [r + m, g + m, b + m];+}++const smoothstep = (a: number, b: number, x: number) => {+ const t = clamp01((x - a) / (b - a || 1e-6));+ return t * t * (3 - 2 * t);+};++const hueDist = (a: number, b: number) => {+ const d = Math.abs(((a - b) % 360) + 360) % 360;+ return d > 180 ? 360 - d : d;+};++/** How strongly a pixel reads as skin: a feathered hue window around warm+ * orange, gated to plausibly-skin saturation. Used to keep a preset's color+ * shifts off faces when its `skin` flag is set. */+export function skinWeight(hueDeg: number, sat: number): number {+ const d = hueDist(hueDeg, 25);+ const hueW = d <= 12 ? 1 : 1 - smoothstep(12, 28, d);+ const satW = smoothstep(0.05, 0.15, sat) * (1 - smoothstep(0.55, 0.78, sat));+ return hueW * satW;+}++/** Feathered partition-of-unity weight of a hue band at a given hue: 1 at the+ * band's center, ramping linearly to 0 at each neighbor's center. */+export function hueBandWeight(hueDeg: number, band: HslBand): number {+ const idx = HSL_BANDS.findIndex((b) => b.id === band);+ if (idx < 0) return 0;+ const c = HSL_BANDS[idx].center;+ const prev = HSL_BANDS[(idx + HSL_BANDS.length - 1) % HSL_BANDS.length].center;+ const next = HSL_BANDS[(idx + 1) % HSL_BANDS.length].center;+ const h = ((hueDeg % 360) + 360) % 360;+ const span = (from: number, to: number) => (((to - from) % 360) + 360) % 360;+ const up = span(prev, c) || 360;+ const down = span(c, next) || 360;+ const fromPrev = span(prev, h);+ if (fromPrev <= up) return fromPrev / up;+ const fromC = span(c, h);+ if (fromC <= down) return 1 - fromC / down;+ return 0;+}++/* ------------------------------------------------------------------ */+/* Preset resolution */+/* ------------------------------------------------------------------ */++/** Scale a grade's every parameter toward neutral: scalars and tuples by t,+ * curve points toward the identity diagonal. Values go fractional — this+ * shape feeds the transform, never the doc. */+export function scaleGradeToward(g: ColorGrade, t: number): ColorGrade {+ if (t >= 1) return g;+ const out: ColorGrade = {};+ for (const k of [+ "brightness",+ "contrast",+ "saturation",+ "exposure",+ "temperature",+ "tint",+ "hue",+ "highlights",+ "shadows",+ "vibrance",+ ] as const) {+ const v = g[k];+ if (v) out[k] = v * t;+ }+ if (g.curves) {+ const curves: NonNullable<ColorGrade["curves"]> = {};+ for (const ch of ["m", "r", "g", "b"] as const) {+ const pts = g.curves[ch];+ if (pts) curves[ch] = pts.map(([x, y]) => [x, x + (y - x) * t] as CurvePoint);+ }+ out.curves = curves;+ }+ if (g.wheels) {+ const wheels: NonNullable<ColorGrade["wheels"]> = {};+ for (const z of ["s", "m", "h"] as const) {+ const w = g.wheels[z];+ if (w) wheels[z] = [w[0] * t, w[1] * t, w[2] * t];+ }+ out.wheels = wheels;+ }+ if (g.hsl) {+ const hsl: NonNullable<ColorGrade["hsl"]> = {};+ for (const band of HSL_BANDS) {+ const v = g.hsl[band.id];+ if (v) hsl[band.id] = [v[0] * t, v[1] * t, v[2] * t];+ }+ out.hsl = hsl;+ }+ return out;+}++/** Look up a preset ref in the catalog and scale it by its amount. Unknown+ * ids resolve to nothing, so docs from newer catalogs render ungraded. */+export function resolvePreset(ref: GradePresetRef | undefined): ColorGrade | undefined {+ if (!ref?.id) return undefined;+ const preset = GRADE_PRESETS[ref.id];+ if (!preset) return undefined;+ const amount = typeof ref.amount === "number" ? Math.max(0, Math.min(1, ref.amount)) : 1;+ if (amount <= 0) return undefined;+ return scaleGradeToward(preset.grade, amount);+}++/* ------------------------------------------------------------------ */+/* The transform */+/* ------------------------------------------------------------------ */++interface Layer {+ gain: number;+ contrast: number;+ saturate: number;+ hue: number;+ tint: { r: number; g: number; b: number } | null;+ highlights: number;+ shadows: number;+ vibrance: number;+ curves: { m?: Float32Array; r?: Float32Array; g?: Float32Array; b?: Float32Array } | null;+ wheels: { zone: "s" | "m" | "h"; chroma: [number, number, number]; luma: number }[];+ bands: { band: HslBand; hueShift: number; sat: number; lum: number }[];+ skinDamp: boolean;+}++function buildLayer(g: ColorGrade, skinDamp: boolean): Layer | null {+ const d = deriveGrade(g);+ const layer: Layer = {+ gain: d.gain,+ contrast: d.contrast,+ saturate: d.saturate,+ hue: d.hue,+ tint: d.tint,+ highlights: (g.highlights || 0) / GRADE_MAX,+ shadows: (g.shadows || 0) / GRADE_MAX,+ vibrance: (g.vibrance || 0) / GRADE_MAX,+ curves: null,+ wheels: [],+ bands: [],+ skinDamp,+ };+ if (g.curves) {+ layer.curves = {};+ for (const ch of ["m", "r", "g", "b"] as const) {+ const pts = g.curves[ch];+ if (pts && pts.length >= 2) layer.curves[ch] = curveLut(pts);+ }+ if (!Object.keys(layer.curves).length) layer.curves = null;+ }+ if (g.wheels) {+ for (const zone of ["s", "m", "h"] as const) {+ const w = g.wheels[zone];+ if (!w || (!w[0] && !w[1] && !w[2])) continue;+ const radius = Math.min(1, Math.hypot(w[0], w[1]) / GRADE_MAX);+ let chroma: [number, number, number] = [0, 0, 0];+ if (radius > 0) {+ const hue = ((Math.atan2(w[1], w[0]) * 180) / Math.PI + 360) % 360;+ const p = hslToRgb(hue, 1, 0.5);+ const mean = (p[0] + p[1] + p[2]) / 3;+ chroma = [+ (p[0] - mean) * radius * 0.35,+ (p[1] - mean) * radius * 0.35,+ (p[2] - mean) * radius * 0.35,+ ];+ }+ layer.wheels.push({ zone, chroma, luma: (w[2] / GRADE_MAX) * 0.25 });+ }+ }+ if (g.hsl) {+ for (const band of HSL_BANDS) {+ const t = g.hsl[band.id];+ if (!t || (!t[0] && !t[1] && !t[2])) continue;+ layer.bands.push({+ band: band.id,+ hueShift: (t[0] / GRADE_MAX) * 30,+ sat: t[1] / GRADE_MAX,+ lum: t[2] / GRADE_MAX,+ });+ }+ }+ const active =+ layer.gain !== 1 ||+ layer.contrast !== 1 ||+ layer.saturate !== 1 ||+ layer.hue !== 0 ||+ layer.tint !== null ||+ layer.highlights !== 0 ||+ layer.shadows !== 0 ||+ layer.vibrance !== 0 ||+ layer.curves !== null ||+ layer.wheels.length > 0 ||+ layer.bands.length > 0;+ return active ? layer : null;+}++function applyLayer(v: [number, number, number], L: Layer, skinW: number): void {+ const chromaScale = L.skinDamp ? 1 - skinW : 1;+ // Tonal: the fast path's exact gain + mid-gray contrast, clipped like the+ // combined lutrgb expression.+ for (let c = 0; c < 3; c++) {+ v[c] = clamp01((clamp01(v[c] * L.gain) - 0.5) * L.contrast + 0.5);+ }+ if (L.wheels.length) {+ const Y = luma(v[0], v[1], v[2]);+ const wS = (1 - Y) * (1 - Y);+ const wH = Y * Y;+ const wM = Math.max(0, 1 - wS - wH);+ for (const w of L.wheels) {+ const weight = w.zone === "s" ? wS : w.zone === "h" ? wH : wM;+ if (weight <= 0) continue;+ for (let c = 0; c < 3; c++) {+ const shift = w.chroma[c] * chromaScale + w.luma;+ if (w.zone === "s") v[c] += shift * weight;+ else if (w.zone === "h") v[c] *= 1 + shift * weight;+ else v[c] = Math.pow(clamp01(v[c]), 1 / Math.max(0.2, 1 + shift * weight * 1.5));+ }+ }+ for (let c = 0; c < 3; c++) v[c] = clamp01(v[c]);+ }+ if (L.highlights || L.shadows) {+ const Y = luma(v[0], v[1], v[2]);+ const sh = L.shadows * 0.3 * (1 - Y) * (1 - Y);+ const hi = L.highlights * 0.3 * Y * Y;+ for (let c = 0; c < 3; c++) v[c] = clamp01(v[c] + sh + hi);+ }+ if (L.curves) {+ for (let c = 0; c < 3; c++) {+ let x = v[c];+ if (L.curves.m) x = sampleCurve(L.curves.m, x);+ const ch = c === 0 ? L.curves.r : c === 1 ? L.curves.g : L.curves.b;+ if (ch) x = sampleCurve(ch, x);+ v[c] = x;+ }+ }+ if (L.tint) {+ v[0] = clamp01(v[0] * (1 + (L.tint.r - 1) * chromaScale));+ v[1] = clamp01(v[1] * (1 + (L.tint.g - 1) * chromaScale));+ v[2] = clamp01(v[2] * (1 + (L.tint.b - 1) * chromaScale));+ }+ const needsHslStage =+ L.hue !== 0 || L.saturate !== 1 || L.vibrance !== 0 || L.bands.length > 0;+ if (needsHslStage) {+ let [h, s, l] = rgbToHsl(v[0], v[1], v[2]);+ const entryHue = h;+ if (L.hue) h += L.hue * chromaScale;+ if (L.saturate !== 1) s *= 1 + (L.saturate - 1) * chromaScale;+ if (L.vibrance) s += L.vibrance * 0.8 * s * (1 - s) * chromaScale;+ for (const b of L.bands) {+ const w = hueBandWeight(entryHue, b.band);+ if (w <= 0) continue;+ h += b.hueShift * w * chromaScale;+ s *= 1 + b.sat * w * chromaScale;+ l *= 1 + b.lum * 0.5 * w;+ }+ const rgb = hslToRgb(h, clamp01(s), clamp01(l));+ v[0] = clamp01(rgb[0]);+ v[1] = clamp01(rgb[1]);+ v[2] = clamp01(rgb[2]);+ }+}++export type GradeTransform = (r: number, g: number, b: number) => [number, number, number];++/**+ * Compile a grade into the pure pixel transform. Values are gamma-encoded+ * BT.709 RGB in [0,1]. Returns null for a neutral grade.+ */+export function createGradeTransform(g: ColorGrade | undefined | null): GradeTransform | null {+ const n = normalizeGrade(g);+ if (!n) return null;+ const layers: Layer[] = [];+ const presetGrade = resolvePreset(n.preset);+ if (presetGrade) {+ const layer = buildLayer(presetGrade, !!n.preset?.skin);+ if (layer) layers.push(layer);+ }+ const manual: ColorGrade = { ...n };+ delete manual.preset;+ const manualLayer = buildLayer(manual, false);+ if (manualLayer) layers.push(manualLayer);+ if (!layers.length) return null;+ const anySkin = layers.some((l) => l.skinDamp);+ return (r, g2, b) => {+ const v: [number, number, number] = [clamp01(r), clamp01(g2), clamp01(b)];+ let skinW = 0;+ if (anySkin) {+ const [h, s] = rgbToHsl(v[0], v[1], v[2]);+ skinW = skinWeight(h, s);+ }+ for (const layer of layers) applyLayer(v, layer, skinW);+ return v;+ };+}++/* ------------------------------------------------------------------ */+/* Filmstrip approximation */+/* ------------------------------------------------------------------ */++/**+ * A DOM-CSS approximation of the whole grade for tiny always-on surfaces+ * (timeline filmstrips, preset tiles). Exact for the fast-path scalars with+ * the preset's scalars folded in by its amount; highlights/shadows and+ * vibrance become small brightness/contrast/saturation nudges; curves,+ * wheels, and hue bands are left out by design — the preview canvas and+ * exports render them for real.+ */+export function gradeCssApprox(+ g: ColorGrade | undefined | null+): { filter: string; tint: string | null } {+ const n = normalizeGrade(g);+ if (!n) return { filter: "", tint: null };+ const presetGrade = resolvePreset(n.preset);+ const eff: ColorGrade = {};+ const keys = [+ "brightness",+ "contrast",+ "saturation",+ "exposure",+ "temperature",+ "tint",+ "hue",+ "highlights",+ "shadows",+ "vibrance",+ ] as const;+ for (const k of keys) {+ const v = (presetGrade?.[k] || 0) + (n[k] || 0);+ if (v) eff[k] = v;+ }+ const approx: ColorGrade = {+ brightness: (eff.brightness || 0) + ((eff.shadows || 0) + (eff.highlights || 0)) * 0.2,+ contrast: (eff.contrast || 0) + ((eff.highlights || 0) - (eff.shadows || 0)) * 0.15,+ saturation: (eff.saturation || 0) + (eff.vibrance || 0) * 0.5,+ exposure: eff.exposure,+ temperature: eff.temperature,+ tint: eff.tint,+ hue: eff.hue,+ };+ if (isNeutralGrade(approx)) return { filter: "", tint: null };+ return { filter: gradeToCssFilter(approx), tint: gradeTint(approx) };+}diff --git a/site/packages/effects-kit/src/gradePresets.test.ts b/site/packages/effects-kit/src/gradePresets.test.tsnew file mode 100644index 00000000..89de6214--- /dev/null+++ b/site/packages/effects-kit/src/gradePresets.test.ts@@ -0,0 +1,84 @@+import { describe, expect, test } from "bun:test";+import { normalizeGrade } from "./colorGrade";+import { EFFECT_LABELS } from "./effects";+import { LOOK_LABELS } from "./looks";+import {+ GRADE_PRESET_CATEGORIES,+ GRADE_PRESET_IDS,+ GRADE_PRESET_PARSE_ERRORS,+ GRADE_PRESETS,+ gradePresetCatalogText,+ gradePresetsInCategory,+ parseGradePresets,+} from "./gradePresets";++describe("shipped catalog", () => {+ test("every shipped JSON entry parses", () => {+ expect(GRADE_PRESET_PARSE_ERRORS).toEqual([]);+ });++ test("ids are unique", () => {+ expect(new Set(GRADE_PRESET_IDS).size).toBe(GRADE_PRESET_IDS.length);+ });++ test("every category ships 6 to 10 presets", () => {+ for (const cat of GRADE_PRESET_CATEGORIES) {+ const n = gradePresetsInCategory(cat.id).length;+ expect(n).toBeGreaterThanOrEqual(6);+ expect(n).toBeLessThanOrEqual(10);+ }+ });++ test("labels collide with no effect or look label", () => {+ const taken = new Set(+ [...Object.values(EFFECT_LABELS), ...Object.values(LOOK_LABELS)].map((l) =>+ l.toLowerCase()+ )+ );+ for (const id of GRADE_PRESET_IDS) {+ expect(taken.has(GRADE_PRESETS[id].label.toLowerCase())).toBe(false);+ }+ });++ test("every recipe is already in range: normalize is a no-op", () => {+ for (const id of GRADE_PRESET_IDS) {+ const grade = GRADE_PRESETS[id].grade;+ expect(normalizeGrade(grade)).toEqual(grade);+ }+ });++ test("catalog text names every category and preset id", () => {+ const text = gradePresetCatalogText();+ for (const cat of GRADE_PRESET_CATEGORIES) expect(text).toContain(cat.label);+ for (const id of GRADE_PRESET_IDS) expect(text).toContain(id);+ });+});++describe("parseGradePresets", () => {+ test("rejects a non-array with a reason", () => {+ const { presets, errors } = parseGradePresets({ id: "x" });+ expect(presets).toEqual([]);+ expect(errors.length).toBe(1);+ });++ test("rejects bad entries individually and keeps good ones", () => {+ const { presets, errors } = parseGradePresets([+ { id: "good-one", label: "Good One", category: "mood", grade: { contrast: 10 } },+ { id: "Bad Id", label: "X", category: "mood", grade: { contrast: 10 } },+ { id: "no-label", label: "", category: "mood", grade: { contrast: 10 } },+ { id: "bad-cat", label: "X", category: "sparkle", grade: { contrast: 10 } },+ { id: "neutral", label: "X", category: "mood", grade: { contrast: 0 } },+ { id: "nested", label: "X", category: "mood", grade: { preset: { id: "mono" } } },+ { id: "good-one", label: "Duplicate", category: "mood", grade: { contrast: 5 } },+ ]);+ expect(presets.map((p) => p.id)).toEqual(["good-one"]);+ expect(errors.length).toBe(6);+ });++ test("recipes are normalized on the way in", () => {+ const { presets } = parseGradePresets([+ { id: "clamped", label: "Clamped", category: "warm", grade: { temperature: 999, tint: 0 } },+ ]);+ expect(presets[0].grade).toEqual({ temperature: 50 });+ });+});diff --git a/site/packages/effects-kit/src/gradePresets.ts b/site/packages/effects-kit/src/gradePresets.tsnew file mode 100644index 00000000..f6cd04ac--- /dev/null+++ b/site/packages/effects-kit/src/gradePresets.ts@@ -0,0 +1,123 @@+/**+ * The color preset catalog: JSON configs the grading engine interprets. Each+ * preset is a named ColorGrade recipe; a clip stores only the preset's id+ * (plus amount and the skin flag), and the renderer expands it through+ * gradeMath. The JSON files beside this one under presets/ are the shipped+ * catalog; parseGradePresets is the one doorway for that data, so a grade a+ * user imports or shares later travels as the same document and enters+ * through the same validation.+ */++import { type ColorGrade, normalizeGrade } from "./colorGrade";+import cinematic from "./presets/cinematic.json";+import film from "./presets/film.json";+import warm from "./presets/warm.json";+import mood from "./presets/mood.json";+import bw from "./presets/bw.json";++export type GradePresetCategory = "cinematic" | "film" | "warm" | "mood" | "bw";++export const GRADE_PRESET_CATEGORIES: { id: GradePresetCategory; label: string }[] = [+ { id: "cinematic", label: "Cinematic" },+ { id: "film", label: "Film" },+ { id: "warm", label: "Warm" },+ { id: "mood", label: "Mood" },+ { id: "bw", label: "B&W" },+];++export interface GradePreset {+ id: string;+ label: string;+ category: GradePresetCategory;+ grade: ColorGrade;+}++const CATEGORY_IDS = new Set(GRADE_PRESET_CATEGORIES.map((c) => c.id));++/**+ * Interpret preset JSON. Every entry is checked structurally and its recipe+ * run through normalizeGrade; a bad entry is rejected with a reason and never+ * partially applied. Recipes may not nest a preset reference.+ */+export function parseGradePresets(json: unknown): { presets: GradePreset[]; errors: string[] } {+ const presets: GradePreset[] = [];+ const errors: string[] = [];+ if (!Array.isArray(json)) {+ return { presets, errors: ["preset config must be a JSON array"] };+ }+ const seen = new Set<string>();+ json.forEach((entry, i) => {+ const at = `entry ${i}`;+ if (!entry || typeof entry !== "object") {+ errors.push(`${at}: not an object`);+ return;+ }+ const e = entry as Record<string, unknown>;+ const id = e.id;+ if (typeof id !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(id)) {+ errors.push(`${at}: id must be a kebab-case string`);+ return;+ }+ if (seen.has(id)) {+ errors.push(`${at}: duplicate id "${id}"`);+ return;+ }+ if (typeof e.label !== "string" || !e.label.trim()) {+ errors.push(`"${id}": label must be a non-empty string`);+ return;+ }+ if (typeof e.category !== "string" || !CATEGORY_IDS.has(e.category as GradePresetCategory)) {+ errors.push(`"${id}": category must be one of ${[...CATEGORY_IDS].join(", ")}`);+ return;+ }+ if (!e.grade || typeof e.grade !== "object") {+ errors.push(`"${id}": grade must be an object`);+ return;+ }+ if ((e.grade as ColorGrade).preset) {+ errors.push(`"${id}": a preset recipe cannot reference another preset`);+ return;+ }+ const grade = normalizeGrade(e.grade as ColorGrade);+ if (!grade) {+ errors.push(`"${id}": grade is neutral or carries no known fields`);+ return;+ }+ seen.add(id);+ presets.push({+ id,+ label: e.label.trim(),+ category: e.category as GradePresetCategory,+ grade,+ });+ });+ return { presets, errors };+}++const shipped = parseGradePresets([...cinematic, ...film, ...warm, ...mood, ...bw]);++/** The shipped catalog, by id. A unit test holds the JSON files to zero+ * parse errors; at runtime bad entries are simply absent. */+export const GRADE_PRESETS: Record<string, GradePreset> = Object.fromEntries(+ shipped.presets.map((p) => [p.id, p])+);++export const GRADE_PRESET_IDS: string[] = shipped.presets.map((p) => p.id);++/** Parse errors from the shipped JSON, surfaced for the catalog test. */+export const GRADE_PRESET_PARSE_ERRORS: string[] = shipped.errors;++export function gradePresetsInCategory(category: GradePresetCategory): GradePreset[] {+ return shipped.presets.filter((p) => p.category === category);+}++/** One line per category, for the AI tool description: the catalog teaches+ * itself from the JSON. */+export function gradePresetCatalogText(): string {+ return GRADE_PRESET_CATEGORIES.map(+ (c) =>+ `${c.label}: ${gradePresetsInCategory(c.id)+ .map((p) => `${p.id} (${p.label})`)+ .join(", ")}`+ ).join("; ");+}diff --git a/site/packages/effects-kit/src/index.ts b/site/packages/effects-kit/src/index.tsindex c6c8dc1a..4beb512e 100644--- a/site/packages/effects-kit/src/index.ts+++ b/site/packages/effects-kit/src/index.ts@@ -11,4 +11,8 @@ export * from "./cutout";export * from "./lottie";export * from "./looks";export * from "./colorGrade";+export * from "./gradeMath";+export * from "./gradeLut";+export * from "./gradePresets";+export * from "./gradeMatch";export * from "./effects";diff --git a/site/packages/effects-kit/src/presets/bw.json b/site/packages/effects-kit/src/presets/bw.jsonnew file mode 100644index 00000000..fb8ef58b--- /dev/null+++ b/site/packages/effects-kit/src/presets/bw.json@@ -0,0 +1,90 @@+[+ {+ "id": "mono",+ "label": "Mono",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "contrast": 10+ }+ },+ {+ "id": "silver",+ "label": "Silver",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "contrast": -4,+ "exposure": 6,+ "shadows": 8,+ "highlights": -4+ }+ },+ {+ "id": "ink",+ "label": "Ink",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "contrast": 24,+ "shadows": -10+ }+ },+ {+ "id": "high-key",+ "label": "High Key",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "exposure": 10,+ "contrast": -6,+ "shadows": 10,+ "highlights": -2+ }+ },+ {+ "id": "low-key",+ "label": "Low Key",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "exposure": -8,+ "contrast": 16,+ "shadows": -10,+ "highlights": -4+ }+ },+ {+ "id": "charcoal",+ "label": "Charcoal",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "contrast": 6,+ "curves": { "m": [[0, 16], [128, 120], [255, 240]] }+ }+ },+ {+ "id": "soft-mono",+ "label": "Soft Mono",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "contrast": -10,+ "exposure": 3,+ "curves": { "m": [[0, 12], [255, 244]] }+ }+ },+ {+ "id": "grit",+ "label": "Grit",+ "category": "bw",+ "grade": {+ "saturation": -50,+ "contrast": 20,+ "exposure": -2,+ "shadows": -6,+ "highlights": 6+ }+ }+]diff --git a/site/packages/effects-kit/src/presets/cinematic.json b/site/packages/effects-kit/src/presets/cinematic.jsonnew file mode 100644index 00000000..ae41e686--- /dev/null+++ b/site/packages/effects-kit/src/presets/cinematic.json@@ -0,0 +1,97 @@+[+ {+ "id": "teal-orange",+ "label": "Teal & Orange",+ "category": "cinematic",+ "grade": {+ "contrast": 10,+ "vibrance": 10,+ "saturation": 6,+ "wheels": { "s": [-22, 0, 0], "h": [12, 7, 0] }+ }+ },+ {+ "id": "bleach-bypass",+ "label": "Bleach Bypass",+ "category": "cinematic",+ "grade": {+ "contrast": 22,+ "saturation": -30,+ "highlights": -6,+ "shadows": -8+ }+ },+ {+ "id": "matinee",+ "label": "Matinee",+ "category": "cinematic",+ "grade": {+ "exposure": 3,+ "contrast": 8,+ "temperature": 4,+ "saturation": 18,+ "vibrance": 8+ }+ },+ {+ "id": "thriller",+ "label": "Thriller",+ "category": "cinematic",+ "grade": {+ "temperature": -14,+ "contrast": 16,+ "shadows": -10,+ "saturation": -10,+ "wheels": { "s": [-8, -14, 0] }+ }+ },+ {+ "id": "night-market",+ "label": "Night Market",+ "category": "cinematic",+ "grade": {+ "temperature": -6,+ "tint": 8,+ "contrast": 10,+ "shadows": 6,+ "vibrance": 16,+ "hsl": { "magenta": [0, 12, 4], "aqua": [0, 10, 0] }+ }+ },+ {+ "id": "sci-fi",+ "label": "Sci-Fi",+ "category": "cinematic",+ "grade": {+ "temperature": -18,+ "tint": -8,+ "contrast": 12,+ "saturation": -6,+ "highlights": -4+ }+ },+ {+ "id": "western",+ "label": "Western",+ "category": "cinematic",+ "grade": {+ "temperature": 16,+ "tint": 4,+ "contrast": 6,+ "shadows": 4,+ "saturation": -4,+ "hsl": { "green": [-10, -25, -4] }+ }+ },+ {+ "id": "indie",+ "label": "Indie",+ "category": "cinematic",+ "grade": {+ "temperature": 3,+ "contrast": -4,+ "saturation": -12,+ "curves": { "m": [[0, 18], [128, 128], [255, 244]] }+ }+ }+]diff --git a/site/packages/effects-kit/src/presets/film.json b/site/packages/effects-kit/src/presets/film.jsonnew file mode 100644index 00000000..eff41739--- /dev/null+++ b/site/packages/effects-kit/src/presets/film.json@@ -0,0 +1,97 @@+[+ {+ "id": "super-8",+ "label": "Super 8",+ "category": "film",+ "grade": {+ "temperature": 14,+ "tint": -3,+ "contrast": 8,+ "saturation": -6,+ "shadows": 8,+ "curves": { "m": [[0, 12], [255, 246]] }+ }+ },+ {+ "id": "faded-film",+ "label": "Faded Film",+ "category": "film",+ "grade": {+ "contrast": -6,+ "saturation": -14,+ "curves": { "m": [[0, 26], [64, 74], [255, 235]] }+ }+ },+ {+ "id": "chrome",+ "label": "Chrome",+ "category": "film",+ "grade": {+ "contrast": 14,+ "saturation": 14,+ "vibrance": 6,+ "highlights": -6,+ "temperature": 2+ }+ },+ {+ "id": "push-process",+ "label": "Push Process",+ "category": "film",+ "grade": {+ "exposure": 4,+ "contrast": 18,+ "saturation": -8,+ "shadows": -6+ }+ },+ {+ "id": "cine-print",+ "label": "Cine Print",+ "category": "film",+ "grade": {+ "contrast": 10,+ "saturation": 4,+ "wheels": { "s": [-10, -6, 0], "m": [8, 4, 0] },+ "curves": { "m": [[0, 10], [192, 198], [255, 248]] }+ }+ },+ {+ "id": "tungsten",+ "label": "Tungsten",+ "category": "film",+ "grade": {+ "temperature": 20,+ "tint": 2,+ "shadows": 4,+ "contrast": 6,+ "vibrance": 4+ }+ },+ {+ "id": "instant",+ "label": "Instant",+ "category": "film",+ "grade": {+ "exposure": 6,+ "contrast": -8,+ "temperature": 5,+ "tint": 6,+ "saturation": -10,+ "curves": { "m": [[0, 20], [255, 240]] }+ }+ },+ {+ "id": "expired",+ "label": "Expired",+ "category": "film",+ "grade": {+ "tint": -12,+ "temperature": 6,+ "saturation": -16,+ "contrast": -4,+ "hsl": { "yellow": [8, -10, 0] },+ "curves": { "m": [[0, 14], [255, 240]] }+ }+ }+]diff --git a/site/packages/effects-kit/src/presets/mood.json b/site/packages/effects-kit/src/presets/mood.jsonnew file mode 100644index 00000000..015cca4a--- /dev/null+++ b/site/packages/effects-kit/src/presets/mood.json@@ -0,0 +1,102 @@+[+ {+ "id": "midnight",+ "label": "Midnight",+ "category": "mood",+ "grade": {+ "exposure": -8,+ "temperature": -12,+ "contrast": 12,+ "saturation": -12,+ "shadows": -6,+ "wheels": { "s": [-8, -12, 0] }+ }+ },+ {+ "id": "moss",+ "label": "Moss",+ "category": "mood",+ "grade": {+ "tint": -14,+ "temperature": 4,+ "saturation": -8,+ "contrast": 6,+ "hsl": { "green": [0, 8, 0] }+ }+ },+ {+ "id": "slate",+ "label": "Slate",+ "category": "mood",+ "grade": {+ "temperature": -8,+ "tint": -2,+ "saturation": -20,+ "contrast": 8+ }+ },+ {+ "id": "dusk",+ "label": "Dusk",+ "category": "mood",+ "grade": {+ "temperature": -4,+ "tint": 8,+ "exposure": -3,+ "contrast": 4,+ "vibrance": 8,+ "wheels": { "h": [6, -10, 0] }+ }+ },+ {+ "id": "neon",+ "label": "Neon",+ "category": "mood",+ "grade": {+ "vibrance": 22,+ "contrast": 10,+ "saturation": 10,+ "temperature": -6,+ "tint": 10+ }+ },+ {+ "id": "arctic",+ "label": "Arctic",+ "category": "mood",+ "grade": {+ "temperature": -20,+ "tint": -2,+ "exposure": 2,+ "contrast": 6,+ "saturation": -6,+ "highlights": 4+ }+ },+ {+ "id": "storm",+ "label": "Storm",+ "category": "mood",+ "grade": {+ "temperature": -10,+ "contrast": 14,+ "saturation": -16,+ "exposure": -4,+ "shadows": -8+ }+ },+ {+ "id": "velvet",+ "label": "Velvet",+ "category": "mood",+ "grade": {+ "contrast": 10,+ "exposure": -4,+ "saturation": 12,+ "temperature": 4,+ "tint": 6,+ "shadows": -6,+ "curves": { "m": [[0, 6], [64, 56], [255, 252]] }+ }+ }+]diff --git a/site/packages/effects-kit/src/presets/warm.json b/site/packages/effects-kit/src/presets/warm.jsonnew file mode 100644index 00000000..9007a5ef--- /dev/null+++ b/site/packages/effects-kit/src/presets/warm.json@@ -0,0 +1,101 @@+[+ {+ "id": "golden-hour",+ "label": "Golden Hour",+ "category": "warm",+ "grade": {+ "exposure": 6,+ "temperature": 18,+ "tint": 3,+ "contrast": 4,+ "highlights": -6,+ "vibrance": 10,+ "hsl": { "orange": [0, 10, 4] }+ }+ },+ {+ "id": "amber",+ "label": "Amber",+ "category": "warm",+ "grade": {+ "temperature": 22,+ "tint": 2,+ "contrast": 6,+ "shadows": 6,+ "saturation": 4+ }+ },+ {+ "id": "honey",+ "label": "Honey",+ "category": "warm",+ "grade": {+ "temperature": 14,+ "tint": 6,+ "exposure": 4,+ "contrast": -2,+ "vibrance": 8,+ "highlights": -4+ }+ },+ {+ "id": "sunbaked",+ "label": "Sunbaked",+ "category": "warm",+ "grade": {+ "temperature": 16,+ "contrast": 10,+ "saturation": -8,+ "highlights": -10,+ "shadows": -4+ }+ },+ {+ "id": "peach",+ "label": "Peach",+ "category": "warm",+ "grade": {+ "temperature": 10,+ "tint": 8,+ "exposure": 5,+ "saturation": 6,+ "contrast": -4,+ "curves": { "m": [[0, 10], [255, 250]] }+ }+ },+ {+ "id": "sepia",+ "label": "Sepia",+ "category": "warm",+ "grade": {+ "temperature": 30,+ "tint": 4,+ "saturation": -35,+ "contrast": 4+ }+ },+ {+ "id": "ember",+ "label": "Ember",+ "category": "warm",+ "grade": {+ "temperature": 24,+ "shadows": -8,+ "contrast": 12,+ "vibrance": 6,+ "hsl": { "red": [0, 12, 0] }+ }+ },+ {+ "id": "bronze",+ "label": "Bronze",+ "category": "warm",+ "grade": {+ "temperature": 18,+ "tint": -4,+ "contrast": 8,+ "saturation": -6,+ "wheels": { "m": [10, 5, 0] }+ }+ }+]diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex eb1a22a8..c8a647fd 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -53,7 +53,7 @@ import { EFFECT_LABELS } from "@donkeycut/effects-kit";import { emptySubtitles, IMAGE_CLIP_SECONDS, SHAPE_LABELS, TRANSITION_DEFAULT_SECONDS, TRANSITION_MAX, TRANSITION_STYLE_LABELS, type ShapeKind } from "@/cut/lib/types";import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionStyle, VideoClip } from "@/cut/lib/types";import { isLottieAsset } from "@/cut/lib/lottieAssets";-import { gradeTint, gradeToCssFilter } from "@donkeycut/effects-kit";+import { gradeCssApprox } from "@donkeycut/effects-kit";import { cn } from "@/lib/utils";const TRANSITION_ICONS: Record<TransitionStyle, LucideIcon> = {@@ -4090,7 +4090,10 @@ function Filmstrip({* element burns paint time for the life of the timeline. */failed?: boolean;}) {- const tint = gradeTint(grade);+ // The filmstrip is a 40px always-on surface: the grade renders as a CSS+ // approximation (exact for the scalar sliders and the preset's scalars;+ // curves/wheels/hue bands show in the preview and exports).+ const { filter, tint } = gradeCssApprox(grade);// No thumbs yet — the media is still streaming into the browser store. A// pulsing skeleton fills the box until the strip can draw real frames.if (!frames.length) {@@ -4106,7 +4109,7 @@ function Filmstrip({return (<divclassName="tl-filmstrip pointer-events-none absolute inset-0 isolate"- style={{ filter: gradeToCssFilter(grade) || undefined }}+ style={{ filter: filter || undefined }}>{frames.map((f, k) => (// eslint-disable-next-line @next/next/no-img-elementdiff --git a/site/src/cut/lib/composite.ts b/site/src/cut/lib/composite.tsindex 330f930d..7e1ddffe 100644--- a/site/src/cut/lib/composite.ts+++ b/site/src/cut/lib/composite.ts@@ -19,7 +19,8 @@* it was reached by playing there or by rendering the 135th frame.*/-import { applyMaskToCanvas, gradeTint, gradeToCssFilter, grainTile, isNeutralGrade, lookCssFilter, lookPost, maskComposite } from "@donkeycut/effects-kit";+import { applyLutToImageData, applyMaskToCanvas, buildGradeLut, gradeKey, gradeNeedsLut, gradeTint, gradeToCssFilter, grainTile, isNeutralGrade, lookCssFilter, lookPost, maskComposite, type GradeLut } from "@donkeycut/effects-kit";+import { applyLutGpu } from "./gradeGpu";import { createRasterCanvas } from "./raster";import { clipCovers, clipPosed, clipPoseAt, clipZoom, contentRect, DEFAULT_BACKGROUND, isFullRect, rectOf, shadowInk } from "./types";import type { ClipShadow, FrameRect, TransitionStyle, VideoClip } from "./types";@@ -65,12 +66,63 @@ type Ctx = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;/** The grain tile advances on this cadence, in seconds per step. */const GRAIN_STEP = 0.08;+/** Compiled grade LUTs, shared across compositors and rebuilt only when a+ * grade actually changes. A cut rarely holds more than a handful of distinct+ * grades at once; the cap just bounds a long editing session. */+const lutCache = new Map<string, GradeLut | null>();+const LUT_CACHE_MAX = 24;++/** What a grade object means to the renderer, memoized on the object itself.+ * Every store edit hands out a fresh grade, so identity is a safe key — and+ * the reads that decide the path (neutral? LUT? which LUT?) each normalize the+ * grade, which is far too much allocation to repeat per clip per frame. */+interface GradeFacts {+ neutral: boolean;+ needsLut: boolean;+ key: string;+}+const gradeFacts = new WeakMap<object, GradeFacts>();++function factsFor(grade: VideoClip["grade"]): GradeFacts | null {+ if (!grade) return null;+ let facts = gradeFacts.get(grade);+ if (!facts) {+ facts = {+ neutral: isNeutralGrade(grade),+ needsLut: gradeNeedsLut(grade),+ key: gradeKey(grade) ?? "",+ };+ gradeFacts.set(grade, facts);+ }+ return facts;+}++function lutForGrade(grade: VideoClip["grade"], key: string): { lut: GradeLut; key: string } | null {+ if (!key) return null;+ if (lutCache.has(key)) {+ const hit = lutCache.get(key)!;+ // Re-insert so the cap evicts the least recently used grade, never one the+ // cut is still playing.+ lutCache.delete(key);+ lutCache.set(key, hit);+ return hit ? { lut: hit, key } : null;+ }+ const lut = buildGradeLut(grade);+ if (lutCache.size >= LUT_CACHE_MAX) {+ const oldest = lutCache.keys().next().value;+ if (oldest !== undefined) lutCache.delete(oldest);+ }+ lutCache.set(key, lut);+ return lut ? { lut, key } : null;+}+export class FrameCompositor {/** Scratch buffers, kept for the compositor's life: the grade pass, the* look's self-copy passes, and the vignette gradient. Allocating these per* frame is the difference between a preview that holds 60fps and one that* fights the garbage collector. */private gradeCanvas: Surface | null = null;+ private gradeLutScratch: Surface | null = null;private lookScratch: Surface | null = null;private vignetteCanvas: Surface | null = null;/** The masked/keyframed-layer pass: the layer draws into `layerScratch`,@@ -124,6 +176,7 @@ export class FrameCompositor {private scratch(field:| "gradeCanvas"+ | "gradeLutScratch"| "lookScratch"| "vignetteCanvas"| "layerScratch"@@ -195,8 +248,9 @@ export class FrameCompositor {clip: VideoClip | undefined): CanvasImageSource {const grade = clip?.grade;+ const facts = factsFor(grade);const lookCss = lookCssFilter(clip?.look, clip?.lookAmount);- if (isNeutralGrade(grade) && !lookCss) return frame.image;+ if ((!facts || facts.neutral) && !lookCss) return frame.image;const w = frame.width;const h = frame.height;const { surface: scratch } = this.scratch("gradeCanvas", w, h);@@ -205,6 +259,35 @@ export class FrameCompositor {// half-applying the tint.if (!ctx || !("filter" in ctx)) return frame.image;ctx.clearRect(0, 0, w, h);+ if (facts?.needsLut) {+ const compiled = lutForGrade(grade, facts.key);+ if (compiled) {+ // The LUT carries the whole grade (preset, curves, wheels, HSL and+ // the scalar sliders); the look's color pass still applies after it,+ // keeping the export's grade-before-look order.+ const gpu = applyLutGpu(frame.image, w, h, compiled.lut, compiled.key);+ if (gpu) {+ ctx.filter = lookCss || "none";+ ctx.drawImage(gpu as CanvasImageSource, 0, 0, w, h);+ ctx.filter = "none";+ } else {+ const { surface: pixels } = this.scratch("gradeLutScratch", w, h);+ const pctx = pixels.getContext("2d") as Ctx | null;+ if (!pctx) return frame.image;+ pctx.clearRect(0, 0, w, h);+ pctx.drawImage(frame.image, 0, 0, w, h);+ const img = pctx.getImageData(0, 0, w, h);+ applyLutToImageData(img.data, compiled.lut);+ pctx.putImageData(img, 0, 0);+ ctx.filter = lookCss || "none";+ ctx.drawImage(pixels, 0, 0, w, h);+ ctx.filter = "none";+ }+ return scratch;+ }+ // A grade whose LUT resolves neutral (an unknown preset id alone)+ // falls through to the fast path for whatever scalars remain.+ }ctx.filter = [gradeToCssFilter(grade), lookCss].filter(Boolean).join(" ") || "none";ctx.drawImage(frame.image, 0, 0, w, h);ctx.filter = "none";diff --git a/site/src/cut/lib/gradeGpu.ts b/site/src/cut/lib/gradeGpu.tsnew file mode 100644index 00000000..dd4d51d7--- /dev/null+++ b/site/src/cut/lib/gradeGpu.ts@@ -0,0 +1,195 @@+/**+ * GPU application of the grade LUT for the preview and in-tab export: the+ * clip's frame renders through a WebGL2 pass that samples the shared 3D LUT+ * with the same tetrahedral scheme ffmpeg's lut3d and the CPU fallback use.+ * The canvas comes from the raster seam; under a headless factory WebGL2 is+ * absent and callers fall back to applyLutToImageData.+ */++import type { GradeLut } from "@donkeycut/effects-kit";+import { createRasterCanvas, type RasterSurface } from "./raster";++const VERT = `#version 300 es+in vec2 aPos;+out vec2 vUv;+void main() {+ vUv = aPos * 0.5 + 0.5;+ gl_Position = vec4(aPos, 0.0, 1.0);+}`;++const FRAG = `#version 300 es+precision highp float;+precision highp sampler3D;+uniform sampler2D uSrc;+uniform sampler3D uLut;+uniform float uSize;+in vec2 vUv;+out vec4 outColor;++vec3 lutAt(ivec3 p) { return texelFetch(uLut, p, 0).rgb; }++void main() {+ vec4 s = texture(uSrc, vUv);+ float n = uSize - 1.0;+ vec3 p = clamp(s.rgb, 0.0, 1.0) * n;+ ivec3 i0 = ivec3(min(floor(p), vec3(uSize - 2.0)));+ vec3 d = p - vec3(i0);+ // Tetrahedral interpolation, matching the CPU pass and ffmpeg's default.+ ivec3 o1; ivec3 o2; float w1; float w2; float w3;+ if (d.r >= d.g) {+ if (d.g >= d.b) { o1 = ivec3(1,0,0); o2 = ivec3(1,1,0); w1 = d.r-d.g; w2 = d.g-d.b; w3 = d.b; }+ else if (d.r >= d.b) { o1 = ivec3(1,0,0); o2 = ivec3(1,0,1); w1 = d.r-d.b; w2 = d.b-d.g; w3 = d.g; }+ else { o1 = ivec3(0,0,1); o2 = ivec3(1,0,1); w1 = d.b-d.r; w2 = d.r-d.g; w3 = d.g; }+ } else {+ if (d.b >= d.g) { o1 = ivec3(0,0,1); o2 = ivec3(0,1,1); w1 = d.b-d.g; w2 = d.g-d.r; w3 = d.r; }+ else if (d.b >= d.r) { o1 = ivec3(0,1,0); o2 = ivec3(0,1,1); w1 = d.g-d.b; w2 = d.b-d.r; w3 = d.r; }+ else { o1 = ivec3(0,1,0); o2 = ivec3(1,1,0); w1 = d.g-d.r; w2 = d.r-d.b; w3 = d.b; }+ }+ float w0 = 1.0 - w1 - w2 - w3;+ vec3 rgb = w0 * lutAt(i0)+ + w1 * lutAt(i0 + o1)+ + w2 * lutAt(i0 + o2)+ + w3 * lutAt(i0 + ivec3(1,1,1));+ outColor = vec4(rgb, s.a);+}`;++interface GpuState {+ canvas: RasterSurface;+ gl: WebGL2RenderingContext;+ program: WebGLProgram;+ srcTex: WebGLTexture;+ sizeLoc: WebGLUniformLocation;+ /** One uploaded texture per grade, so two graded clips in the same frame+ * take turns binding instead of re-uploading 33³ floats twice a frame. */+ luts: Map<string, WebGLTexture>;+}++/** Uploaded LUT textures kept at once; a 33³ RGBA32F texture is ~0.6MB. */+const LUT_TEXTURE_MAX = 6;++let state: GpuState | null | false = null;++function init(): GpuState | false {+ const canvas = createRasterCanvas(2, 2);+ const gl = (canvas.getContext as (id: string, opts?: unknown) => unknown)("webgl2", {+ premultipliedAlpha: false,+ preserveDrawingBuffer: true,+ }) as WebGL2RenderingContext | null;+ if (!gl) return false;+ const compile = (type: number, src: string) => {+ const sh = gl.createShader(type)!;+ gl.shaderSource(sh, src);+ gl.compileShader(sh);+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) return null;+ return sh;+ };+ const vs = compile(gl.VERTEX_SHADER, VERT);+ const fs = compile(gl.FRAGMENT_SHADER, FRAG);+ if (!vs || !fs) return false;+ const program = gl.createProgram()!;+ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return false;+ gl.useProgram(program);+ const buf = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);+ const posLoc = gl.getAttribLocation(program, "aPos");+ gl.enableVertexAttribArray(posLoc);+ gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);+ const srcTex = gl.createTexture()!;+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, srcTex);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.uniform1i(gl.getUniformLocation(program, "uSrc"), 0);+ gl.uniform1i(gl.getUniformLocation(program, "uLut"), 1);+ const sizeLoc = gl.getUniformLocation(program, "uSize");+ if (!sizeLoc) return false;+ return { canvas, gl, program, srcTex, sizeLoc, luts: new Map() };+}++/** Bind the LUT's texture, uploading it the first time this grade is seen. */+function bindLut(s: GpuState, lut: GradeLut, key: string): void {+ const { gl } = s;+ gl.activeTexture(gl.TEXTURE1);+ const held = s.luts.get(key);+ if (held) {+ gl.bindTexture(gl.TEXTURE_3D, held);+ // Re-insert so the cap drops the grade least recently drawn.+ s.luts.delete(key);+ s.luts.set(key, held);+ return;+ }+ const tex = gl.createTexture()!;+ gl.bindTexture(gl.TEXTURE_3D, tex);+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE);+ const n = lut.size * lut.size * lut.size;+ const rgba = new Float32Array(n * 4);+ for (let i = 0; i < n; i++) {+ rgba[i * 4] = lut.data[i * 3];+ rgba[i * 4 + 1] = lut.data[i * 3 + 1];+ rgba[i * 4 + 2] = lut.data[i * 3 + 2];+ rgba[i * 4 + 3] = 1;+ }+ gl.texImage3D(gl.TEXTURE_3D, 0, gl.RGBA32F, lut.size, lut.size, lut.size, 0, gl.RGBA, gl.FLOAT, rgba);+ s.luts.set(key, tex);+ if (s.luts.size > LUT_TEXTURE_MAX) {+ const oldest = s.luts.keys().next().value;+ if (oldest !== undefined && oldest !== key) {+ const stale = s.luts.get(oldest);+ if (stale) gl.deleteTexture(stale);+ s.luts.delete(oldest);+ }+ }+}++/**+ * Render `source` through the LUT and return a canvas holding the result, or+ * null when WebGL2 is unavailable (headless) — callers then use the CPU pass.+ * The returned canvas is shared and valid until the next call.+ */+export function applyLutGpu(+ source: CanvasImageSource,+ w: number,+ h: number,+ lut: GradeLut,+ key: string+): RasterSurface | null {+ if (state === false) return null;+ if (!state) {+ try {+ state = init();+ } catch {+ state = false;+ }+ if (!state) return null;+ }+ const s = state;+ const { gl } = s;+ try {+ if (s.canvas.width !== w || s.canvas.height !== h) {+ s.canvas.width = w;+ s.canvas.height = h;+ }+ bindLut(s, lut, key);+ gl.viewport(0, 0, w, h);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, s.srcTex);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source as TexImageSource);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.uniform1f(s.sizeLoc, lut.size);+ gl.drawArrays(gl.TRIANGLES, 0, 3);+ return s.canvas;+ } catch {+ return null;+ }+}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 2736c1e6..8481e641 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -531,8 +531,8 @@ export interface VideoClip {// Color grading (the dual-renderer math) lives in the effects kit; the model// types and ranges re-export here so doc-model consumers keep one import.-export { GRADE_HUE_MAX, GRADE_MAX } from "@donkeycut/effects-kit";-export type { ColorGrade } from "@donkeycut/effects-kit";+export { GRADE_BASIC_FIELDS, GRADE_HUE_MAX, GRADE_MAX, HSL_BANDS } from "@donkeycut/effects-kit";+export type { ColorGrade, GradePresetRef, HslBand } from "@donkeycut/effects-kit";/** 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. */@@ -763,6 +763,12 @@ export const transitionStyleOfAnim = (style: AnimStyle): TransitionStyle =>// Looks (dual preview/export recipes) live in the effects kit; the ids and// labels re-export here so doc-model consumers keep one import.export { LOOK_IDS, LOOK_LABELS } from "@donkeycut/effects-kit";+export {+ GRADE_PRESET_CATEGORIES,+ GRADE_PRESET_IDS,+ GRADE_PRESETS,+} from "@donkeycut/effects-kit";+export type { GradePreset, GradePresetCategory } from "@donkeycut/effects-kit";export type { LookStyle } from "@donkeycut/effects-kit";/** Migrate docs saved before per-clip animations existed: the retired edgediff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex 592421c2..8318eafb 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -4,7 +4,7 @@ import path from "node:path";import { atempoChain, hasStream, num, videoColorInfo } from "./util";import { assertGraphSafe, fexpr } from "./filterGraph";import { CLIP_MAX_ZOOM, projectFadeSeconds, regionPx, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";-import { effectFilterLines, gradeToFfmpegFilter, lookFilterLines, shortestTurn, sortedKeys, type OverlayKey } from "@donkeycut/effects-kit";+import { buildGradeLut, effectFilterLines, gradeKey, gradeNeedsLut, gradeToFfmpegFilter, lookFilterLines, lutToCube, shortestTurn, sortedKeys, type OverlayKey } from "@donkeycut/effects-kit";// The render pipeline itself: spec in, finished mp4 out. Shared by the local// engine's job registry (jobs.ts) and the cloud render worker, which stage@@ -666,6 +666,30 @@ export async function runExport(const filters: string[] = [];+ // Grades that use the extended primitives (curves, wheels, HSL, presets…)+ // bake through the shared 3D LUT: one .cube per distinct grade, written to+ // the job dir and applied with lut3d at the exact chain position the+ // fast-path lutrgb/hue chain occupies. Scalar-only grades keep that+ // original chain byte for byte.+ const gradeLutChain = new Map<string, string>();+ for (const owner of [...spec.clips, ...(spec.overlayVideos ?? [])]) {+ if (!gradeNeedsLut(owner.grade)) continue;+ const key = gradeKey(owner.grade);+ if (!key || gradeLutChain.has(key)) continue;+ const lut = buildGradeLut(owner.grade);+ if (!lut) {+ gradeLutChain.set(key, "");+ continue;+ }+ const file = path.join(job.tmpDir, `grade_${gradeLutChain.size}.cube`);+ await io.writeFile(file, lutToCube(lut));+ gradeLutChain.set(key, `lut3d=file=${fexpr(file)}:interp=tetrahedral,`);+ }+ const gradeChain = (grade: ExportSpec["clips"][number]["grade"]): string =>+ gradeNeedsLut(grade)+ ? gradeLutChain.get(gradeKey(grade)) ?? ""+ : gradeToFfmpegFilter(grade);+// Per-clip timeline length (source span compressed/expanded by speed). A// gap spacer (no file) keeps its exact length: flooring it at 0.1s would// land everything after the gap later than the timeline shows, drifting@@ -1038,7 +1062,7 @@ export async function runExport(// a still just replays its looped input.// The grade sits after the color conversion (so it acts on the same// BT.709 values the preview shows) and before the terminal format.- let core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeToFfmpegFilter(c.grade)}format=${clipFmt}`;+ let core = `${timebase},fps=${fps},${frame},setsar=1,${colorFix.get(c.file) ?? ""}${gradeChain(c.grade)}format=${clipFmt}`;// The look bakes in after grade + framing, before the edge effects, so// animations move already-graded pixels (matching the preview order).if (c.look) {@@ -1349,7 +1373,7 @@ export async function runExport(const timebase = oc.image? `[${idx}:v]setpts=PTS-STARTPTS`: `[${idx}:v]trim=${num(oc.in)}:${num(oc.out)},setpts=(PTS-STARTPTS)/${num(ospeed)}`;- let core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeToFfmpegFilter(oc.grade)}format=${lookFmt}`;+ let core = `${timebase},fps=${fps},${framing},setsar=1,${colorFix.get(oc.file) ?? ""}${gradeChain(oc.grade)}format=${lookFmt}`;// Looks bake into footage overlays only: an image may carry alpha, which// the look chain's internal filters would flatten onto black over the// tracks beneath. The alpha fades stay safe: they apply after the look.