Open source CapCut alternative.
TypeScript
feat(site): grade log footage in scene light [rebuild]
David Le7986c0a4f63f
diff --git a/docs/guides/cut/color.md b/docs/guides/cut/color.mdindex 09ed0157..75ee5a00 100644--- a/docs/guides/cut/color.md+++ b/docs/guides/cut/color.md@@ -8,13 +8,13 @@ A clip's color is one recipe: what its code values mean (the source profile), thEvery video carries a source profile, read from its header at import: Apple Log and Log 2 by Apple's metadata identifier, HLG and PQ by the transfer tag beside a BT.2020 matrix, sRGB by its transfer, Rec.709 otherwise. The Color panel shows the detection and takes a per-asset override.-Rec.709 and sRGB sources draw as they are. Log goes through the ACES 2.0 output transform, HLG and PQ through the BT.2100 OOTF on a 100-nit display, so the grade and any creative LUT see a Rec.709 picture. A technical Log→Rec.709 LUT is a conversion of its own: it goes on a clip whose source is set to "Rec.709 (no conversion)".+Rec.709 and sRGB draw as they are; HLG and PQ convert through the BT.2100 OOTF on a 100-nit display, so the grade sees a Rec.709 picture. Log is graded in scene light, then rendered by the ACES 2.0 output transform. A technical Log→Rec.709 LUT is a conversion of its own: it goes on a clip whose source is set to "Rec.709 (no conversion)".That needs the code values untouched, and a browser converts a decoded frame by its bitstream tags, so the parameter set's tags are rewritten to neutral Rec.709 / sRGB before the decoder sees them. The matrix a decoder draws with differs by browser, so each route is measured once per session and the clip's LUT undoes it before applying the file's own. ffmpeg and headless renders read the file's matrix and need no fix. ProRes masters and their preview proxies are in [Local Compute](local-compute.md).## LUTs-A `.cube` or `.3dl` file is a Library file keyed by its content, so the same file dropped twice is one LUT and it travels with a project. The built-in film LUTs are `.cube` files the site serves, keyed the same way. A grade names either by `lut:<key>`; the recipe bakes it between the source conversion and the grade, and an export stages its bytes beside the job, so every renderer applies the same numbers.+A `.cube` or `.3dl` file is a Library file keyed by its content, so the same file dropped twice is one LUT and it travels with a project. The built-in film LUTs are `.cube` files the site serves, keyed the same way. A grade names either by `lut:<key>`, and an export stages its bytes beside the job, so every renderer applies the same numbers.## HDR deliverydiff --git a/site/packages/effects-kit/src/colorDifference.test.ts b/site/packages/effects-kit/src/colorDifference.test.tsnew file mode 100644index 00000000..2bf25121--- /dev/null+++ b/site/packages/effects-kit/src/colorDifference.test.ts@@ -0,0 +1,21 @@+import { describe, expect, test } from "bun:test";+import { type Lab, deltaE2000 } from "./colorDifference";++describe("CIEDE2000", () => {+ // Pairs from Sharma, Wu and Dalal (2005), table 1, with their ΔE00.+ const PAIRS: [Lab, Lab, number][] = [+ [[50, 2.6772, -79.7751], [50, 0, -82.7485], 2.0425],+ [[50, 3.1571, -77.2803], [50, 0, -82.7485], 2.8615],+ [[50, 2.5, 0], [50, 0, -2.5], 4.3065],+ [[50, 2.5, 0], [73, 25, -18], 27.1492],+ [[50, -0.001, 2.49], [50, 0.0009, -2.49], 4.8045],+ [[60.2574, -34.0099, 36.2677], [60.4626, -34.1751, 39.4387], 1.2644],+ [[22.7233, 20.0904, -46.694], [23.0331, 14.973, -42.5619], 2.0373],+ [[90.9257, -0.5406, -0.9208], [88.6381, -0.8985, -0.7239], 1.5381],+ ];+ for (const [p, q, want] of PAIRS) {+ test(`${p.join(",")} vs ${q.join(",")}`, () => {+ expect(Math.abs(deltaE2000(p, q) - want)).toBeLessThan(1e-4);+ });+ }+});diff --git a/site/packages/effects-kit/src/colorDifference.ts b/site/packages/effects-kit/src/colorDifference.tsnew file mode 100644index 00000000..d92e97be--- /dev/null+++ b/site/packages/effects-kit/src/colorDifference.ts@@ -0,0 +1,88 @@+/**+ * Perceptual color difference: 8-bit sRGB / Rec.709 display values into+ * CIELAB (D65), and the CIEDE2000 difference between two Lab colors. A ΔE00+ * near 1 is the smallest difference an observer sees side by side; 2–3 reads+ * as the same color across a cut.+ */++import { bt1886Decode } from "./colorSpace";++export type Lab = [number, number, number];++const XN = 0.95047;+const ZN = 1.08883;++const f = (t: number) => (t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116);++/** Display values 0..255 (Rec.709 primaries, BT.1886) → CIELAB under D65. */+export function displayToLab(r: number, g: number, b: number): Lab {+ const lr = bt1886Decode(r / 255);+ const lg = bt1886Decode(g / 255);+ const lb = bt1886Decode(b / 255);+ const x = (0.4124 * lr + 0.3576 * lg + 0.1805 * lb) / XN;+ const y = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;+ const z = (0.0193 * lr + 0.1192 * lg + 0.9505 * lb) / ZN;+ const fy = f(y);+ return [116 * fy - 16, 500 * (f(x) - fy), 200 * (fy - f(z))];+}++/** Chroma and hue angle (degrees, 0..360) of a Lab color. */+export function labChromaHue(lab: Lab): { c: number; h: number } {+ const h = (Math.atan2(lab[2], lab[1]) * 180) / Math.PI;+ return { c: Math.hypot(lab[1], lab[2]), h: h < 0 ? h + 360 : h };+}++const rad = (d: number) => (d * Math.PI) / 180;+const deg = (r: number) => (r * 180) / Math.PI;++/** CIEDE2000 (Sharma, Wu and Dalal's statement of the formula). */+export function deltaE2000(p: Lab, q: Lab): number {+ const [L1, a1, b1] = p;+ const [L2, a2, b2] = q;+ const C1 = Math.hypot(a1, b1);+ const C2 = Math.hypot(a2, b2);+ const Cm = (C1 + C2) / 2;+ const G = 0.5 * (1 - Math.sqrt(Cm ** 7 / (Cm ** 7 + 25 ** 7)));+ const a1p = (1 + G) * a1;+ const a2p = (1 + G) * a2;+ const C1p = Math.hypot(a1p, b1);+ const C2p = Math.hypot(a2p, b2);+ const hue = (b: number, a: number) => {+ if (!a && !b) return 0;+ const h = deg(Math.atan2(b, a));+ return h < 0 ? h + 360 : h;+ };+ const h1p = hue(b1, a1p);+ const h2p = hue(b2, a2p);+ const dLp = L2 - L1;+ const dCp = C2p - C1p;+ let dhp = 0;+ if (C1p * C2p) {+ dhp = h2p - h1p;+ if (dhp > 180) dhp -= 360;+ else if (dhp < -180) dhp += 360;+ }+ const dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(rad(dhp / 2));+ const Lpm = (L1 + L2) / 2;+ const Cpm = (C1p + C2p) / 2;+ let hpm = h1p + h2p;+ if (C1p * C2p) {+ if (Math.abs(h1p - h2p) <= 180) hpm = (h1p + h2p) / 2;+ else hpm = h1p + h2p < 360 ? (h1p + h2p + 360) / 2 : (h1p + h2p - 360) / 2;+ }+ const T =+ 1 -+ 0.17 * Math.cos(rad(hpm - 30)) ++ 0.24 * Math.cos(rad(2 * hpm)) ++ 0.32 * Math.cos(rad(3 * hpm + 6)) -+ 0.2 * Math.cos(rad(4 * hpm - 63));+ const dTheta = 30 * Math.exp(-(((hpm - 275) / 25) ** 2));+ const Rc = 2 * Math.sqrt(Cpm ** 7 / (Cpm ** 7 + 25 ** 7));+ const Sl = 1 + (0.015 * (Lpm - 50) ** 2) / Math.sqrt(20 + (Lpm - 50) ** 2);+ const Sc = 1 + 0.045 * Cpm;+ const Sh = 1 + 0.015 * Cpm * T;+ const Rt = -Math.sin(rad(2 * dTheta)) * Rc;+ return Math.sqrt(+ (dLp / Sl) ** 2 + (dCp / Sc) ** 2 + (dHp / Sh) ** 2 + Rt * (dCp / Sc) * (dHp / Sh)+ );+}diff --git a/site/packages/effects-kit/src/colorPipeline.ts b/site/packages/effects-kit/src/colorPipeline.tsindex ac6cc5b6..a8b127eb 100644--- a/site/packages/effects-kit/src/colorPipeline.ts+++ b/site/packages/effects-kit/src/colorPipeline.ts@@ -13,16 +13,23 @@* other through the transfer at 1000 nits, so an HDR source keeps its* range)* 2 the clip's library LUT, mixed by its amount- * 3 the grade (preset layer, then manual), gradeMath.ts+ * 3 the grade (manual layer, then preset), gradeMath.ts* 4 output: SDR as is; an SDR source delivered as HDR takes the BT.2408* mapping (Rec.709 white to 203 nits in the Rec.2020 container)** Sharpen and clarity are spatial and run on the picture afterwards* (detail.ts); they never enter the LUT or its key.*- * The source conversion is the expensive stage (the ACES transform), and it- * never changes while sliders move, so it can be sampled once onto its own- * lattice and the cheap stages composed on top per edit.+ * A graded log clip takes stages 1 and 3 in the other order: the grade works+ * on the scene light the camera recorded and the ACES output transform+ * renders the result, so its shoulder carries a brightened sky into white+ * the way it carries the ungraded one; the LUT then reads the rendered+ * picture.+ *+ * The source conversion is the expensive stage (the ACES transform). An+ * ungraded or display-referred clip samples it once onto its own lattice and+ * composes the cheap stages on top per edit; a graded log clip runs the+ * transform per node, on the draft cube while a slider moves.*/import { type ColorGrade, gradeWithoutDetail } from "./colorGrade";@@ -53,7 +60,7 @@ import {srgbEncode,} from "./colorSpace";import { type GradeLut, GRADE_LUT_SIZE, stableJson } from "./gradeLut";-import { type GradeTransform, createGradeTransform } from "./gradeMath";+import { type GradeSpace, type GradeTransform, createGradeTransform, sceneGradeSpace } from "./gradeMath";import { type ParsedLut, sampleLut } from "./lutFile";/** The file's Y'CbCr matrix and range beside the ones the decoder drew the@@ -192,6 +199,7 @@ function matrixFixTransform(drawn: DrawnColor): GradeTransform {const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);const REC2020_TO_AP0 = rgbToRgbMatrix(REC2020_PRIMARIES, AP0_PRIMARIES, BRADFORD);+const AP0_TO_REC2020 = mat3Inv(REC2020_TO_AP0);const AWG_TO_AP0 = rgbToRgbMatrix(APPLE_WIDE_GAMUT_PRIMARIES, AP0_PRIMARIES, BRADFORD);const REC2020_TO_REC709 = rgbToRgbMatrix(REC2020_PRIMARIES, REC709_PRIMARIES);const SDR_PEAK_NITS = 100;@@ -217,6 +225,44 @@ function sceneDecoder(profile: SourceProfile): ((r: number, g: number, b: number}}+/** The grade space of a log clip: scene light in Rec.2020 primaries, encoded+ * by the output transform's response to grey. One per output transform. */+const sceneSpaces = new Map<AcesOutputPresetId, GradeSpace>();++function sceneSpaceFor(output: OutputSpace): GradeSpace {+ const id = acesPresetFor(output);+ let space = sceneSpaces.get(id);+ if (space) return space;+ const ot = acesOutputTransform(id);+ space = sceneGradeSpace(output, REC2020_PRIMARIES, (y) => {+ const [r, g, b] = mat3Apply(REC2020_TO_AP0, y, y, y);+ return ot.forward(r, g, b)[1];+ });+ sceneSpaces.set(id, space);+ return space;+}++/** Code values → the graded scene → the output transform, for a log clip+ * with a grade: the grade runs on scene light and the transform renders it.+ * Null when the profile is not log or the grade is neutral. */+function sceneGradedTransform(recipe: ClipColorRecipe): GradeTransform | null {+ const scene = sceneDecoder(recipe.profile);+ if (!scene) return null;+ const space = sceneSpaceFor(recipe.output);+ const gradeFn = createGradeTransform(gradeWithoutDetail(recipe.grade), space);+ if (!gradeFn) return null;+ const fix = needsMatrixFix(recipe) ? matrixFixTransform(recipe) : null;+ const ot = acesOutputTransform(acesPresetFor(recipe.output));+ return (r, g, b) => {+ const [fr, fg, fb] = fix ? fix(r, g, b) : [r, g, b];+ const [ar, ag, ab] = scene(clamp01(fr), clamp01(fg), clamp01(fb));+ const [sr, sg, sb] = mat3Apply(AP0_TO_REC2020, ar, ag, ab);+ const [gr, gg, gb] = gradeFn(space.encode(sr), space.encode(sg), space.encode(sb));+ const [or, og, ob] = mat3Apply(REC2020_TO_AP0, space.decode(gr), space.decode(gg), space.decode(gb));+ return ot.forward(or, og, ob);+ };+}+/** HLG signal → PQ signal on a 1000-nit display: the BT.2100 OOTF gives the* display light, and ST 2084 encodes it. What the final pass of a PQ* delivery runs over the HLG composite. */@@ -296,37 +342,60 @@ function outputTransform(profile: SourceProfile, output: OutputSpace): GradeTran/* The composed mapping *//* ------------------------------------------------------------------ */+/** The library LUT mixed by its amount, on display values; null without one. */+function lutStage(recipe: ClipColorRecipe, userLut: ParsedLut | undefined): GradeTransform | null {+ const lutRef = recipe.grade?.lut;+ const amount = lutRef && userLut ? (lutRef.amount ?? 1) : 0;+ if (!amount || !userLut) return null;+ return (r, g, b) => {+ const l = sampleLut(userLut, clamp01(r), clamp01(g), clamp01(b));+ return [r + (l[0] - r) * amount, g + (l[1] - g) * amount, b + (l[2] - b) * amount];+ };+}+/** Stages 2–4: the LUT, the grade and the output mapping on display values. */function postSourceTransform(recipe: ClipColorRecipe, userLut: ParsedLut | undefined): GradeTransform | null {const grade = gradeWithoutDetail(recipe.grade);const gradeSpace: OutputSpace = isSdrSource(recipe.profile) ? "sdr" : recipe.output;- const lutRef = grade?.lut;- const lutAmount = lutRef && userLut ? (lutRef.amount ?? 1) : 0;+ const lutFn = lutStage(recipe, userLut);const gradeFn = createGradeTransform(grade, gradeSpace);const outFn = outputTransform(recipe.profile, recipe.output);- if (!lutAmount && !gradeFn && !outFn) return null;+ if (!lutFn && !gradeFn && !outFn) return null;return (r, g, b) => {let v: [number, number, number] = [r, g, b];- if (lutAmount && userLut) {- const l = sampleLut(userLut, clamp01(v[0]), clamp01(v[1]), clamp01(v[2]));- v = [- v[0] + (l[0] - v[0]) * lutAmount,- v[1] + (l[1] - v[1]) * lutAmount,- v[2] + (l[2] - v[2]) * lutAmount,- ];- }+ if (lutFn) v = lutFn(v[0], v[1], v[2]);if (gradeFn) v = gradeFn(v[0], v[1], v[2]);if (outFn) v = outFn(clamp01(v[0]), clamp01(v[1]), clamp01(v[2]));return v;};}+/** The whole mapping of a graded log clip: the scene grade and its rendering,+ * then the LUT on the rendered picture. Null for every other recipe. */+function sceneClipTransform(recipe: ClipColorRecipe, userLut: ParsedLut | undefined): GradeTransform | null {+ const graded = sceneGradedTransform(recipe);+ if (!graded) return null;+ const lutFn = lutStage(recipe, userLut);+ if (!lutFn) return graded;+ return (r, g, b) => {+ const v = graded(r, g, b);+ return lutFn(v[0], v[1], v[2]);+ };+}+/*** Compile the recipe into the pure mapping from source code values to output* code values, both in [0,1]. Returns null when the mapping is identity: an* SDR-in-SDR clip with no grade and no LUT.*/export function createClipTransform(recipe: ClipColorRecipe, userLut?: ParsedLut): GradeTransform | null {+ const scene = sceneClipTransform(recipe, userLut);+ if (scene) {+ return (r, g, b) => {+ const v = scene(r, g, b);+ return [clamp01(v[0]), clamp01(v[1]), clamp01(v[2])];+ };+ }const source = sourceTransform(recipe.profile, recipe.output, recipe);const post = postSourceTransform(recipe, userLut);if (!source && !post) return null;@@ -455,6 +524,18 @@ export function clearSourceLatticeCache(): void {*/export function buildClipLut(recipe: ClipColorRecipe, userLut?: ParsedLut, source?: SourceLattice): GradeLut | null {const size = recipe.size;+ // A graded log clip runs the output transform after its grade, so no+ // rendered lattice can stand in for it: every node takes the whole path.+ const scene = sceneClipTransform(recipe, userLut);+ if (scene) {+ return {+ size,+ data: fillLattice(size, (r, g, b) => {+ const v = scene(r, g, b);+ return [clamp01(v[0]), clamp01(v[1]), clamp01(v[2])];+ }),+ };+ }const post = postSourceTransform(recipe, userLut);const lattice =source &&diff --git a/site/packages/effects-kit/src/gradeEval.test.ts b/site/packages/effects-kit/src/gradeEval.test.tsindex 42b549dc..1b630e7c 100644--- a/site/packages/effects-kit/src/gradeEval.test.ts+++ b/site/packages/effects-kit/src/gradeEval.test.ts@@ -4,6 +4,20 @@ import { bt1886Decode } from "./colorSpace";import { applyLutToImageData, type GradeLut } from "./gradeLut";import { createGradeTransform } from "./gradeMath";import { GRADE_PRESETS, type GradePreset } from "./gradePresets";+import {+ CHART,+ IDENTITY,+ PATCHES,+ PREMISE,+ SKIN,+ hsv,+ hueDelta,+ levelsHold,+ measure as measureColors,+ monochrome,+ saturationBounded,+ skinStaysSkin,+} from "./gradeSpec";/*** Color-science evals for the shipped preset catalog, in two tiers.@@ -34,64 +48,6 @@ import { GRADE_PRESETS, type GradePreset } from "./gradePresets";* whole chart survives a neutral grade within a small color difference.*/-/** ColorChecker Classic, sRGB. */-const CHART: Record<string, [number, number, number]> = {- darkSkin: [115, 82, 68],- lightSkin: [194, 150, 130],- blueSky: [98, 122, 157],- foliage: [87, 108, 67],- blueFlower: [133, 128, 177],- bluishGreen: [103, 189, 170],- orange: [214, 126, 44],- purplishBlue: [80, 91, 166],- moderateRed: [193, 90, 99],- purple: [94, 60, 108],- yellowGreen: [157, 188, 64],- orangeYellow: [224, 163, 46],- blue: [56, 61, 150],- green: [70, 148, 73],- red: [175, 54, 60],- yellow: [231, 199, 31],- magenta: [187, 86, 149],- cyan: [8, 133, 161],- white95: [243, 243, 242],- neutral8: [200, 200, 200],- neutral65: [160, 160, 160],- neutral5: [122, 122, 121],- neutral35: [85, 85, 85],- black2: [52, 52, 52],-};--const PATCHES = Object.keys(CHART);-const SKIN = ["darkSkin", "lightSkin"];-const COLORFUL = PATCHES.filter((n) => !/^(white|neutral|black)/.test(n) && !SKIN.includes(n));-/** The chart's gray ramp, darkest first. */-const RAMP = ["black2", "neutral35", "neutral5", "neutral65", "neutral8", "white95"];-/** A synthetic exposure ramp for tone-response readings: index 0 is black. */-const GRAY = [0, 32, 64, 128, 192, 224, 255];-const [, SHADOW, , MID, , HIGH, WHITE] = GRAY.map((_, i) => i);--const hsv = ([r, g, b]: number[]) => {- const mx = Math.max(r, g, b);- const mn = Math.min(r, g, b);- const d = mx - mn;- let h = 0;- if (d) {- if (mx === r) h = ((g - b) / d) % 6;- else if (mx === g) h = (b - r) / d + 2;- else h = (r - g) / d + 4;- h = (h * 60 + 360) % 360;- }- return { h, s: mx ? d / mx : 0 };-};-const luma = ([r, g, b]: number[]) => 0.2126 * r + 0.7152 * g + 0.0722 * b;-const hueDelta = (a: number, b: number) => {- let d = (b - a) % 360;- if (d > 180) d -= 360;- if (d < -180) d += 360;- return Math.abs(d);-};-/** Push a list of colors through a LUT with the production tetrahedral pass. */function through(lut: GradeLut, colors: number[][]): number[][] {const px = new Uint8ClampedArray(colors.length * 4);@@ -105,63 +61,6 @@ function through(lut: GradeLut, colors: number[][]): number[][] {return colors.map((_, i) => [px[i * 4], px[i * 4 + 1], px[i * 4 + 2]]);}-interface Measured {- /** The graded chart, by patch name. */- patch: Record<string, number[]>;- /** Pure black and pure white as rendered — the film toe and shoulder. */- black: number;- white: number;- /** Mid gray as rendered: the look's overall level. */- mid: number;- /** Tone-curve slope across the middle of the range: contrast. */- slope: number;- /** R−B at shadow / mid / highlight. Positive is warm. */- warm: { s: number; m: number; h: number };- /** G − (R+B)/2 at shadow / mid / highlight. Positive is green, negative magenta. */- green: { s: number; m: number; h: number };- /** Mean saturation multiplier over the chart's colorful patches. */- sat: number;- /** Hue variety left in the chart: 1 is the full wheel, 0 is a single tone. */- spread: number;- /** R−B on the light-skin patch. */- skinWarm: number;-}--function measure(lut: GradeLut): Measured {- const chart = through(- lut,- PATCHES.map((n) => CHART[n])- );- const patch: Record<string, number[]> = {};- PATCHES.forEach((n, i) => (patch[n] = chart[i]));- const gray = through(- lut,- GRAY.map((s) => [s, s, s])- );- const warmOf = (c: number[]) => c[0] - c[2];- const greenOf = (c: number[]) => Math.round(c[1] - (c[0] + c[2]) / 2);- const mults = COLORFUL.map((n) => {- const before = hsv(CHART[n]).s;- return before > 0.05 ? hsv(patch[n]).s / before : 1;- });- // Circular mean of the surviving hues: a toning process collapses them all- // onto one, which shows up here as a spread near zero.- const hues = COLORFUL.filter((n) => hsv(patch[n]).s > 0.08).map((n) => hsv(patch[n]).h);- const cx = hues.reduce((a, h) => a + Math.cos((h * Math.PI) / 180), 0) / (hues.length || 1);- const cy = hues.reduce((a, h) => a + Math.sin((h * Math.PI) / 180), 0) / (hues.length || 1);- return {- patch,- black: luma(gray[0]),- white: luma(gray[WHITE]),- mid: luma(gray[MID]),- slope: (luma(gray[HIGH]) - luma(gray[SHADOW])) / (GRAY[HIGH] - GRAY[SHADOW]),- warm: { s: warmOf(gray[SHADOW]), m: warmOf(gray[MID]), h: warmOf(gray[HIGH]) },- green: { s: greenOf(gray[SHADOW]), m: greenOf(gray[MID]), h: greenOf(gray[HIGH]) },- sat: mults.reduce((a, b) => a + b, 0) / mults.length,- spread: 1 - Math.hypot(cx, cy),- skinWarm: warmOf(patch.lightSkin),- };-}const lutOf = (p: GradePreset, extra: { amount?: number; skin?: boolean } = {}): GradeLut => {const lut = buildGradeLut({ preset: { id: p.id, ...extra } });@@ -172,86 +71,31 @@ const lutOf = (p: GradePreset, extra: { amount?: number; skin?: boolean } = {}):const presets = Object.values(GRADE_PRESETS);const colorPresets = presets.filter((p) => p.category !== "bw");const bwPresets = presets.filter((p) => p.category === "bw");-/** A toning process puts one hue over the whole frame, so the rails that- * assume the grade preserved color relationships do not apply to it. */-const isToned = (m: Measured) => m.spread <= 0.1;++/** Push a chart through a preset's real LUT, the way every renderer draws it. */+const measure = (lut: GradeLut) => measureColors((colors) => through(lut, colors));/* ------------------------------------------------------------------ *//* Tier 1: safety *//* ------------------------------------------------------------------ */describe("skin stays skin", () => {- for (const p of colorPresets)- test(p.id, () => {- const m = measure(lutOf(p));- for (const name of SKIN) {- const before = hsv(CHART[name]);- const after = hsv(m.patch[name]);- // Saturation may deepen by at most about a fifth of the scale, and a- // face never reads more saturated than sunburn territory.- expect(after.s - before.s).toBeLessThanOrEqual(0.22);- expect(after.s).toBeLessThanOrEqual(0.7);- // While the face still carries color it holds the skin-tone line: the- // warm band, close to where it started. A muted face may drift — with- // little chroma its hue no longer reads — and a toned monochrome puts- // every subject on the tone's hue by definition, so only the band- // applies there.- if (after.s >= 0.3) {- expect(after.h).toBeGreaterThanOrEqual(5);- expect(after.h).toBeLessThanOrEqual(45);- if (!isToned(m)) expect(hueDelta(before.h, after.h)).toBeLessThanOrEqual(12);- }- }- });+ for (const p of colorPresets) test(p.id, () => skinStaysSkin(measure(lutOf(p)), expect));});describe("saturation energy is bounded", () => {- for (const p of colorPresets)- test(p.id, () => {- const m = measure(lutOf(p));- const mults = COLORFUL.map((n) => {- const before = hsv(CHART[n]).s;- return before > 0.05 ? hsv(m.patch[n]).s / before : 1;- });- // A grade may accent a hue; it never approaches doubling one, and the- // chart as a whole gains at most ~40%.- expect(m.sat).toBeLessThanOrEqual(1.4);- expect(Math.max(...mults)).toBeLessThanOrEqual(1.75);- });+ for (const p of colorPresets) test(p.id, () => saturationBounded(measure(lutOf(p)), expect));});describe("levels hold broadcast discipline", () => {- for (const p of presets)- test(p.id, () => {- const m = measure(lutOf(p));- // The gray ramp stays monotonic — a reversal is solarization.- const ramp = RAMP.map((n) => luma(m.patch[n]));- for (let i = 1; i < ramp.length; i++) expect(ramp[i]).toBeGreaterThanOrEqual(ramp[i - 1] - 1);- // Chart black keeps shadow detail.- expect(luma(m.patch.black2)).toBeGreaterThanOrEqual(12);- // A cast on the mid grays stays in warming-gel range. A toning process- // is a deliberate wash over the whole frame, judged by its own rail- // below instead.- if (!isToned(m)) {- for (const name of ["neutral5", "neutral65"]) {- const c = m.patch[name];- expect(Math.max(...c) - Math.min(...c)).toBeLessThanOrEqual(48);- }- }- });+ for (const p of presets) test(p.id, () => levelsHold(measure(lutOf(p)), expect));});describe("black & white means black & white", () => {- for (const p of bwPresets)- test(p.id, () => {- const m = measure(lutOf(p));- for (const name of PATCHES) {- const c = m.patch[name];- expect(Math.max(...c) - Math.min(...c)).toBeLessThanOrEqual(2);- }- });+ for (const p of bwPresets) test(p.id, () => monochrome(measure(lutOf(p)), expect));});+describe("intensity scales toward neutral", () => {for (const p of presets)test(p.id, () => {@@ -288,335 +132,7 @@ describe("the skin flag protects faces", () => {});});-/* ------------------------------------------------------------------ */-/* Tier 2: identity */-/* ------------------------------------------------------------------ */-interface Signature {- /** What this preset is emulating, in the world. */- process: string;- /** What emulating it has to measure like on the chart. */- holds(m: Measured): void;-}--const IDENTITY: Record<string, Signature> = {- /* — cinematic ---------------------------------------------------- */- "teal-orange": {- process: "the complementary blockbuster split: shadows toward teal, skin and highlights toward orange",- holds: (m) => {- expect(m.warm.s).toBeLessThanOrEqual(-15);- expect(m.warm.h - m.warm.s).toBeGreaterThanOrEqual(30);- expect(m.skinWarm).toBeGreaterThanOrEqual(40);- },- },- "bleach-bypass": {- process: "silver retention: the bleach step is skipped so metallic silver stays in the print — contrast climbs and color drains",- holds: (m) => {- expect(m.sat).toBeLessThanOrEqual(0.75);- expect(m.slope).toBeGreaterThanOrEqual(1.15);- expect(m.black).toBeLessThanOrEqual(10);- },- },- matinee: {- process: "an old Hollywood matinee print: bright, warm, and full-blooded in color",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(3);- expect(m.mid).toBeGreaterThanOrEqual(130);- expect(m.sat).toBeGreaterThanOrEqual(1.1);- },- },- thriller: {- process: "the hard, cold tension grade: contrast up, everything pulled off warm",- holds: (m) => {- expect(m.warm.m).toBeLessThanOrEqual(-10);- expect(m.slope).toBeGreaterThanOrEqual(1.12);- expect(m.black).toBeLessThanOrEqual(10);- },- },- "night-market": {- process: "a neon-lit street after dark: cool highlights over saturated signage color",- holds: (m) => {- expect(m.warm.h).toBeLessThanOrEqual(-6);- expect(m.sat).toBeGreaterThanOrEqual(1.08);- },- },- "sci-fi": {- process: "cold blue-cyan futurism, the cast deepening as it climbs the range",- holds: (m) => {- expect(m.warm.h).toBeLessThanOrEqual(-25);- expect(m.warm.h).toBeLessThan(m.warm.m);- },- },- western: {- process: "sun-baked dust: strongly warm, and muted by the haze rather than punchy",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(12);- expect(m.sat).toBeLessThanOrEqual(1.0);- },- },- indie: {- process: "the flat lifted-contrast indie look: milky blacks, gentle slope, drained color",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(14);- expect(m.slope).toBeLessThanOrEqual(0.94);- expect(m.sat).toBeLessThanOrEqual(0.82);- },- },-- /* — film --------------------------------------------------------- */- "16mm": {- process: "16mm color negative: a base-plus-fog toe, a gentle shoulder, and the stock's crossover from cool shadows into warm highlights",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(8);- expect(m.white).toBeLessThanOrEqual(252);- expect(m.warm.h - m.warm.s).toBeGreaterThanOrEqual(8);- expect(m.sat).toBeLessThanOrEqual(1.05);- },- },- "super-8": {- process: "Super 8 home-movie reversal: warm, soft-shouldered, and lifted",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(14);- expect(m.warm.m).toBeGreaterThanOrEqual(10);- expect(m.slope).toBeLessThanOrEqual(1.0);- expect(m.sat).toBeLessThanOrEqual(0.95);- },- },- "faded-film": {- process: "a faded release print: the cyan dye layer goes first, so the image drifts pink as it flattens",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(25);- expect(m.slope).toBeLessThanOrEqual(0.82);- expect(m.sat).toBeLessThanOrEqual(0.68);- expect(m.green.m).toBeLessThanOrEqual(-4);- },- },- chrome: {- process: "Kodachrome-style reversal: dense blacks under famously rich color",- holds: (m) => {- expect(m.sat).toBeGreaterThanOrEqual(1.18);- expect(m.black).toBeLessThanOrEqual(8);- },- },- "push-process": {- process: "pushed development: underexposure bought back in the tank — contrast and grain climb, the toe crushes, highlights blow, and color goes flat",- holds: (m) => {- expect(m.slope).toBeGreaterThanOrEqual(1.2);- expect(m.black).toBeLessThanOrEqual(6);- expect(m.sat).toBeLessThanOrEqual(0.96);- },- },- "cine-print": {- process: "print stock, the contrastiest link in the photochemical chain: dense blacks and controlled color",- holds: (m) => {- expect(m.slope).toBeGreaterThanOrEqual(1.12);- expect(m.black).toBeLessThanOrEqual(12);- },- },- tungsten: {- process: "daylight stock under 3200K tungsten light: a source warming the whole scene, so the cast reaches the shadows rather than washing only the highlights",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(18);- expect(m.warm.s).toBeGreaterThanOrEqual(12);- expect(m.warm.h - m.warm.s).toBeLessThanOrEqual(28);- },- },- instant: {- process: "integral-tripack instant film: a milky toe, muted dyes, and cool shadows running into warm highlights",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(25);- expect(m.slope).toBeLessThanOrEqual(0.88);- expect(m.sat).toBeLessThanOrEqual(0.72);- expect(m.warm.s).toBeLessThan(0);- expect(m.warm.h).toBeGreaterThanOrEqual(5);- },- },- expired: {- process: "expired stock: the emulsion layers lose sensitivity at different rates, so a green-yellow cast settles over a fogged toe",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(20);- expect(m.green.m).toBeGreaterThanOrEqual(6);- expect(m.sat).toBeLessThanOrEqual(0.68);- expect(m.slope).toBeLessThanOrEqual(0.92);- },- },-- /* — warm --------------------------------------------------------- */- "golden-hour": {- process: "low sun near the horizon: warm and bright, the light itself lifting the frame",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(16);- expect(m.mid).toBeGreaterThanOrEqual(130);- },- },- amber: {- process: "an amber wash laid over the grade, weighted to the highlights the way a gel reads rather than a room light",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(20);- expect(m.warm.h - m.warm.s).toBeGreaterThanOrEqual(30);- },- },- honey: {- process: "a soft honeyed warmth that leaves contrast where it found it",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(12);- expect(m.slope).toBeLessThanOrEqual(1.08);- },- },- sunbaked: {- process: "hard sun on dry ground: warm and slightly bleached",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(12);- expect(m.sat).toBeLessThanOrEqual(1.02);- },- },- peach: {- process: "a pale peach cast over a softly lifted toe",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(9);- expect(m.black).toBeGreaterThanOrEqual(8);- },- },- sepia: {- process: "sepia toning: the print's silver is converted to silver sulfide, so the whole frame carries one brown tone rather than a tint over surviving color",- holds: (m) => {- expect(m.spread).toBeLessThanOrEqual(0.08);- expect(m.warm.m).toBeGreaterThanOrEqual(28);- },- },- ember: {- process: "firelight: warm and contrasty, the glow strongest up top",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(17);- expect(m.slope).toBeGreaterThanOrEqual(1.08);- },- },- bronze: {- process: "a burnished bronze cast, warm and slightly muted",- holds: (m) => {- expect(m.warm.m).toBeGreaterThanOrEqual(18);- expect(m.sat).toBeLessThanOrEqual(1.02);- },- },-- /* — mood --------------------------------------------------------- */- midnight: {- process: "deep night: cool throughout and genuinely dark",- holds: (m) => {- expect(m.warm.m).toBeLessThanOrEqual(-8);- expect(m.mid).toBeLessThanOrEqual(120);- },- },- moss: {- process: "damp woodland green, strengthening through the highlights",- holds: (m) => {- expect(m.green.m).toBeGreaterThanOrEqual(4);- expect(m.green.h).toBeGreaterThanOrEqual(m.green.m);- },- },- slate: {- process: "cool grey stone: the cast pulled off warm and the color drained down",- holds: (m) => {- expect(m.warm.m).toBeLessThanOrEqual(-4);- expect(m.sat).toBeLessThanOrEqual(0.85);- },- },- dusk: {- process: "the light after sundown: cool, dimming, and going magenta up top",- holds: (m) => {- expect(m.warm.m).toBeLessThan(0);- expect(m.mid).toBeLessThanOrEqual(126);- },- },- neon: {- process: "neon: color pushed hard against a cool ground",- holds: (m) => {- expect(m.sat).toBeGreaterThanOrEqual(1.18);- expect(m.warm.h).toBeLessThan(0);- },- },- arctic: {- process: "cold open daylight off snow: a strong blue cast climbing with the tone",- holds: (m) => {- expect(m.warm.h).toBeLessThanOrEqual(-28);- expect(m.warm.h).toBeLessThan(m.warm.m);- },- },- storm: {- process: "storm light: cool, dark, and drained",- holds: (m) => {- expect(m.warm.m).toBeLessThanOrEqual(-5);- expect(m.sat).toBeLessThanOrEqual(0.96);- expect(m.mid).toBeLessThanOrEqual(124);- },- },- velvet: {- process: "deep low-light richness: color held up while the frame sits down",- holds: (m) => {- expect(m.sat).toBeGreaterThanOrEqual(1.15);- expect(m.mid).toBeLessThanOrEqual(118);- },- },-- /* — black & white ------------------------------------------------ */- mono: {- process: "a straight panchromatic conversion: neutral, with normal contrast",- holds: (m) => {- expect(m.black).toBeLessThanOrEqual(8);- expect(m.slope).toBeGreaterThanOrEqual(1.0);- },- },- silver: {- process: "a silver-gelatin print: a gently lifted toe and a soft slope",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(10);- expect(m.slope).toBeLessThanOrEqual(1.05);- },- },- ink: {- process: "a hard graphic conversion: solid ink blacks, a steep clean slope, no veil in the toe",- holds: (m) => {- expect(m.slope).toBeGreaterThanOrEqual(1.2);- expect(m.black).toBeLessThanOrEqual(8);- },- },- "high-key": {- process: "high-key lighting: the whole frame carried up, shadows opened",- holds: (m) => {- expect(m.mid).toBeGreaterThanOrEqual(140);- expect(m.black).toBeGreaterThanOrEqual(14);- },- },- "low-key": {- process: "low-key lighting: the frame carried down onto dense blacks",- holds: (m) => {- expect(m.mid).toBeLessThanOrEqual(116);- expect(m.black).toBeLessThanOrEqual(8);- },- },- charcoal: {- process: "charcoal on paper: a lifted toe under a soft, slightly dark rendering",- holds: (m) => {- expect(m.black).toBeGreaterThanOrEqual(10);- expect(m.slope).toBeLessThanOrEqual(1.0);- expect(m.mid).toBeLessThanOrEqual(126);- },- },- "soft-mono": {- process: "a soft monochrome: low slope over an open toe",- holds: (m) => {- expect(m.slope).toBeLessThanOrEqual(0.92);- expect(m.black).toBeGreaterThanOrEqual(16);- },- },- grit: {- process: "pushed reportage monochrome: steep and harsh, but grain veils the toe — a pushed negative never scans to a clean black",- holds: (m) => {- expect(m.slope).toBeGreaterThanOrEqual(1.15);- expect(m.black).toBeGreaterThanOrEqual(10);- },- },-};/* ------------------------------------------------------------------ *//* Tier 3: slider physics */@@ -638,14 +154,25 @@ function deltaE(a: number[], b: number[]): number {}describe("slider physics", () => {- test("a stop of exposure doubles linear light on every grey", () => {+ test("a stop of exposure doubles linear light on every grey below the shoulder", () => {const t = createGradeTransform({ exposure: 25 })!;- for (const v of [0.1, 0.3, 0.5, 0.7]) {+ for (const v of [0.1, 0.3, 0.5, 0.55]) {const out = t(v, v, v);expect(Math.abs(bt1886Decode(out[0]) / bt1886Decode(v) - 2)).toBeLessThan(1e-6);}});+ test("a stop of exposure rolls the highlights into white without clipping them", () => {+ const t = createGradeTransform({ exposure: 25 })!;+ let prev = -1;+ for (let i = 160; i <= 250; i++) {+ const out = t(i / 255, i / 255, i / 255)[0];+ expect(out).toBeGreaterThan(prev);+ expect(out).toBeLessThan(1);+ prev = out;+ }+ });+test("highlights at full never clip and keep the ramp in order, even a stop over", () => {for (const grade of [{ highlights: 50 }, { highlights: 50, exposure: 25 }, { highlights: -50 }]) {const t = createGradeTransform(grade)!;@@ -742,7 +269,7 @@ describe("a preset measures like the thing it names", () => {const sig = IDENTITY[p.id];if (!sig) continue; // the coverage test above is what reports thistest(`${p.id} — ${sig.process}`, () => {- sig.holds(measure(lutOf(p)));+ sig.holds(measure(lutOf(p)), expect);});}});@@ -771,19 +298,9 @@ describe("no two presets are the same look", () => {});describe("presets in a category share its premise", () => {- const premise: Partial<Record<GradePreset["category"], (m: Measured) => void>> = {- // A warm preset is warm — no exceptions, that is what the shelf means.- warm: (m) => expect(m.warm.m).toBeGreaterThanOrEqual(8),- // A film preset emulates a stock, and a stock has a characteristic curve:- // a toe that lifts black, a shoulder that rolls highlights, or a slope- // away from straight-through. A recipe that only shifts color is a cast,- // not a stock.- film: (m) =>- expect(m.black >= 8 || m.white <= 250 || Math.abs(m.slope - 1) >= 0.1).toBe(true),- };for (const p of presets) {- const check = premise[p.category];+ const check = PREMISE[p.category];if (!check) continue;- test(`${p.category}: ${p.id}`, () => check(measure(lutOf(p))));+ test(`${p.category}: ${p.id}`, () => check(measure(lutOf(p)), expect));}});diff --git a/site/packages/effects-kit/src/gradeLut.test.ts b/site/packages/effects-kit/src/gradeLut.test.tsindex 3206d32d..863abafc 100644--- a/site/packages/effects-kit/src/gradeLut.test.ts+++ b/site/packages/effects-kit/src/gradeLut.test.ts@@ -90,16 +90,16 @@ describe("buildGradeLut", () => {for (let ch = 0; ch < 3; ch++) expect(Math.abs(stop(grey, grey, grey)[ch] - bt1886Encode(0.36))).toBeLessThan(1e-6);const contrast = createGradeTransform({ contrast: 50 })!;for (let ch = 0; ch < 3; ch++) expect(Math.abs(contrast(grey, grey, grey)[ch] - grey)).toBeLessThan(1e-6);- // Full contrast is the 1.5 power about the pivot: a stop above grey lands- // 1.5 stops above.- const up = bt1886Encode(0.36);+ // Full contrast is the 1.5 power about the pivot: half a stop above grey+ // lands three quarters of a stop above, under the shoulder's knee.+ const up = bt1886Encode(0.18 * Math.SQRT2);const out = contrast(up, up, up)[0];- expect(Math.abs(out - bt1886Encode(0.18 * Math.pow(2, 1 + CONTRAST_POWER_AT_MAX)))).toBeLessThan(1e-6);+ expect(Math.abs(out - bt1886Encode(0.18 * Math.pow(2, 0.5 * (1 + CONTRAST_POWER_AT_MAX))))).toBeLessThan(1e-6);});- test("a brightness slider is a linear gain", () => {+ test("a brightness slider is a linear gain below the shoulder", () => {const t = createGradeTransform({ brightness: 20 })!;- for (const v of [0.1, 0.4, 0.7]) expect(Math.abs(t(v, v, v)[0] - v * 1.2)).toBeLessThan(1e-6);+ for (const v of [0.1, 0.4, 0.6]) expect(Math.abs(t(v, v, v)[0] - v * 1.2)).toBeLessThan(1e-6);});});diff --git a/site/packages/effects-kit/src/gradeMath.ts b/site/packages/effects-kit/src/gradeMath.tsindex 9dd47878..6a349c3a 100644--- a/site/packages/effects-kit/src/gradeMath.ts+++ b/site/packages/effects-kit/src/gradeMath.ts@@ -1,12 +1,14 @@/*** The grade's pixel math: one pure transform on display values that every* renderer consumes through the clip LUT (colorPipeline.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 runs its stages in one order, on the container the project- * delivers in (Rec.709/BT.1886 for SDR, Rec.2100 HLG or PQ for HDR):+ * resolves to at most two layers — the manual adjustments, which balance the+ * shot, and the preset on top, the look (scaled by its amount, optionally+ * kept off skin tones) — and each layer runs its stages in one order, on the+ * container the project delivers in (Rec.709/BT.1886 for SDR, Rec.2100 HLG or+ * PQ for HDR):*- * light, in linear light (the container's transfer inverted):+ * light, in linear light with headroom (the container's transfer inverted,+ * then the shoulder below inverted):* monochrome (a negative saturation slider, see below) → white balance* (CAT02) → exposure (stops) → contrast (a power about 18% grey) →* highlights / shadows / whites / blacks / brilliance (smooth luminance@@ -23,6 +25,15 @@* Skin protection is one rule at the layer's end: the tone lands in full and* the chroma the layer moved blends back toward the pixel's own by the skin* weight.+ *+ * No control throws picture away. Linear light carries headroom above the+ * container's white, and leaving it for display values passes through a+ * shoulder that is the identity up to SHOULDER_KNEE and rolls everything up+ * to HEADROOM times white smoothly into white; entering inverts it exactly,+ * so an ungraded pixel round-trips unchanged and a brightened highlight+ * compresses where it used to clip. Every darkening move is a gain, never a+ * subtraction, so nothing crosses black: a shadow pushed down keeps its+ * detail. gradeRange.test.ts holds both.*/import {@@ -55,6 +66,7 @@ import {oklabMatrices,pqDecode,pqEncode,+ rgbToXyzMatrix,spow,whiteBalanceMatrix,} from "./colorSpace";@@ -86,16 +98,28 @@ const HIGHLIGHTS_STOPS = 3.4;const SHADOWS_STOPS = 6.75;const WHITES_STOPS = 0.7;const BRILLIANCE_STOPS = 0.5;-/** Blacks is an additive offset in linear light, so it reaches black. The- * slider maps to it through its signed square: a linear offset shows on the- * encoded ramp as its 1/2.4 power, so the first notches would otherwise jump. */+/** Raised blacks are an additive lift in linear light, through the slider's+ * signed square: a linear offset shows on the encoded ramp as its 1/2.4+ * power, so the first notches would otherwise jump. */const BLACKS_OFFSET = 0.03;+/** Lowered blacks are a gain on the darkest tones, this many stops at black+ * at full travel: dense shadows that keep their detail. */+const BLACKS_DARKEN_STOPS = 2;-/** Wheel amplitudes at a full puck / luma trim. */+/** Wheel amplitudes at a full puck / luma trim. A raised lift adds light+ * toward black; a lowered one is a gain that reaches WHEEL_LIFT_DARKEN at+ * black. Offset is a per-channel gain in stops, the printer light. */const WHEEL_LIFT = 0.03;+const WHEEL_LIFT_DARKEN = 0.6;const WHEEL_GAMMA = 0.35;const WHEEL_GAIN = 0.5;-const WHEEL_OFFSET = 0.05;+const WHEEL_OFFSET_STOPS = 1;++/** The shoulder between linear light and display values: identity up to+ * this share of the container's white, then a smooth roll into white that+ * reaches it at HEADROOM times white with zero slope. */+export const SHOULDER_KNEE = 0.5;+export const HEADROOM = 4;/* ------------------------------------------------------------------ *//* The container a grade works in */@@ -110,6 +134,9 @@ export interface GradeSpace {encode(l: number): number;/** Linear value of an 18% grey card (BT.2408 for the HDR containers). */pivot: number;+ /** Linear value of the container's white, where the shoulder lands;+ * Infinity for scene light, whose encoding is its own shoulder. */+ white: number;/** Luminance weights of the container's primaries. */luma: [number, number, number];oklab: { toLms: Mat3; fromLms: Mat3 };@@ -127,6 +154,7 @@ export function gradeSpaceFor(output: OutputSpace): GradeSpace {decode: bt1886Decode,encode: bt1886Encode,pivot: 0.18,+ white: 1,luma: [0.2126, 0.7152, 0.0722],oklab: oklabMatrices(REC709_PRIMARIES),};@@ -137,6 +165,7 @@ export function gradeSpaceFor(output: OutputSpace): GradeSpace {decode: (v) => (v < 0 ? -hlgOetfInverse(-v) : hlgOetfInverse(v)),encode: (l) => (l < 0 ? -hlgOetf(-l) : hlgOetf(l)),pivot: hlgOetfInverse(0.38),+ white: 1,luma: [0.2627, 0.678, 0.0593],oklab: oklabMatrices(REC2020_PRIMARIES),};@@ -147,6 +176,7 @@ export function gradeSpaceFor(output: OutputSpace): GradeSpace {decode: (v) => (v < 0 ? -pqDecode(-v) / 1000 : pqDecode(v) / 1000),encode: (l) => (l < 0 ? -pqEncode(-l * 1000) : pqEncode(l * 1000)),pivot: 26 / 1000,+ white: 10,luma: [0.2627, 0.678, 0.0593],oklab: oklabMatrices(REC2020_PRIMARIES),};@@ -155,6 +185,91 @@ export function gradeSpaceFor(output: OutputSpace): GradeSpace {return s;}+/**+ * The grade space of scene light rendered by a display transform: linear is+ * scene-linear in `primaries` (18% grey at 0.18, no ceiling), and the+ * encoding is the transform's own response to a neutral, so curves, masks+ * and fade read a tone as the viewer will see it. `neutral` samples the+ * transform on grey from 2^LO to 2^HI; the encoding is piecewise linear in+ * log2 between the samples, and its inverse inverts that same function, so+ * the round trip is exact.+ */+export function sceneGradeSpace(output: OutputSpace, primaries: Primaries, neutral: (y: number) => number): GradeSpace {+ const LO = -16;+ const HI = 12;+ const N = 1024;+ const xs = new Float64Array(N);+ const vs = new Float64Array(N);+ for (let i = 0; i < N; i++) {+ xs[i] = LO + ((HI - LO) * i) / (N - 1);+ vs[i] = neutral(Math.pow(2, xs[i]));+ // A plateau at the top would make the inverse ambiguous; keep it rising.+ if (i && vs[i] <= vs[i - 1]) vs[i] = vs[i - 1] + 1e-9;+ }+ const y0 = Math.pow(2, LO);+ const encode = (y: number): number => {+ if (y <= y0) return (vs[0] * y) / y0;+ const x = Math.log2(y);+ if (x >= HI) return vs[N - 1];+ const f = ((x - LO) / (HI - LO)) * (N - 1);+ const i = Math.floor(f);+ return vs[i] + (vs[i + 1] - vs[i]) * (f - i);+ };+ const decode = (v: number): number => {+ if (v <= vs[0]) return (v / vs[0]) * y0;+ if (v >= vs[N - 1]) return Math.pow(2, HI);+ let lo = 0;+ let hi = N - 1;+ while (hi - lo > 1) {+ const mid = (lo + hi) >> 1;+ if (vs[mid] <= v) lo = mid;+ else hi = mid;+ }+ const x = xs[lo] + ((xs[hi] - xs[lo]) * (v - vs[lo])) / (vs[hi] - vs[lo]);+ return Math.pow(2, x);+ };+ const xyz = rgbToXyzMatrix(primaries);+ return {+ output,+ primaries,+ decode,+ encode,+ pivot: 0.18,+ white: Infinity,+ luma: [xyz[3], xyz[4], xyz[5]],+ oklab: oklabMatrices(primaries),+ };+}++/* ------------------------------------------------------------------ */+/* The shoulder */+/* ------------------------------------------------------------------ */++/** Linear light with headroom → the container's linear range: identity to+ * the knee, then k + (w − k)·(1 − (1 − u)ⁿ) up to HEADROOM·w, where u runs+ * 0..1 across the roll and n makes the slope 1 at the knee. */+export function shoulder(x: number, white: number): number {+ const k = SHOULDER_KNEE * white;+ if (x <= k) return x;+ const top = HEADROOM * white;+ if (x >= top) return white;+ const n = (top - k) / (white - k);+ const u = (x - k) / (top - k);+ return k + (white - k) * (1 - Math.pow(1 - u, n));+}++/** The shoulder's exact inverse: the container's linear range → linear light+ * with headroom. White maps to HEADROOM·white. */+export function unshoulder(y: number, white: number): number {+ const k = SHOULDER_KNEE * white;+ if (y <= k) return y;+ const top = HEADROOM * white;+ if (y >= white) return top;+ const n = (top - k) / (white - k);+ const t = (y - k) / (white - k);+ return k + (top - k) * (1 - Math.pow(1 - t, 1 / n));+}+/* ------------------------------------------------------------------ *//* Monotone tone curves *//* ------------------------------------------------------------------ */@@ -488,17 +603,17 @@ let LIN = false;function toLinear(space: GradeSpace): void {if (LIN) return;- R = space.decode(R);- G = space.decode(G);- B = space.decode(B);+ R = unshoulder(space.decode(clamp01(R)), space.white);+ G = unshoulder(space.decode(clamp01(G)), space.white);+ B = unshoulder(space.decode(clamp01(B)), space.white);LIN = true;}function toDisplay(space: GradeSpace): void {if (!LIN) return;- R = space.encode(R);- G = space.encode(G);- B = space.encode(B);+ R = space.encode(shoulder(R, space.white));+ G = space.encode(shoulder(G, space.white));+ B = space.encode(shoulder(B, space.white));LIN = false;}@@ -527,6 +642,15 @@ function fromOklab(F: Mat3, Lk: number, a: number, bb: number): void {B = F[6] * l3 + F[7] * m3 + F[8] * s3;}+/** One channel through the lift wheel: a raise adds light toward black, a+ * lowering scales toward black, so the channel never crosses zero. Both+ * fade out at white and leave the headroom above it alone. */+function lift(c: number, a: number): number {+ const toBlack = 1 - Math.min(1, Math.max(0, c));+ if (a >= 0) return c + WHEEL_LIFT * a * toBlack;+ return c * (1 + WHEEL_LIFT_DARKEN * a * toBlack);+}+function applyLayer(v: [number, number, number], L: Layer, space: GradeSpace, skinW: number): void {const damp = L.skinDamp ? skinW : 0;const pre0 = v[0];@@ -569,26 +693,29 @@ function applyLayer(v: [number, number, number], L: Layer, space: GradeSpace, sk}if (L.masks) {const y = space.luma[0] * R + space.luma[1] * G + space.luma[2] * B;- const yl = clamp01(y);- const V = clamp01(space.encode(yl));+ // The masks read the tone as it will show: through the shoulder.+ const ys = shoulder(Math.max(0, y), space.white);+ const yl = clamp01(ys);+ const V = clamp01(space.encode(ys));const iv = 1 - V;let stops = 0;if (L.highlights) stops += L.highlights * HIGHLIGHTS_STOPS * V * V * iv;if (L.shadows) stops += L.shadows * SHADOWS_STOPS * iv * iv * V;if (L.whites) stops += L.whites * WHITES_STOPS * V * V * V * V;if (L.brilliance) stops += L.brilliance * BRILLIANCE_STOPS * (1 - 2 * V) * 4 * V * iv;+ if (L.blacks < 0) stops += L.blacks * BLACKS_DARKEN_STOPS * iv * iv * iv * iv;if (stops) {const k = Math.pow(2, stops);R *= k;G *= k;B *= k;}- if (L.blacks) {+ if (L.blacks > 0) {// The mask is on linear luminance: an offset masked on the encoded// value would rise faster than the signal near black and fold the// ramp over.const iy = 1 - yl;- const off = L.blacks * Math.abs(L.blacks) * BLACKS_OFFSET * iy * iy * iy;+ const off = L.blacks * L.blacks * BLACKS_OFFSET * iy * iy * iy;R += off;G += off;B += off;@@ -597,9 +724,9 @@ function applyLayer(v: [number, number, number], L: Layer, space: GradeSpace, skfor (const w of L.wheels) {const a = w.amount;if (w.zone === "s") {- R += WHEEL_LIFT * a[0] * (1 - R);- G += WHEEL_LIFT * a[1] * (1 - G);- B += WHEEL_LIFT * a[2] * (1 - B);+ R = lift(R, a[0]);+ G = lift(G, a[1]);+ B = lift(B, a[2]);} else if (w.zone === "m") {R = spow(R, 1 / (1 + WHEEL_GAMMA * a[0]));G = spow(G, 1 / (1 + WHEEL_GAMMA * a[1]));@@ -609,9 +736,9 @@ function applyLayer(v: [number, number, number], L: Layer, space: GradeSpace, skG *= 1 + WHEEL_GAIN * a[1];B *= 1 + WHEEL_GAIN * a[2];} else {- R += WHEEL_OFFSET * a[0];- G += WHEEL_OFFSET * a[1];- B += WHEEL_OFFSET * a[2];+ R *= Math.pow(2, WHEEL_OFFSET_STOPS * a[0]);+ G *= Math.pow(2, WHEEL_OFFSET_STOPS * a[1]);+ B *= Math.pow(2, WHEEL_OFFSET_STOPS * a[2]);}}}@@ -697,17 +824,14 @@ export type GradeTransform = (r: number, g: number, b: number) => [number, numbe*/export function createGradeTransform(g: ColorGrade | undefined | null,- output: OutputSpace = "sdr"+ output: OutputSpace | GradeSpace = "sdr"): GradeTransform | null {const n = normalizeGrade(g);if (!n) return null;- const space = gradeSpaceFor(output);+ const space = typeof output === "string" ? gradeSpaceFor(output) : output;+ // The manual adjustments balance the shot first, so the look lands on a+ // corrected picture the same way on every clip.const layers: Layer[] = [];- const presetGrade = resolvePreset(n.preset);- if (presetGrade) {- const layer = buildLayer(presetGrade, space, !!n.preset?.skin);- if (layer) layers.push(layer);- }const manual: ColorGrade = { ...n };delete manual.preset;delete manual.lut;@@ -715,6 +839,11 @@ export function createGradeTransform(delete manual.clarity;const manualLayer = buildLayer(manual, space, false);if (manualLayer) layers.push(manualLayer);+ const presetGrade = resolvePreset(n.preset);+ if (presetGrade) {+ const layer = buildLayer(presetGrade, space, !!n.preset?.skin);+ if (layer) layers.push(layer);+ }if (!layers.length) return null;const anySkin = layers.some((l) => l.skinDamp);return (r, g2, b) => {diff --git a/site/packages/effects-kit/src/gradeSpec.ts b/site/packages/effects-kit/src/gradeSpec.tsnew file mode 100644index 00000000..aaca493b--- /dev/null+++ b/site/packages/effects-kit/src/gradeSpec.ts@@ -0,0 +1,604 @@+/**+ * The color-science spec the shipped grade presets are held to, as data the+ * tests and the preset tuner both read (gradeEval.test.ts runs it under+ * bun's expect; scripts/tune-grade-presets.ts sums how far each bound is+ * missed and fits the recipes to it). A check takes `expect` as an argument,+ * so the same lines are an assertion in a test and a penalty in a fit.+ */++import type { ColorGrade } from "./colorGrade";+import { displayToLab, labChromaHue } from "./colorDifference";+import { createClipTransform } from "./colorPipeline";+import { type OutputSpace, type SourceProfile, appleLogEncode, bt1886Encode, hlgOetf, hlgOetfInverse } from "./colorSpace";+import type { GradePreset } from "./gradePresets";+import type { ParsedLut } from "./lutFile";++export interface Expectation {+ toBe(v: unknown): void;+ toBeLessThan(n: number): void;+ toBeLessThanOrEqual(n: number): void;+ toBeGreaterThan(n: number): void;+ toBeGreaterThanOrEqual(n: number): void;+}++export type Expect = (v: unknown) => Expectation;+++/** ColorChecker Classic, sRGB. */+export const CHART: Record<string, [number, number, number]> = {+ darkSkin: [115, 82, 68],+ lightSkin: [194, 150, 130],+ blueSky: [98, 122, 157],+ foliage: [87, 108, 67],+ blueFlower: [133, 128, 177],+ bluishGreen: [103, 189, 170],+ orange: [214, 126, 44],+ purplishBlue: [80, 91, 166],+ moderateRed: [193, 90, 99],+ purple: [94, 60, 108],+ yellowGreen: [157, 188, 64],+ orangeYellow: [224, 163, 46],+ blue: [56, 61, 150],+ green: [70, 148, 73],+ red: [175, 54, 60],+ yellow: [231, 199, 31],+ magenta: [187, 86, 149],+ cyan: [8, 133, 161],+ white95: [243, 243, 242],+ neutral8: [200, 200, 200],+ neutral65: [160, 160, 160],+ neutral5: [122, 122, 121],+ neutral35: [85, 85, 85],+ black2: [52, 52, 52],+};++export const PATCHES = Object.keys(CHART);+export const SKIN = ["darkSkin", "lightSkin"];+export const COLORFUL = PATCHES.filter((n) => !/^(white|neutral|black)/.test(n) && !SKIN.includes(n));+/** The chart's gray ramp, darkest first. */+export const RAMP = ["black2", "neutral35", "neutral5", "neutral65", "neutral8", "white95"];+/** A synthetic exposure ramp for tone-response readings: index 0 is black. */+export const GRAY = [0, 32, 64, 128, 192, 224, 255];+export const [, SHADOW, , MID, , HIGH, WHITE] = GRAY.map((_, i) => i);++export const hsv = ([r, g, b]: number[]) => {+ const mx = Math.max(r, g, b);+ const mn = Math.min(r, g, b);+ const d = mx - mn;+ let h = 0;+ if (d) {+ if (mx === r) h = ((g - b) / d) % 6;+ else if (mx === g) h = (b - r) / d + 2;+ else h = (r - g) / d + 4;+ h = (h * 60 + 360) % 360;+ }+ return { h, s: mx ? d / mx : 0 };+};+export const luma = ([r, g, b]: number[]) => 0.2126 * r + 0.7152 * g + 0.0722 * b;+export const hueDelta = (a: number, b: number) => {+ let d = (b - a) % 360;+ if (d > 180) d -= 360;+ if (d < -180) d += 360;+ return Math.abs(d);+};++++export interface Measured {+ /** The graded chart, by patch name. */+ patch: Record<string, number[]>;+ /** Pure black and pure white as rendered — the film toe and shoulder. */+ black: number;+ white: number;+ /** Mid gray as rendered: the look's overall level. */+ mid: number;+ /** Tone-curve slope across the middle of the range: contrast. */+ slope: number;+ /** R−B at shadow / mid / highlight. Positive is warm. */+ warm: { s: number; m: number; h: number };+ /** G − (R+B)/2 at shadow / mid / highlight. Positive is green, negative magenta. */+ green: { s: number; m: number; h: number };+ /** Mean saturation multiplier over the chart's colorful patches. */+ sat: number;+ /** Hue variety left in the chart: 1 is the full wheel, 0 is a single tone. */+ spread: number;+ /** R−B on the light-skin patch. */+ skinWarm: number;+}++export function measure(apply: (colors: number[][]) => number[][]): Measured {+ const chart = apply(PATCHES.map((n) => CHART[n]));+ const patch: Record<string, number[]> = {};+ PATCHES.forEach((n, i) => (patch[n] = chart[i]));+ const gray = apply(GRAY.map((s) => [s, s, s]));+ const warmOf = (c: number[]) => c[0] - c[2];+ const greenOf = (c: number[]) => Math.round(c[1] - (c[0] + c[2]) / 2);+ const mults = COLORFUL.map((n) => {+ const before = hsv(CHART[n]).s;+ return before > 0.05 ? hsv(patch[n]).s / before : 1;+ });+ // Circular mean of the surviving hues: a toning process collapses them all+ // onto one, which shows up here as a spread near zero.+ const hues = COLORFUL.filter((n) => hsv(patch[n]).s > 0.08).map((n) => hsv(patch[n]).h);+ const cx = hues.reduce((a, h) => a + Math.cos((h * Math.PI) / 180), 0) / (hues.length || 1);+ const cy = hues.reduce((a, h) => a + Math.sin((h * Math.PI) / 180), 0) / (hues.length || 1);+ return {+ patch,+ black: luma(gray[0]),+ white: luma(gray[WHITE]),+ mid: luma(gray[MID]),+ slope: (luma(gray[HIGH]) - luma(gray[SHADOW])) / (GRAY[HIGH] - GRAY[SHADOW]),+ warm: { s: warmOf(gray[SHADOW]), m: warmOf(gray[MID]), h: warmOf(gray[HIGH]) },+ green: { s: greenOf(gray[SHADOW]), m: greenOf(gray[MID]), h: greenOf(gray[HIGH]) },+ sat: mults.reduce((a, b) => a + b, 0) / mults.length,+ spread: 1 - Math.hypot(cx, cy),+ skinWarm: warmOf(patch.lightSkin),+ };+}++/** A toning process puts one hue over the whole frame, so the rails that+ * assume the grade preserved color relationships do not apply to it. */+export const isToned = (m: Measured) => m.spread <= 0.1;++/* ------------------------------------------------------------------ */+/* Tier 1: safety */+/* ------------------------------------------------------------------ */++/** Skin chroma a look may add, as a multiple of the face's own. */+export const SKIN_CHROMA_GAIN_MAX = 1.35;+/** Degrees of Lab hue a colored face may move off where it started. */+export const SKIN_HUE_DRIFT_MAX = 10;++/** Measured in CIELAB, where the chart's skin patches sit on the skin-tone+ * line near a 45° hue angle. A face may warm or cool along that line and+ * gain at most a third more chroma; past that it reads sunburned or painted.+ * While the face still carries color it holds the line. A muted face may+ * drift — with little chroma its hue no longer reads — and a toned+ * monochrome puts every subject on the tone's hue by definition. */+export function skinStaysSkin(m: Measured, expect: Expect): void {+ for (const name of SKIN) {+ const before = labChromaHue(displayToLab(...CHART[name]));+ const after = labChromaHue(displayToLab(...(m.patch[name] as [number, number, number])));+ expect(after.c / before.c).toBeLessThanOrEqual(SKIN_CHROMA_GAIN_MAX);+ if (after.c >= before.c * 0.6 && !isToned(m)) {+ expect(hueDelta(before.h, after.h)).toBeLessThanOrEqual(SKIN_HUE_DRIFT_MAX);+ }+ }+}++/** A grade may accent a hue; it never approaches doubling one, and the chart+ * as a whole gains at most ~40%. */+export function saturationBounded(m: Measured, expect: Expect): void {+ const mults = COLORFUL.map((n) => {+ const before = hsv(CHART[n]).s;+ return before > 0.05 ? hsv(m.patch[n]).s / before : 1;+ });+ expect(m.sat).toBeLessThanOrEqual(1.4);+ expect(Math.max(...mults)).toBeLessThanOrEqual(1.75);+}++/** The gray ramp stays monotonic — a reversal is solarization — chart black+ * keeps shadow detail, and a cast on the mid grays stays in warming-gel+ * range. A toning process is a deliberate wash, judged by its own rail. */+export function levelsHold(m: Measured, expect: Expect): void {+ const ramp = RAMP.map((n) => luma(m.patch[n]));+ for (let i = 1; i < ramp.length; i++) expect(ramp[i]).toBeGreaterThanOrEqual(ramp[i - 1] - 1);+ expect(luma(m.patch.black2)).toBeGreaterThanOrEqual(12);+ if (isToned(m)) return;+ for (const name of ["neutral5", "neutral65"]) {+ const c = m.patch[name];+ expect(Math.max(...c) - Math.min(...c)).toBeLessThanOrEqual(48);+ }+}++/** Black and white carries no color on any patch. */+export function monochrome(m: Measured, expect: Expect): void {+ for (const name of PATCHES) {+ const c = m.patch[name];+ expect(Math.max(...c) - Math.min(...c)).toBeLessThanOrEqual(2);+ }+}++/* ------------------------------------------------------------------ */+/* Tier 2: identity */+/* ------------------------------------------------------------------ */+++export interface Signature {+ /** What this preset is emulating, in the world. */+ process: string;+ /** What emulating it has to measure like on the chart. */+ holds(m: Measured, expect: Expect): void;+}++export const IDENTITY: Record<string, Signature> = {+ /* — cinematic ---------------------------------------------------- */+ "teal-orange": {+ process: "the complementary blockbuster split: shadows toward teal, skin and highlights toward orange",+ holds: (m, expect) => {+ expect(m.warm.s).toBeLessThanOrEqual(-15);+ expect(m.warm.h - m.warm.s).toBeGreaterThanOrEqual(30);+ expect(m.skinWarm).toBeGreaterThanOrEqual(40);+ },+ },+ "bleach-bypass": {+ process: "silver retention: the bleach step is skipped so metallic silver stays in the print — contrast climbs and color drains",+ holds: (m, expect) => {+ expect(m.sat).toBeLessThanOrEqual(0.75);+ expect(m.slope).toBeGreaterThanOrEqual(1.15);+ expect(m.black).toBeLessThanOrEqual(10);+ },+ },+ matinee: {+ process: "an old Hollywood matinee print: bright, warm, and full-blooded in color",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(3);+ expect(m.mid).toBeGreaterThanOrEqual(130);+ expect(m.sat).toBeGreaterThanOrEqual(1.1);+ },+ },+ thriller: {+ process: "the hard, cold tension grade: contrast up, everything pulled off warm",+ holds: (m, expect) => {+ expect(m.warm.m).toBeLessThanOrEqual(-10);+ expect(m.slope).toBeGreaterThanOrEqual(1.12);+ expect(m.black).toBeLessThanOrEqual(10);+ },+ },+ "night-market": {+ process: "a neon-lit street after dark: cool highlights over saturated signage color",+ holds: (m, expect) => {+ expect(m.warm.h).toBeLessThanOrEqual(-6);+ expect(m.sat).toBeGreaterThanOrEqual(1.08);+ },+ },+ "sci-fi": {+ process: "cold blue-cyan futurism, the cast deepening as it climbs the range",+ holds: (m, expect) => {+ expect(m.warm.h).toBeLessThanOrEqual(-25);+ expect(m.warm.h).toBeLessThan(m.warm.m);+ },+ },+ western: {+ process: "sun-baked dust: strongly warm, and muted by the haze rather than punchy",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(12);+ expect(m.sat).toBeLessThanOrEqual(1.0);+ },+ },+ indie: {+ process: "the flat lifted-contrast indie look: milky blacks, gentle slope, drained color",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(14);+ expect(m.slope).toBeLessThanOrEqual(0.94);+ expect(m.sat).toBeLessThanOrEqual(0.82);+ },+ },++ /* — film --------------------------------------------------------- */+ "16mm": {+ process: "16mm color negative: a base-plus-fog toe, a gentle shoulder, and the stock's crossover from cool shadows into warm highlights",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(8);+ expect(m.white).toBeLessThanOrEqual(252);+ expect(m.warm.h - m.warm.s).toBeGreaterThanOrEqual(8);+ expect(m.sat).toBeLessThanOrEqual(1.05);+ },+ },+ "super-8": {+ process: "Super 8 home-movie reversal: warm, soft-shouldered, and lifted",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(14);+ expect(m.warm.m).toBeGreaterThanOrEqual(10);+ expect(m.slope).toBeLessThanOrEqual(1.0);+ expect(m.sat).toBeLessThanOrEqual(0.95);+ },+ },+ "faded-film": {+ process: "a faded release print: the cyan dye layer goes first, so the image drifts pink as it flattens",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(25);+ expect(m.slope).toBeLessThanOrEqual(0.82);+ expect(m.sat).toBeLessThanOrEqual(0.68);+ expect(m.green.m).toBeLessThanOrEqual(-4);+ },+ },+ chrome: {+ process: "Kodachrome-style reversal: dense blacks under famously rich color",+ holds: (m, expect) => {+ expect(m.sat).toBeGreaterThanOrEqual(1.18);+ expect(m.black).toBeLessThanOrEqual(8);+ },+ },+ "push-process": {+ process: "pushed development: underexposure bought back in the tank — contrast and grain climb, the toe crushes, highlights blow, and color goes flat",+ holds: (m, expect) => {+ expect(m.slope).toBeGreaterThanOrEqual(1.2);+ expect(m.black).toBeLessThanOrEqual(6);+ expect(m.sat).toBeLessThanOrEqual(0.96);+ },+ },+ "cine-print": {+ process: "print stock, the contrastiest link in the photochemical chain: dense blacks and controlled color",+ holds: (m, expect) => {+ expect(m.slope).toBeGreaterThanOrEqual(1.12);+ expect(m.black).toBeLessThanOrEqual(12);+ },+ },+ tungsten: {+ process: "daylight stock under 3200K tungsten light: a source warming the whole scene, so the cast reaches the shadows rather than washing only the highlights",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(18);+ expect(m.warm.s).toBeGreaterThanOrEqual(12);+ expect(m.warm.h - m.warm.s).toBeLessThanOrEqual(28);+ },+ },+ instant: {+ process: "integral-tripack instant film: a milky toe, muted dyes, and cool shadows running into warm highlights",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(25);+ expect(m.slope).toBeLessThanOrEqual(0.88);+ expect(m.sat).toBeLessThanOrEqual(0.72);+ expect(m.warm.s).toBeLessThan(0);+ expect(m.warm.h).toBeGreaterThanOrEqual(5);+ },+ },+ expired: {+ process: "expired stock: the emulsion layers lose sensitivity at different rates, so a green-yellow cast settles over a fogged toe",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(20);+ expect(m.green.m).toBeGreaterThanOrEqual(6);+ expect(m.sat).toBeLessThanOrEqual(0.68);+ expect(m.slope).toBeLessThanOrEqual(0.92);+ },+ },++ /* — warm --------------------------------------------------------- */+ "golden-hour": {+ process: "low sun near the horizon: warm and bright, the light itself lifting the frame",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(16);+ expect(m.mid).toBeGreaterThanOrEqual(130);+ },+ },+ amber: {+ process: "an amber wash laid over the grade, weighted to the highlights the way a gel reads rather than a room light",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(20);+ expect(m.warm.h - m.warm.s).toBeGreaterThanOrEqual(30);+ },+ },+ honey: {+ process: "a soft honeyed warmth that leaves contrast where it found it",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(12);+ expect(m.slope).toBeLessThanOrEqual(1.08);+ },+ },+ sunbaked: {+ process: "hard sun on dry ground: warm and slightly bleached",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(12);+ expect(m.sat).toBeLessThanOrEqual(1.02);+ },+ },+ peach: {+ process: "a pale peach cast over a softly lifted toe",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(9);+ expect(m.black).toBeGreaterThanOrEqual(8);+ },+ },+ sepia: {+ process: "sepia toning: the print's silver is converted to silver sulfide, so the whole frame carries one brown tone rather than a tint over surviving color",+ holds: (m, expect) => {+ expect(m.spread).toBeLessThanOrEqual(0.08);+ expect(m.warm.m).toBeGreaterThanOrEqual(28);+ },+ },+ ember: {+ process: "firelight: warm and contrasty, the glow strongest up top",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(17);+ expect(m.slope).toBeGreaterThanOrEqual(1.08);+ },+ },+ bronze: {+ process: "a burnished bronze cast, warm and slightly muted",+ holds: (m, expect) => {+ expect(m.warm.m).toBeGreaterThanOrEqual(18);+ expect(m.sat).toBeLessThanOrEqual(1.02);+ },+ },++ /* — mood --------------------------------------------------------- */+ midnight: {+ process: "deep night: cool throughout and genuinely dark",+ holds: (m, expect) => {+ expect(m.warm.m).toBeLessThanOrEqual(-8);+ expect(m.mid).toBeLessThanOrEqual(120);+ },+ },+ moss: {+ process: "damp woodland green, strengthening through the highlights",+ holds: (m, expect) => {+ expect(m.green.m).toBeGreaterThanOrEqual(4);+ expect(m.green.h).toBeGreaterThanOrEqual(m.green.m);+ },+ },+ slate: {+ process: "cool grey stone: the cast pulled off warm and the color drained down",+ holds: (m, expect) => {+ expect(m.warm.m).toBeLessThanOrEqual(-4);+ expect(m.sat).toBeLessThanOrEqual(0.85);+ },+ },+ dusk: {+ process: "the light after sundown: cool, dimming, and going magenta up top",+ holds: (m, expect) => {+ expect(m.warm.m).toBeLessThan(0);+ expect(m.mid).toBeLessThanOrEqual(126);+ },+ },+ neon: {+ process: "neon: color pushed hard against a cool ground",+ holds: (m, expect) => {+ expect(m.sat).toBeGreaterThanOrEqual(1.18);+ expect(m.warm.h).toBeLessThan(0);+ },+ },+ arctic: {+ process: "cold open daylight off snow: a strong blue cast climbing with the tone",+ holds: (m, expect) => {+ expect(m.warm.h).toBeLessThanOrEqual(-28);+ expect(m.warm.h).toBeLessThan(m.warm.m);+ },+ },+ storm: {+ process: "storm light: cool, dark, and drained",+ holds: (m, expect) => {+ expect(m.warm.m).toBeLessThanOrEqual(-5);+ expect(m.sat).toBeLessThanOrEqual(0.96);+ expect(m.mid).toBeLessThanOrEqual(124);+ },+ },+ velvet: {+ process: "deep low-light richness: color held up while the frame sits down",+ holds: (m, expect) => {+ expect(m.sat).toBeGreaterThanOrEqual(1.15);+ expect(m.mid).toBeLessThanOrEqual(118);+ },+ },++ /* — black & white ------------------------------------------------ */+ mono: {+ process: "a straight panchromatic conversion: neutral, with normal contrast",+ holds: (m, expect) => {+ expect(m.black).toBeLessThanOrEqual(8);+ expect(m.slope).toBeGreaterThanOrEqual(1.0);+ },+ },+ silver: {+ process: "a silver-gelatin print: a gently lifted toe and a soft slope",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(10);+ expect(m.slope).toBeLessThanOrEqual(1.05);+ },+ },+ ink: {+ process: "a hard graphic conversion: solid ink blacks, a steep clean slope, no veil in the toe",+ holds: (m, expect) => {+ expect(m.slope).toBeGreaterThanOrEqual(1.2);+ expect(m.black).toBeLessThanOrEqual(8);+ },+ },+ "high-key": {+ process: "high-key lighting: the whole frame carried up, shadows opened",+ holds: (m, expect) => {+ expect(m.mid).toBeGreaterThanOrEqual(140);+ expect(m.black).toBeGreaterThanOrEqual(14);+ },+ },+ "low-key": {+ process: "low-key lighting: the frame carried down onto dense blacks",+ holds: (m, expect) => {+ expect(m.mid).toBeLessThanOrEqual(116);+ expect(m.black).toBeLessThanOrEqual(8);+ },+ },+ charcoal: {+ process: "charcoal on paper: a lifted toe under a soft, slightly dark rendering",+ holds: (m, expect) => {+ expect(m.black).toBeGreaterThanOrEqual(10);+ expect(m.slope).toBeLessThanOrEqual(1.0);+ expect(m.mid).toBeLessThanOrEqual(126);+ },+ },+ "soft-mono": {+ process: "a soft monochrome: low slope over an open toe",+ holds: (m, expect) => {+ expect(m.slope).toBeLessThanOrEqual(0.92);+ expect(m.black).toBeGreaterThanOrEqual(16);+ },+ },+ grit: {+ process: "pushed reportage monochrome: steep and harsh, but grain veils the toe — a pushed negative never scans to a clean black",+ holds: (m, expect) => {+ expect(m.slope).toBeGreaterThanOrEqual(1.15);+ expect(m.black).toBeGreaterThanOrEqual(10);+ },+ },+};++/** What every preset on a shelf shares. A warm preset is warm — that is what+ * the shelf means. A film preset emulates a stock, and a stock has a+ * characteristic curve: a toe that lifts black, a shoulder that rolls+ * highlights, or a slope away from straight-through; a recipe that only+ * shifts color is a cast. */+export const PREMISE: Partial<Record<GradePreset["category"], (m: Measured, expect: Expect) => void>> = {+ warm: (m, expect) => expect(m.warm.m).toBeGreaterThanOrEqual(8),+ // The best of the three, each as its share of the way past its bound.+ film: (m, expect) =>+ expect(Math.max((m.black - 8) / 8, (250 - m.white) / 5, (Math.abs(m.slope - 1) - 0.1) / 0.1)).toBeGreaterThanOrEqual(0),+};++/* ------------------------------------------------------------------ */+/* Range */+/* ------------------------------------------------------------------ */++/**+ * Range retention: a look may move tones anywhere it likes, but it may not+ * throw picture away. A grey ramp in stops about 18% grey runs through the+ * real clip transform for each source; the window is every stop the ungraded+ * rendering shows as gradation — between near-black and near-white, at least+ * WINDOW_SLOPE code values per stop — and a grade loses the stops of that+ * window it pushes onto the floor or the ceiling of the 8-bit output. A hard clip or crush is exactly that loss; a soft shoulder or toe+ * keeps the stops, only closer together.+ */++const FLOOR = 2 / 255;+const CEILING = 253 / 255;+const WINDOW_LO = 8 / 255;+const WINDOW_HI = 250 / 255;+/** Gradation the base must show for a stop to count: 2 code values. */+const WINDOW_SLOPE = 2 / 255;+const STEP = 0.05;+/** A fold below a 10-bit step is invisible: a quarter of an 8-bit code. */+const FOLD_MAX = 0.25 / 255;+/** BT.2408 grey in an HLG signal. */+const HLG_GREY = 0.38;+/** The stops a look may give up in the visible window. */+export const LOOK_LOSS_MAX = 0.5;++/** Code value of a scene or display grey `stops` from 18% grey, per source. */+function rampCode(profile: SourceProfile, stops: number): number {+ const lin = 0.18 * 2 ** stops;+ if (profile === "apple-log" || profile === "apple-log-2") return appleLogEncode(lin);+ if (profile === "hlg") return hlgOetf(Math.min(1, hlgOetfInverse(HLG_GREY) * 2 ** stops));+ return bt1886Encode(Math.min(1, lin));+}++export function rangeRamp(profile: SourceProfile, output: OutputSpace, grade?: ColorGrade, lut?: ParsedLut): number[] {+ const t = createClipTransform({ profile, output, size: 33, ...(grade ? { grade } : {}) }, lut);+ const out: number[] = [];+ for (let s = -12; s <= 9 + 1e-9; s += STEP) {+ const c = rampCode(profile, s);+ out.push(t ? t(c, c, c)[1] : c);+ }+ return out;+}++/** Stops of the base window the graded ramp floors or ceilings. */+export function stopsLost(base: number[], graded: number[]): number {+ let lost = 0;+ for (let i = 1; i < base.length; i++) {+ if (base[i] < WINDOW_LO || base[i] > WINDOW_HI) continue;+ if ((base[i] - base[i - 1]) / STEP < WINDOW_SLOPE) continue;+ if (graded[i] <= FLOOR || graded[i] >= CEILING) lost += STEP;+ }+ return lost;+}++export function isMonotone(values: number[]): boolean {+ return values.every((v, i) => i === 0 || v >= values[i - 1] - FOLD_MAX);+}