Skip to content

Open source CapCut alternative.

TypeScript

fix(site): refit grade presets to the color spec [rebuild]

David Le91ddad41a71b
diff --git a/site/packages/effects-kit/src/gradeRange.test.ts b/site/packages/effects-kit/src/gradeRange.test.ts
new file mode 100644
index 00000000..84dab90c
--- /dev/null
+++ b/site/packages/effects-kit/src/gradeRange.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import type { ColorGrade } from "./colorGrade";
+import type { OutputSpace, SourceProfile } from "./colorSpace";
+import { GRADE_PRESET_IDS } from "./gradePresets";
+import { LOOK_LOSS_MAX, isMonotone, rangeRamp, stopsLost } from "./gradeSpec";
+import { parseCube } from "./lutFile";
+
+const CASES: [SourceProfile, OutputSpace][] = [
+ ["rec709", "sdr"],
+ ["apple-log", "sdr"],
+ ["apple-log-2", "sdr"],
+ ["hlg", "sdr"],
+ ["apple-log-2", "hlg"],
+];
+
+describe("presets keep the picture's range", () => {
+ for (const [profile, output] of CASES) {
+ const base = rangeRamp(profile, output);
+ for (const id of GRADE_PRESET_IDS) {
+ test(`${id} on ${profile} → ${output}`, () => {
+ const graded = rangeRamp(profile, output, { preset: { id } });
+ expect(isMonotone(graded)).toBe(true);
+ expect(stopsLost(base, graded)).toBeLessThanOrEqual(LOOK_LOSS_MAX);
+ });
+ }
+ }
+});
+
+describe("single controls never fold or hard-clip the ramp", () => {
+ const SLIDERS: (keyof ColorGrade)[] = [
+ "exposure",
+ "contrast",
+ "highlights",
+ "shadows",
+ "whites",
+ "blacks",
+ "brilliance",
+ "fade",
+ "temperature",
+ "tint",
+ "saturation",
+ "vibrance",
+ ];
+ const WHEEL_SETTINGS: ColorGrade[] = (["s", "m", "h", "o"] as const).flatMap((z) => [
+ { wheels: { [z]: [0, 0, -25] } },
+ { wheels: { [z]: [0, 0, 25] } },
+ ]);
+ /** A control at half travel may spend this many stops of the window. */
+ const CONTROL_LOSS_MAX = 1;
+ for (const [profile, output] of CASES.slice(0, 3)) {
+ const base = rangeRamp(profile, output);
+ const grades: [string, ColorGrade][] = [
+ ...SLIDERS.flatMap((k) =>
+ [-25, 25].filter((v) => v > 0 || k !== "fade").map((v) => [`${k} ${v}`, { [k]: v } as ColorGrade] as [string, ColorGrade])
+ ),
+ ...WHEEL_SETTINGS.map((g) => [JSON.stringify(g.wheels), g] as [string, ColorGrade]),
+ ];
+ for (const [name, grade] of grades) {
+ test(`${name} on ${profile}`, () => {
+ const graded = rangeRamp(profile, output, grade);
+ expect(isMonotone(graded)).toBe(true);
+ expect(stopsLost(base, graded)).toBeLessThanOrEqual(CONTROL_LOSS_MAX);
+ });
+ }
+ }
+});
+
+describe("built-in LUTs keep the picture's range", () => {
+ // Every .cube the site ships is a built-in look.
+ const dir = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../public/cut/luts");
+ const files = readdirSync(dir).filter((f) => f.endsWith(".cube"));
+ for (const [profile, output] of CASES.slice(0, 3)) {
+ const base = rangeRamp(profile, output);
+ for (const file of files) {
+ test(`${file} on ${profile}`, () => {
+ const lut = parseCube(readFileSync(path.join(dir, file), "utf8"));
+ const graded = rangeRamp(profile, output, { lut: { id: `lut:${file}` } }, lut);
+ expect(isMonotone(graded)).toBe(true);
+ expect(stopsLost(base, graded)).toBeLessThanOrEqual(LOOK_LOSS_MAX);
+ });
+ }
+ }
+});
diff --git a/site/packages/effects-kit/src/presets/bw.json b/site/packages/effects-kit/src/presets/bw.json
index a057e90d..000efae0 100644
--- a/site/packages/effects-kit/src/presets/bw.json
+++ b/site/packages/effects-kit/src/presets/bw.json
@@ -30,11 +30,11 @@
"category": "bw",
"look": "hard-contrast black and white, deep blacks",
"grade": {
- "saturation": -50,
"contrast": 13,
+ "saturation": -50,
"shadows": -3,
- "curves": { "m": [[0, 0], [48, 32], [128, 134], [208, 244], [255, 255]] },
- "blacks": -33
+ "blacks": -33,
+ "curves": { "m": [[0, 0], [48, 32], [128, 134], [208, 244], [255, 253]] }
}
},
{
@@ -96,12 +96,12 @@
"category": "bw",
"look": "gritty, high-contrast black and white",
"grade": {
- "saturation": -50,
"contrast": 13,
+ "saturation": -50,
"exposure": -2,
"highlights": 7,
- "curves": { "m": [[0, 16], [48, 38], [128, 138], [200, 226], [255, 255]] },
- "blacks": -16
+ "blacks": -16,
+ "curves": { "m": [[0, 16], [48, 33], [128, 138], [200, 233], [255, 255]] }
}
}
]
diff --git a/site/packages/effects-kit/src/presets/cinematic.json b/site/packages/effects-kit/src/presets/cinematic.json
index cfb15820..fbb5ff76 100644
--- a/site/packages/effects-kit/src/presets/cinematic.json
+++ b/site/packages/effects-kit/src/presets/cinematic.json
@@ -5,11 +5,11 @@
"category": "cinematic",
"look": "warm skin over teal shadows, extra saturation; blockbuster",
"grade": {
- "contrast": 7,
- "vibrance": -2,
+ "contrast": 14,
"saturation": 6,
- "wheels": { "s": [-39, -1, -16], "h": [6, 6, 3] },
- "blacks": 13
+ "blacks": 13,
+ "vibrance": -2,
+ "wheels": { "s": [-47, -17, 0], "h": [13, 6, 3] }
}
},
{
@@ -18,7 +18,7 @@
"category": "cinematic",
"look": "desaturated and silvery, crushed blacks; gritty",
"grade": {
- "contrast": 8,
+ "contrast": 27,
"saturation": -27,
"highlights": 10,
"shadows": -14,
@@ -31,12 +31,13 @@
"category": "cinematic",
"look": "very warm, rich saturated color; classic Hollywood",
"grade": {
- "exposure": 9,
"contrast": -7,
+ "saturation": 10,
+ "exposure": 9,
"temperature": 4,
- "saturation": 18,
+ "blacks": -25,
"vibrance": 6,
- "blacks": -25
+ "hsl": { "orange": [0, -4, 0] }
}
},
{
@@ -45,12 +46,12 @@
"category": "cinematic",
"look": "cool and muted, darker, crushed blacks; tense",
"grade": {
+ "contrast": 23,
+ "saturation": -12,
"temperature": -17,
- "contrast": 10,
"shadows": -9,
- "saturation": -6,
- "wheels": { "s": [-6, -12, 0] },
- "blacks": -28
+ "blacks": -28,
+ "wheels": { "s": [-6, -12, 0] }
}
},
{
@@ -59,13 +60,13 @@
"category": "cinematic",
"look": "warm and saturated, slightly dim; night streets",
"grade": {
+ "contrast": -1,
"temperature": -6,
"tint": 4,
- "contrast": 1,
"shadows": -1,
+ "blacks": -7,
"vibrance": 20,
- "hsl": { "aqua": [-4, 2, 5], "magenta": [4, 8, 7] },
- "blacks": -7
+ "hsl": { "aqua": [-4, 2, 5], "magenta": [4, 8, 7] }
}
},
{
@@ -88,13 +89,13 @@
"category": "cinematic",
"look": "warm golden and dusty, lifted blacks",
"grade": {
+ "contrast": -1,
+ "saturation": -2,
"temperature": 18,
"tint": 7,
- "contrast": 3,
"shadows": 3,
- "saturation": -2,
- "hsl": { "green": [-6, -32, -16] },
- "blacks": 3
+ "blacks": 3,
+ "hsl": { "green": [-6, -32, -16] }
}
},
{
diff --git a/site/packages/effects-kit/src/presets/film.json b/site/packages/effects-kit/src/presets/film.json
index bf515cf4..58f0dca3 100644
--- a/site/packages/effects-kit/src/presets/film.json
+++ b/site/packages/effects-kit/src/presets/film.json
@@ -5,27 +5,18 @@
"category": "film",
"look": "slightly muted, lifted cool shadows; handheld film",
"grade": {
- "saturation": -2,
- "vibrance": 6,
"contrast": 3,
+ "saturation": -2,
"highlights": -9,
"shadows": 3,
+ "blacks": 2,
+ "vibrance": 6,
"curves": {
"r": [[0, 10], [24, 24], [64, 64], [128, 133], [192, 199], [224, 230], [255, 248]],
- "g": [[0, 11], [24, 25], [64, 64], [128, 129], [192, 194], [224, 225], [255, 245]],
+ "g": [[0, 11], [24, 25], [64, 64], [128, 129], [192, 194], [224, 225], [255, 242]],
"b": [[0, 17], [24, 31], [64, 68], [128, 125], [192, 187], [224, 217], [255, 239]]
},
- "hsl": {
- "red": [5, 2, 0],
- "orange": [-5, 1, 1],
- "yellow": [5, -6, -2],
- "green": [4, -7, 2],
- "aqua": [17, 7, -10],
- "blue": [5, -2, 3],
- "purple": [-1, -5, 1],
- "magenta": [3, 0, -1]
- },
- "blacks": 2
+ "hsl": { "red": [5, 2, 0], "orange": [-5, 1, 1], "yellow": [5, -6, -2], "green": [4, -7, 2], "aqua": [17, 7, -10], "blue": [5, -2, 3], "purple": [-1, -5, 1], "magenta": [3, 0, -1] }
}
},
{
@@ -63,12 +54,12 @@
"category": "film",
"look": "very warm and saturated, deep blacks; slide film",
"grade": {
- "contrast": -2,
- "saturation": 14,
- "vibrance": 7,
+ "contrast": 11,
+ "saturation": 6,
+ "temperature": -4,
"highlights": 14,
- "temperature": 2,
- "blacks": -23
+ "blacks": -23,
+ "vibrance": 7
}
},
{
@@ -77,12 +68,12 @@
"category": "film",
"look": "high contrast, dark midtones, bright whites; pushed film",
"grade": {
- "exposure": 4,
"contrast": 17,
"saturation": -21,
+ "exposure": 8,
"shadows": -5,
- "curves": { "m": [[0, 0], [32, 14], [128, 132], [224, 238], [255, 255]] },
- "blacks": -31
+ "blacks": -31,
+ "curves": { "m": [[0, 0], [32, 22], [128, 132], [224, 238], [255, 255]] }
}
},
{
@@ -93,9 +84,9 @@
"grade": {
"contrast": 12,
"saturation": -2,
- "wheels": { "s": [-14, -10, -10], "m": [0, 1, 2] },
- "curves": { "m": [[0, 6], [32, 20], [128, 130], [192, 204], [255, 250]] },
- "blacks": -15
+ "blacks": -15,
+ "curves": { "m": [[0, 6], [32, 20], [128, 130], [192, 204], [255, 252]] },
+ "wheels": { "s": [-14, -10, -10], "m": [0, 1, 2] }
}
},
{
@@ -104,16 +95,17 @@
"category": "film",
"look": "warm and saturated, softly lifted blacks",
"grade": {
+ "contrast": 4,
"temperature": 6,
"tint": 3,
- "contrast": 4,
+ "blacks": -8,
"vibrance": 4,
"curves": {
"r": [[0, 14], [128, 134], [255, 250]],
"g": [[0, 8], [128, 126], [255, 243]],
"b": [[0, 2], [128, 114], [255, 230]]
},
- "blacks": -8
+ "hsl": { "orange": [0, -7, 0] }
}
},
{
@@ -122,15 +114,15 @@
"category": "film",
"look": "bright, washed-out instant photo, lifted blacks",
"grade": {
- "exposure": 6,
"contrast": -13,
"saturation": -11,
+ "exposure": 6,
+ "blacks": 9,
"curves": {
- "r": [[0, 20], [64, 78], [128, 138], [255, 240]],
+ "r": [[0, 20], [64, 78], [128, 144], [255, 240]],
"g": [[0, 30], [64, 84], [128, 136], [255, 234]],
"b": [[0, 33], [64, 84], [128, 128], [255, 222]]
- },
- "blacks": 9
+ }
}
},
{
@@ -139,15 +131,15 @@
"category": "film",
"look": "faded and color-shifted, lifted blacks, muted",
"grade": {
- "saturation": -16,
"contrast": -1,
+ "saturation": -21,
+ "blacks": 11,
"curves": {
- "r": [[0, 28], [64, 74], [128, 132], [255, 236]],
+ "r": [[0, 27], [64, 74], [128, 132], [255, 236]],
"g": [[0, 20], [64, 79], [128, 140], [255, 242]],
"b": [[0, 32], [64, 71], [128, 118], [255, 212]]
},
- "hsl": { "yellow": [0, -34, -4], "green": [15, -12, 8] },
- "blacks": 11
+ "hsl": { "yellow": [0, -34, -4], "green": [15, -12, 8] }
}
}
]
diff --git a/site/packages/effects-kit/src/presets/mood.json b/site/packages/effects-kit/src/presets/mood.json
index 80d953b0..fd21d579 100644
--- a/site/packages/effects-kit/src/presets/mood.json
+++ b/site/packages/effects-kit/src/presets/mood.json
@@ -20,12 +20,12 @@
"category": "mood",
"look": "olive green, muted, earthy",
"grade": {
- "tint": -10,
- "temperature": 6,
- "saturation": -5,
"contrast": 3,
- "hsl": { "green": [-2, 4, 5] },
- "blacks": -7
+ "saturation": -5,
+ "temperature": -2,
+ "tint": -10,
+ "blacks": -7,
+ "hsl": { "orange": [-8, 0, 0], "green": [-2, 4, 5] }
}
},
{
@@ -47,13 +47,13 @@
"category": "mood",
"look": "warm magenta-red, dimmed highlights",
"grade": {
- "temperature": -4,
- "tint": 2,
- "exposure": -3,
"contrast": 3,
+ "exposure": -3,
+ "temperature": -4,
+ "tint": -4,
+ "blacks": -7,
"vibrance": 6,
- "wheels": { "h": [5, -10, -6] },
- "blacks": -7
+ "wheels": { "h": [5, -10, -6] }
}
},
{
@@ -62,12 +62,12 @@
"category": "mood",
"look": "saturated magenta-red, deep blacks; nightlife",
"grade": {
- "vibrance": 22,
"contrast": -4,
- "saturation": 10,
+ "saturation": 4,
"temperature": -2,
"tint": 6,
- "blacks": -22
+ "blacks": -22,
+ "vibrance": 22
}
},
{
@@ -106,13 +106,13 @@
"look": "deep warm red, dark and rich",
"grade": {
"contrast": 6,
- "exposure": -4,
"saturation": 12,
- "temperature": 3,
+ "exposure": -4,
+ "temperature": -4,
"tint": 4,
"shadows": -6,
- "curves": { "m": [[0, 6], [64, 56], [255, 252]] },
- "blacks": -19
+ "blacks": -19,
+ "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.json
index 7c134537..df52634e 100644
--- a/site/packages/effects-kit/src/presets/warm.json
+++ b/site/packages/effects-kit/src/presets/warm.json
@@ -5,14 +5,14 @@
"category": "warm",
"look": "warm, saturated sunset glow",
"grade": {
+ "contrast": -5,
"exposure": 6,
"temperature": 17,
"tint": 3,
- "contrast": 1,
"highlights": 2,
+ "blacks": -8,
"vibrance": 13,
- "hsl": { "orange": [-14, 2, 0] },
- "blacks": -8
+ "hsl": { "orange": [-14, -6, 0] }
}
},
{
@@ -21,11 +21,11 @@
"category": "warm",
"look": "strong amber cast, lifted blacks",
"grade": {
- "temperature": 23,
+ "saturation": -16,
+ "temperature": 31,
"tint": 6,
"shadows": 7,
- "saturation": 6,
- "blacks": 5
+ "blacks": 12
}
},
{
@@ -34,13 +34,13 @@
"category": "warm",
"look": "soft warm yellow, gentle",
"grade": {
+ "contrast": -10,
+ "exposure": 4,
"temperature": 15,
"tint": 8,
- "exposure": 4,
- "contrast": -4,
- "vibrance": 9,
"highlights": -4,
- "blacks": 1
+ "blacks": 1,
+ "vibrance": 9
}
},
{
@@ -90,12 +90,12 @@
"category": "warm",
"look": "intense red-orange, deep blacks",
"grade": {
+ "contrast": 20,
"temperature": 19,
"shadows": -1,
- "contrast": 12,
+ "blacks": -21,
"vibrance": 3,
- "hsl": { "red": [0, 5, 6] },
- "blacks": -21
+ "hsl": { "red": [0, 5, 6], "orange": [0, -16, 0] }
}
},
{
@@ -104,12 +104,12 @@
"category": "warm",
"look": "warm and metallic, muted, bright whites",
"grade": {
+ "contrast": 10,
+ "saturation": -13,
"temperature": 21,
"tint": 1,
- "contrast": 10,
- "saturation": -5,
- "wheels": { "m": [6, 2, 5] },
- "blacks": -6
+ "blacks": -6,
+ "wheels": { "m": [6, 2, 5] }
}
}
]
diff --git a/site/scripts/tune-grade-presets.ts b/site/scripts/tune-grade-presets.ts
new file mode 100644
index 00000000..612e1753
--- /dev/null
+++ b/site/scripts/tune-grade-presets.ts
@@ -0,0 +1,228 @@
+// Fits the shipped grade presets to the color-science spec
+// (packages/effects-kit/src/gradeSpec.ts): each recipe's own numbers, plus
+// orange and red hue bands that hold skin, move by coordinate descent until
+// every bound the spec sets — identity, skin, saturation, levels, range on
+// every source — is met with a small margin, staying as close to the
+// original recipe as the bounds allow. Only presets that miss a bound move.
+//
+// cd site && ./node_modules/.bin/bun scripts/tune-grade-presets.ts [preset ids…] [--write]
+
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import {
+ type ColorGrade,
+ GRADE_SCALAR_FIELDS,
+ createGradeTransform,
+ normalizeGrade,
+} from "../packages/effects-kit/src/index";
+import { GRADE_PRESETS, type GradePreset } from "../packages/effects-kit/src/gradePresets";
+import {
+ type Expect,
+ IDENTITY,
+ LOOK_LOSS_MAX,
+ PREMISE,
+ isMonotone,
+ levelsHold,
+ measure,
+ monochrome,
+ rangeRamp,
+ saturationBounded,
+ skinStaysSkin,
+ stopsLost,
+} from "../packages/effects-kit/src/gradeSpec";
+import type { OutputSpace, SourceProfile } from "../packages/effects-kit/src/colorSpace";
+
+const PRESET_DIR = path.join(import.meta.dir, "../packages/effects-kit/src/presets");
+const FILES = ["cinematic", "film", "warm", "mood", "bw"];
+
+/** The sources and outputs a look has to keep its range on. */
+const RANGE_CASES: [SourceProfile, OutputSpace][] = [
+ ["rec709", "sdr"],
+ ["apple-log", "sdr"],
+ ["apple-log-2", "sdr"],
+ ["hlg", "sdr"],
+ ["apple-log-2", "hlg"],
+];
+
+/** How far inside each bound the fit aims, so LUT quantization cannot tip a
+ * fitted value back over: a few percent of the bound. */
+const margin = (n: number) => Math.max(Math.abs(n) * 0.03, 0.01);
+
+/** An expect that records how far each bound is missed instead of throwing. */
+function recorder(): { expect: Expect; total: () => number } {
+ let miss = 0;
+ const expect: Expect = (v) => ({
+ toBe: (want) => {
+ if (v !== want) miss += 1;
+ },
+ toBeLessThan: (n) => (miss += Math.max(0, (v as number) - (n - margin(n))) / Math.max(1, Math.abs(n))),
+ toBeLessThanOrEqual: (n) => (miss += Math.max(0, (v as number) - (n - margin(n))) / Math.max(1, Math.abs(n))),
+ toBeGreaterThan: (n) => (miss += Math.max(0, n + margin(n) - (v as number)) / Math.max(1, Math.abs(n))),
+ toBeGreaterThanOrEqual: (n) => (miss += Math.max(0, n + margin(n) - (v as number)) / Math.max(1, Math.abs(n))),
+ });
+ return { expect, total: () => miss };
+}
+
+/** Every bound the spec sets for a preset, summed as misses. */
+function misses(p: GradePreset, grade: ColorGrade): number {
+ const t = createGradeTransform(grade);
+ if (!t) return 1e6;
+ const m = measure((colors) =>
+ colors.map((c) => t(c[0] / 255, c[1] / 255, c[2] / 255).map((v) => Math.max(0, Math.min(255, Math.round(v * 255)))))
+ );
+ const { expect, total } = recorder();
+ IDENTITY[p.id]?.holds(m, expect);
+ PREMISE[p.category]?.(m, expect);
+ levelsHold(m, expect);
+ if (p.category === "bw") monochrome(m, expect);
+ else {
+ skinStaysSkin(m, expect);
+ saturationBounded(m, expect);
+ }
+ let range = 0;
+ for (const [profile, output] of RANGE_CASES) {
+ const base = rangeRamp(profile, output);
+ const graded = rangeRamp(profile, output, grade);
+ range += Math.max(0, stopsLost(base, graded) - (LOOK_LOSS_MAX - 0.1));
+ if (!isMonotone(graded)) range += 1;
+ }
+ return total() + range;
+}
+
+/** A tunable number inside a grade, by path. */
+type Knob = { path: (string | number)[]; min: number; max: number };
+
+const SCALAR_RANGE = new Map(GRADE_SCALAR_FIELDS.map(([k, min, max]) => [k, [min, max] as const]));
+
+function knobsOf(g: ColorGrade): Knob[] {
+ const knobs: Knob[] = [];
+ for (const [k, v] of Object.entries(g)) {
+ if (typeof v === "number") {
+ const [min, max] = SCALAR_RANGE.get(k) ?? [-50, 50];
+ knobs.push({ path: [k], min, max });
+ }
+ }
+ for (const zone of Object.keys(g.wheels ?? {})) for (let i = 0; i < 3; i++) knobs.push({ path: ["wheels", zone, i], min: -50, max: 50 });
+ for (const band of new Set([...Object.keys(g.hsl ?? {}), "orange", "red"]))
+ for (let i = 0; i < 2; i++) knobs.push({ path: ["hsl", band, i], min: -50, max: 50 });
+ for (const [ch, pts] of Object.entries(g.curves ?? {}))
+ for (let i = 0; i < (pts as unknown[]).length; i++) knobs.push({ path: ["curves", ch, i, 1], min: 0, max: 255 });
+ return knobs;
+}
+
+function read(g: ColorGrade, p: (string | number)[]): number {
+ let o: unknown = g;
+ for (const k of p) o = (o as Record<string | number, unknown> | undefined)?.[k];
+ return typeof o === "number" ? o : 0;
+}
+
+function write(g: ColorGrade, p: (string | number)[], v: number): ColorGrade {
+ const out = structuredClone(g) as Record<string, unknown>;
+ let o: Record<string | number, unknown> = out;
+ for (let i = 0; i < p.length - 1; i++) {
+ if (o[p[i]] === undefined) o[p[i]] = p[i] === "hsl" ? {} : [0, 0, 0];
+ o = o[p[i]] as Record<string | number, unknown>;
+ }
+ o[p[p.length - 1]] = v;
+ return out as ColorGrade;
+}
+
+/** A curve keeps its points rising: a point moves only between its neighbors. */
+function curveOk(g: ColorGrade, p: (string | number)[]): boolean {
+ if (p[0] !== "curves") return true;
+ const pts = g.curves?.[p[1] as "m"] ?? [];
+ return pts.every((pt, i) => i === 0 || pt[1] >= pts[i - 1][1]);
+}
+
+/** Squared distance from the original recipe, each knob over its span. */
+function drift(g: ColorGrade, from: ColorGrade, knobs: Knob[]): number {
+ return knobs.reduce((a, k) => a + ((read(g, k.path) - read(from, k.path)) / (k.max - k.min)) ** 2, 0);
+}
+
+const DRIFT_WEIGHT = 0.5;
+const STEPS = [8, 4, 2, 1];
+
+function fit(p: GradePreset): { grade: ColorGrade; before: number; after: number } {
+ const from = p.grade;
+ const knobs = knobsOf(from);
+ const cost = (g: ColorGrade) => misses(p, g) * 100 + DRIFT_WEIGHT * drift(g, from, knobs);
+ let best = from;
+ let bestCost = cost(from);
+ const before = misses(p, from);
+ // Steepest coordinate descent: each round takes the single knob move that
+ // helps most, so the recipe changes only where the bounds need it.
+ for (const step of STEPS) {
+ for (;;) {
+ let move: ColorGrade | null = null;
+ let moveCost = bestCost;
+ for (const k of knobs) {
+ for (const dir of [-1, 1]) {
+ const v = Math.max(k.min, Math.min(k.max, read(best, k.path) + dir * step));
+ const g = write(best, k.path, v);
+ if (!curveOk(g, k.path)) continue;
+ const c = cost(g);
+ if (c < moveCost - 1e-9) {
+ move = g;
+ moveCost = c;
+ }
+ }
+ }
+ if (!move) break;
+ best = move;
+ bestCost = moveCost;
+ }
+ }
+ return { grade: normalizeGrade(best) ?? from, before, after: misses(p, best) };
+}
+
+/* ------------------------------------------------------------------ */
+/* Writing the catalog back in its own layout */
+/* ------------------------------------------------------------------ */
+
+const inline = (v: unknown): string =>
+ Array.isArray(v)
+ ? `[${v.map(inline).join(", ")}]`
+ : v && typeof v === "object"
+ ? `{ ${Object.entries(v).map(([k, x]) => `"${k}": ${inline(x)}`).join(", ")} }`
+ : JSON.stringify(v);
+
+function gradeText(g: ColorGrade): string {
+ const lines = Object.entries(g).map(([k, v]) => {
+ if (k === "curves" && Object.keys(v as object).length > 1) {
+ const chans = Object.entries(v as object).map(([c, pts]) => ` "${c}": ${inline(pts)}`);
+ return ` "curves": {\n${chans.join(",\n")}\n }`;
+ }
+ return ` "${k}": ${inline(v)}`;
+ });
+ return `{\n${lines.join(",\n")}\n }`;
+}
+
+function writeCatalog(file: string, presets: GradePreset[]): void {
+ const entries = presets.map(
+ (p) =>
+ ` {\n "id": ${JSON.stringify(p.id)},\n "label": ${JSON.stringify(p.label)},\n "category": ${JSON.stringify(p.category)},\n "look": ${JSON.stringify(p.look)},\n "grade": ${gradeText(p.grade)}\n }`
+ );
+ writeFileSync(path.join(PRESET_DIR, `${file}.json`), `[\n${entries.join(",\n")}\n]\n`);
+}
+
+const args = process.argv.slice(2);
+const shouldWrite = args.includes("--write");
+const wanted = new Set(args.filter((a) => !a.startsWith("--")));
+const tuned = new Map<string, ColorGrade>();
+for (const p of Object.values(GRADE_PRESETS)) {
+ if (wanted.size && !wanted.has(p.id)) continue;
+ if (!wanted.size && misses(p, p.grade) === 0) continue;
+ const { grade, before, after } = fit(p);
+ tuned.set(p.id, grade);
+ console.log(`${p.id.padEnd(14)} misses ${before.toFixed(3)} → ${after.toFixed(3)} ${JSON.stringify(grade)}`);
+}
+if (shouldWrite) {
+ for (const file of FILES) {
+ const raw = JSON.parse(readFileSync(path.join(PRESET_DIR, `${file}.json`), "utf8")) as GradePreset[];
+ writeCatalog(
+ file,
+ raw.map((p) => (tuned.has(p.id) ? { ...p, grade: tuned.get(p.id)! } : p))
+ );
+ }
+ console.log(`wrote ${tuned.size} presets`);
+}