diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 9f8f6f872ae..cdcbafb4147 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -127,12 +127,17 @@ pub enum Process { /// V16, with Apple ProRAW's tone sliders running in Lightroom's fitted tone chain /// (`lightcraft_pipeline::proraw`). V17, + /// V17, with Whites and the parametric curve from a fitted model, and the tone curves applied + /// hue-preserving: Whites, the parametric and point curve in linear ProPhoto RGB, then the red, green and + /// blue curves per channel, before the colour stage (`lightcraft_pipeline::curve_stage`, + /// `docs/curve-stage.md`). + V18, } impl Process { /// Every process, oldest first (`ProcessVersion(9)` names none and renders as V8; 11 and 12 name none and /// render as V10). - pub const ALL: [Process; 14] = [ + pub const ALL: [Process; 15] = [ Process::V1, Process::V2, Process::V3, @@ -147,8 +152,9 @@ impl Process { Process::V15, Process::V16, Process::V17, + Process::V18, ]; - pub const LATEST: Process = Process::V17; + pub const LATEST: Process = Process::V18; pub const fn version(self) -> ProcessVersion { match self { @@ -166,6 +172,7 @@ impl Process { Process::V15 => ProcessVersion(15), Process::V16 => ProcessVersion(16), Process::V17 => ProcessVersion(17), + Process::V18 => ProcessVersion(18), } } } diff --git a/crates/engine/src/files/load.rs b/crates/engine/src/files/load.rs index 1ef908a00f1..5d8b4d57443 100644 --- a/crates/engine/src/files/load.rs +++ b/crates/engine/src/files/load.rs @@ -258,6 +258,12 @@ fn load_bytes_now( let proraw = (dcp.is_none() && camera_look.is_none()).then(|| proraw_tone(&raw, t.baseline_exposure as f32, &img.data)).flatten().map(Arc::new); let local_tone = local_tone(&raw); + // From process V18 a profile without a tone curve of its own (Adobe Standard) renders with the fitted + // default curve, shifted by the camera's measured exposure offset (`lightcraft_pipeline::default_tone`). + let default_tone = dcp.filter(|p| p.color.profile.tone_curve.is_none()).map(|_| { + let m = &raw.metadata; + lightcraft_pipeline::default_tone::camera_ev(m.make.as_deref().unwrap_or(""), m.model.as_deref().unwrap_or("")) + }); let (temp, tint) = scale.as_shot(xy); return Ok(( img, @@ -271,6 +277,7 @@ fn load_bytes_now( legacy_relative_wb: scale.legacy_relative, camera_color, camera_tone, + default_tone, mattes, local_tone, proraw, diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 7a1690394ea..3d50b5a366a 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -117,6 +117,11 @@ struct SmartFacts { lens: Option, camera_color: Option, local_tone: Option, + /// `SourceInfo::default_tone`. Smart previews are built without the photo's camera profile, so this is `None` for + /// them today and an offline photo renders on its stored camera tone (`docs/default-tone.md`); recorded so a + /// preview built with the profile can carry it without a format change. + #[serde(default)] + default_tone: Option, /// Apple ProRAW's profile curve for Lightroom's tone chain (absent before version 4: such a /// proxy renders ProRAW on the camera-curve path, retaining V16 behavior). #[serde(default, deserialize_with = "lenient_proraw")] @@ -239,6 +244,7 @@ pub(crate) fn encode_with_lens_key(img: &Rgb32f, info: Option<&SourceInfo>, lens lens: i.lens, camera_color: i.camera_color.as_deref().cloned(), local_tone: i.local_tone.as_deref().cloned(), + default_tone: i.default_tone, proraw: i.proraw.as_deref().cloned(), mattes: matte_list, }; @@ -287,6 +293,7 @@ pub fn decode(bytes: &[u8]) -> Result<(Rgb32f, Option, Option 0.01, "V7 keeps the file's own tone: {}", v7.apply(0.18)); +} + #[test] fn import_choose_cache_persist_and_delete() { let dir = temp_dir("session"); diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index c978493eaf5..c11e5522eeb 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -427,6 +427,18 @@ fn constants() -> String { let rows: Vec = m.iter().map(|r| format!("vec3({:?}, {:?}, {:?})", r[0], r[1], r[2])).collect(); s += &format!("const {name} = array, 3>({});\n", rows.join(", ")); } + { + use lightcraft_pipeline::hs_range as hr; + s += &format!( + "const HS_H_AMP: f32 = {:?};\nconst HS_H_SPAN: f32 = {:?};\nconst HS_H_POW: f32 = {:?};\nconst HS_H_REACH: f32 = {:?};\nconst HS_H_AMP_MIN: f32 = {:?};\nconst HS_H_AMP_MAX: f32 = {:?};\n", + hr::H_AMP, + hr::H_SPAN, + hr::H_POW, + hr::H_REACH, + hr::H_AMP_RANGE.0, + hr::H_AMP_RANGE.1 + ); + } s += &format!( "const TONE_MIN_EV: f32 = {LUT_MIN_EV:?};\nconst TONE_MAX_EV: f32 = {LUT_MAX_EV:?};\nconst TONE_N: u32 = {LUT_N}u;\nconst CHROMA_N: u32 = {CHROMA_N}u;\n" ); diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index e760bda9aa6..3db87351347 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -23,6 +23,18 @@ const FIELDS: &[(&str, usize)] = &[ ("SRGB_OFF", 1), ("CURVE_OFF", 1), ("CURVES", 1), + ("STAGE", 1), + ("STAGE_OFF", 1), + ("STAGE_REFINE", 1), + ("MSTAGE", 1), + ("MSTAGE_OFF", 1), + ("MGRADE", 1), + ("MGRADE_OFF", 1), + ("RGB_TONE", 1), + ("HS_RANGE", 1), + ("HS_RANGE_LO", 1), + ("HS_RANGE_HI", 1), + ("STAGE_WHITES", 1), ("GAIN", 1), ("EV", 1), ("AIR", 1), @@ -296,20 +308,40 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr let srgb_off = aux.len(); aux.extend_from_slice(&srgb_lut()[..]); let curve_off = aux.len(); - if let Some(c) = &fp.curves { - for l in c { - if l.v.len() != CURVE_N as usize { - // a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and - // the mask terms that follow) and make the kernel read the wrong data. `fail()` - // records the failure on this thread so the render falls back to the CPU; the - // partial `(p, aux)` returned here is never bound to a pipeline. - fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N)); - // `p` is only assembled below the curve loop, so an empty block is as good as any: - // the caller (render.rs) gates on `failed()` right after this returns and bails to - // the CPU fallback before indexing `p` or uploading `aux`. - return (Vec::new(), aux); - } - aux.extend_from_slice(&l.v); + let stage_off = curve_off + fp.curves.as_ref().map_or(0, |c| c.len() * CURVE_N as usize); + // process V18's stage (red, green, blue, then the base table) or the earlier processes' curves + // (and Whites alone after the base table, when Refine Saturation needs it) + let tables = fp.curves.iter().flatten().chain(fp.curve_stage.iter().flat_map(|c| c.chan.iter().chain([&c.base]).chain(c.whites.iter()))); + for l in tables { + if l.v.len() != CURVE_N as usize { + // a wrong-length curve would shift every later aux offset (CURVE_OFF, MASK_OFF and + // the mask terms that follow) and make the kernel read the wrong data. `fail()` + // records the failure on this thread so the render falls back to the CPU; the + // partial `(p, aux)` returned here is never bound to a pipeline. + fail(FailKind::Fatal, format!("curve table has {} entries, expected {}", l.v.len(), CURVE_N)); + // `p` is only assembled below the curve loop, so an empty block is as good as any: + // the caller (render.rs) gates on `failed()` right after this returns and bails to + // the CPU fallback before indexing `p` or uploading `aux`. + return (Vec::new(), aux); + } + aux.extend_from_slice(&l.v); + } + // process V18's mixer stage: its 9 chroma and 3 lightness keys, then its table + let mstage_off = aux.len(); + if let Some(cs) = &fp.mixer_stage { + aux.extend(cs.chroma.iter().flatten()); + aux.extend_from_slice(&cs.light); + aux.extend_from_slice(&cs.table[..]); + } + // process V18's Colour Grading: the Luminance curve, then per wheel its tint, damping and profile + let mgrade_off = aux.len(); + let mgrade = fp.ops.measured_grading.as_ref(); + if let Some(g) = mgrade { + aux.extend_from_slice(&g.lum); + for w in &g.wheels { + aux.extend_from_slice(&w.tint); + aux.extend(w.damping.iter().flatten()); + aux.extend_from_slice(&w.profile); } } let mask_off = aux.len(); @@ -358,6 +390,19 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.u("SRGB_OFF", srgb_off as u32); p.u("CURVE_OFF", curve_off as u32); p.b("CURVES", fp.curves.is_some()); + p.b("STAGE", fp.curve_stage.is_some()); + p.u("STAGE_OFF", stage_off as u32); + p.f("STAGE_REFINE", fp.curve_stage.as_ref().map_or(1.0, |c| c.refine)); + p.b("MSTAGE", fp.mixer_stage.is_some()); + p.u("MSTAGE_OFF", mstage_off as u32); + // 0: off, else 1 + the number of wheels with a tint + p.u("MGRADE", mgrade.map_or(0, |g| 1 + g.wheels.len() as u32)); + p.u("MGRADE_OFF", mgrade_off as u32); + p.b("RGB_TONE", fp.rgb_tone); + p.b("HS_RANGE", fp.hs_range.is_some()); + p.f("HS_RANGE_LO", fp.hs_range.map_or(0.0, |r| r.lo)); + p.f("HS_RANGE_HI", fp.hs_range.map_or(0.0, |r| r.hi)); + p.b("STAGE_WHITES", fp.curve_stage.as_ref().is_some_and(|c| c.whites.is_some())); p.f("REFINE_SAT", fp.refine_sat); p.f("GAIN", fp.gain); p.f("EV", fp.ev); diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index f7cde89ca86..fdec3d75c0b 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -814,6 +814,7 @@ pub fn render( image_size: (w, h), px_per_long: plan.px_per_long, air_pre: prep.air, + hs_range: plan.hs_range, space: req.space, draft: req.quality == lightcraft_pipeline::Quality::Draft, }); diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 265e84b1faa..249ec1cc5b8 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -98,6 +98,32 @@ fn light_channel(k: u32, x: f32) -> f32 { return light_eval(k, encode_srgb(x)); } +// `FrameRange::highlights` (process V18): Highlights scaled by the frame's tonal range HS_RANGE_LO..HS_RANGE_HI. +fn hs_range_highlights(hh: f32, base: f32) -> f32 { + if (hh == 0.0) { + return 0.0; + } + let span = max(pf(F_HS_RANGE_HI) - pf(F_HS_RANGE_LO), 0.1); + let amp = clamp(HS_H_AMP * pow(span / HS_H_SPAN, HS_H_POW), HS_H_AMP_MIN, HS_H_AMP_MAX); + let low = -1.0 - HS_H_REACH * max(span - HS_H_SPAN, 0.0); + return hh * amp * sstep(low, 2.8, base); +} + +// `default_tone::rgb_tone`: the base tone on the largest and smallest linear ProPhoto channel, the middle +// channel keeping its place between them (process V18 with the fitted default curve). +fn rgb_tone(c: vec3) -> vec3 { + let p = max(mul3(PRO_FROM_2020, c), vec3(0.0)); + let a = max(p.x, max(p.y, p.z)); + let b = min(p.x, min(p.y, p.z)); + let fa = tone_apply(a); + let fb = tone_apply(b); + var o = vec3(fa); + if (a > b) { + o = vec3(fb) + vec3(fa - fb) * (p - vec3(b)) / (a - b); + } + return mul3(PRO_TO_2020, o); +} + // `Operator::luminance`: scaled by F of the ProPhoto luminance over it. fn light_lum(k: u32, p: vec3) -> vec3 { let y = PRO_Y.x * p.x + PRO_Y.y * p.y + PRO_Y.z * p.z; @@ -127,6 +153,149 @@ fn light_ops(d: vec3) -> vec3 { return mul3(PRO_TO_2020, p); } +// `mixer_stage::level`: the lower and upper of three keys around `x` and the upper's weight, clamped. +struct CLevel { + a: u32, + b: u32, + f: f32, +} + +fn mstage_level(k: vec3, x: f32) -> CLevel { + if (x <= k.x) { + return CLevel(0u, 0u, 0.0); + } + if (x <= k.y) { + return CLevel(0u, 1u, (x - k.x) / (k.y - k.x)); + } + if (x <= k.z) { + return CLevel(1u, 2u, (x - k.y) / (k.z - k.y)); + } + return CLevel(2u, 2u, 0.0); +} + +// `MixerStage::look`, with the level keys at `keys` (9 chroma by lightness level, then 3 lightness) and the table +// after them: (hue shift, chroma factor, lightness change). +fn mstage_look(keys: u32, l: f32, c: f32, h: f32) -> vec3 { + let t = keys + 12u; + let hd = ((h * 57.29577951308232) % 360.0 + 360.0) % 360.0 / 5.0; + let i0 = u32(hd) % 72u; + let i1 = (i0 + 1u) % 72u; + let fh = hd - floor(hd); + let lb = mstage_level(vec3(aux[keys + 9u], aux[keys + 10u], aux[keys + 11u]), l); + var r = array, 2>(vec3(0.0), vec3(0.0)); + for (var j = 0u; j < 2u; j++) { + let m = select(lb.a, lb.b, j == 1u); + let ck = vec3(aux[keys + 3u * m], aux[keys + 3u * m + 1u], aux[keys + 3u * m + 2u]); + let cb = mstage_level(ck, c); + var v = vec3(0.0); + for (var o = 0u; o < 3u; o++) { + let r0 = t + ((m * 3u + cb.a) * 3u + o) * 72u; + let r1 = t + ((m * 3u + cb.b) * 3u + o) * 72u; + let a = aux[r0 + i0] * (1.0 - fh) + aux[r0 + i1] * fh; + let b = aux[r1 + i0] * (1.0 - fh) + aux[r1 + i1] * fh; + v[o] = a * (1.0 - cb.f) + b * cb.f; + } + if (c < ck.x) { + v.z *= max(c / ck.x, 0.0); + } + r[j] = v; + } + return r[0] * (1.0 - lb.f) + r[1] * lb.f; +} + +// `MixerStage::apply`: the colour mixer, through OkLCh. +fn mixer_stage(d: vec3) -> vec3 { + let lab = oklab(d); + let l = lab.x; + let c = sqrt(lab.y * lab.y + lab.z * lab.z); + // atan2(0, 0) is undefined in WGSL; the CPU's gives 0 + let h = select(atan2(lab.z, lab.y), 0.0, c == 0.0); + let r = mstage_look(pu(F_MSTAGE_OFF), l, c, h); + let h2 = h + r.x; + let c2 = c * r.y; + return oklab_inv(vec3(max(l + r.z, 0.0), c2 * cos(h2), c2 * sin(h2))); +} + +// A table of process V18's curve stage (`Lut1::eval`) at offset `o` in `aux`. +fn stage_lut(o: u32, x: f32) -> f32 { + let f = clamp(x, 0.0, 1.0) * f32(CURVE_N - 1u); + let i = min(u32(f), CURVE_N - 2u); + let t = f - f32(i); + return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t; +} + +// `CurveStage::apply`: the base table on the largest and smallest channel of sRGB-encoded linear ProPhoto, the +// middle one keeping its place between them in linear light, then the red, green and blue curves per channel. +// `curve_stage::hue_preserving`: the table at `o` on the largest and smallest channel of `e`, the middle one keeping +// its place between them in linear light (`pc`). Linear, in [0, 1]. +fn stage_hue_preserving(o: u32, e: vec3, pc: vec3, hi: u32, lo: u32) -> vec3 { + let la = srgb_linear(stage_lut(o, e[hi])); + let lb = srgb_linear(stage_lut(o, e[lo])); + let pa = pc[hi]; + let pb = pc[lo]; + var out = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + var t = 1.0; + if (pa > pb) { + t = (pc[k] - pb) / (pa - pb); + } + out[k] = clamp(lb + (la - lb) * t, 0.0, 1.0); + } + return out; +} + +fn curve_stage(d: vec3) -> vec3 { + let p = mul3(PRO_FROM_2020, d); + var pc = clamp(p, vec3(0.0), vec3(1.0)); + var e = vec3(srgb_exact(pc.x), srgb_exact(pc.y), srgb_exact(pc.z)); + var hi = 0u; + var lo = 0u; + for (var k = 1u; k < 3u; k++) { + if (e[k] > e[hi]) { + hi = k; + } + if (e[k] < e[lo]) { + lo = k; + } + } + let off = pu(F_STAGE_OFF); + let base = stage_hue_preserving(off + 3u * CURVE_N, e, pc, hi, lo); + var curved = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + curved[k] = stage_lut(off + k * CURVE_N, srgb_exact(base[k])); + } + var q = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + q[k] = srgb_linear(clamp(curved[k], 0.0, 1.0)); + } + let rs = pf(F_STAGE_REFINE); + if (rs < 1.0) { + // the saturation back towards the input's after Whites, at the curves' luminance + var reference = e; + if (pu(F_STAGE_WHITES) != 0u) { + let w = stage_hue_preserving(off + 4u * CURVE_N, e, pc, hi, lo); + reference = vec3(srgb_exact(w.x), srgb_exact(w.y), srgb_exact(w.z)); + } + let rr = refine_saturation(reference, curved, rs); + var r = vec3(0.0); + for (var k = 0u; k < 3u; k++) { + r[k] = srgb_linear(clamp(rr[k], 0.0, 1.0)); + } + let yq = dot(q, PRO_Y); + let yr = dot(r, PRO_Y); + q = r; + if (yr > 1e-6) { + q = r * (yq / yr); + } + } + for (var k = 0u; k < 3u; k++) { + if (p[k] > 1.0) { + q[k] += p[k] - 1.0; + } + } + return mul3(PRO_TO_2020, q); +} + // `proraw::tone_rgb`: the table at `o` on linear ProPhoto `p`, hue-preserving (the largest and // smallest channel go through it, the middle one keeps its relative position between them). fn tone_rgb_at(o: u32, p: vec3) -> vec3 { @@ -386,9 +555,63 @@ fn color_ops(rgb: vec3, local_sat: f32, local_hue: f32) -> vec3 { lab.x += pf(F_WHEELS + 3u * k + 2u) * wt; } } + if (pu(F_MGRADE) != 0u) { + lab = measured_grade(lab); + } return oklab_inv(lab); } +// `grading_stage` lightness grid (65 entries at `o`), clamped. +fn mgrade_grid(o: u32, l: f32) -> f32 { + let p = clamp(l, 0.0, 1.0) * 64.0; + let i = min(u32(p), 63u); + return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * (p - f32(i)); +} + +// `GradingStage::apply`: each wheel's damped tint by its lightness profile, then the Luminance curve. +fn measured_grade(lab: vec3) -> vec3 { + let off = pu(F_MGRADE_OFF); + let n = pu(F_MGRADE) - 1u; + let c = sqrt(lab.y * lab.y + lab.z * lab.z); + // atan2(0, 0) is undefined in WGSL; the CPU's gives 0 + let hue = select(atan2(lab.z, lab.y), 0.0, c == 0.0); + var out = lab; + for (var k = 0u; k < n; k++) { + let w = off + 65u + k * 85u; + let p = mgrade_grid(w + 20u, lab.x); + if (p == 0.0) { + continue; + } + let ta = aux[w]; + let tb = aux[w + 1u]; + let diff = abs(wrap_angle(hue - atan2(tb, ta))); + // linear between the 30° bins' centres (15°, 45° … 165°) + let pos = clamp(diff * 57.29577951308232 / 30.0 - 0.5, 0.0, 5.0); + let j = min(u32(pos), 4u); + let fa = pos - f32(j); + let d0 = aux[w + 2u + j] * (1.0 - fa) + aux[w + 3u + j] * fa; + let d1 = aux[w + 8u + j] * (1.0 - fa) + aux[w + 9u + j] * fa; + let d2 = aux[w + 14u + j] * (1.0 - fa) + aux[w + 15u + j] * fa; + // the damping's chroma levels (`grading_stage::CHROMA`) + var damp = 1.0; + if (c <= 0.04) { + damp = 1.0 + (d0 - 1.0) * c / 0.04; + } else if (c <= 0.08) { + let f = (c - 0.04) / 0.04; + damp = d0 * (1.0 - f) + d1 * f; + } else if (c <= 0.12) { + let f = (c - 0.08) / 0.04; + damp = d1 * (1.0 - f) + d2 * f; + } else { + damp = d2; + } + out.y += p * ta * damp; + out.z += p * tb * damp; + } + out.x = max(lab.x + mgrade_grid(off, lab.x), 0.0); + return out; +} + // `colorops::calibrate`: primaries matrix, then the shadows tint (luminance kept). fn calibrate(c0: vec3) -> vec3 { var c = c0; @@ -727,8 +950,12 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let ss = pf(F_SH) + lt[5]; if (hh != 0.0 || ss != 0.0) { let ws = 1.0 - sstep(-4.8, 0.3, base); - let wh = sstep(-1.0, 2.8, base); - delta += ss * 1.7 * ws * sqrt(ws) + hh * 1.7 * wh; + delta += ss * 1.7 * ws * sqrt(ws); + if (pu(F_HS_RANGE) != 0u) { + delta += hs_range_highlights(hh, base); + } else { + delta += hh * 1.7 * sstep(-1.0, 2.8, base); + } } if (lt[6] != 0.0) { delta += lt[6] * 0.8 * sstep(0.5, 3.0, l1); @@ -792,7 +1019,9 @@ fn main(@builtin(global_invocation_id) gid: vec3) { } else { let yl = lum2020(c); let o = tone_apply(yl); - if (yl > 1e-9) { + if (pu(F_RGB_TONE) != 0u) { + d = rgb_tone(c); + } else if (yl > 1e-9) { d = c * o / yl; } let k = chroma_scale(o); @@ -811,6 +1040,14 @@ fn main(@builtin(global_invocation_id) gid: vec3) { d = light_ops(d); } + // --- process V18: the colour mixer, then Whites and the tone curves + if (pu(F_MSTAGE) != 0u) { + d = mixer_stage(d); + } + if (pu(F_STAGE) != 0u) { + d = curve_stage(d); + } + // --- colour d = color_ops(d, lt[11], lt[12]); if (tint_on) { diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 67fa3a445c8..c79c32df150 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -233,7 +233,9 @@ fn curve_input_matches_the_gpu_prefix_and_keeps_later_operations_out() { let v = 0.01 + x as f32 / 500.0; [v, v * (0.25 + y as f32 / 100.0), v * 0.4] })); - let mut s = DevelopSettings::default(); + // up to V17 the curves act on the encoded output, so a curve's input is the output of its predecessors; V18 samples + // where its curve stage reads (`lightcraft_pipeline` `v18_samples_where_the_curve_stage_reads_not_after_the_colour_tools`) + let mut s = DevelopSettings { process: Process::V17.version(), ..DevelopSettings::default() }; s.light.exposure = 0.5; s.curve.shadows = 45.0; s.curve.master = vec![Point::new(0.0, 0.04), Point::new(0.25, 0.65), Point::new(1.0, 0.95)]; @@ -988,6 +990,158 @@ fn light_v3_operators_match() { } } +/// Process V18's curve stage: Whites, the parametric curve, the point curves and Refine Saturation, on a camera curve +/// and without one, in SDR and HDR. +#[test] +fn curve_stage_matches() { + if !gpu() { + return; + } + use lightcraft_geom::Point; + let src = scene(0, 960, 640); + let curve = lightcraft_pipeline::tone::CameraTone::new(std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + })) + .unwrap(); + let raw = SourceInfo { raw: true, camera_tone: Some(curve), ..Default::default() }; + let req = RenderRequest::fit(720, 720); + let v18 = || DevelopSettings { process: Process::V18.version(), ..Default::default() }; + for v in [-100.0, -30.0, 40.0, 100.0] { + let mut s = v18(); + s.light.whites = v; + check(&format!("V18 Whites {v}"), &src, &raw, &s, &req); + } + let mut s = v18(); + s.curve.highlights = -40.0; + s.curve.lights = 25.0; + s.curve.darks = -15.0; + s.curve.shadows = 30.0; + check("V18 parametric", &src, &raw, &s, &req); + s.curve.master = vec![Point { x: 0.0, y: 0.05 }, Point { x: 0.5, y: 0.55 }, Point { x: 1.0, y: 0.95 }]; + s.curve.red = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.4, y: 0.5 }, Point { x: 1.0, y: 1.0 }]; + s.curve.blue = vec![Point { x: 0.0, y: 0.1 }, Point { x: 1.0, y: 0.9 }]; + s.light.whites = -25.0; + check("V18 curves", &src, &raw, &s, &req); + s.curve.refine_saturation = 30.0; + check("V18 Refine Saturation", &src, &raw, &s, &req); + check("V18 curves, no camera curve", &src, &SourceInfo::default(), &s, &req); + s.curve.split_mid = 40.0; + check("V18 other splits", &src, &raw, &s, &req); + s.curve.split_mid = 50.0; + s.hdr.enabled = true; + s.hdr.max_ev = 2.0; + check("V18 HDR preview", &src, &raw, &s, &req); +} + +/// Process V18's mixer stage matches the CPU's, alone, with Calibration (still V7's operator), with the curve +/// stage after it, and with V7's colour tools (Saturation, B&W) that still follow. +#[test] +fn mixer_stage_matches() { + if !gpu() { + return; + } + let src = scene(0, 960, 640); + let raw = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(720, 720); + let v18 = || DevelopSettings { process: Process::V18.version(), ..Default::default() }; + let mut s = v18(); + s.mixer.orange.sat = -60.0; + s.mixer.blue.hue = -40.0; + s.mixer.green.lum = 70.0; + s.mixer.magenta.hue = 15.0; + check("V18 mixer", &src, &raw, &s, &req); + s.calibration.red_hue = 45.0; + s.calibration.blue_sat = 60.0; + s.calibration.shadows_tint = 30.0; + check("V18 mixer and calibration", &src, &raw, &s, &req); + s.curve.master = vec![Point { x: 0.0, y: 0.05 }, Point { x: 0.5, y: 0.6 }, Point { x: 1.0, y: 0.95 }]; + s.color.saturation = 20.0; + check("V18 colour stage, curves, Saturation", &src, &raw, &s, &req); + check("V18 colour stage, not raw", &src, &SourceInfo::default(), &s, &req); + s.treatment = lightcraft_develop::Treatment::Bw; + check("V18 colour stage, B&W", &src, &raw, &s, &req); +} + +/// Process V18's measured Colour Grading matches the CPU's: single wheels, all four with Blending and Balance, +/// Luminance only, and together with the mixer stage, the curves and B&W. +#[test] +fn grading_stage_matches() { + if !gpu() { + return; + } + let src = scene(0, 960, 640); + let raw = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(720, 720); + let v18 = || DevelopSettings { process: Process::V18.version(), ..Default::default() }; + let mut s = v18(); + s.grading.shadows = lightcraft_develop::Wheel { hue: 210.0, sat: 40.0, lum: 0.0 }; + check("V18 shadows wheel", &src, &raw, &s, &req); + s.grading.midtones = lightcraft_develop::Wheel { hue: 45.0, sat: 22.0, lum: -20.0 }; + s.grading.highlights = lightcraft_develop::Wheel { hue: 46.0, sat: 80.0, lum: 30.0 }; + s.grading.global = lightcraft_develop::Wheel { hue: 300.0, sat: 15.0, lum: 10.0 }; + s.grading.blending = 70.0; + s.grading.balance = -35.0; + check("V18 four wheels", &src, &raw, &s, &req); + let mut l = v18(); + l.grading.highlights.lum = -60.0; + check("V18 grading Luminance only", &src, &raw, &l, &req); + s.mixer.orange.sat = 40.0; + s.curve.master = vec![Point { x: 0.0, y: 0.05 }, Point { x: 0.5, y: 0.6 }, Point { x: 1.0, y: 0.95 }]; + check("V18 grading, mixer, curves", &src, &raw, &s, &req); + s.treatment = lightcraft_develop::Treatment::Bw; + check("V18 grading, B&W", &src, &raw, &s, &req); +} + +/// Process V18's default curve for a raw whose profile has no tone curve (`default_tone`): the GPU applies it hue +/// preserving on linear ProPhoto channels as the CPU does, alone, with an exposure offset, with Exposure and +/// Contrast, with the curves and colour stages, and in HDR. +#[test] +fn default_tone_matches() { + if !gpu() { + return; + } + let src = scene(0, 960, 640); + let req = RenderRequest::fit(720, 720); + let v18 = || DevelopSettings { process: Process::V18.version(), ..Default::default() }; + let plain = SourceInfo { raw: true, default_tone: Some(0.0), ..Default::default() }; + check("V18 default curve", &src, &plain, &v18(), &req); + let shifted = SourceInfo { default_tone: Some(-0.1), ..plain.clone() }; + let mut s = v18(); + s.light.exposure = 0.7; + s.light.contrast = 30.0; + check("V18 default curve, offset, Exposure, Contrast", &src, &shifted, &s, &req); + s.mixer.orange.sat = 40.0; + s.grading.shadows = lightcraft_develop::Wheel { hue: 210.0, sat: 40.0, lum: 0.0 }; + s.curve.master = vec![Point { x: 0.0, y: 0.05 }, Point { x: 0.5, y: 0.6 }, Point { x: 1.0, y: 0.95 }]; + check("V18 default curve, mixer, grading, curves", &src, &shifted, &s, &req); + let mut h = v18(); + h.hdr.enabled = true; + check("V18 default curve, HDR", &src, &plain, &h, &req); +} + +/// Process V18's Highlights relative to the frame's tonal range (`hs_range`): the GPU uses the plan's range as the CPU +/// does, darkening and brightening, with Shadows, with Exposure, and in a window of a larger frame. +#[test] +fn hs_range_matches() { + if !gpu() { + return; + } + let src = scene(0, 960, 640); + let raw = SourceInfo { raw: true, ..Default::default() }; + let req = RenderRequest::fit(720, 720); + let v18 = || DevelopSettings { process: Process::V18.version(), ..Default::default() }; + let mut s = v18(); + s.light.highlights = -100.0; + check("V18 Highlights -100", &src, &raw, &s, &req); + s.light.highlights = 60.0; + s.light.shadows = 40.0; + s.light.exposure = -0.5; + check("V18 Highlights +60, Shadows, Exposure", &src, &raw, &s, &req); + let win = RenderRequest { window: Some(lightcraft_pipeline::PixelWindow { x: 200, y: 120, w: 320, h: 240 }), ..req }; + check("V18 Highlights in a window", &src, &raw, &s, &win); +} + /// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log /// luminance; V2 to V7: of its fine median, V8 on: of its detail-free plane, a radius that grows with the render) matches the CPU's, and /// a warm cache never hands one process the other's base. diff --git a/crates/pipeline/src/colorops.rs b/crates/pipeline/src/colorops.rs index 468123be016..6ddfae1e8eb 100644 --- a/crates/pipeline/src/colorops.rs +++ b/crates/pipeline/src/colorops.rs @@ -2,6 +2,7 @@ use std::ops::Deref; +use lightcraft_color::perceptual::{oklab_from_2020, oklab_to_2020}; use lightcraft_develop::{Calibration, DevelopSettings, Process}; pub use craft_develop::colorops::{ @@ -10,13 +11,17 @@ pub use craft_develop::colorops::{ /// The colour tools' parameters, resolved once per render (fields are read by the GPU kernel). #[derive(Clone, Debug)] -pub struct ColorOps(pub craft_develop::colorops::ColorOps); +pub struct ColorOps { + pub ops: craft_develop::colorops::ColorOps, + /// Process V18's Colour Grading from its fitted model (`ops.grading` is `None` from V18 on). + pub measured_grading: Option, +} impl Deref for ColorOps { type Target = craft_develop::colorops::ColorOps; fn deref(&self) -> &Self::Target { - &self.0 + &self.ops } } @@ -26,7 +31,28 @@ impl ColorOps { if let Some((wheels, _, _)) = ops.grading.as_mut() { wheels[3] = global_wheel(wheels[3], s.process.process()); } - ColorOps(ops) + // from process V18 the colour stage applies the mixer (`crate::mixer_stage`) + ops.mixer &= s.process.process() < Process::V18; + // and Colour Grading from its fitted model (`crate::grading_stage`), last, as the earlier grading + if s.process.process() >= Process::V18 { + ops.grading = None; + } + ColorOps { ops, measured_grading: crate::grading_stage::GradingStage::new(s) } + } + + pub fn is_identity(&self) -> bool { + self.ops.is_identity() && self.measured_grading.is_none() + } + + /// The colour tools on linear Rec.2020, then V18's Colour Grading on OkLab. `local_sat` (−1..1) and `local_hue` + /// (radians) come from masks. + #[inline] + pub fn apply(&self, rgb: [f32; 3], local_sat: f32, local_hue: f32) -> [f32; 3] { + let out = self.ops.apply(rgb, local_sat, local_hue); + match &self.measured_grading { + Some(g) => oklab_to_2020(g.apply(oklab_from_2020(out))), + None => out, + } } } @@ -76,4 +102,18 @@ mod tests { assert_eq!((v13.0.signum(), v13.1.signum(), v13.2), (v10.0.signum(), v10.1.signum(), v10.2), "same hue, same luminance"); assert_eq!(tint(Process::V10, false), tint(Process::V13, false), "the shadows wheel is unchanged"); } + + #[test] + fn v18_leaves_the_mixer_to_the_mixer_stage() { + // from V18 `crate::mixer_stage` applies the mixer, so `ColorOps` must not apply it again + let mut s = DevelopSettings { process: Process::V7.version(), ..DevelopSettings::default() }; + s.mixer.blue.sat = -100.0; + assert!(ColorOps::new(&s).mixer); + // V17 still applies the earlier mixer, and has no mixer stage + s.process = Process::V17.version(); + assert!(ColorOps::new(&s).mixer); + assert!(crate::mixer_stage::MixerStage::new(&s).is_none()); + s.process = Process::V18.version(); + assert!(!ColorOps::new(&s).mixer); + } } diff --git a/crates/pipeline/src/curve.rs b/crates/pipeline/src/curve.rs index 16b3df808e6..79e110650e8 100644 --- a/crates/pipeline/src/curve.rs +++ b/crates/pipeline/src/curve.rs @@ -9,6 +9,9 @@ use lightcraft_develop::ToneCurve; pub use craft_develop::curve::{PARAM_AMOUNTS, PARAM_LUT}; /// The parametric (region) curve of a [`ToneCurve`], backed by `craft_develop::curve::ParametricCurve`. +/// +/// Processes V1 to V17 render it, and V18 renders it when the splits are moved. The curve editor draws it +/// through [`crate::curve_stage::ParametricGraph`], which picks the measured regions where V18 renders those. #[derive(Clone, Debug)] pub struct ParametricCurve(craft_develop::curve::ParametricCurve); diff --git a/crates/pipeline/src/curve_input.rs b/crates/pipeline/src/curve_input.rs index 9e1269fcbf5..d279f448fbc 100644 --- a/crates/pipeline/src/curve_input.rs +++ b/crates/pipeline/src/curve_input.rs @@ -3,7 +3,7 @@ //! The normal renderer is unchanged. A small, separate render shares its spatial stages and //! per-pixel code, stopping before the selected curve and everything that follows it. -use lightcraft_develop::{DevelopSettings, ToneCurve}; +use lightcraft_develop::{DevelopSettings, Process, ToneCurve}; use lightcraft_raster::{Histogram, Rgb32f, Rgba8}; use serde::{Deserialize, Serialize}; use std::sync::Arc; @@ -100,6 +100,7 @@ pub(crate) fn finish( image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, + hs_range: p.hs_range, space: request.space, draft: request.quality == crate::Quality::Draft, }); @@ -107,7 +108,12 @@ pub(crate) fn finish( if let Some(display) = &request.display { fp.for_display(display, request.proof); } - fp.curves = crate::finish::curve_luts(&input.predecessors(&settings.curve)); + // only the predecessors, wherever the process applies its curves (encoded output, or V18's curve stage) + let predecessors = DevelopSettings { curve: input.predecessors(&settings.curve), ..settings.clone() }; + fp.curves = if settings.process.process() < Process::V18 { crate::finish::curve_luts(&predecessors.curve) } else { None }; + fp.curve_stage = crate::finish::curve_stage_for(&predecessors, fp.proraw.is_some()); + // V18's curves read sRGB-encoded linear ProPhoto after the tone map: sample there, not after the colour tools + fp.sample_at_curve_stage = settings.process.process() >= Process::V18; fp.refine_sat = 1.0; // the samples, and the 8-bit pixels as `finish` dithers them at the same place in the output let samples = crate::finish::finish_with(p, &fp, false, true, |x, y, e| { @@ -115,7 +121,8 @@ pub(crate) fn finish( (e, [crate::finish::enc(e[0], d), crate::finish::enc(e[1], d), crate::finish::enc(e[2], d), 255]) }); let (samples, data): (Vec<[f32; 3]>, Vec<[u8; 4]>) = samples.into_iter().unzip(); - let histogram = of_encoded(&samples, fp.out_luma); + let weights = if fp.sample_at_curve_stage { crate::light_v3::PRO_Y } else { fp.out_luma }; + let histogram = of_encoded(&samples, weights); let image = Rgba8 { width: w, height: h, data }; Rendered { image, histogram, deep: None } } diff --git a/crates/pipeline/src/curve_input_tests.rs b/crates/pipeline/src/curve_input_tests.rs index 5426374ccf1..f0c1caba7a0 100644 --- a/crates/pipeline/src/curve_input_tests.rs +++ b/crates/pipeline/src/curve_input_tests.rs @@ -55,9 +55,11 @@ fn input_follows_exposure_but_not_its_own_curve_or_later_curves() { assert_ne!(a.image, b.image); } +/// Up to V17 the curves act on the encoded output, so a curve's input is the output of its predecessors. (V18: +/// `v18_samples_where_the_curve_stage_reads_not_after_the_colour_tools`.) #[test] fn each_curve_sees_exactly_its_predecessors_including_profile_contributions() { - let mut s = DevelopSettings::default(); + let mut s = DevelopSettings { process: lightcraft_develop::Process::V17.version(), ..DevelopSettings::default() }; s.profile.id = "lc.film.golden-hour".into(); s.curve.shadows = 45.0; s.curve.master = bent(); @@ -171,7 +173,8 @@ fn diagnostic_and_normal_renders_share_spatial_cache_without_changing_pixels() { fn input_uses_the_display_primaries_and_effective_edit() { let src = source(); let info = SourceInfo::default(); - let mut s = DevelopSettings::default(); + // up to V17 the curves act on the encoded output, in the display's primaries (V18's read ProPhoto) + let mut s = DevelopSettings { process: lightcraft_develop::Process::V17.version(), ..DevelopSettings::default() }; s.light.exposure = 1.0; s.curve.lights = 55.0; s.curve.master = bent(); @@ -181,7 +184,7 @@ fn input_uses_the_display_primaries_and_effective_edit() { let mut effective = s.effective().into_owned(); effective.curve = CurveInput::Red.predecessors(&effective.curve); assert_eq!(disabled.image, crate::render(&src, &info, &effective, &req).image); - let mut previous = DevelopSettings::default(); + let mut previous = DevelopSettings { process: lightcraft_develop::Process::V17.version(), ..DevelopSettings::default() }; previous.curve.lights = 45.0; let srgb = render(&src, &info, &previous, &req, None, CurveInput::Red).unwrap(); for space in [OutputSpace::DisplayP3, OutputSpace::Rec2020] { @@ -220,3 +223,36 @@ fn an_over_budget_brush_mask_fails_the_sample_instead_of_dropping_strokes() { s.masks.push(brush(vec![stroke(0.2, 0.6)])); assert!(render(&source(), &SourceInfo::default(), &s, &full_size, None, CurveInput::Master).is_ok()); } + +/// Under V18 the curves read the colour where the curve stage runs, after the tone map and before the colour tools: +/// Saturation, which comes after them, leaves every curve's input alone; on V17 it is part of it (review on #4076). +#[test] +fn v18_samples_where_the_curve_stage_reads_not_after_the_colour_tools() { + use lightcraft_develop::Process; + for ch in [CurveInput::Parametric, CurveInput::Master, CurveInput::Red] { + let on = |p: Process, saturation: f64| { + let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; + s.color.saturation = saturation; + sample(&s, ch).histogram + }; + assert_eq!(on(Process::V18, -100.0), on(Process::V18, 0.0), "V18 {ch:?}: Saturation is after the curves"); + assert_ne!(on(Process::V17, -100.0), on(Process::V17, 0.0), "V17 {ch:?}: the curves read the encoded output"); + } +} + +/// On Apple ProRAW the chain applies Whites, so the curve stage the sample is built with leaves it out, as the render's +/// does: Whites alone gives no stage, a curve a stage of its own (review on #4076). +#[test] +fn proraw_curve_input_applies_whites_once() { + use lightcraft_develop::Process; + let mut s = DevelopSettings { process: Process::V18.version(), ..DevelopSettings::default() }; + s.light.whites = 40.0; + assert!(crate::finish::curve_stage_for(&s, false).is_some(), "elsewhere the stage applies Whites"); + assert!(crate::finish::curve_stage_for(&s, true).is_none(), "on ProRAW the chain does"); + s.curve.master = bent(); + let with_curve = crate::finish::curve_stage_for(&s, true).expect("the curve"); + let mut alone = s.clone(); + alone.light.whites = 0.0; + let curve_only = crate::finish::curve_stage_for(&alone, false).expect("the curve"); + assert_eq!(with_curve.base.v, curve_only.base.v, "the ProRAW stage is the curve without Whites"); +} diff --git a/crates/pipeline/src/curve_stage.rs b/crates/pipeline/src/curve_stage.rs new file mode 100644 index 00000000000..bb60d8880dd --- /dev/null +++ b/crates/pipeline/src/curve_stage.rs @@ -0,0 +1,585 @@ +//! Process V18's tone-curve stage ([`lightcraft_develop::Process::V18`]): Whites, the parametric curve and the point +//! curves. `docs/curve-stage.md` records how the model was measured and fitted. +//! +//! - Whites, the parametric curve, the master point curve, Contrast and Blacks act hue-preserving on linear ProPhoto +//! RGB: the curve maps the largest and the smallest channel (on sRGB-encoded values), and the middle channel keeps +//! its relative position between them in linear light. +//! - The red, green and blue curves act per channel on sRGB-encoded linear ProPhoto RGB, after the master curve. +//! - Whites reaches into the midtones, and each parametric region is broad and overlapping; the regions add. +//! - Whites and the four regions come from a fitted model (`curve_stage_model`, written by `tools/lr_tone_charts.py +//! fit`): per slider direction, two smooth bumps whose gain, position and width change with the amount +//! ([`response`]). +//! +//! The stage runs after the tone map, Process V4's calibrated Contrast and Blacks and V18's colour mixer +//! ([`crate::mixer_stage`]), before the colour stage. It +//! replaces the curves of V17 and earlier on encoded output values; the tone map leaves Whites to it. + +use lightcraft_color::spline::{Lut1, MonotoneCurve}; +use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; +use lightcraft_develop::{DevelopSettings, Process, ToneCurve}; +use lightcraft_geom::Point; + +use crate::curve::ParametricCurve; +use crate::curve_stage_model as m; +use crate::light_v3::PRO_Y; + +/// Entries per table (as the shipping curve tables). +pub const N: usize = 1024; + +/// The least a region must be able to move the drawn parametric curve for a drag to move its slider: half an 8-bit level. +const REACH_MIN: f64 = 0.5 / 255.0; + +/// The default parametric splits (25, 50, 75): the fitted regions hold for them only. +const DEFAULT_SPLITS: [f64; 3] = [25.0, 50.0, 75.0]; + +/// The stage's tables: `base` (Whites, then the parametric curve, then the master point curve) acts hue-preserving, +/// `chan` (red, green, blue point curves) per channel. All on sRGB-encoded linear ProPhoto values. +#[derive(Clone, Debug)] +pub struct CurveStage { + pub chan: [Lut1; 3], + pub base: Lut1, + /// Refine Saturation, 0..1, on what the curves did (1 when only Whites is set). + pub refine: f32, + /// Whites alone, when Refine Saturation is below 1: the saturation it restores is the colour's after Whites, as + /// Lightroom's Refine Saturation belongs to the tone curve and Whites comes before it. + pub whites: Option, +} + +/// A bump of peak 1 at `p / (p + q)`, 0 at black and white and outside them. +fn bump(x: f64, p: f64, q: f64) -> f64 { + if x <= 0.0 || x >= 1.0 { + return 0.0; + } + let peak = p / (p + q); + (p * (x / peak).ln() + q * ((1.0 - x) / (1.0 - peak)).ln()).exp() +} + +/// The fitted response of a slider at `amount` (−100 to 100, clamped) for input `x`: output minus input on +/// sRGB-encoded values. Per direction, two bumps with gain `a1 t + a2 t² + a3 t³` (t = |amount| / 100) and shape +/// exponents `e^(p0 + p1 t)`, `e^(q0 + q1 t)`. +fn response(fit: &[m::Response; 2], amount: f32, x: f32) -> f32 { + if amount == 0.0 || !amount.is_finite() { + return 0.0; + } + let [negative, positive] = fit; + let side = if amount < 0.0 { negative } else { positive }; + let (t, x) = ((f64::from(amount) / 100.0).abs().min(1.0), f64::from(x)); + let r: f64 = side + .iter() + .map(|[a1, a2, a3, p0, p1, q0, q1]| (a1 * t + a2 * t * t + a3 * t * t * t) * bump(x, (p0 + p1 * t).exp(), (q0 + q1 * t).exp())) + .sum(); + r as f32 +} + +/// Whether `c` holds the default splits, the ones the regions are fitted for. +fn default_splits(c: &ToneCurve) -> bool { + [c.split_shadows, c.split_mid, c.split_highlights].iter().zip(DEFAULT_SPLITS).all(|(s, d)| (s - d).abs() <= 1e-6) +} + +/// The fitted regions at `x`, before the curve is kept monotone: the four responses added to the diagonal. +fn regions_at(amounts: [f32; 4], x: f32) -> f32 { + (x + regions_delta(amounts, x)).clamp(0.0, 1.0) +} + +/// The sum of the four fitted region responses at `x`. +fn regions_delta(amounts: [f32; 4], x: f32) -> f32 { + amounts.iter().zip(m::REGIONS.iter()).map(|(a, r)| response(r, *a, x)).sum() +} + +/// The fitted parametric curve at the default splits. +fn fitted_parametric(amounts: [f32; 4]) -> Lut1 { + let mut lut = Lut1::from_fn(N, |x| regions_at(amounts, x)); + monotone(&mut lut); + lut +} + +/// The parametric curve: the fitted regions at the default splits, else the analytic model of earlier processes. +fn parametric(c: &ToneCurve) -> Lut1 { + if !default_splits(c) { + return ParametricCurve::new(c).to_lut(); + } + fitted_parametric([c.shadows, c.darks, c.lights, c.highlights].map(|v| v as f32)) +} + +/// The parametric curve as `s`'s process renders it, for the Edit panel's graph and its drag: the fitted regions +/// under V18 at the default splits, else the analytic [`ParametricCurve`] (earlier processes, and V18 with moved +/// splits). Whites is left out of the graph. +#[derive(Clone, Debug)] +pub struct ParametricGraph { + model: ParametricCurve, + /// The fitted curve, when it is the one rendered. + fitted: Option, +} + +impl ParametricGraph { + /// The graph for `s`: the fitted curve when `s`'s process is V18 or later and the splits are the defaults. + pub fn new(s: &DevelopSettings) -> ParametricGraph { + let model = ParametricCurve::new(&s.curve); + let fitted = (s.process.process() >= Process::V18 && default_splits(&s.curve)).then(|| fitted_parametric(model.amounts.map(|a| a as f32))); + ParametricGraph { model, fitted } + } + + /// Whether the graph is the fitted curve (else the analytic one). + pub fn is_fitted(&self) -> bool { + self.fitted.is_some() + } + + /// The curve at `x` (0 = black, 1 = white). + pub fn at(&self, x: f64) -> f64 { + match &self.fitted { + Some(lut) => lut.eval(if x.is_nan() { 0.0 } else { x as f32 }) as f64, + None => self.model.at(x), + } + } + + /// The region that owns graph position `x` (the splits tile the graph: [`ParametricCurve::region_at`]). + pub fn region_at(&self, x: f64) -> usize { + self.model.region_at(x) + } + + /// Region `region`'s slider amount. + pub fn amount(&self, region: usize) -> f64 { + self.model.amounts.get(region).copied().unwrap_or(0.0) + } + + /// The amount for region `region` after a drag that grabbed the curve at `x`, with the region at `from`, and moved + /// it `delta` in output level (a fraction of the graph's height; up is positive). The other regions stay as they + /// are, and the level is the drawn curve's (kept monotone). A level the region cannot reach saturates at ±100; no + /// motion, or a region that cannot visibly move the line in that direction, keeps `from`. + pub fn dragged_amount(&self, region: usize, x: f64, from: f64, delta: f64) -> f64 { + if delta == 0.0 || !delta.is_finite() { + return from; + } + if self.fitted.is_none() { + let per_unit = self.model.level_per_unit(region, x); + return if per_unit.abs() > f64::EPSILON { (from + delta / per_unit).clamp(-100.0, 100.0).round() } else { from }; + } + // The fitted regions are not linear in the amount: search the amount that puts the drawn curve at the target, + // on the side of `from` the drag goes to (so a flat stretch never makes the slider jump back). The drawn curve + // is kept monotone, a running maximum, so its level at `x` reads the curve's entries up to `x`; the other + // regions' share of them is the same for every amount tried. + let Some(fit) = m::REGIONS.get(region) else { return from }; + let pos = x.clamp(0.0, 1.0) as f32 * (N - 1) as f32; + let j = (pos as usize).min(N - 2); + let f = pos - j as f32; + let mut others = self.model.amounts.map(|v| v as f32); + if let Some(v) = others.get_mut(region) { + *v = 0.0; + } + let entries: Vec<(f32, f32)> = (0..=j + 1) + .map(|i| { + let g = i as f32 / (N - 1) as f32; + (g, regions_delta(others, g)) + }) + .collect(); + let level = |a: f64| { + let (mut m, mut at) = (f32::NEG_INFINITY, [0.0f32; 2]); + for (i, (g, rest)) in entries.iter().enumerate() { + m = m.max((g + rest + response(fit, a as f32, *g)).clamp(0.0, 1.0)); + if let Some(v) = i.checked_sub(j).and_then(|k| at.get_mut(k)) { + *v = m; + } + } + (at[0] + (at[1] - at[0]) * f) as f64 + }; + let (start, end) = (level(from), if delta > 0.0 { 100.0 } else { -100.0 }); + let (target, reach) = (start + delta, level(end)); + // where the drawn line is held by a peak to its left, the region may hardly move it: then the slider stays + if (reach - start).abs() < REACH_MIN { + return from; + } + if (delta > 0.0 && reach < target) || (delta < 0.0 && reach > target) { + return end; + } + let (mut lo, mut hi) = if delta > 0.0 { (from, 100.0) } else { (-100.0, from) }; + // 20 halvings of the 200-wide range are well inside the rounding to whole amounts + for _ in 0..20 { + let mid = (lo + hi) / 2.0; + if level(mid) < target { + lo = mid; + } else { + hi = mid; + } + } + let a = if delta > 0.0 { hi } else { lo }; + a.clamp(-100.0, 100.0).round() + } +} + +/// The fitted Whites curve at `amount`, or `None` at 0. +fn whites(amount: f64) -> Option { + if amount == 0.0 { + return None; + } + let mut lut = Lut1::from_fn(N, |x| (x + response(&m::WHITES, amount as f32, x)).clamp(0.0, 1.0)); + monotone(&mut lut); + Some(lut) +} + +/// Keeps a table non-decreasing (tone order never reverses). +fn monotone(lut: &mut Lut1) { + let mut m = f32::NEG_INFINITY; + for v in &mut lut.v { + m = m.max(*v); + *v = m; + } +} + +impl CurveStage { + /// The stage for `s`: `None` before V18, or when Whites, the parametric curve and every point curve are neutral. + pub fn new(s: &DevelopSettings) -> Option { + if s.process.process() < Process::V18 { + return None; + } + let c = &s.curve; + let parametric_on = c.highlights != 0.0 || c.lights != 0.0 || c.darks != 0.0 || c.shadows != 0.0; + let master = !ToneCurve::point_curve_is_identity(&c.master); + let chans = [&c.red, &c.green, &c.blue].map(|p| !ToneCurve::point_curve_is_identity(p)); + let w = whites(s.light.whites); + if w.is_none() && !parametric_on && !master && !chans.iter().any(|b| *b) { + return None; + } + let to_pts = |p: &[Point]| p.iter().map(|q| (q.x, q.y)).collect::>(); + let mut base = if parametric_on { parametric(c) } else { Lut1::identity(N) }; + if let Some(w) = &w { + base = base.compose_len(w, N); + } + if master { + base = MonotoneCurve::new(&to_pts(&c.master)).to_lut(N).compose_len(&base, N); + } + let per = [&c.red, &c.green, &c.blue]; + let chan = std::array::from_fn(|i| match per.get(i) { + Some(p) if chans.get(i).copied().unwrap_or(false) => MonotoneCurve::new(&to_pts(p)).to_lut(N), + _ => Lut1::identity(N), + }); + let curves_on = parametric_on || master || chans.iter().any(|b| *b); + let refine = if curves_on { (c.refine_saturation / 100.0).clamp(0.0, 1.0) as f32 } else { 1.0 }; + let whites = w.filter(|_| refine < 1.0); + Some(CurveStage { chan, base, refine, whites }) + } + + /// Linear Rec.2020 in and out (display referred, after the tone map). + /// + /// The curves are looked up on the colour clamped to [0, 1] in linear ProPhoto; whatever a channel had + /// above white is added back after them, so HDR input keeps slope 1 above white and is not clipped by an + /// active curve (`hdr_values_keep_slope_one_above_white`). + pub fn apply(&self, d: [f32; 3]) -> [f32; 3] { + let (to, from) = matrices(); + let p = mul3(to, d); + let pc = p.map(|v| v.clamp(0.0, 1.0)); + let e = pc.map(linear_to_srgb); + let (mut hi, mut lo) = (0usize, 0usize); + for k in 1..3 { + if e[k] > e[hi] { + hi = k; + } + if e[k] < e[lo] { + lo = k; + } + } + let base = hue_preserving(&self.base, e, pc, hi, lo); + let curved: [f32; 3] = std::array::from_fn(|k| self.chan[k].eval(linear_to_srgb(base[k]))); + let lin = |v: [f32; 3]| v.map(|x| srgb_to_linear(x.clamp(0.0, 1.0))); + let mut q = lin(curved); + if self.refine < 1.0 { + // the saturation back towards the input's after Whites, at the curves' luminance + let reference = match &self.whites { + Some(w) => hue_preserving(w, e, pc, hi, lo).map(linear_to_srgb), + None => e, + }; + let r = lin(crate::finish::refine_saturation(reference, curved, self.refine)); + let y = |v: [f32; 3]| PRO_Y[0] * v[0] + PRO_Y[1] * v[1] + PRO_Y[2] * v[2]; + let (yq, yr) = (y(q), y(r)); + q = if yr > 1e-6 { r.map(|v| v * yq / yr) } else { r }; + } + for (k, v) in q.iter_mut().enumerate() { + if let Some(over) = p.get(k).filter(|x| **x > 1.0) { + *v += over - 1.0; + } + } + mul3(from, q) + } +} + +/// `table` on the largest and smallest channel of the encoded colour `e` (`pc` in linear light, `hi` and `lo` its +/// largest and smallest channel); the middle one keeps its place between them in linear light. Linear, in [0, 1]. +fn hue_preserving(table: &Lut1, e: [f32; 3], pc: [f32; 3], hi: usize, lo: usize) -> [f32; 3] { + let (la, lb) = (srgb_to_linear(table.eval(e[hi])), srgb_to_linear(table.eval(e[lo]))); + let (pa, pb) = (pc[hi], pc[lo]); + std::array::from_fn(|k| { + let t = if pa > pb { (pc[k] - pb) / (pa - pb) } else { 1.0 }; + (lb + (la - lb) * t).clamp(0.0, 1.0) + }) +} + +/// Linear Rec.2020 to linear ProPhoto and back, built once. +fn matrices() -> &'static ([[f32; 3]; 3], [[f32; 3]; 3]) { + static M: std::sync::OnceLock<([[f32; 3]; 3], [[f32; 3]; 3])> = std::sync::OnceLock::new(); + M.get_or_init(crate::light_v3::prophoto_matrices) +} + +/// Multiplies a colour by a 3 × 3 matrix. +fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { + std::array::from_fn(|r| m[r][0] * d[0] + m[r][1] * d[1] + m[r][2] * d[2]) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Default settings on process V18. + fn v18() -> DevelopSettings { + DevelopSettings { process: Process::V18.version(), ..Default::default() } + } + + /// V18 settings with only Whites at `v`. + fn with_whites(v: f64) -> DevelopSettings { + let mut s = v18(); + s.light.whites = v; + s + } + + /// Display-linear grey whose sRGB encoding is `e`, through the stage, back to encoded. + fn grey(stage: &CurveStage, e: f32) -> f32 { + linear_to_srgb(stage.apply([srgb_to_linear(e); 3])[1]) + } + + #[test] + fn earlier_processes_and_neutral_settings_have_no_stage() { + assert!(CurveStage::new(&v18()).is_none(), "neutral settings are the identity"); + for p in Process::ALL.iter().filter(|p| **p < Process::V18) { + let s = DevelopSettings { process: p.version(), ..with_whites(-50.0) }; + assert!(CurveStage::new(&s).is_none(), "{p:?}"); + } + } + + #[test] + fn whites_reaches_into_the_midtones_as_measured() { + let stage = CurveStage::new(&with_whites(-50.0)).expect("Whites set"); + let drop = (0.6 - grey(&stage, 0.6)) * 255.0; + assert!((7.0..13.0).contains(&drop), "encoded 0.6 fell by {drop}/255"); + let dark = (0.05 - grey(&stage, 0.05)).abs() * 255.0; + assert!(dark < 2.0, "the shadows hardly move: {dark}/255"); + let up = CurveStage::new(&with_whites(50.0)).expect("Whites set"); + assert!(grey(&up, 0.6) > 0.6); + } + + #[test] + fn regions_add_and_act_in_their_own_range() { + let curve = |f: fn(&mut ToneCurve)| { + let mut s = v18(); + f(&mut s.curve); + CurveStage::new(&s).expect("a region set") + }; + let shadows = curve(|c| c.shadows = 50.0); + let highlights = curve(|c| c.highlights = 50.0); + let both = curve(|c| { + c.shadows = 50.0; + c.highlights = 50.0; + }); + assert!(grey(&shadows, 0.15) - 0.15 > 3.0 * (grey(&shadows, 0.85) - 0.85).abs(), "Shadows lifts the dark end"); + assert!(grey(&highlights, 0.85) - 0.85 > 3.0 * (grey(&highlights, 0.15) - 0.15).abs(), "Highlights lifts the bright end"); + for e in [0.15f32, 0.4, 0.6, 0.85] { + let sum = e + (grey(&shadows, e) - e) + (grey(&highlights, e) - e); + assert!((grey(&both, e) - sum).abs() < 1.5 / 255.0, "{e}"); + } + } + + #[test] + fn other_splits_fall_back_to_the_analytic_curve() { + let mut s = v18(); + s.curve.highlights = 50.0; + s.curve.split_mid = 40.0; + let stage = CurveStage::new(&s).expect("a region set"); + assert_eq!(stage.base.v, crate::curve::ParametricCurve::new(&s.curve).to_lut().v); + } + + /// Every fitted response grows with its slider in the slider's direction, never acts against it, and is 0 at black, + /// at white and at amount 0; amounts beyond ±100 act as ±100. + #[test] + fn fitted_responses_grow_with_the_slider_and_stay_inside_black_and_white() { + let fits = std::iter::once(&m::WHITES).chain(m::REGIONS.iter()); + for (i, fit) in fits.enumerate() { + for sign in [-1.0f32, 1.0] { + for k in 0..=64 { + let x = k as f32 / 64.0; + let mut prev = 0.0f32; + for a in (0..=20).map(|j| sign * 5.0 * j as f32) { + let r = sign * response(fit, a, x); + // steadily: never back by more than a twentieth of an 8-bit level + assert!(r >= -1e-6 && r + 0.05 / 255.0 >= prev, "fit {i} at {x}, amount {a}: {r} after {prev}"); + prev = r; + } + assert_eq!(response(fit, sign * 150.0, x), response(fit, sign * 100.0, x)); + } + assert_eq!(response(fit, sign * 60.0, 0.0), 0.0); + assert_eq!(response(fit, sign * 60.0, 1.0), 0.0); + } + assert_eq!(response(fit, 0.0, 0.5), 0.0); + assert_eq!(response(fit, f32::NAN, 0.5), 0.0); + } + } + + /// The four regions peak in tone order: Shadows lowest, then Darks, Lights, Highlights, each one's strongest lift + /// above the one before's. + #[test] + fn the_regions_peak_in_tone_order() { + let peak = |fit: &[m::Response; 2]| { + (0..=256) + .map(|k| k as f32 / 256.0) + .fold((0.0f32, 0.0f32), |b, x| if response(fit, 50.0, x) > b.1 { (x, response(fit, 50.0, x)) } else { b }) + .0 + }; + let peaks = m::REGIONS.each_ref().map(peak); + assert!(peaks.windows(2).all(|w| w[0] < w[1]), "{peaks:?}"); + } + + /// What the graph draws is the stage's base curve, and the analytic one where the stage uses that. + #[test] + fn the_graph_is_the_curve_the_stage_renders() { + let mut s = v18(); + (s.curve.shadows, s.curve.darks, s.curve.lights, s.curve.highlights) = (40.0, -30.0, 25.0, -60.0); + let graph = ParametricGraph::new(&s); + assert!(graph.is_fitted()); + let stage = CurveStage::new(&s).expect("regions set"); + for i in 0..=64 { + let x = i as f32 / 64.0; + assert!((graph.at(x as f64) as f32 - stage.base.eval(x)).abs() < 1e-6, "{x}"); + } + // moved splits and earlier processes draw the analytic curve, as they render it + s.curve.split_mid = 40.0; + let moved = ParametricGraph::new(&s); + assert!(!moved.is_fitted()); + assert_eq!(moved.at(0.6), ParametricCurve::new(&s.curve).at(0.6)); + s.curve.split_mid = 50.0; + let v17 = DevelopSettings { process: Process::V17.version(), ..s }; + assert!(!ParametricGraph::new(&v17).is_fitted()); + } + + /// Refine Saturation restores the colour after Whites, not before it: at 0, a curve on top of Whites leaves the + /// saturation Whites gives a colour, as Whites alone does (review on #4099). + #[test] + fn refine_saturation_keeps_what_whites_did() { + let sat = |d: [f32; 3]| { + let p = mul3(&matrices().0, d); + let (hi, lo) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2])); + (hi - lo) / hi + }; + let colour = mul3(&matrices().1, [0.9, 0.6, 0.3]); + let mut s = v18(); + s.light.whites = 80.0; + let alone = CurveStage::new(&s).expect("Whites").apply(colour); + s.curve.master = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.5, y: 0.56 }, Point { x: 1.0, y: 1.0 }]; + s.curve.refine_saturation = 0.0; + let refined = CurveStage::new(&s).expect("Whites and a curve").apply(colour); + let whites_did = (sat(alone) - sat(colour)).abs(); + assert!(whites_did > 0.05, "Whites changes the saturation: {} vs {}", sat(alone), sat(colour)); + // close to Whites alone, not pulled back towards the colour before Whites + assert!((sat(refined) - sat(alone)).abs() < 0.3 * whites_did, "refined {} vs Whites alone {}", sat(refined), sat(alone)); + } + + /// In every region, the amount a drag picks moves the drawn curve by the drag's motion. + #[test] + fn a_graph_drag_puts_the_fitted_curve_where_the_hand_is() { + let mut s = v18(); + s.curve.darks = 30.0; + let graph = ParametricGraph::new(&s); + for (region, x) in [(0usize, 0.15f64), (1, 0.375), (2, 0.625), (3, 0.85)] { + for delta in [-0.04, 0.03] { + let from = graph.amount(region); + let a = graph.dragged_amount(region, x, from, delta); + let mut after = s.clone(); + let c = &mut after.curve; + *[&mut c.shadows, &mut c.darks, &mut c.lights, &mut c.highlights][region] = a; + let got = ParametricGraph::new(&after).at(x) - graph.at(x); + assert!((got - delta).abs() < 0.004, "region {region} at {x}: moved {got}, wanted {delta} (amount {from} → {a})"); + } + assert_eq!(graph.dragged_amount(region, x, graph.amount(region), 0.0), graph.amount(region), "no motion, no change"); + assert_eq!(graph.dragged_amount(region, x, 0.0, 1.0), 100.0, "out of reach saturates high"); + assert_eq!(graph.dragged_amount(region, x, 0.0, -1.0), -100.0, "and low"); + } + } + + /// Where opposite regions fold the fitted curve back, the drag follows the curve as drawn (held flat by the peak + /// to its left): Lights +80 and Highlights −100 fold it above 0.75. A region that reaches the peak moves the held + /// line with the hand; one that cannot reach it keeps its value instead of running to the end. + #[test] + fn a_graph_drag_follows_the_drawn_curve_where_it_is_flattened() { + let mut s = v18(); + (s.curve.shadows, s.curve.darks, s.curve.lights, s.curve.highlights) = (-50.0, 100.0, 80.0, -100.0); + let graph = ParametricGraph::new(&s); + let x = 0.86; + let raw = regions_at(graph.model.amounts.map(|v| v as f32), x as f32) as f64; + assert!(graph.at(x) - raw > 0.05, "the stretch is flattened, or this proves nothing: {} vs {raw}", graph.at(x)); + let drawn = |region: usize, a: f64| { + let mut after = s.clone(); + let c = &mut after.curve; + *[&mut c.shadows, &mut c.darks, &mut c.lights, &mut c.highlights][region] = a; + ParametricGraph::new(&after).at(x) + }; + for (region, delta) in [(2usize, -0.03), (3, 0.03)] { + let from = graph.amount(region); + let a = graph.dragged_amount(region, x, from, delta); + let moved = drawn(region, a) - graph.at(x); + assert!((moved - delta).abs() < 0.004, "region {region}: {from} → {a} moved the line {moved}"); + } + // Shadows does not reach the peak that holds the line, so its slider stays + assert!((drawn(0, 100.0) - graph.at(x)).abs() < REACH_MIN, "Shadows cannot move the held line"); + assert_eq!(graph.dragged_amount(0, x, -50.0, 0.03), -50.0); + } + + #[test] + fn tone_order_never_reverses_and_every_table_fits_the_gpu() { + for w in [-100.0, -50.0, 37.0, 100.0] { + let mut s = with_whites(w); + s.curve.shadows = -100.0; + s.curve.lights = 100.0; + let stage = CurveStage::new(&s).expect("set"); + assert!(stage.base.v.windows(2).all(|p| p[0] <= p[1]), "{w}"); + assert!(stage.chan.iter().chain([&stage.base]).all(|l| l.v.len() == N), "{w}"); + } + } + + #[test] + fn the_middle_channel_keeps_its_place_in_linear_prophoto() { + let stage = CurveStage::new(&with_whites(-100.0)).expect("Whites set"); + let (to, from) = matrices(); + let input = [0.55f32, 0.27, 0.08]; + let out = mul3(to, stage.apply(mul3(from, input))); + let at = |p: [f32; 3]| (p[1] - p[2]) / (p[0] - p[2]); + assert!((at(out) - at(input)).abs() < 1e-3, "{out:?}"); + } + + #[test] + fn colour_curves_act_per_channel_after_the_master() { + let mut s = v18(); + s.curve.red = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.5, y: 0.7 }, Point { x: 1.0, y: 1.0 }]; + let stage = CurveStage::new(&s).expect("a red curve"); + let (to, from) = matrices(); + let out = mul3(to, stage.apply(mul3(from, [srgb_to_linear(0.5); 3]))); + assert!((linear_to_srgb(out[0]) - 0.7).abs() < 2e-3, "{out:?}"); + assert!((linear_to_srgb(out[1]) - 0.5).abs() < 2e-3, "{out:?}"); + } + + #[test] + fn hdr_values_keep_slope_one_above_white() { + let stage = CurveStage::new(&with_whites(-50.0)).expect("Whites set"); + let (a, b) = (stage.apply([2.0; 3]), stage.apply([3.0; 3])); + assert!((b[0] - a[0] - 1.0).abs() < 1e-3, "{a:?} {b:?}"); + } + + #[test] + fn refine_saturation_at_zero_undoes_what_the_curves_added() { + let mut s = v18(); + s.curve.master = vec![Point { x: 0.0, y: 0.0 }, Point { x: 0.25, y: 0.15 }, Point { x: 0.75, y: 0.85 }, Point { x: 1.0, y: 1.0 }]; + let sat = |stage: &CurveStage| { + let (to, from) = matrices(); + let p = mul3(to, stage.apply(mul3(from, [0.5, 0.25, 0.12]))).map(linear_to_srgb); + (p[0] - p[2]) / (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) + }; + let full = sat(&CurveStage::new(&s).expect("a curve")); + s.curve.refine_saturation = 0.0; + let none = sat(&CurveStage::new(&s).expect("a curve")); + assert!(none < full, "{none} {full}"); + } +} diff --git a/crates/pipeline/src/curve_stage_model.rs b/crates/pipeline/src/curve_stage_model.rs new file mode 100644 index 00000000000..aae839e7df8 --- /dev/null +++ b/crates/pipeline/src/curve_stage_model.rs @@ -0,0 +1,19 @@ +// Written by `tools/lr_tone_charts.py fit`: LightCraft's model of Whites and the parametric regions, fitted to the +// tool's grey-step charts (provenance in docs/curve-stage.md). Constants of the model only. + +/// One bump of a response: `[a1, a2, a3, p0, p1, q0, q1]`, gain `a1 t + a2 t² + a3 t³` (t = |amount| / 100), shape +/// exponents `e^(p0 + p1 t)` and `e^(q0 + q1 t)` ([`crate::curve_stage`]). +pub type Bump = [f64; 7]; +/// A slider direction's response: two bumps, added. +pub type Response = [Bump; 2]; + +/// Whites: negative, positive. +pub const WHITES: [Response; 2] = [[[-8.677986e-02, 2.059910e-02, -1.475161e-03, 1.084063e+00, -7.146165e-02, 7.463740e-01, -1.101123e+00], [-6.097932e-02, 2.162057e-02, -1.096353e-02, 1.843174e+00, 7.765309e-01, -1.820367e-01, 2.624658e-01]], [[4.491106e-02, 2.338704e-01, -4.586305e-02, 9.656835e-01, -4.030916e-01, -1.003725e+00, 5.542276e-01], [1.938421e-02, -8.766121e-02, 1.285831e-01, 4.062532e+00, -2.298370e+00, 3.928699e+00, -2.151902e+00]]]; + +/// Shadows, Darks, Lights, Highlights at the default splits (25, 50, 75): negative, positive. +pub const REGIONS: [[Response; 2]; 4] = [ + [[[-2.304904e-01, 5.397332e-01, -6.521258e-01, 5.201966e-01, -2.332761e+00, 2.029401e+00, 3.919508e-01], [2.322669e-02, -2.558633e-01, 1.479527e-01, 1.186677e+00, 5.075634e-01, 2.511894e+00, 3.430482e-01]], [[6.250307e-02, -3.253250e-03, 1.768197e-03, -5.212752e-01, -7.111264e-02, 2.313180e+00, -1.136211e-01], [6.286758e-02, 2.093856e-02, 8.466331e-03, 1.302920e+00, 1.043781e-01, 2.604516e+00, 8.384981e-02]]], + [[[2.129550e-01, -1.408218e+00, 2.309347e+00, 4.947582e-01, -1.714892e+00, 1.699307e+00, -6.420795e-01], [-5.249287e-01, 1.634143e+00, -2.399744e+00, 7.555377e-02, -1.304895e+00, 6.002093e-01, 2.401095e-01]], [[1.031476e-01, 3.281627e-02, 1.671911e-02, 5.258136e-01, 3.590506e-01, 9.760341e-01, 2.054602e-01], [6.812073e-02, 1.988377e-03, 5.246361e-03, -1.268885e+00, 1.303334e-01, 3.041567e-01, -9.264136e-02]]], + [[[-1.891098e-01, -2.287609e-02, 4.896024e-03, 1.011762e+00, -7.761107e-02, 4.262329e-02, -9.366133e-02], [-1.171421e-02, -1.146297e-02, -1.531020e-02, 1.645838e+00, 5.732118e-02, 1.456855e+00, 1.833067e-01]], [[-1.125586e-01, 1.431238e+00, -2.702337e+00, 1.792564e+00, -2.246400e-01, 4.144821e-01, -6.849247e-01], [5.280858e-01, -1.775048e+00, 2.776570e+00, 9.675963e-01, 3.076062e-01, 5.110037e-01, -9.632875e-01]]], + [[[-1.081283e-01, -3.328262e-02, -1.114034e-03, 1.725021e+00, -4.534782e-02, 8.818974e-02, -8.042736e-03], [2.358962e-02, 9.943229e-03, 1.375851e-03, 2.617848e+00, -4.358847e-02, 2.360366e+00, -4.425145e-02]], [[-6.006532e-02, 4.574089e-01, -2.733591e-01, 2.232173e+00, 5.657972e-01, 7.143387e-01, 9.022714e-01], [2.802296e-01, -7.070198e-01, 5.853124e-01, 2.094691e+00, 5.061273e-01, 7.808968e-01, -1.635143e+00]]], +]; diff --git a/crates/pipeline/src/default_tone.rs b/crates/pipeline/src/default_tone.rs new file mode 100644 index 00000000000..51cbaa308b0 --- /dev/null +++ b/crates/pipeline/src/default_tone.rs @@ -0,0 +1,162 @@ +//! The default base curve for a profile without a tone curve of its own (process V18). `docs/default-tone.md` +//! records how it was measured and fitted. +//! +//! A camera profile without a tone curve of its own (a DCP without `ProfileToneCurve`) leaves the base tone to the +//! raw converter. Up to V17 LightCraft keeps the photo's own tone (the curve fitted to its camera JPEG, +//! `lightcraft_engine::files`). From V18 such a raw ([`SourceInfo::default_tone`]) gets a fitted default curve +//! (`tools/lr_tone_charts.py base`, [`crate::default_tone_model`]): a monotone curve through 12 knots evenly spaced +//! in stops, applied hue preserving on linear ProPhoto channels ([`rgb_tone`]). The curve is fitted to a chart +//! without a baseline exposure, and raws of other formats need an exposure offset per camera: [`camera_ev`] holds +//! the offsets measured on photos, and other cameras get none. + +use crate::SourceInfo; +use crate::default_tone_model as m; +use crate::tone::CameraTone; +use lightcraft_color::spline::MonotoneCurve; +use lightcraft_develop::{DevelopSettings, Process}; + +/// Exposure offsets per camera (make, model, stops) for a raw rendered through its Adobe Standard profile: the shift +/// of the curve that leaves the camera's unedited photos no brighter or darker on average than the reference renders +/// they were measured against (`docs/default-tone.md`). +const CAMERA_EV: [(&str, &str, f32); 4] = + [("Panasonic", "DC-S9", -0.10), ("Panasonic", "DC-S5", -0.04), ("Panasonic", "DC-S5M2", -0.03), ("Panasonic", "DC-S5M2X", -0.05)]; + +/// The measured exposure offset of a camera in stops, 0 for a camera not measured. +pub fn camera_ev(make: &str, model: &str) -> f32 { + CAMERA_EV.iter().find(|(m, n, _)| make.trim().eq_ignore_ascii_case(m) && model.trim().eq_ignore_ascii_case(n)).map_or(0.0, |c| c.2) +} + +/// The default curve of `info` under `s`: from process V18, for a raw whose profile has no tone curve. +pub fn for_source(s: &DevelopSettings, info: &SourceInfo) -> Option { + let v18 = s.process.process() >= Process::V18; + curve(info.default_tone.filter(|_| v18 && info.raw)?) +} + +/// The fitted curve with the scene shifted by `ev` stops: 32 knots, evenly spaced in stops over the fitted range. +/// Below the first knot the curve runs straight to black; past the last it rolls off into white +/// ([`CameraTone::apply_rolloff`]). +pub fn curve(ev: f32) -> Option { + if !ev.is_finite() { + return None; + } + let gain = 2f32.powf(ev); + let ln2 = std::f32::consts::LN_2; + let (x0, x1) = (m::STOPS.0 as f32 * ln2, m::STOPS.1 as f32 * ln2); + let knots: [[f32; 2]; 32] = std::array::from_fn(|i| { + let x = (x0 + (x1 - x0) * i as f32 / 31.0).exp(); + [x / gain, grey(x).min(0.9995)] + }); + CameraTone::new(knots) +} + +/// The fitted curve's output at chart value `x`: a monotone curve through [`m::KNOTS`], evenly spaced in stops from +/// [`m::STOPS`]`.0` to [`m::STOPS`]`.1`, held at the first knot's value below it. +fn grey(x: f32) -> f32 { + static CURVE: std::sync::OnceLock = std::sync::OnceLock::new(); + let curve = CURVE.get_or_init(|| { + let n = m::KNOTS.len().max(2) - 1; + let pts: Vec<(f64, f64)> = + m::KNOTS.iter().enumerate().map(|(i, y)| (m::STOPS.0 + (m::STOPS.1 - m::STOPS.0) * i as f64 / n as f64, *y)).collect(); + MonotoneCurve::new(&pts) + }); + let stops = f64::from(x).max(2f64.powf(m::STOPS.0)).log2(); + curve.eval(stops) as f32 +} + +/// The base tone, hue preserving: `tone` on the largest and smallest channel in linear ProPhoto, the middle +/// channel keeping its place between them (linear Rec.2020 in and out). +pub fn rgb_tone(c: [f32; 3], tone: impl Fn(f32) -> f32) -> [f32; 3] { + let (to, from) = matrices(); + let p = mul3(to, c).map(|v| v.max(0.0)); + let (mut hi, mut lo) = (0, 0); + for k in 1..3 { + if p[k] > p[hi] { + hi = k; + } + if p[k] < p[lo] { + lo = k; + } + } + let (a, b) = (p[hi], p[lo]); + let (fa, fb) = (tone(a), tone(b)); + let out: [f32; 3] = std::array::from_fn(|k| if a > b { fb + (fa - fb) * (p[k] - b) / (a - b) } else { fa }); + mul3(from, out) +} + +/// Linear Rec.2020 to linear ProPhoto and back, built once. +fn matrices() -> &'static ([[f32; 3]; 3], [[f32; 3]; 3]) { + static M: std::sync::OnceLock<([[f32; 3]; 3], [[f32; 3]; 3])> = std::sync::OnceLock::new(); + M.get_or_init(crate::light_v3::prophoto_matrices) +} + +/// Multiplies a colour by a 3 × 3 matrix. +fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { + std::array::from_fn(|r| m[r][0] * d[0] + m[r][1] * d[1] + m[r][2] * d[2]) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Settings on process `p`. + fn on(p: Process) -> DevelopSettings { + DevelopSettings { process: p.version(), ..Default::default() } + } + + /// A raw rendered through a profile without a tone curve, with exposure offset `ev`. + fn raw(ev: Option) -> SourceInfo { + SourceInfo { raw: true, default_tone: ev, ..Default::default() } + } + + #[test] + fn only_v9_raws_whose_profile_has_no_curve_get_it() { + assert!(for_source(&on(Process::V18), &raw(Some(0.0))).is_some()); + assert!(for_source(&on(Process::V7), &raw(Some(0.0))).is_none()); + assert!(for_source(&on(Process::V17), &raw(Some(0.0))).is_none()); + assert!(for_source(&on(Process::V18), &raw(None)).is_none()); + let rendered = SourceInfo { raw: false, ..raw(Some(0.0)) }; + assert!(for_source(&on(Process::V18), &rendered).is_none()); + } + + #[test] + fn the_curve_rises_with_contrast_and_the_offset_shifts_it() { + let c = curve(0.0).unwrap(); + // tone order never reverses, and the curve runs from near black to near white over the chart's range + let xs: Vec = (0..=60).map(|i| 2f32.powf(-9.0 + 9.0 * i as f32 / 60.0)).collect(); + assert!(xs.windows(2).all(|w| c.apply(w[0]) <= c.apply(w[1]))); + assert!(c.apply(0.002) < 0.002 && c.apply(1.0) > 0.99, "{} {}", c.apply(0.002), c.apply(1.0)); + // a toe: deep shadows are darker than the scene, the midtones brighter + assert!(c.apply(0.004) < 0.004 && c.apply(0.05) > 0.05); + // the chart's mid grey (scene 0.18) lands well above display 0.18: a base curve with contrast and lift + let mid = c.apply(0.18); + assert!(mid > 0.35 && mid < 0.45, "{mid}"); + // -0.1 stops: the scene needs 2^0.1 more light for the same output + let d = curve(-0.1).unwrap(); + assert!((d.apply(0.18 * 2f32.powf(0.1)) - mid).abs() < 2e-3); + assert!(curve(f32::NAN).is_none()); + } + + #[test] + fn camera_offsets_are_by_make_and_model() { + assert_eq!(camera_ev("Panasonic", "DC-S9"), -0.10); + assert_eq!(camera_ev("PANASONIC ", "dc-s9"), -0.10); + assert_eq!(camera_ev("Panasonic", "DC-S5M2"), -0.03); + assert_eq!(camera_ev("Panasonic", "DC-G9M2"), 0.0); + assert_eq!(camera_ev("Sony", "ILCE-7M4"), 0.0); + } + + #[test] + fn rgb_tone_keeps_grey_grey_and_hue_in_prophoto() { + let c = curve(0.0).unwrap(); + let f = |v: f32| c.apply_rolloff(v); + let g = rgb_tone([0.18; 3], f); + assert!(g.iter().all(|v| (v - c.apply(0.18)).abs() < 1e-4), "{g:?}"); + // the middle ProPhoto channel keeps its relative place between the others + let (to, from) = matrices(); + let p = [0.30, 0.12, 0.05]; + let o = mul3(to, rgb_tone(mul3(from, p), f)); + let (r0, r1) = ((p[1] - p[2]) / (p[0] - p[2]), (o[1] - o[2]) / (o[0] - o[2])); + assert!((r0 - r1).abs() < 1e-3, "{r0} {r1}"); + assert!((o[0] - f(0.30)).abs() < 1e-4 && (o[2] - f(0.05)).abs() < 1e-4); + } +} diff --git a/crates/pipeline/src/default_tone_model.rs b/crates/pipeline/src/default_tone_model.rs new file mode 100644 index 00000000000..9ce6a39cddb --- /dev/null +++ b/crates/pipeline/src/default_tone_model.rs @@ -0,0 +1,7 @@ +// Written by `tools/lr_tone_charts.py base`: LightCraft's default base curve, fitted to the tool's neutral +// grey-step chart (provenance in docs/default-tone.md). Knots of the curve only. + +/// The knots' range in stops of the chart's linear value: from the darkest grey step to white. +pub const STOPS: (f64, f64) = (-8.965784e+00, 0.0); +/// The curve's linear ProPhoto output at the knots, evenly spaced over [`STOPS`]. +pub const KNOTS: [f64; 12] = [0.000000e+00, 8.133183e-04, 3.366455e-03, 7.031622e-03, 1.633029e-02, 3.958236e-02, 9.053161e-02, 1.968403e-01, 3.887485e-01, 6.233585e-01, 8.545124e-01, 1.000000e+00]; diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 29486f269a7..8c4474c0b7b 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -148,10 +148,12 @@ impl GrainModel { seed: g.seed, }) }), - Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 if draft => { + Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 | Process::V18 + if draft => + { crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal) } - Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 => { + Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 | Process::V18 => { crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal) } } @@ -256,6 +258,9 @@ pub struct FinishParams { /// A LUT profile and its amount (0..2), applied to the display-encoded colour. pub lut: Option<(std::sync::Arc, f32)>, pub tone: ToneMap, + /// Process V18 with the fitted default curve ([`crate::default_tone`]): the tone map applies hue preserving + /// on linear ProPhoto channels ([`crate::default_tone::rgb_tone`]) instead of scaling by luminance. + pub rgb_tone: bool, /// Process V4's calibrated Contrast and Blacks on the camera-look path, applied after /// the tone map (`None`: another process or path, or both at 0; see [`crate::light_v3`]). pub light: Option, @@ -271,6 +276,13 @@ pub struct FinishParams { pub shadow_tint: f32, /// Tone curves (parametric ∘ point, per channel) on encoded values, 1024 entries each. pub curves: Option<[Lut1; 3]>, + /// Process V18's colour mixer (it replaces the mixer in `ops`). + pub mixer_stage: Option, + /// Process V18's Whites and tone curves (they replace `curves`, which stays `None` from V18 on). + pub curve_stage: Option, + /// A curve-input sample ([`crate::curve_input`]) under V18 is taken where the curve stage reads: right after it, as + /// sRGB-encoded linear ProPhoto, before the colour tools and the output. + pub sample_at_curve_stage: bool, /// Refine Saturation as 0..1 (1 = the curves' own saturation). pub refine_sat: f32, pub vig: Option, @@ -283,6 +295,8 @@ pub struct FinishParams { pub proof: Option, pub hl: f32, pub sh: f32, + /// Process V18: Highlights acts relative to the frame's tonal range, exposure included ([`crate::hs_range`]). + pub hs_range: Option, pub clar: f32, pub tex: f32, pub dehaze: f32, @@ -322,6 +336,8 @@ pub struct FinishParamsInput<'a> { pub image_size: (usize, usize), pub px_per_long: f64, pub air_pre: f32, + /// The whole frame's tonal range before exposure ([`crate::Plan::hs_range`]). + pub hs_range: Option, pub space: OutputSpace, /// A draft render (a drag, [`crate::Quality::Draft`]): see [`GrainModel::new`]. pub draft: bool, @@ -330,7 +346,7 @@ pub struct FinishParamsInput<'a> { impl FinishParams { /// Parameters for a `w × h` render into `space`; `ev`/`air_pre` as in [`crate::Prepared`]. pub fn new(input: FinishParamsInput<'_>) -> FinishParams { - let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space, draft } = input; + let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, hs_range, space, draft } = input; let effects = s.section_enabled("effects"); let (clar, tex, dehaze) = if effects { ((s.effects.clarity / 100.0) as f32, texture_slider(s.effects.texture, s.process.process()), (s.effects.dehaze / 100.0) as f32) @@ -359,10 +375,14 @@ impl FinishParams { calib: if calibration { crate::colorops::calibration_matrix(&s.calibration) } else { None }, shadow_tint: if calibration { (s.calibration.shadows_tint / 100.0) as f32 } else { 0.0 }, tone: base_tone(s, info, peak), + rgb_tone: crate::default_tone::for_source(s, info).is_some(), light: crate::light_v3::LightOps::new(s, info), lut: crate::lut::get(&s.profile.id).map(|l| (l, (s.profile.amount / 100.0).clamp(0.0, 2.0) as f32)), ops: ColorOps::new(s), - curves: curve_luts(&s.curve), + curves: if s.process.process() < Process::V18 { curve_luts(&s.curve) } else { None }, + mixer_stage: crate::mixer_stage::MixerStage::new(s), + sample_at_curve_stage: false, + curve_stage: curve_stage_for(s, proraw.is_some()), refine_sat: (s.curve.refine_saturation / 100.0).clamp(0.0, 1.0) as f32, vig: if effects { vignette(s) } else { None }, to_out: space.from_working(), @@ -371,6 +391,7 @@ impl FinishParams { proof: None, hl: if proraw.is_some() { 0.0 } else { (s.light.highlights / 100.0) as f32 }, sh: if proraw.is_some() { 0.0 } else { tone_slider(s.light.shadows, SHADOWS_EASE, s.process.process()) }, + hs_range: hs_range.filter(|_| crate::hs_range::wanted(s)).map(|r| r.shifted(ev)), proraw, lr_hs, clar, @@ -489,6 +510,26 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), }, + // V17, with Whites moved out of the tone map: the curve stage applies Whites (`crate::curve_stage`). A raw + // whose profile has no tone curve gets the fitted default curve (`crate::default_tone`) instead of its own. + Process::V18 => match crate::default_tone::for_source(s, info).or(info.camera_tone.filter(|_| info.raw)) { + Some(curve) => ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak), + None if info.raw => ToneMap::rolloff_hdr(l.contrast, 0.0, l.blacks, peak), + None => ToneMap::display_hdr(l.contrast, 0.0, l.blacks, peak), + }, + } +} + +/// The curve stage of `s` ([`crate::curve_stage`]). Apple ProRAW's chain applies Whites itself (`crate::proraw`), so +/// on ProRAW (`proraw`) the stage keeps only the curves. The render and the curve editor's input sample +/// ([`crate::curve_input`]) both build it here, so Whites applies once in each. +pub(crate) fn curve_stage_for(s: &DevelopSettings, proraw: bool) -> Option { + if proraw && s.light.whites != 0.0 { + let mut no_whites = s.clone(); + no_whites.light.whites = 0.0; + crate::curve_stage::CurveStage::new(&no_whites) + } else { + crate::curve_stage::CurveStage::new(s) } } @@ -504,6 +545,7 @@ pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &So image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, + hs_range: p.hs_range, space, draft, }); @@ -538,6 +580,7 @@ pub(crate) fn finish_deep(p: &Prepared, s: &DevelopSettings, frame: &Frame, info image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, + hs_range: p.hs_range, space, draft, }); @@ -589,6 +632,7 @@ pub(crate) fn finish_with( let preview_light = if exact { None } else { light.as_ref().and_then(|lo| crate::light_v3::PreviewOps::new(lo, &|v| encode_srgb(srgb, v))) }; let peak = fp.peak; let hdr = peak > 1.0; + let to_pro = crate::light_v3::prophoto_matrices().0; let mut out = vec![T::default(); w * h]; // the vignette splits into a column term and a row term, so each is computed once let vig_fall = vig.as_ref().map(|v| VigFalloff::new(v, aspect)); @@ -611,7 +655,7 @@ pub(crate) fn finish_with( // --- local tone in log luminance let shift = l1 - l0; let base = p.base.data[i] + fp.ev + shift; - let delta = local_tone_delta(p, fp, i, base, l1, &local); + let delta = local_tone_delta(p, fp, i, base, l1, &local, fp.hs_range.as_ref()); if delta != 0.0 { let g = delta.exp2(); c = c.map(|v| v * g); @@ -626,12 +670,22 @@ pub(crate) fn finish_with( // Lightroom's chain (per channel, with its Highlights / Shadows) let mut d = match &fp.proraw { Some(map) => proraw_tone(map, fp.lr_hs.as_ref(), c, base), - None => luminance_tone(&fp.tone, c, peak), + None => luminance_tone(&fp.tone, c, peak, fp.rgb_tone), }; // --- process V4: calibrated Contrast, Blacks (ProPhoto with the sRGB transfer) d = apply_light(d, light.as_ref(), preview_light.as_ref(), exact, srgb); + // --- process V18: the colour mixer, then Whites and the tone curves + d = fp.mixer_stage.as_ref().map_or(d, |stage| stage.apply(d)); + d = fp.curve_stage.as_ref().map_or(d, |stage| stage.apply(d)); + if stop_after_curves && fp.sample_at_curve_stage { + let pro = mul3(&to_pro, d); + // (above SDR white stays above 1, beyond the curve's axes, as on the output path) + *px = store(vx_u + x, vy_u + y, pro.map(|v| linear_to_srgb(v.max(0.0)))); + continue; + } + // --- colour d = fp.ops.apply(d, l_sat, l_hue); if let Some((dir, amt)) = local.tint { @@ -843,10 +897,18 @@ fn adjust_scene_pixel(p: &Prepared, fp: &FinishParams, index: usize, raw: [f32; } /// The tone map on luminance, with the curve's chroma scale and desaturation above `peak`. -fn luminance_tone(tone: &ToneMap, c: [f32; 3], peak: f32) -> [f32; 3] { +fn luminance_tone(tone: &ToneMap, c: [f32; 3], peak: f32, rgb: bool) -> [f32; 3] { let yl = luminance_2020(c); let o = tone.apply(yl); - let mut d = if yl > 1e-9 { c.map(|v| v * o / yl) } else { [0.0; 3] }; + // from process V18 the fitted default curve applies hue preserving on linear ProPhoto channels + // ([`FinishParams::rgb_tone`]) instead of scaling by the luminance change + let mut d = if rgb { + crate::default_tone::rgb_tone(c, |v| tone.apply(v)) + } else if yl > 1e-9 { + c.map(|v| v * o / yl) + } else { + [0.0; 3] + }; let k = tone.chroma_scale(o); if k != 1.0 { d = d.map(|v| o + (v - o) * k); @@ -881,14 +943,26 @@ fn proraw_tone(map: &crate::proraw::ProRawMap, lr_hs: Option<&crate::proraw::LrH map.apply_hdr(c, map.apply_contrast_rgb(d)) } -fn local_tone_delta(p: &Prepared, fp: &FinishParams, index: usize, base: f32, l1: f32, local: &PixelLocalTerms) -> f32 { +fn local_tone_delta( + p: &Prepared, + fp: &FinishParams, + index: usize, + base: f32, + l1: f32, + local: &PixelLocalTerms, + range: Option<&crate::hs_range::FrameRange>, +) -> f32 { let [_, _, _, l_con, l_hl, l_sh, l_wh, l_bl, l_tex, l_clar, _, _, _, l_sharp, l_noise, _, _] = local.values; let mut delta = 0.0; let (highlights, shadows) = (fp.hl + l_hl, fp.sh + l_sh); if highlights != 0.0 || shadows != 0.0 { let shadow_weight = 1.0 - smooth(-4.8, 0.3, base); let highlight_weight = smooth(-1.0, 2.8, base); - delta += shadows * 1.7 * shadow_weight * shadow_weight.sqrt() + highlights * 1.7 * highlight_weight; + delta += shadows * 1.7 * shadow_weight * shadow_weight.sqrt(); + delta += match range { + Some(r) => r.highlights(highlights, base), + None => highlights * 1.7 * highlight_weight, + }; } if l_wh != 0.0 { delta += l_wh * 0.8 * smooth(0.5, 3.0, l1); @@ -1125,6 +1199,7 @@ mod tests { image_size: (64, 8), px_per_long: 64.0, air_pre: 0.0, + hs_range: None, space: OutputSpace::Srgb, draft: false, }); @@ -1194,7 +1269,9 @@ mod tests { src.data[16 + x] = [0.01, 1.5, 0.02]; // row 2: green edge src.data[24 + x] = [0.02, 0.05, 1.8]; // row 3: blue edge } - let mut s = DevelopSettings::default(); + // the legacy pipeline: from V18 Highlights scales with the frame's tonal range (`crate::hs_range`), which + // this 8 px chart barely has, so -30 no longer pulls the green edge out of the clip + let mut s = DevelopSettings { process: Process::V16.version(), ..Default::default() }; s.light.highlights = -30.0; s.light.shadows = 20.0; s.curve.master = vec![Point::new(0.0, 0.04), Point::new(0.5, 0.56), Point::new(1.0, 0.96)]; diff --git a/crates/pipeline/src/grading_stage.rs b/crates/pipeline/src/grading_stage.rs new file mode 100644 index 00000000000..db8bc51d531 --- /dev/null +++ b/crates/pipeline/src/grading_stage.rs @@ -0,0 +1,342 @@ +//! Process V18's Colour Grading ([`lightcraft_develop::Process::V18`]), from a fitted model (`grading_stage_model`, +//! written by `tools/lr_grading_charts.py fit`). `docs/grading-stage.md` records how it was measured and fitted. Per +//! wheel (shadows, midtones, highlights, global): +//! - an OkLab tint (a, b) by wheel hue and saturation: one smooth shape around the hue circle shared by the wheels, +//! a size per wheel and a saturation curve per wheel; +//! - a lightness profile, the share of the tint each lightness gets, by Blending and Balance. The shadows wheel +//! reaches well into the midtones and the global wheel peaks in the midtones; +//! - a damping: colours that already lean the tint's way get less of it (55 to 87% for saturated colours in the same +//! direction), by their chroma and the angle between their hue and the tint's; +//! - the wheel's Luminance as a lightness change by lightness. +//! +//! The wheels act on the same input colour and their changes add. The stage replaces the grading of V17 and earlier at the end of +//! [`crate::colorops::ColorOps`], in the same place. + +use lightcraft_develop::{ColorGrading, DevelopSettings, Process, Wheel}; + +use crate::grading_stage_model as m; + +/// The damping's chroma levels: the chart's colour patches (`tools/lr_grading_charts.py`), where the stage samples +/// the model. +pub const CHROMA: [f32; 3] = [0.04, 0.08, 0.12]; + +/// Lightness grid entries (0 to 1). +pub const GRID: usize = 65; + +/// One active wheel, resolved for a render. +#[derive(Clone, Debug)] +pub struct WheelStage { + /// OkLab (a, b) at full share. + pub tint: [f32; 2], + /// Share of the tint by lightness. + pub profile: [f32; GRID], + /// Share by chroma level ([`CHROMA`]) and angle (6 bins of 30°, sampled at their centres). + pub damping: [[f32; 6]; 3], +} + +#[derive(Clone, Debug)] +pub struct GradingStage { + /// Wheels with a saturation above 0. + pub wheels: Vec, + /// Every wheel's Luminance together: the lightness change by lightness. + pub lum: [f32; GRID], +} + +/// `v` on a lightness grid, linear, clamped to 0..1. +fn on_grid(v: &[f32; GRID], l: f32) -> f32 { + let p = l.clamp(0.0, 1.0) * (GRID - 1) as f32; + let i = (p as usize).min(GRID - 2); + match (v.get(i), v.get(i + 1)) { + (Some(a), Some(b)) => a + (b - a) * (p - i as f32), + _ => 0.0, + } +} + +/// (lower index, upper index, weight of the upper) of `x` in the sorted `keys`, clamped. +fn bracket(keys: &[f32], x: f32) -> (usize, usize, f32) { + let n = keys.len(); + match (keys.first(), keys.last()) { + (Some(lo), Some(hi)) if n >= 2 && x > *lo => { + if x >= *hi { + return (n - 1, n - 1, 0.0); + } + let i = keys.windows(2).position(|w| x <= w[1]).unwrap_or(0); + (i, i + 1, (x - keys[i]) / (keys[i + 1] - keys[i])) + } + _ => (0, 0, 0.0), + } +} + +/// `c0 + Σ c[2k−1] cos(k h) + c[2k] sin(k h)`. +fn fourier(c: &[f64], h: f64) -> f64 { + let (first, rest) = c.split_first().map_or((0.0, &[][..]), |(f, r)| (*f, r)); + first + rest.as_chunks::<2>().0.iter().enumerate().map(|(k, [c, s])| c * ((k + 1) as f64 * h).cos() + s * ((k + 1) as f64 * h).sin()).sum::() +} + +/// A bump of peak 1 at `p / (p + q)`, with `x` and `1 − x` held at 1e-12 or more, as the fit computes it +/// (`tools/lr_grading_charts.py`): with a small `q` it still acts at white, and the fitted constants describe the +/// render there too (review on #4103). +fn bump(x: f64, p: f64, q: f64) -> f64 { + let peak = p / (p + q); + let (u, v) = (x.clamp(1e-12, 1.0), (1.0 - x).clamp(1e-12, 1.0)); + (p * (u / peak).ln() + q * (v / (1.0 - peak)).ln()).exp() +} + +/// The tint of wheel `w` at `hue` (degrees) and `sat` (0..100): the shared direction and size around the hue circle, +/// the wheel's size and its saturation curve `s (1 + g1 (s − 1) + g2 (s − 1)²)`, `s` = sat / 100. +fn tint(w: usize, hue: f32, sat: f32) -> [f32; 2] { + let (Some(scale), Some([g1, g2])) = (m::WHEEL_SIZE.get(w), m::WHEEL_SAT.get(w)) else { return [0.0; 2] }; + let h = f64::from(hue).to_radians(); + let s = (f64::from(sat) / 100.0).clamp(0.0, 1.0); + let angle = h + fourier(&m::TINT_ANGLE, h); + let size = (fourier(&m::TINT_SIZE, h) + scale).exp() * s * (1.0 + g1 * (s - 1.0) + g2 * (s - 1.0) * (s - 1.0)); + [(size * angle.cos()) as f32, (size * angle.sin()) as f32] +} + +/// Two bumps whose gain and exponents are quadratic in `b` and `c`, at lightness `l` ([`m::SHARE`]). +fn share(p: &[f64; 30], b: f64, c: f64, l: f64) -> f64 { + p.as_chunks::<15>() + .0 + .iter() + .map(|q| { + let f = |i: usize| q[i] + q[i + 1] * b + q[i + 2] * b * b + q[i + 3] * c + q[i + 4] * c * c; + f(0) * bump(l, f(5).exp(), f(10).exp()) + }) + .sum() +} + +/// The share of wheel `w`'s tint by lightness, at Blending and Balance (the global wheel ignores Balance). +fn profile(w: usize, blending: f32, balance: f32) -> [f32; GRID] { + let Some(p) = m::SHARE.get(w) else { return [0.0; GRID] }; + let b = f64::from(blending.clamp(0.0, 100.0)) / 100.0 - 0.5; + let c = if w == 3 { 0.0 } else { f64::from(balance.clamp(-100.0, 100.0)) / 100.0 }; + std::array::from_fn(|i| share(p, b, c, i as f64 / (GRID - 1) as f64).max(0.0) as f32) +} + +/// Wheel `w`'s Luminance `v` (−100..100) as a lightness change by lightness: per direction two bumps, gain and +/// exponents changing with the amount ([`m::LUM`]). +fn luminance(w: usize, v: f32) -> [f32; GRID] { + let Some(p) = m::LUM.get(w) else { return [0.0; GRID] }; + let t = (f64::from(v) / 100.0).clamp(-1.0, 1.0); + let (a, side) = (t.abs(), if t < 0.0 { 0 } else { 12 }); + std::array::from_fn(|i| { + let l = i as f64 / (GRID - 1) as f64; + let r: f64 = p[side..side + 12] + .as_chunks::<6>() + .0 + .iter() + .map(|[g1, g2, p0, p1, q0, q1]| (g1 * a + g2 * a * a) * bump(l, (p0 + p1 * a).exp(), (q0 + q1 * a).exp())) + .sum(); + (t.signum() * r) as f32 + }) +} + +/// Wheel `w`'s damping by chroma level and angle bin: `1 + (C / 0.12)^exp(e) (d0 + d1 cos a + d2 cos 2a)` at the bins' +/// centres (15°, 45° … 165°). +fn damping(w: usize) -> [[f32; 6]; 3] { + let Some([d0, d1, d2, e]) = m::DAMPING.get(w).copied() else { return [[1.0; 6]; 3] }; + std::array::from_fn(|k| { + let c = f64::from(CHROMA.get(k).copied().unwrap_or(0.0)) / 0.12; + std::array::from_fn(|j| { + let a = (15.0 + 30.0 * j as f64).to_radians(); + (1.0 + c.powf(e.exp()) * (d0 + d1 * a.cos() + d2 * (2.0 * a).cos())) as f32 + }) + }) +} + +impl GradingStage { + /// The stage for `s`: `None` before V18 or when Colour Grading is neutral. + pub fn new(s: &DevelopSettings) -> Option { + if s.process.process() < Process::V18 || s.grading.is_neutral() { + return None; + } + let g: &ColorGrading = &s.grading; + let wheels: [&Wheel; 4] = [&g.shadows, &g.midtones, &g.highlights, &g.global]; + let (blending, balance) = (g.blending as f32, g.balance as f32); + let mut lum = [0.0f32; GRID]; + let mut out = Vec::new(); + for (w, wheel) in wheels.iter().enumerate() { + if wheel.sat > 0.0 && wheel.sat.is_finite() { + out.push(WheelStage { + tint: tint(w, wheel.hue as f32, wheel.sat as f32), + profile: profile(w, blending, balance), + damping: damping(w), + }); + } + if wheel.lum != 0.0 && wheel.lum.is_finite() { + let l = luminance(w, wheel.lum as f32); + lum.iter_mut().zip(l).for_each(|(a, b)| *a += b); + } + } + Some(GradingStage { wheels: out, lum }) + } + + /// Colour Grading on OkLab. + pub fn apply(&self, lab: [f32; 3]) -> [f32; 3] { + let [l0, a0, b0] = lab; + let c = (a0 * a0 + b0 * b0).sqrt(); + let hue = b0.atan2(a0); + let (mut a, mut b) = (a0, b0); + for w in &self.wheels { + let p = on_grid(&w.profile, l0); + if p == 0.0 { + continue; + } + let diff = (hue - w.tint[1].atan2(w.tint[0]) + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; + // each angle bin is the mean over 30°: linear between the bins' centres (15°, 45° … 165°), so the + // damping has no step along a hue gradient + let pos = (diff.abs().to_degrees() / 30.0 - 0.5).clamp(0.0, 5.0); + let j = (pos as usize).min(4); + let fa = pos - j as f32; + let level = |k: usize| w.damping.get(k).map_or(1.0, |r| r[j] * (1.0 - fa) + r[j + 1] * fa); + let damp = if c <= CHROMA[0] { + 1.0 + (level(0) - 1.0) * c / CHROMA[0] + } else { + let (k0, k1, f) = bracket(&CHROMA, c); + level(k0) * (1.0 - f) + level(k1) * f + }; + a += p * w.tint[0] * damp; + b += p * w.tint[1] * damp; + } + [(l0 + on_grid(&self.lum, l0)).max(0.0), a, b] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The model's Luminance runs on to white as the fit computed it: highlights Luminance −100 still darkens white, + /// continuous with the grid step below it, instead of dropping to 0 there (review on #4103). + #[test] + fn highlights_luminance_reaches_white_as_fitted() { + let l = luminance(2, -100.0); + let (white, below) = (l[GRID - 1], l[GRID - 2]); + assert!(white < 0.0, "white is darkened: {white}"); + assert!((white - below).abs() < 0.25 * below.abs(), "no step at white: {below} then {white}"); + } + + /// Default settings on process V18. + fn v18() -> DevelopSettings { + DevelopSettings { process: Process::V18.version(), ..Default::default() } + } + + /// The stage for V18 settings with Colour Grading set by `f`. + fn stage(f: impl Fn(&mut ColorGrading)) -> GradingStage { + let mut s = v18(); + f(&mut s.grading); + GradingStage::new(&s).expect("stage") + } + + #[test] + fn only_v8_with_grading_gets_the_stage() { + assert!(GradingStage::new(&v18()).is_none()); + let mut s = v18(); + s.grading.shadows.hue = 200.0; + assert!(GradingStage::new(&s).is_none(), "a hue without saturation is neutral"); + s.grading.shadows.sat = 30.0; + assert!(GradingStage::new(&s).is_some()); + s.process = Process::V7.version(); + assert!(GradingStage::new(&s).is_none()); + } + + #[test] + fn the_shadows_wheel_tints_greys_and_reaches_into_the_midtones() { + // a warm shadows tint (wheel hue 30) + let st = stage(|g| { + g.shadows.hue = 30.0; + g.shadows.sat = 60.0; + }); + let dark = st.apply([0.3, 0.0, 0.0]); + let mid = st.apply([0.6, 0.0, 0.0]); + let bright = st.apply([0.95, 0.0, 0.0]); + let size = |x: [f32; 3]| x[1].hypot(x[2]); + assert!(dark[1] > 0.0 && dark[2] > 0.0, "warm: {dark:?}"); + assert!(size(mid) > 0.3 * size(dark), "the shadows wheel reaches the midtones: {mid:?} vs {dark:?}"); + assert!(size(bright) < 0.3 * size(dark), "{bright:?}"); + assert_eq!(dark[0], 0.3, "the tint leaves lightness alone"); + } + + #[test] + fn colours_leaning_the_tints_way_get_less_of_it() { + let st = stage(|g| { + g.global.hue = 30.0; + g.global.sat = 100.0; + }); + let grey = st.apply([0.6, 0.0, 0.0]); + let t = [grey[1], grey[2]]; + let n = t[0].hypot(t[1]); + let along = [0.1 * t[0] / n, 0.1 * t[1] / n]; + let same = st.apply([0.6, along[0], along[1]]); + let gain = ((same[1] - along[0]) * t[0] + (same[2] - along[1]) * t[1]) / (n * n); + assert!(gain < 0.95 && gain > 0.3, "{gain}"); + } + + #[test] + fn the_damping_has_no_step_along_a_hue_gradient() { + // shadows at chroma 0.12, where the damping changes most with the angle + let st = stage(|g| { + g.shadows.hue = 30.0; + g.shadows.sat = 100.0; + }); + let grey = st.apply([0.3, 0.0, 0.0]); + let tint = grey[2].atan2(grey[1]); + let added = |deg: f32| { + let h = tint + deg.to_radians(); + let lab = [0.3, 0.12 * h.cos(), 0.12 * h.sin()]; + let out = st.apply(lab); + (out[1] - lab[1]).hypot(out[2] - lab[2]) + }; + let mut prev = added(0.0); + for i in 1..=360 { + let now = added(i as f32 * 0.5); + assert!((now - prev).abs() < 0.02 * prev, "{}°: {prev} → {now}", i as f32 * 0.5); + prev = now; + } + } + + #[test] + fn saturation_and_hue_interpolate() { + let size = |sat: f64, hue: f64| { + let st = stage(|g| { + g.midtones.hue = hue; + g.midtones.sat = sat; + }); + let x = st.apply([0.5, 0.0, 0.0]); + (x[1].hypot(x[2]), x[2].atan2(x[1])) + }; + let (s10, _) = size(10.0, 120.0); + let (s25, h25) = size(25.0, 120.0); + let (s75, _) = size(75.0, 120.0); + assert!(s10 < s25 && s25 < s75, "{s10} {s25} {s75}"); + let (_, h_mid) = size(25.0, 135.0); + let (_, h150) = size(25.0, 150.0); + assert!((h25.min(h150)..=h25.max(h150)).contains(&h_mid), "{h25} {h_mid} {h150}"); + } + + #[test] + fn luminance_moves_lightness_and_nothing_else() { + let st = stage(|g| g.highlights.lum = 60.0); + assert!(st.wheels.is_empty()); + let x = st.apply([0.85, 0.02, -0.01]); + assert!(x[0] > 0.85, "{x:?}"); + assert_eq!([x[1], x[2]], [0.02, -0.01]); + let st = stage(|g| g.highlights.lum = -100.0); + assert!(st.apply([0.85, 0.0, 0.0])[0] < 0.85); + } + + #[test] + fn balance_moves_the_split() { + let at = |balance: f64| { + let st = stage(|g| { + g.shadows.hue = 220.0; + g.shadows.sat = 50.0; + g.balance = balance; + }); + let x = st.apply([0.55, 0.0, 0.0]); + x[1].hypot(x[2]) + }; + // Balance towards the highlights narrows the shadows wheel's reach + assert!(at(100.0) < at(0.0) && at(0.0) < at(-100.0), "{} {} {}", at(100.0), at(0.0), at(-100.0)); + } +} diff --git a/crates/pipeline/src/grading_stage_model.rs b/crates/pipeline/src/grading_stage_model.rs new file mode 100644 index 00000000000..957755c212c --- /dev/null +++ b/crates/pipeline/src/grading_stage_model.rs @@ -0,0 +1,29 @@ +// Written by `tools/lr_grading_charts.py fit`: LightCraft's model of Colour Grading, fitted to the tool's charts +// (provenance in docs/grading-stage.md). Constants of the model only. Wheels: shadows, midtones, highlights, global. + +/// The tint's direction around the hue circle, as an offset from the wheel hue (radians): a Fourier series of the +/// wheel hue, `c0 + c1 cos h + c2 sin h + c3 cos 2h + ...`. +pub const TINT_ANGLE: [f64; 9] = [4.537397e-01, 4.685374e-02, 3.516632e-02, -2.941264e-01, -6.525125e-02, -2.285195e-02, -5.390789e-03, 2.384883e-02, -3.397357e-02]; +/// The tint's log size around the hue circle, the same kind of series. +pub const TINT_SIZE: [f64; 9] = [9.016546e+00, -2.308289e-02, -1.193683e-02, 5.711376e-02, -2.991360e-01, 2.256077e-02, -1.541201e-02, 4.477781e-02, 5.903262e-02]; +/// Each wheel's log size, added to [`TINT_SIZE`]. +pub const WHEEL_SIZE: [f64; 4] = [-1.122302e+01, -1.114375e+01, -1.127223e+01, -1.113500e+01]; +/// Each wheel's saturation curve `[g1, g2]`: size `s (1 + g1 (s - 1) + g2 (s - 1)²)` at saturation `s` (0 to 1). +pub const WHEEL_SAT: [[f64; 2]; 4] = [[-5.099721e-01, -3.733126e-01], [-5.285381e-03, -3.145074e-03], [-1.233650e-01, -9.725189e-02], [-1.128777e-02, -6.350617e-03]]; +/// Each wheel's share of the tint by lightness: two bumps of 15 constants, `[g, gb, gb2, gc, gc2, p, pb, ..., q, ...]`, +/// each value quadratic in Blending (`b` = Blending / 100 - 0.5) and Balance (`c` = Balance / 100). +pub const SHARE: [[f64; 30]; 4] = [ + [5.727402e-01, 1.796601e-01, 2.844851e-01, -2.035986e-01, -2.285662e-01, -4.321244e-01, -5.602665e-01, 1.568028e+00, -2.424290e-01, -3.241123e-01, 6.053978e-01, -1.695886e+00, 1.969183e+00, 2.848613e-01, 2.521213e-01, 4.019223e-01, -5.052266e-03, 1.105097e+00, -5.266974e-01, 4.437433e-01, 1.749971e+00, -8.663990e-01, -1.420143e-01, 1.269084e-01, -4.439682e-01, 2.451509e+00, -1.520918e+00, -1.678961e+00, 1.398612e+00, -2.388321e-01], + [5.147531e-01, -1.249462e-01, -8.910247e-01, 1.684162e-01, -2.229180e-01, 2.100216e+00, -2.969117e-01, 1.688835e-01, 2.983615e-02, -5.530777e-01, 1.753003e+00, -2.956195e-01, 6.032166e-01, 1.072575e+00, -1.061905e-01, 5.090626e-01, 1.089723e-01, 9.146510e-01, -1.904599e-01, -2.414139e-01, 1.523251e+00, -5.576709e-01, 2.254867e-01, -5.251367e-01, 4.181351e-01, 9.500922e-01, -5.285901e-01, 3.261999e-01, 4.481717e-01, 7.667991e-02], + [-3.429880e-01, 2.072252e-03, 5.462619e-01, -4.017026e-02, -1.844514e-01, 2.507969e+00, -2.002773e+00, -2.033001e+00, -3.134357e-01, -7.954968e-01, 1.761763e+00, -2.033995e+00, -1.717121e+00, 1.173802e+00, -4.993600e-01, 1.111279e+00, 7.601260e-01, 8.073856e-01, 8.132208e-01, 3.199555e-01, 1.597379e+00, -8.727681e-01, 4.703415e-01, -5.751525e-01, -3.463468e-01, 1.260884e-01, -1.566368e-01, 4.284988e-01, 1.729485e-01, -1.623375e-01], + [1.000379e+00, -5.600347e-10, -1.412064e-10, -1.279783e+02, 7.097896e+01, 3.170903e-01, -4.148178e-09, -2.497543e-08, -2.456334e+01, -6.616531e+01, -1.259770e-01, -3.764265e-09, -8.380342e-09, -2.805683e+01, 6.243955e+00, 1.928859e-01, 2.365470e-10, 2.691471e-08, 3.856527e+00, -4.947252e+00, 7.187187e-01, 3.656593e-08, 1.100689e-06, -4.644110e+01, 1.973927e+01, 3.282210e+00, 3.513006e-08, 9.391124e-07, -9.284069e+01, -9.615467e+01], +]; +/// Each wheel's Luminance, negative then positive: two bumps of `[g1, g2, p0, p1, q0, q1]` each. +pub const LUM: [[f64; 24]; 4] = [ + [1.317930e-01, -9.660312e-02, 2.384303e-01, -7.957007e-01, 1.751565e+00, -1.253591e+00, -7.438407e-02, 1.856952e-01, 5.387669e+00, -4.716013e+00, 5.282639e+00, -3.222175e+00, 2.402675e-01, -1.409104e-01, 5.609386e-01, 1.938077e-01, 3.763936e+00, 1.097849e-01, 1.391984e-01, -1.854798e-02, -1.881605e-01, -3.710358e-01, 1.455610e+00, -1.538185e-01], + [3.394504e-02, -6.074374e-03, 2.140452e+00, 1.407142e-01, 1.823146e+00, 1.595518e-01, 4.265653e-02, 8.080533e-03, 1.650195e+00, 4.501870e-02, 1.039394e+00, 3.850345e-03, 4.204713e-02, -6.589058e-03, 1.645483e+00, -1.255438e-01, 1.031704e+00, -5.808203e-02, 3.448076e-02, 7.553287e-03, 2.150151e+00, -3.481531e-02, 1.827579e+00, -3.995998e-02], + [3.711674e-02, -1.485479e-02, 2.734528e+00, 8.404184e-02, 8.434023e-01, 1.167529e-01, 9.407997e-02, -2.112981e-03, 1.245802e+00, -3.251068e-02, -5.239417e+00, -4.203818e-01, 8.289980e-03, 6.834684e-04, 2.423068e+00, 8.895512e-04, 2.537429e+00, -2.344666e-02, 7.604731e-02, 7.278265e-03, 2.015782e+00, 7.895969e-02, 2.639166e-01, 6.995097e-02], + [1.759469e-02, -4.413933e-04, 1.056872e+00, -3.032456e-01, 3.439023e+00, -4.108334e-01, 7.496469e-02, 2.163202e-03, 3.727577e-01, 4.360411e-02, -1.068520e-01, -1.071032e-01, 1.765972e-02, 1.011221e-03, 7.901337e-01, 1.540931e-01, 3.231144e+00, 2.850728e-01, 7.502087e-02, 1.785074e-03, 3.835838e-01, -4.661289e-02, -1.037254e-01, 9.842938e-02], +]; +/// Each wheel's damping `[d0, d1, d2, e]`: `1 + (C / 0.12)^exp(e) (d0 + d1 cos a + d2 cos 2a)`. +pub const DAMPING: [[f64; 4]; 4] = [[-8.600308e-02, -2.343227e-01, -2.969460e-02, 2.451045e-02], [-6.245100e-02, -1.852009e-02, 1.932367e-02, -1.237717e+00], [-9.249844e-02, -4.322517e-02, 2.915900e-02, 2.210430e-01], [-7.574510e-02, -4.579070e-02, -6.333758e-03, 8.455495e-02]]; diff --git a/crates/pipeline/src/hs_range.rs b/crates/pipeline/src/hs_range.rs new file mode 100644 index 00000000000..78912298133 --- /dev/null +++ b/crates/pipeline/src/hs_range.rs @@ -0,0 +1,128 @@ +//! Highlights relative to the photo's own tonal range (process V18, `docs/hs-range.md`). +//! +//! Up to V17 Highlights moves the base layer's log luminance by a fixed weight of its absolute level. From V18 it acts +//! relative to the frame: on a photo with a wide tonal range it reaches further down and works harder. It takes the +//! frame's range from the base layer's percentiles ([`FrameRange`]). Shadows keeps V17's rule (`docs/hs-range.md`). + +use lightcraft_develop::Process; + +/// The base layer's tonal range in log₂ luminance (exposure included): its 2nd and 99th percentile. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameRange { + pub lo: f32, + pub hi: f32, +} + +/// Long edge (px) of the whole-frame render the range is measured on, for every output size. +pub const PROXY_EDGE: usize = 384; +/// Percentiles of the base layer that span the frame's range. +const P_LO: f32 = 0.02; +const P_HI: f32 = 0.99; +/// Highlights: strength `H_AMP · (span / H_SPAN)^H_POW` (clamped to `H_AMP_RANGE`), reaching down to +/// `−1 − H_REACH · (span − H_SPAN)` stops. +pub const H_AMP: f32 = 0.7; +pub const H_SPAN: f32 = 5.0; +pub const H_POW: f32 = 2.4; +pub const H_REACH: f32 = 0.8; +pub const H_AMP_RANGE: (f32, f32) = (0.2, 8.0); + +/// Whether `s` uses the frame's range: process V18 with Highlights, globally or in a visible mask. +pub fn wanted(s: &lightcraft_develop::DevelopSettings) -> bool { + let v18 = s.process.process() >= Process::V18; + v18 && (s.light.highlights != 0.0 || s.masks.iter().any(|m| m.visible && !m.components.is_empty() && m.adjust.highlights != 0.0)) +} + +impl FrameRange { + /// The range after exposure `ev` (stops). + pub fn shifted(self, ev: f32) -> FrameRange { + FrameRange { lo: self.lo + ev, hi: self.hi + ev } + } + + /// The range of base-layer values `base` (log₂ luminance before exposure `ev`), from every value (a proxy of + /// [`PROXY_EDGE`] px holds about 100 000); `None` without a finite value. + pub fn of(base: &[f32], ev: f32) -> Option { + let mut sample: Vec = base.iter().copied().filter(|v| v.is_finite()).collect(); + if sample.is_empty() { + return None; + } + // the two percentiles by selection: no sort of the whole proxy on every render + let last = sample.len() - 1; + let mut at = |q: f32| { + let i = ((q * last as f32) as usize).min(last); + *sample.select_nth_unstable_by(i, f32::total_cmp).1 + ev + }; + let lo = at(P_LO); + Some(FrameRange { lo, hi: at(P_HI) }) + } + + /// The change in log₂ luminance that Highlights (−1..1) makes at base-layer value `base`. + pub fn highlights(&self, highlights: f32, base: f32) -> f32 { + if highlights == 0.0 { + return 0.0; + } + let span = (self.hi - self.lo).max(0.1); + let amp = (H_AMP * (span / H_SPAN).powf(H_POW)).clamp(H_AMP_RANGE.0, H_AMP_RANGE.1); + let low = -1.0 - H_REACH * (span - H_SPAN).max(0.0); + highlights * amp * smooth(low, 2.8, base) + } +} + +/// Hermite smooth step from `e0` to `e1`. +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +#[cfg(test)] +mod tests { + use super::*; + use lightcraft_develop::DevelopSettings; + + /// Settings on process `p` with Highlights at `h` (−100..100). + fn on(p: Process, h: f64) -> DevelopSettings { + let mut s = DevelopSettings { process: p.version(), ..Default::default() }; + s.light.highlights = h; + s + } + + #[test] + fn only_v9_with_highlights_uses_the_range() { + assert!(wanted(&on(Process::V18, -40.0))); + assert!(!wanted(&on(Process::V18, 0.0))); + assert!(!wanted(&on(Process::V17, -40.0))); + assert!(!wanted(&on(Process::V7, -40.0))); + } + + #[test] + fn the_range_is_the_2nd_to_99th_percentile_and_exposure_shifts_it() { + let base: Vec = (0..7000).map(|i| (i % 1000) as f32 / 100.0 - 5.0).collect(); + let r = FrameRange::of(&base, 0.0).unwrap(); + assert!((r.lo - -4.8).abs() < 0.05 && (r.hi - 4.9).abs() < 0.05, "{r:?}"); + assert_eq!(FrameRange::of(&base, 1.0).unwrap(), r.shifted(1.0)); + assert!(FrameRange::of(&[f32::NAN], 0.0).is_none()); + } + + #[test] + fn a_thin_bright_stripe_does_not_flip_the_range_as_it_moves() { + // a 350 px wide frame with a 3 px bright stripe (under 1 % of it), one column apart + let frame = |x0: usize| -> Vec { + (0..350 * 200).map(|i| if (x0..x0 + 3).contains(&(i % 350)) { 3.0 } else { (i % 350) as f32 / 350.0 * 4.0 - 4.0 }).collect() + }; + let (a, b) = (FrameRange::of(&frame(140), 0.0).unwrap(), FrameRange::of(&frame(141), 0.0).unwrap()); + assert!((a.hi - b.hi).abs() < 1e-3 && (a.lo - b.lo).abs() < 1e-3, "{a:?} {b:?}"); + } + + #[test] + fn a_wider_range_makes_highlights_stronger_and_reach_further_down() { + let narrow = FrameRange { lo: -3.0, hi: 2.0 }; + let wide = FrameRange { lo: -6.0, hi: 2.0 }; + assert_eq!(narrow.highlights(0.0, 1.0), 0.0); + // in the highlights + assert!(wide.highlights(-1.0, 2.0) < narrow.highlights(-1.0, 2.0) && narrow.highlights(-1.0, 2.0) < 0.0); + // below the narrow frame's reach (−1 stop), the wide frame's still acts + assert_eq!(narrow.highlights(-1.0, -1.5), 0.0); + assert!(wide.highlights(-1.0, -1.5) < 0.0); + // a 5-stop frame at full Highlights is about V17's strength at the top (0.7 against 1.7: a gentler start) + assert!((narrow.highlights(-1.0, 2.8) - -0.7).abs() < 1e-4); + } +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 82c8b1dbcce..8574e141b1e 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -12,6 +12,8 @@ //! 3. tone map — contrast / whites / blacks filmic curve on luminance, highlight desaturation //! 4. colour — vibrance, saturation, colour mixer, colour grading, B&W (OkLCh) //! 5. display — gamut map to the output space (sRGB unless [`RenderRequest::space`] says otherwise), encode, tone curves (parametric + point), vignette, grain +//! (from process V18 the colour mixer, then the tone curves and Whites, run between 3 and 4 instead: +//! [`mixer_stage`], [`curve_stage`]) //! //! Spatial parameters are specified relative to the image's long edge, so a 400 px preview and a //! 60 MP export look alike. @@ -31,9 +33,19 @@ pub mod crystal; pub mod cull; pub mod curve; pub mod curve_input; +pub mod curve_stage; +#[rustfmt::skip] +mod curve_stage_model; +pub mod default_tone; +#[rustfmt::skip] +mod default_tone_model; pub mod dust; pub mod finish; pub mod geometry; +pub mod grading_stage; +#[rustfmt::skip] +mod grading_stage_model; +pub mod hs_range; pub mod lens_blur; pub mod light_v3; // generated (`light_v3_params.rs`), kept in its own compact layout @@ -44,6 +56,9 @@ pub mod local_tone; pub mod lut; pub mod mask_space; pub mod masks; +pub mod mixer_stage; +#[rustfmt::skip] +mod mixer_stage_model; pub mod nrc_joint; pub mod optics; pub mod output; @@ -58,6 +73,7 @@ pub mod upright; pub mod visualize; pub use curve::{PARAM_AMOUNTS, PARAM_LUT, ParametricCurve}; +pub use curve_stage::ParametricGraph; pub use output::{DeepImage, DeepSamples, DisplaySpace, OutputDepth, OutputSpace, OutputTrc, Proof, ProofLut, proof_profile, register_proof_profile}; pub use visualize::{MaskView, Overlay}; @@ -101,6 +117,11 @@ pub struct SourceInfo { /// the developed pixels (Bradford, linear Rec.2020). pub camera_color: Option>, pub camera_tone: Option, + /// The raw is rendered through a camera profile without a tone curve of its own (a DCP without + /// `ProfileToneCurve`, such as Adobe Standard): from process V18 its base tone is the fitted default curve, + /// with the scene shifted by this many stops, the camera's measured exposure offset + /// ([`default_tone`]; 0 for a camera not measured). `None`: the profile has its own curve, or no profile. + pub default_tone: Option, /// Segmentation mattes stored in the file (DNG semantic masks): AI masks use them. pub mattes: Option>, /// The raw's own local tone mapping (DNG `ProfileGainTableMap`), rendered only when the @@ -127,6 +148,7 @@ impl Default for SourceInfo { legacy_relative_wb: false, camera_color: None, camera_tone: None, + default_tone: None, mattes: None, local_tone: None, proraw: None, @@ -310,6 +332,8 @@ pub(crate) struct Prepared { pub chroma_blur: Option>, /// Airlight of `dark` (before exposure). pub air: f32, + /// The whole frame's tonal range for process V18's Highlights (before exposure; [`Plan::hs_range`]). + pub hs_range: Option, pub masks: Vec, /// Output pixels per unit of the source long edge. pub px_per_long: f64, @@ -488,6 +512,9 @@ pub struct Plan<'a> { pub eyes: Vec, /// The whole frame's dehaze airlight, for a windowed render (which can't see the whole frame). pub fixed_air: Option, + /// Process V18 with Highlights: the whole frame's tonal range ([`hs_range`]), from a small render of it so that + /// every render of the photo (a window, a preview, an export) shares it. + pub hs_range: Option, /// A windowed render works on a larger window when spots reach into it (see /// [`spots::window_for_reads`]); this is the requested window inside the rendered one, which /// the result is cut to. @@ -542,6 +569,12 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R let mut fixed_air = None; let mut frame_context = None; let mut keep = None; + // a proxy of one fixed size whatever the output's, so a thumbnail, a preview, a window and an export share the range + let hs_range = hs_range::wanted(s).then(|| { + let (pw, ph) = RenderRequest::fit(hs_range::PROXY_EDGE, hs_range::PROXY_EDGE).size(&frame); + local::frame_range(src, info, s, &frame, pw.max(1), ph.max(1)) + }); + let hs_range = hs_range.flatten(); let full = (frame.clone(), full_w, full_h); let (frame, w, h) = match req.window { Some(win) => { @@ -626,6 +659,7 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R noise_key, eyes, fixed_air, + hs_range, keep, mattes: info.mattes.clone(), lens_subject, @@ -666,6 +700,7 @@ pub fn colour_noise(src: &Rgb32f, info: &SourceInfo, p: &Plan<'_>) -> Option bool { - crate::proraw::active(s, info).is_none() - && craft_develop::light_v3::applies(&crate::bridge::to_craft_settings(s), info.raw, info.camera_tone.is_some()) + // a raw on the fitted default curve (process V18) has a camera curve too, even when no tone was fitted to its JPEG + let camera_curve = info.camera_tone.is_some() || crate::default_tone::for_source(s, info).is_some(); + crate::proraw::active(s, info).is_none() && craft_develop::light_v3::applies(&crate::bridge::to_craft_settings(s), info.raw, camera_curve) } impl LightOps { diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index c8b7c736064..18b87bb51c1 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -305,7 +305,7 @@ pub(crate) fn prepare(img: Arc, plan: &Plan<'_>, q: Quality, planes: &mu }; let ev = s.light.exposure as f32; let masks = timed("masks", || masks::evaluate(&s.masks, frame, img.width, img.height, &img, &log_l, ev, mattes)); - Prepared { img, log_l, base, clarity_blur, texture_blur, sharpen_blur, dark, chroma_blur, air, masks, px_per_long } + Prepared { img, log_l, base, clarity_blur, texture_blur, sharpen_blur, dark, chroma_blur, air, hs_range: None, masks, px_per_long } } /// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide). @@ -316,6 +316,26 @@ pub(crate) fn frame_airlight(src: &Rgb32f, info: &SourceInfo, s: &DevelopSetting airlight(&gaussian(&img.map(dark_of), sigma)) } +/// The tonal range of the whole output frame for process V18's Highlights ([`crate::hs_range`]): the base layer's +/// percentiles on a small render of it (`proxy_w` px wide), so that a window, a preview and an export of one photo +/// share it. Before exposure, like [`Prepared::base`](crate::Prepared), and after the same stages before it that +/// change tone: the camera's local tone mapping when it is on, then the white balance (as `lin_cpu`). +pub(crate) fn frame_range( + src: &Rgb32f, + info: &SourceInfo, + s: &DevelopSettings, + frame: &Frame, + proxy_w: usize, + proxy_h: usize, +) -> Option { + let mut img = Rgb32f::clone(&frame_proxy(src, frame, proxy_w, proxy_h)); + crate::local_tone::apply_in(&mut img, info, s, frame); + white_balance(&mut img, info, s); + let ppl = frame.px_per_long(proxy_w); + let base = tone_base(&img.map(log_lum), (0.015 * ppl as f32).max(1.0), tone_base_detail(s, ppl), base_keeps_gaps(s)); + crate::hs_range::FrameRange::of(&base.data, 0.0) +} + /// The whole output frame's neighbourhood for Lightroom's Highlights / Shadows on Apple ProRAW /// (log luminance blurred by [`crate::proraw::LR_CONTEXT_SIGMA`] of the long edge, as the base plane /// of a whole render), estimated on a small render of it (`proxy_w` × `proxy_h`): its σ spans far @@ -381,3 +401,49 @@ fn frame_proxy(src: &Rgb32f, frame: &Frame, w: usize, h: usize) -> Arc { pub fn airlight(dark: &Plane) -> f32 { craft_develop::local::airlight(&crate::bridge::to_craft_plane(dark)) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Highlights' range is measured on the tones it adjusts: with the camera's local tone mapping on, the range proxy + /// gets the same gain as the render before its base (review on #4100). + #[test] + fn the_range_is_measured_after_the_local_tone_map() { + use lightcraft_develop::{DevelopSettings, Process}; + use lightcraft_raw::gaintable::{GainTableMap, SourcePlacement}; + let src = Rgb32f::from_fn(192, 128, |x, y| { + let t = 0.02 + 0.2 * ((x * 5 + y * 3) % 192) as f32 / 192.0; + [t, t, t] + }); + // a gain rising from 1 at the left of the frame to 4 at the right + let local_tone = crate::local_tone::LocalTone { + map: GainTableMap { + points_v: 1, + points_h: 2, + points_n: 1, + spacing_v: 1.0, + spacing_h: 1.0, + origin_v: 0.0, + origin_h: 0.0, + weights: [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0, 0.0], + gamma: 1.0, + gains: vec![1.0, 4.0], + }, + placement: SourcePlacement { rect: [0.0, 0.0, 1.0, 1.0], orientation: lightcraft_geom::Orientation::Normal }, + }; + let info = SourceInfo { raw: true, local_tone: Some(Arc::new(local_tone)), ..Default::default() }; + let mut s = DevelopSettings { process: Process::V18.version(), ..Default::default() }; + s.light.highlights = -60.0; + let range = |on: bool| { + let mut s = s.clone(); + s.profile.camera_local_tone = on; + let frame = crate::frame_for(&src, &info, &s, true); + frame_range(&src, &info, &s, &frame, 96, 64).expect("a range") + }; + let (off, on) = (range(false), range(true)); + // the brightened right lifts the top of the range by up to log2(4) = 2 stops, the dark end by less + assert!(on.hi - off.hi > 1.0, "{off:?} -> {on:?}"); + assert!(on.hi - off.hi > on.lo - off.lo, "{off:?} -> {on:?}"); + } +} diff --git a/crates/pipeline/src/mixer_stage.rs b/crates/pipeline/src/mixer_stage.rs new file mode 100644 index 00000000000..bc423b6d6ed --- /dev/null +++ b/crates/pipeline/src/mixer_stage.rs @@ -0,0 +1,307 @@ +//! Process V18's mixer stage ([`lightcraft_develop::Process::V18`]): the colour mixer. `docs/mixer-stage.md` records +//! how the model was measured and fitted. +//! +//! - Each slider's effect comes from a fitted model (`mixer_stage_model`, written by `tools/lr_mixer_charts.py fit`): +//! each band has a centre and a width on each side, shared by its Hue, Saturation and Luminance sliders; each kind +//! of slider has a gain that grows faster than linearly with the amount and a dependence on the colour's chroma and +//! lightness; each band scales them per slider and output ([`response`]). +//! - The bands differ from those of V17 and earlier: their centres sit elsewhere on the hue circle (Orange at OkLab hue 50, not 82), Blue +//! is wider and Red and Magenta narrower. +//! - All 24 sliders act on the same input colour: their hue and lightness changes add and their chroma changes +//! multiply. +//! - The mixer acts before the tone curves. +//! +//! The stage runs after the tone map and Process V4's calibrated Contrast and Blacks, before the curve stage +//! ([`crate::curve_stage`]). It replaces the mixer of V17 and earlier in [`crate::colorops::ColorOps`]. + +use lightcraft_color::perceptual::{lab_to_lch, lch_to_lab, oklab_from_2020, oklab_to_2020}; +use lightcraft_develop::{DevelopSettings, Process}; + +use crate::mixer_stage_model as m; + +/// Hue bins per table row (5° each, from OkLab hue 0). +pub const HUES: usize = 72; +/// Table rows per output: 3 lightness levels × 3 chroma levels, lightness major. +pub const ROWS: usize = 9; +/// Outputs per row: hue shift, chroma, lightness change. +const OUTPUTS: usize = 3; +/// Values of the combined table: [`ROWS`] × outputs × [`HUES`]. +pub const TABLE_LEN: usize = ROWS * OUTPUTS * HUES; +/// Sliders in the model: mixer bands (red … magenta) × (hue, saturation, luminance). +const SLIDERS: usize = 24; +/// Where the combined table samples the model: OkLab lightness levels. +const LIGHT: [f32; 3] = [0.55, 0.78, 0.92]; +/// The table's chroma levels per lightness level: bright colours reach less chroma, so their levels sit lower. +const CHROMA: [[f32; 3]; 3] = [[0.07, 0.13, 0.19], [0.045, 0.09, 0.14], [0.025, 0.05, 0.09]]; + +/// The stage's combined response table: per row (lightness level × 3 + chroma level), output and hue bin, the hue +/// shift (radians), the chroma factor and the lightness change of every slider together, sampled from the model. +#[derive(Clone, Debug)] +pub struct MixerStage { + /// OkLab chroma of the table's chroma levels, per lightness level ([`CHROMA`]). + pub chroma: [[f32; 3]; 3], + /// OkLab lightness of the table's lightness levels ([`LIGHT`]). + pub light: [f32; 3], + pub table: Box<[f32; TABLE_LEN]>, +} + +/// The fitted response of slider `slider` (band × 3 + kind) output `out` at amount `t` (−1 to 1) for OkLCh chroma `c`, +/// lightness `l` and hue `h` (degrees): a hue shift in degrees, a relative chroma change or a lightness change. +/// `amp · gain(t) · band(h) · level(dc, dl)` with the band's shape shared by its three sliders, and the gain and level +/// dependence shared by all bands' sliders of one kind (docs/mixer-stage.md). +fn response(slider: usize, out: usize, t: f64, c: f64, l: f64, h: f64) -> f64 { + let (band, kind) = (slider / 3, slider % 3); + let (Some([centre, left, right]), Some(k), Some(amp)) = + (m::BANDS.get(band), m::KINDS.get(kind).and_then(|k| k.get(out)), m::AMPS.get(band).and_then(|a| a.get(kind)).and_then(|a| a.get(out))) + else { + return 0.0; + }; + let [g1, g2, g3, g4, g5, g6, ac, al] = *k; + let (at, dc, dl) = (t.abs(), (c - m::REF_CHROMA.0) / m::REF_CHROMA.1, (l - m::REF_LIGHT.0) / m::REF_LIGHT.1); + let gain = if t < 0.0 { g1 * at + g2 * at * at + g3 * at * at * at } else { g4 * at + g5 * at * at + g6 * at * at * at }; + let d = (h - centre + 180.0).rem_euclid(360.0) - 180.0; + let z = d / (if d < 0.0 { *left } else { *right }).exp(); + amp * gain * (-0.5 * z * z).exp() * (ac * dc + al * dl).exp() +} + +/// The combined table of `(slider, amount)` pairs: hue and lightness changes add, chroma changes multiply. +fn combine(sliders: &[(usize, f32)]) -> Option> { + let active: Vec<(usize, f64)> = sliders + .iter() + .filter(|(i, v)| *v != 0.0 && v.is_finite() && *i < SLIDERS) + .map(|(i, v)| (*i, (f64::from(*v) / 100.0).clamp(-1.0, 1.0))) + .collect(); + if active.is_empty() { + return None; + } + let mut t = Box::new([0.0f32; TABLE_LEN]); + for row in 0..ROWS { + let (li, ci) = (row / 3, row % 3); + let l = f64::from(LIGHT.get(li).copied().unwrap_or(0.0)); + let c = f64::from(CHROMA.get(li).and_then(|r| r.get(ci)).copied().unwrap_or(0.0)); + for out in 0..OUTPUTS { + for bin in 0..HUES { + let h = bin as f64 * (360.0 / HUES as f64); + let mut acc = if out == 1 { 1.0 } else { 0.0 }; + for (slider, t) in &active { + let r = response(*slider, out, *t, c, l, h) as f32; + match out { + 0 => acc += r.to_radians(), + 1 => acc *= (1.0 + r).max(0.0), + _ => acc += r, + } + } + if let Some(slot) = t.get_mut((row * OUTPUTS + out) * HUES + bin) { + *slot = acc; + } + } + } + } + Some(t) +} + +/// Position of `x` between the three levels `keys`: (lower, upper, weight of the upper), clamped. +fn level(keys: &[f32; 3], x: f32) -> (usize, usize, f32) { + if x <= keys[0] { + (0, 0, 0.0) + } else if x <= keys[1] { + (0, 1, (x - keys[0]) / (keys[1] - keys[0])) + } else if x <= keys[2] { + (1, 2, (x - keys[1]) / (keys[2] - keys[1])) + } else { + (2, 2, 0.0) + } +} + +impl MixerStage { + /// The stage for `s`: `None` before V18, or when the mixer is neutral. + pub fn new(s: &DevelopSettings) -> Option { + if s.process.process() < Process::V18 { + return None; + } + let sliders: Vec<(usize, f32)> = s.mixer.bands().iter().flat_map(|b| [b.hue, b.sat, b.lum]).enumerate().map(|(i, v)| (i, v as f32)).collect(); + combine(&sliders).map(|table| MixerStage { chroma: CHROMA, light: LIGHT, table }) + } + + /// The (hue shift, chroma factor, lightness change) for OkLCh `l`, `c`, `h`: linear in hue, bilinear in the chroma + /// and lightness levels, clamped to the table's. Below the lowest chroma level the lightness change fades + /// out towards neutral. + pub fn look(&self, l: f32, c: f32, h: f32) -> [f32; 3] { + let hd = h.to_degrees().rem_euclid(360.0) / 5.0; + let i0 = (hd as usize) % HUES; + let i1 = (i0 + 1) % HUES; + let fh = hd - hd.floor(); + let (l0, l1, fl) = level(&self.light, l); + let at = |row: usize, out: usize, bin: usize| self.table.get((row * OUTPUTS + out) * HUES + bin).copied().unwrap_or(0.0); + // per lightness level: bilinear in its own chroma keys, the lightness change faded out below the lowest + let per_level = |m: usize| { + let keys = self.chroma.get(m).copied().unwrap_or([1.0; 3]); + let (c0, c1, fc) = level(&keys, c); + let mut r = [0.0f32; 3]; + for (out, v) in r.iter_mut().enumerate() { + let hue = |row: usize| at(row, out, i0) * (1.0 - fh) + at(row, out, i1) * fh; + *v = hue(m * 3 + c0) * (1.0 - fc) + hue(m * 3 + c1) * fc; + } + if c < keys[0] { + r[2] *= (c / keys[0]).max(0.0); + } + r + }; + let (a, b) = (per_level(l0), per_level(l1)); + std::array::from_fn(|k| a[k] * (1.0 - fl) + b[k] * fl) + } + + /// The colour mixer on linear Rec.2020 (through OkLCh). + pub fn apply(&self, d: [f32; 3]) -> [f32; 3] { + let [l, c, h] = lab_to_lch(oklab_from_2020(d)); + let [dh, k, dl] = self.look(l, c, h); + oklab_to_2020(lch_to_lab([(l + dl).max(0.0), c * k, h + dh])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use lightcraft_develop::Hsl; + + /// Default settings on process V18. + fn v18() -> DevelopSettings { + DevelopSettings { process: Process::V18.version(), ..Default::default() } + } + + /// OkLCh of a linear Rec.2020 colour (`h` in radians). + fn lch_of(d: [f32; 3]) -> [f32; 3] { + lab_to_lch(oklab_from_2020(d)) + } + + /// Linear Rec.2020 of OkLCh (`h` in degrees). + fn colour(l: f32, c: f32, h: f32) -> [f32; 3] { + oklab_to_2020(lch_to_lab([l, c, h.to_radians()])) + } + + /// Hue change from `a` to `b` in degrees, in -180..180. + fn hue_shift(a: [f32; 3], b: [f32; 3]) -> f32 { + let d = (lch_of(b)[2] - lch_of(a)[2]).to_degrees(); + (d + 180.0).rem_euclid(360.0) - 180.0 + } + + /// Every slider's fitted response stays finite and within plausible ranges over the colours the table samples, + /// and is 0 at amount 0. + #[test] + fn the_fitted_responses_stay_plausible() { + for slider in 0..SLIDERS { + for out in 0..OUTPUTS { + // Blue Luminance −100 darkens pale blues and raises their chroma severalfold + let limit = [180.0, 8.0, 0.5][out]; + for t in [-1.0, -0.6, -0.25, 0.3, 0.75, 1.0] { + for (li, row) in CHROMA.iter().enumerate() { + for c in row { + for bin in 0..HUES { + let r = response(slider, out, t, f64::from(*c), f64::from(LIGHT[li]), bin as f64 * 5.0); + assert!(r.is_finite() && r.abs() <= limit, "slider {slider} out {out} at {t}: {r}"); + } + } + } + } + assert_eq!(response(slider, out, 0.0, 0.1, 0.7, 50.0), 0.0); + } + } + } + + /// Each band acts around its own centre: a slider moves colours at its band's centre more than colours half the + /// hue circle away. + #[test] + fn each_band_acts_around_its_own_centre() { + for (band, [centre, ..]) in m::BANDS.iter().enumerate() { + let at = |h: f64| response(band * 3 + 1, 1, 1.0, 0.09, 0.75, h).abs(); + assert!(at(*centre) > 5.0 * at(centre + 180.0), "band {band}: {} vs {}", at(*centre), at(centre + 180.0)); + } + } + + #[test] + fn only_v8_with_a_mixer_gets_the_stage() { + assert!(MixerStage::new(&v18()).is_none()); + let mut s = v18(); + s.calibration.blue_hue = -20.0; + assert!(MixerStage::new(&s).is_none(), "Calibration keeps the earlier operator"); + s.mixer.orange.sat = 30.0; + assert!(MixerStage::new(&s).is_some()); + s.process = Process::V7.version(); + assert!(MixerStage::new(&s).is_none()); + } + + #[test] + fn a_band_moves_its_own_colours_and_leaves_the_others() { + let mut s = v18(); + s.mixer.orange = Hsl { hue: 0.0, sat: -60.0, lum: 0.0 }; + let st = MixerStage::new(&s).expect("stage"); + // the Orange band's centre sits near OkLab hue 51 + let orange = colour(0.7, 0.1, 55.0); + let out = st.apply(orange); + assert!(lch_of(out)[1] < lch_of(orange)[1] * 0.7, "{:?} -> {:?}", lch_of(orange), lch_of(out)); + let blue = colour(0.6, 0.1, 255.0); + let b = lch_of(st.apply(blue)); + assert!((b[1] / lch_of(blue)[1] - 1.0).abs() < 0.03 && (b[0] - lch_of(blue)[0]).abs() < 0.005, "{b:?}"); + } + + #[test] + fn hue_and_luminance_follow_the_measured_direction() { + let mut s = v18(); + s.mixer.blue.hue = -100.0; + let st = MixerStage::new(&s).expect("stage"); + let blue = colour(0.6, 0.1, 255.0); + // Blue Hue −100 turns blue towards aqua (lower OkLab hue) + assert!(hue_shift(blue, st.apply(blue)) < -10.0, "{}", hue_shift(blue, st.apply(blue))); + let mut s = v18(); + s.mixer.green.lum = -80.0; + let st = MixerStage::new(&s).expect("stage"); + let green = colour(0.7, 0.1, 140.0); + assert!(lch_of(st.apply(green))[0] < lch_of(green)[0] - 0.03); + } + + #[test] + fn amounts_interpolate_and_grow_with_the_slider() { + let shift = |v: f64| { + let mut s = v18(); + s.mixer.yellow.hue = v; + let st = MixerStage::new(&s).expect("stage"); + let c = colour(0.85, 0.1, 100.0); + hue_shift(c, st.apply(c)).abs() + }; + let (a, b, c, d) = (shift(10.0), shift(25.0), shift(60.0), shift(100.0)); + assert!(a < b && b < c && c < d, "{a} {b} {c} {d}"); + assert!(a < b * 0.5, "a small amount does little: {a} vs {b}"); + } + + #[test] + fn sliders_combine_on_the_same_input() { + let one = |f: &dyn Fn(&mut DevelopSettings)| { + let mut s = v18(); + f(&mut s); + MixerStage::new(&s).expect("stage") + }; + let a = one(&|s| s.mixer.orange.sat = 40.0); + let b = one(&|s| s.mixer.orange.lum = -30.0); + let both = one(&|s| { + s.mixer.orange.sat = 40.0; + s.mixer.orange.lum = -30.0; + }); + // on a table node (lightness and chroma level 1, hue bin 11), where no interpolation blurs the rule + let (l, c, h) = (a.light[1], a.chroma[1][1], 55f32.to_radians()); + let (ra, rb, r) = (a.look(l, c, h), b.look(l, c, h), both.look(l, c, h)); + assert!((r[1] - ra[1] * rb[1]).abs() < 1e-5, "chroma changes multiply: {ra:?} {rb:?} {r:?}"); + assert!((r[2] - ra[2] - rb[2]).abs() < 1e-5, "lightness changes add"); + } + + #[test] + fn near_neutral_colours_keep_their_lightness() { + let mut s = v18(); + s.mixer.red.lum = 100.0; + s.mixer.blue.sat = 60.0; + let st = MixerStage::new(&s).expect("stage"); + for g in [0.02f32, 0.18, 0.7] { + let out = st.apply([g; 3]); + assert!(out.iter().all(|v| (v - g).abs() < 5e-4 * g.max(0.1)), "{g}: {out:?}"); + } + } +} diff --git a/crates/pipeline/src/mixer_stage_model.rs b/crates/pipeline/src/mixer_stage_model.rs new file mode 100644 index 00000000000..2259bd359cf --- /dev/null +++ b/crates/pipeline/src/mixer_stage_model.rs @@ -0,0 +1,28 @@ +// Written by `tools/lr_mixer_charts.py fit`: LightCraft's model of the colour mixer, fitted to the tool's OkLCh +// charts (provenance in docs/mixer-stage.md). Constants of the model only. + +/// The model's reference chroma and lightness: `dc = (C - centre) / scale`, `dl` likewise. +pub const REF_CHROMA: (f64, f64) = (0.09, 0.05); +pub const REF_LIGHT: (f64, f64) = (0.75, 0.15); + +/// Per band (Red, Orange, Yellow, Green, Aqua, Blue, Purple, Magenta): centre (OkLab hue, degrees), and the log +/// width below and above it. +pub const BANDS: [[f64; 3]; 8] = [[1.056355e+01, 2.142675e+00, 2.882902e+00], [5.235518e+01, 2.955835e+00, 2.924987e+00], [9.557576e+01, 2.870749e+00, 2.863375e+00], [1.376844e+02, 2.921264e+00, 2.829833e+00], [1.765499e+02, 2.695884e+00, 3.410620e+00], [2.508539e+02, 3.546682e+00, 3.470813e+00], [3.203744e+02, 3.494201e+00, 2.515159e+00], [3.506300e+02, 2.465887e+00, 2.192506e+00]]; +/// Per kind of slider (Hue, Saturation, Luminance) and output (hue shift, chroma change, lightness change): +/// `[g1, g2, g3, g4, g5, g6, ac, al]`, the gain over the amount and the dependence on chroma and lightness. +pub const KINDS: [[[f64; 8]; 3]; 3] = [ + [[-4.323290e+01, 1.140123e+01, -1.971998e+00, 3.579899e+01, -3.396945e+00, 1.139293e-01, 3.039906e-03, -1.299506e-02], [1.632521e-01, 1.817798e-01, -1.448031e-01, -2.445462e-01, 1.451632e-01, 3.425786e-03, -4.306765e-02, 2.213804e-02], [1.531619e-02, 1.438906e-02, -1.266002e-02, -1.390940e-02, 1.278640e-02, -4.338112e-03, 3.129566e-01, 2.375574e-02]], + [[3.273785e+00, -1.244630e+00, 4.423037e-01, -1.170054e+00, -2.740789e-01, 3.109724e-01, 1.016000e-01, -4.698930e-02], [-9.942227e-01, 8.075213e-02, -1.624837e-02, 4.043782e-01, 8.378880e-02, 7.812639e-02, -4.461127e-02, 2.679039e-02], [3.407854e-02, -7.774084e-03, 1.181682e-03, -2.030212e-02, -4.497270e-03, -3.568729e-03, 3.405041e-01, 6.932380e-02]], + [[1.668229e+00, 2.247261e+00, -2.874728e+00, -1.670834e+00, 9.233549e-01, -1.132851e-01, 2.303680e-01, 2.692762e-01], [2.692747e-01, 8.645293e-01, -6.701797e-01, -4.049544e-01, 1.613264e-01, -3.954560e-02, 3.810795e-01, 7.054621e-01], [-1.357489e-01, -6.734327e-02, 1.574065e-04, 1.379849e-01, -4.921972e-02, 9.846145e-03, 2.549411e-01, 1.667821e-01]], +]; +/// Per band, kind and output: the amplitude. +pub const AMPS: [[[f64; 3]; 3]; 8] = [ + [[7.783745e-01, 1.463725e+00, -1.045525e+00], [-1.586499e+00, 9.551631e-01, 7.593528e-01], [1.374411e+00, 5.434142e-01, 1.060449e+00]], + [[1.204791e+00, 2.029242e+00, -3.439860e+00], [-3.753353e+00, 9.458131e-01, 1.418248e-01], [1.840221e+00, 4.050216e-01, 1.224534e+00]], + [[1.138206e+00, -7.413565e-01, -1.493105e+00], [-1.771401e+00, 9.581541e-01, -6.985713e-01], [4.703549e-01, 4.010265e-01, 1.161590e+00]], + [[1.035375e+00, -1.813417e+00, 1.526335e+00], [3.710304e-01, 1.051789e+00, -2.632189e-01], [-3.499853e-01, 6.077505e-01, 1.123950e+00]], + [[1.157134e+00, 1.099041e+00, 1.051931e+00], [2.990588e-01, 1.028351e+00, 3.761758e-01], [-7.947505e-01, 1.878065e+00, 8.466702e-01]], + [[2.147215e+00, 1.369851e+00, 3.388000e+00], [3.167160e+00, 1.241693e+00, 2.524865e+00], [-5.042469e+00, 2.143033e+00, 1.455712e+00]], + [[1.409940e+00, -1.366548e+00, -1.691332e+00], [-5.005204e-02, 1.027433e+00, 1.797208e+00], [-1.925561e-01, 1.178752e+00, 1.173833e+00]], + [[6.165394e-01, -9.364707e-02, -3.676874e-01], [-1.062197e-01, 1.043411e+00, 8.290845e-01], [5.187354e-02, 8.899672e-01, 1.035930e+00]], +]; diff --git a/crates/pipeline/src/proraw.rs b/crates/pipeline/src/proraw.rs index ae7c2e848e5..07e34015565 100644 --- a/crates/pipeline/src/proraw.rs +++ b/crates/pipeline/src/proraw.rs @@ -919,7 +919,9 @@ mod tests { let tone = std::sync::Arc::new(curve(PRORAW_TONE_KNOTS, |x| x.powf(0.6))); let info = SourceInfo { raw: true, proraw: Some(tone), ..Default::default() }; let mut s = DevelopSettings::default(); - assert_eq!(s.process.process(), Process::V17); + assert!(s.process.process() >= Process::V17); + assert!(active(&s, &info).is_some(), "the latest process activates ProRAW"); + s.process = Process::V17.version(); assert!(active(&s, &info).is_some(), "V17 activates ProRAW"); s.process = Process::V16.version(); assert!(active(&s, &info).is_none(), "V16 keeps the camera-curve path"); diff --git a/crates/pipeline/src/tests.rs b/crates/pipeline/src/tests.rs index ed85e83c193..6af4ddbace1 100644 --- a/crates/pipeline/src/tests.rs +++ b/crates/pipeline/src/tests.rs @@ -1,4 +1,4 @@ -use lightcraft_develop::{DevelopSettings, controls}; +use lightcraft_develop::{DevelopSettings, Process, controls}; use lightcraft_raster::Rgb32f; use crate::{RenderRequest, SourceInfo, render}; @@ -474,13 +474,23 @@ fn refine_saturation_tames_a_contrast_curve() { lightcraft_geom::Point::new(0.7, 0.85), lightcraft_geom::Point::new(1.0, 1.0), ]; - let full = render(&src, &info, &s, &req).image.data[0]; + let curved = s.clone(); s.curve.refine_saturation = 0.0; - let refined = render(&src, &info, &s, &req).image.data[0]; - assert!(sat(full) > sat(refined), "{flat:?} {full:?} {refined:?}"); - // the curve's tone change stays - let y = |p: [u8; 4]| 0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32; - assert!((y(full) - y(refined)).abs() < 2.0); + let y = |p: [u8; 4], lin: bool| { + let c = |v: u8| if lin { lightcraft_color::transfer::srgb_to_linear(v as f32 / 255.0) } else { v as f32 }; + 0.2126 * c(p[0]) + 0.7152 * c(p[1]) + 0.0722 * c(p[2]) + }; + for process in [Process::V7, Process::V18] { + let on = |s: &DevelopSettings| render(&src, &info, &DevelopSettings { process: process.version(), ..s.clone() }, &req).image.data[0]; + let (full, refined) = (on(&curved), on(&s)); + assert!(sat(full) > sat(refined), "{process:?}: {flat:?} {full:?} {refined:?}"); + // the curve's tone change stays: up to V17 the encoded luma, from V18 the luminance + if process < Process::V18 { + assert!((y(full, false) - y(refined, false)).abs() < 2.0, "{process:?}: {full:?} {refined:?}"); + } else { + assert!((y(full, true) / y(refined, true) - 1.0).abs() < 0.03, "{process:?}: {full:?} {refined:?}"); + } + } } #[test] diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs index 971cf155776..eace63da12d 100644 --- a/crates/pipeline/src/tests_grain.rs +++ b/crates/pipeline/src/tests_grain.rs @@ -35,7 +35,7 @@ fn processes_before_v7_keep_the_value_noise() { Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => { assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}") } - Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 => { + Process::V7 | Process::V8 | Process::V10 | Process::V13 | Process::V14 | Process::V15 | Process::V16 | Process::V17 | Process::V18 => { assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}") } } diff --git a/crates/pipeline/src/tests_proraw.rs b/crates/pipeline/src/tests_proraw.rs index 31a57ad7c45..410d4fd543e 100644 --- a/crates/pipeline/src/tests_proraw.rs +++ b/crates/pipeline/src/tests_proraw.rs @@ -75,6 +75,18 @@ fn v17_renders_everything_else_as_v16() { } } +/// V18's curve stage leaves Whites to the ProRAW chain, which applies it itself: Whites alone renders a ProRAW +/// photo as on V17, where a second Whites would brighten it again. +#[test] +fn v18_leaves_proraw_whites_to_the_chain() { + let info = proraw_info(); + let mut s = DevelopSettings::for_raw(5200.0, 4.0); + controls::set(&mut s, "light.whites", 40.0); + let at = |p: Process| deep(&info, &DevelopSettings { process: p.version(), ..s.clone() }); + assert!(at(Process::V18) == at(Process::V17), "Whites applies once"); + assert!(at(Process::V17) != deep(&info, &DevelopSettings { process: Process::V17.version(), ..DevelopSettings::for_raw(5200.0, 4.0) })); +} + #[test] fn v17_keeps_checked_white_balance_and_v9_fallback() { let info = SourceInfo { as_shot_temp: 5500.0, as_shot_tint: 0.0, proraw: None, ..proraw_info() }; diff --git a/crates/pipeline/src/tests_window.rs b/crates/pipeline/src/tests_window.rs index a8cb651bf1f..2d847d5b7f3 100644 --- a/crates/pipeline/src/tests_window.rs +++ b/crates/pipeline/src/tests_window.rs @@ -133,6 +133,28 @@ fn spatial_adjustments_agree_inside_the_halo() { } } +// Given process V18's Highlights (relative to the frame's tonal range), a window takes the range of the whole frame, +// not of its own pixels: a window over the bright or the dark part renders as the full render does there +#[test] +fn highlights_take_the_frames_range_not_the_windows() { + let mut s = DevelopSettings::default(); + assert_eq!(s.process.process(), lightcraft_develop::Process::V18); + controls::set(&mut s, "light.highlights", -100.0); + for (x, y) in [(0, 0), (W - 400, H - 300), (300, 180)] { + check("highlights", &s, PixelWindow { x, y, w: 400, h: 300 }, 6, 0.8); + } +} + +// Given process V18's Highlights, a thumbnail and a large render measure the same frame range +#[test] +fn highlights_range_is_the_same_for_small_and_large_renders() { + let mut s = DevelopSettings::default(); + controls::set(&mut s, "light.highlights", -60.0); + let range = |w: usize, h: usize| crate::plan(&scene(), &SourceInfo::default(), &s, &RenderRequest::fit(w, h)).hs_range.expect("range"); + let (small, large) = (range(160, 120), range(W, H)); + assert!((small.lo - large.lo).abs() < 1e-4 && (small.hi - large.hi).abs() < 1e-4, "{small:?} {large:?}"); +} + // Given a huge virtual frame (48000 px: an 800 % zoom), only the window is rendered #[test] fn a_window_of_a_huge_frame_is_cheap() { diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 370ede41c4d..075472b0690 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -8,7 +8,7 @@ use egui::{Align2, Color32, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2}; use lightcraft_catalog::PhotoId; use lightcraft_develop::{ControlSpec, DevelopSettings, Section, Track, WbMode, controls}; use lightcraft_geom::Point; -use lightcraft_pipeline::{PARAM_AMOUNTS, ParametricCurve}; +use lightcraft_pipeline::{PARAM_AMOUNTS, ParametricGraph}; use lightcraft_raster::Histogram; use serde_json::{Value, json}; diff --git a/crates/ui-egui/src/panels/edit/curve.rs b/crates/ui-egui/src/panels/edit/curve.rs index 9f27031701e..ee02baecbe8 100644 --- a/crates/ui-egui/src/panels/edit/curve.rs +++ b/crates/ui-egui/src/panels/edit/curve.rs @@ -1,6 +1,6 @@ use super::sliders::control; use super::{ - Align2, Color32, DevelopSettings, Icon, LightcraftApp, Mesh, PARAM_AMOUNTS, ParametricCurve, PhotoId, Point, Pos2, Rect, RichText, Sense, Stroke, + Align2, Color32, DevelopSettings, Icon, LightcraftApp, Mesh, PARAM_AMOUNTS, ParametricGraph, PhotoId, Point, Pos2, Rect, RichText, Sense, Stroke, Tokens, Vertex, controls, hex, json, paint, pos2, text_button, vec2, }; use super::{Histogram, Slot}; @@ -80,12 +80,11 @@ const PARAM_GRAB: f32 = 14.0; /// The whole gesture runs inside one `develop` interaction, so it is one undo step (Ctrl+Z takes the /// gesture back, not the last frame of it), and every write goes through `develop.set`, so the /// slider, the curve and what is drawn are the same state rather than three things kept in step. -fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui::Response, d: &DevelopSettings) { +fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui::Response, d: &DevelopSettings, model: &ParametricGraph) { if r.width() <= 1.0 || r.height() <= 1.0 { return; } let t = Tokens::get(ui.ctx()); - let model = ParametricCurve::new(&d.curve); let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height()); let from_screen_x = |q: Pos2| ((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64; // the graph x of a point, and how far it is from the drawn curve (in screen points) @@ -110,7 +109,7 @@ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui:: let x = from_screen_x(q); let _ = app.run("develop.beginInteraction", json!({"label": "Parametric Curve"})); let region = model.region_at(x); - let initial_amount = model.amounts.get(region).copied().unwrap_or(0.0); + let initial_amount = model.amount(region); let start_pos = to_screen(x, model.at(x)); dragged = Some((region, x, initial_amount, start_pos.y)); ui.data_mut(|dd| dd.insert_temp(cursor_id, start_pos)); @@ -127,9 +126,7 @@ fn param_drag(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect, resp: &egui:: ui.data_mut(|d| d.insert_temp(cursor_id, cursor)); let delta_y = start_y - cursor.y; let delta_level = (delta_y / r.height()) as f64; - let per_unit = model.level_per_unit(region, x); - let new_amount = - if per_unit.abs() > f64::EPSILON { (initial_amount + delta_level / per_unit).clamp(-100.0, 100.0).round() } else { initial_amount }; + let new_amount = model.dragged_amount(region, x, initial_amount, delta_level); if let Some(&id) = PARAM_AMOUNTS.get(region) { set = Some((id, new_amount)); } @@ -306,15 +303,15 @@ pub(super) fn curve_editor(app: &mut LightcraftApp, ui: &mut egui::Ui, id: Photo let to_screen = |x: f64, y: f64| pos2(r.left() + x as f32 * r.width(), r.bottom() - y as f32 * r.height()); let from_screen = |q: Pos2| (((q.x - r.left()) / r.width()).clamp(0.0, 1.0) as f64, ((r.bottom() - q.y) / r.height()).clamp(0.0, 1.0) as f64); if ch == "parametric" { - // The Effective curve: the model the renderer builds from the four region sliders, sampled - // here and rebuilt every frame. The graph holds no state of its own, so a slider moved by - // hand, a Reset or an Undo redraws it from the settings in the same frame it changes. - let c = &d.curve; - let model = ParametricCurve::new(c); + // The Effective curve: the one the renderer builds from the four region sliders for this + // process (the fitted regions under V18 at the default splits), sampled here and rebuilt every + // frame. The graph holds no state of its own, so a slider moved by hand, a Reset or an Undo + // redraws it from the settings in the same frame it changes. + let model = ParametricGraph::new(d); let pts: Vec = (0..=CURVE_SAMPLES).map(|i| to_screen(i as f64 / CURVE_SAMPLES as f64, model.at(i as f64 / CURVE_SAMPLES as f64))).collect(); p.add(egui::Shape::line(pts, Stroke::new(2.0, Color32::from_gray(220)))); - param_drag(app, ui, r, &resp, d); + param_drag(app, ui, r, &resp, d, &model); curve_footer(app, ui, d); for &c in PARAM_AMOUNTS.iter().rev() { control(app, ui, d, c, true); diff --git a/crates/ui-egui/src/tests/curve.rs b/crates/ui-egui/src/tests/curve.rs index e64d2cbb561..a9819e99819 100644 --- a/crates/ui-egui/src/tests/curve.rs +++ b/crates/ui-egui/src/tests/curve.rs @@ -6,7 +6,7 @@ use serde_json::json; use crate::headless::Headless; use crate::{LightcraftApp, Services}; -use lightcraft_pipeline::ParametricCurve; +use lightcraft_pipeline::{ParametricCurve, ParametricGraph}; const T: Duration = Duration::from_secs(20); @@ -40,6 +40,11 @@ fn exec(h: &mut Headless, command: &str, params: serde_json::Value) -> serde_jso r["result"].clone() } +/// The parametric graph the panel draws for the selected photo's settings (its process decides fitted or analytic). +fn graph(h: &Headless) -> ParametricGraph { + ParametricGraph::new(&develop(h)) +} + fn develop(h: &Headless) -> lightcraft_develop::DevelopSettings { let id = h.app.session.active().expect("active photo"); (*h.app.session.develop_of(id).unwrap_or_default()).clone() @@ -276,9 +281,10 @@ fn the_parametric_graph_paints_the_model_the_renderer_uses() { h.step(); let settings = develop(&h).curve; assert_eq!(settings, c, "the sliders hold the folded shape"); - let graph = curve_graph_rect(&mut h); - let painted = painted_param_curve(&h, graph); - let model = ParametricCurve::new(&c); + let model = graph(&h); + let rect = curve_graph_rect(&mut h); + let painted = painted_param_curve(&h, rect); + assert!(model.is_fitted(), "the demo photo is on the latest process, which renders the fitted regions"); let mut checked = 0; for i in 0..=24 { let x = i as f64 / 24.0; @@ -401,8 +407,8 @@ fn one_graph_drag_that_moves_several_regions_is_one_undo_step() { } /// The screen point where a drag should grab the curve: graph fraction `fx`, on the line itself. -fn on_curve(r: [f32; 4], c: &lightcraft_develop::ToneCurve, fx: f32) -> [f32; 2] { - let y = ParametricCurve::new(c).at(fx as f64); +fn on_curve(r: [f32; 4], g: &ParametricGraph, fx: f32) -> [f32; 2] { + let y = g.at(fx as f64); [r[0] + fx * r[2], r[1] + (1.0 - y as f32) * r[3]] } @@ -415,9 +421,10 @@ fn dragging_the_curve_moves_the_region_slider() { h.step(); let r = curve_graph_rect(&mut h); let c = develop(&h).curve; + let g = graph(&h); let undo_before = h.app.session.undo.len(); // grab the line inside the Lights window (x = 0.625) and pull it down - let [x, y] = on_curve(r, &c, 0.625); + let [x, y] = on_curve(r, &g, 0.625); let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y + 0.08 * r[3], "steps": 8}), T); assert_eq!(d["ok"], true, "{d}"); h.step(); @@ -430,8 +437,13 @@ fn dragging_the_curve_moves_the_region_slider() { // the graph really is redrawn below where the line was let graph = curve_graph_rect(&mut h); let painted = painted_param_curve(&h, graph)(0.625); - let before_level = ParametricCurve::new(&c).at(0.625); + let before_level = g.at(0.625); assert!(painted < before_level - 0.02, "the painted line followed the drag down: {painted} vs before {before_level}"); + // and lands where the hand is: at most 0.08 lower, and at least that less the drag threshold (6 points), which + // swallows the hand's first steps (how many depends on how the framework starts a drag) + let moved = before_level - painted; + let threshold = 6.0 / r[3] as f64; + assert!(moved < 0.08 + 0.006 && moved > 0.08 - threshold - 0.006, "the line moved {moved} for a hand motion of 0.08"); // and Undo takes the whole gesture back to where it started exec(&mut h, "edit.undo", json!({})); assert_eq!(develop(&h).curve, c, "undo restores the value the drag started from"); @@ -449,7 +461,7 @@ fn a_horizontal_drag_with_zero_vertical_motion_changes_nothing() { assert_eq!(before.darks, 60.0); assert_eq!(before.lights, 0.0); let r = curve_graph_rect(&mut h); - let [x, y] = on_curve(r, &before, 0.51); + let [x, y] = on_curve(r, &graph(&h), 0.51); // Drag purely horizontally from x=0.51: dx = 20 px, dy = 0 let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x + 20.0, "toY": y, "steps": 6}), T); assert_eq!(d["ok"], true, "{d}"); @@ -465,16 +477,16 @@ fn a_horizontal_drag_with_zero_vertical_motion_changes_nothing() { fn dragging_the_curve_up_raises_the_region_slider() { let mut h = curve_open("parametric"); let r = curve_graph_rect(&mut h); - let c = develop(&h).curve; + let g = graph(&h); // x = 0.375 is inside the Darks window - let [x, y] = on_curve(r, &c, 0.375); + let [x, y] = on_curve(r, &g, 0.375); let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y - 0.08 * r[3], "steps": 8}), T); assert_eq!(d["ok"], true, "{d}"); h.step(); let after = develop(&h).curve; assert!(after.darks > 0.0, "the Darks slider follows the line up: {}", after.darks); assert_eq!((after.shadows, after.lights, after.highlights), (0.0, 0.0, 0.0), "the other regions stay put: {after:?}"); - assert!(ParametricCurve::new(&after).at(0.375) > ParametricCurve::new(&c).at(0.375), "the curve is drawn bent up at the Darks region"); + assert!(graph(&h).at(0.375) > g.at(0.375), "the curve is drawn bent up at the Darks region"); } /// Which region a drag moves is decided by where on the line it is grabbed: the same drag gesture @@ -486,9 +498,9 @@ fn the_region_dragged_is_the_one_under_the_pointer() { { let mut h = curve_open("parametric"); let r = curve_graph_rect(&mut h); - let c = develop(&h).curve; - assert_eq!(ParametricCurve::new(&c).region_at(fx as f64), region, "x = {fx} belongs to {control}"); - let [x, y] = on_curve(r, &c, fx); + let g = graph(&h); + assert_eq!(g.region_at(fx as f64), region, "x = {fx} belongs to {control}"); + let [x, y] = on_curve(r, &g, fx); let d = h.request("ui.drag", json!({"x": x, "y": y, "toX": x, "toY": y - 0.06 * r[3], "steps": 6}), T); assert_eq!(d["ok"], true, "{d}"); h.step(); @@ -535,7 +547,7 @@ fn hovering_the_line_names_the_region_it_would_move() { exec(&mut h, "develop.set", json!({"control": "curve.lights", "value": 60})); h.step(); let r = curve_graph_rect(&mut h); - let [x, y] = on_curve(r, &develop(&h).curve, 0.625); + let [x, y] = on_curve(r, &graph(&h), 0.625); let q = h.request("ui.move", json!({"x": x, "y": y}), T); assert_eq!(q["ok"], true, "{q}"); h.step(); diff --git a/docs/curve-stage.md b/docs/curve-stage.md new file mode 100644 index 00000000000..8bc68e0f46f --- /dev/null +++ b/docs/curve-stage.md @@ -0,0 +1,118 @@ +# Whites and the tone curves, measured (process V18) + +> **Changes:** [revision history](#revision-history) + +Process V18 renders Whites, the parametric curve and the point curves the way Lightroom does, with LightCraft's own +model fitted to measurements of Camera Raw's output. V1 to V17 are unchanged (`docs/process-versions.md`). The code is +`crates/pipeline/src/curve_stage.rs`, the model's fitted constants `crates/pipeline/src/curve_stage_model.rs`, and the +GPU kernel's `curve_stage` in `crates/gpu/src/wgsl/finish.wgsl`. + +## What was wrong + +Up to V17 Whites is part of the tone map, which acts on luminance, and the curves act on each channel of the +display-encoded output. Measured against Camera Raw, this goes wrong in three ways: + +- **Whites reaches too little.** Lightroom's Whites moves the upper midtones too: at Whites −50 an sRGB-encoded 0.6 + drops by about 10/255. V17's Whites barely touches them. +- **The parametric regions are too narrow.** Lightroom's Highlights, Lights, Darks and Shadows regions are broad and + overlap, and they add: the sum of the single regions reproduces three at once within 1/255. +- **Per-channel curves shift hues.** A contrast curve applied to R, G and B separately pushes orange towards red and + saturates. Lightroom's master curve keeps the hue. It maps the largest and the smallest channel through the curve, + and the middle channel keeps its relative position between them in linear light. + +## What V18 does + +After the tone map, V4's calibrated Contrast and Blacks and V18's colour mixer ([mixer-stage.md](mixer-stage.md)), +before the colour stage: + +1. Convert linear Rec.2020 to linear ProPhoto RGB (D50, Bradford) and encode with the sRGB curve, as the V4 + operators do (`light_v3::prophoto_matrices`). +2. Build the base table: Whites, then the parametric curve, then the master point curve. Whites and each of the four + regions add a fitted response to the diagonal (below). The regions are fitted for Lightroom's default splits + (25, 50, 75). With other splits the parametric curve is the analytic model of the earlier processes. The table is + kept non-decreasing. +3. Apply the base table to the largest and smallest channel. The middle channel keeps its relative position between + them in linear light. +4. Apply the red, green and blue point curves to each channel. +5. Refine Saturation (below 100) moves saturation back towards the colour after Whites, and then rescales to the + curves' linear luminance, so the tone change stays. In Lightroom it belongs to the tone curve, and Whites comes + before it, so Whites keeps its saturation change whether a curve is set or not (V17 and earlier refine on encoded + output, where there is no Whites). +6. Values above SDR white (an HDR render) continue with slope 1. + +The tone map no longer applies Whites under V18 (`finish::base_tone`), and the V17 output-curve tables are not built +(`FinishParams::curves` is `None`). With Whites, the parametric curve and the point curves all neutral, the curve +stage does not run. + +## The model + +Each slider direction (negative and positive) of Whites and of each region has its own response, output minus input +on sRGB-encoded values: the sum of two smooth bumps. With `t` = |amount| / 100, + + response(x) = Σ (a1 t + a2 t² + a3 t³) · bump(x, e^(p0 + p1 t), e^(q0 + q1 t)) + bump(x, p, q) = (x / m)^p · ((1 − x) / (1 − m))^q, m = p / (p + q) + +A bump is 0 at black and white and 1 at its peak `m`. The gain grows faster than linearly with the amount, and the +bump's position and width move with the amount, as Lightroom's regions widen and move when pushed harder. That is 7 +constants per bump, 14 per slider direction and 140 in all. The fit keeps every response growing with the amount at +every input and never acting against the slider, so dragging the graph moves the slider steadily. + +## The Edit panel's graph + +The parametric graph draws the curve the photo renders, from `curve_stage::ParametricGraph`: the fitted regions +under V18 at the default splits, else the analytic model. Dragging the line moves the region under the pointer by +the amount that puts the drawn curve where the pointer is. The fitted regions are not linear in the amount, so the +amount is searched for, on the side of the starting value the drag moves to, on the curve as drawn (kept monotone, so +where opposite regions fold it back the line is held flat by the peak to its left). A level out of the region's reach +saturates at ±100. A region that cannot move the line by half an 8-bit level in that direction keeps its value. +Whites is not part of the graph, as in Lightroom. + +## How it was measured + +`tools/lr_tone_charts.py charts OUT_DIR` writes linear DNG charts: 48 grey steps from 0.002 to 1 and OkLCh colour +patches, with the settings in the DNG's XMP. It writes one neutral chart, Whites at each measured amount, and each +parametric region at each measured amount. The charts are original test data. Every chart was rendered through +Camera Raw to a 16-bit Adobe RGB (1998) TIFF. Only that output is measured, and nothing of Adobe's is copied or +shipped, and no measurement is committed. `tools/lr_tone_charts.py fit RENDER_DIR OUT_RS [CHART_DIR]` takes the charts' `curve__manifest.json` from CHART_DIR +(RENDER_DIR when the renders sit beside the charts), reads the grey steps of +each render as sRGB-encoded linear ProPhoto values, fits the model to them and writes only its constants, +`curve_stage_model.rs`. It needs numpy, scipy and tifffile (`tools/requirements-lr-tone-charts.txt`). Running the +tool again reproduces the committed charts byte for byte, and the constants with the pinned packages. + +How close the model is to the measured response, as the stage renders it (both clamped to 0..1), over 257 inputs and +every measured amount, in 8-bit levels of the sRGB-encoded output: + +| Setting | negative: RMS | max | positive: RMS | max | +|---|---|---|---|---| +| Whites | 0.15 | 0.88 | 0.27 | 1.62 | +| Shadows | 0.39 | 2.18 | 0.34 | 1.37 | +| Darks | 0.33 | 1.73 | 0.19 | 1.32 | +| Lights | 0.05 | 0.17 | 0.37 | 1.04 | +| Highlights | 0.15 | 0.64 | 0.52 | 2.29 | + +Every largest error but one (Darks +50, at black) is at ±75 or ±100. + +The grey steps leave out how colour is treated. To check that, the colour patches of the same renders were +predicted from the grey-step curves under the hue-preserving rule in step 3. The prediction is within 0.03 to 0.16 +(OkLab × 100) of Camera Raw's patches, against 0.3 to 3.4 for V17's per-channel curves. + +## Limits + +- The regions are fitted with Lightroom's default splits. Moved splits use the earlier analytic model. +- The point curves' shape between the points is LightCraft's spline, not measured. What is measured for them is how + they apply: hue preserving, then the red, green and blue curves per channel. +- Local (mask) Whites keeps the earlier processes' operator. +- Apple ProRAW keeps V17's Lightroom tone chain (`crate::proraw`), which applies Whites itself. On those photos the + stage applies only the curves. +- The measurements use Camera Raw's process version 2012 controls (`crs:ProcessVersion` 11.0). + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-10 | minor | Process V18: measured Whites and parametric curve, hue-preserving master curve | +| 2026-11-11 | minor | The Edit panel's parametric graph draws and drags the measured regions under V18 | +| 2026-12-02 | patch | Renumbered from V9 to V17, on top of V16: main retired 9 | +| 2026-11-24 | minor | Whites and the regions are a fitted model instead of measured tables | +| 2026-12-03 | patch | Renumbered from V17 to V18, on top of V17: main took 17 for Apple ProRAW (#4196) | +| 2026-12-03 | patch | Refine Saturation restores the colour after Whites, so Whites alone and Whites with a curve agree (review on #4099) | diff --git a/docs/default-tone.md b/docs/default-tone.md new file mode 100644 index 00000000000..dd78ea2ba68 --- /dev/null +++ b/docs/default-tone.md @@ -0,0 +1,108 @@ +# The default base curve for profiles without one (process V18) + +> **Changes:** [revision history](#revision-history) + +Process V18 gives a raw rendered through a camera profile without a tone curve of its own the base tone Lightroom +gives it, with LightCraft's own curve fitted to measurements of Camera Raw's output. V1 to V17 are unchanged +(`docs/process-versions.md`). The code is `crates/pipeline/src/default_tone.rs`, the curve's fitted knots +`crates/pipeline/src/default_tone_model.rs`, and the GPU kernel's `rgb_tone` in `crates/gpu/src/wgsl/finish.wgsl`. + +## What was wrong + +A DNG camera profile (`.dcp`) may carry a tone curve (`ProfileToneCurve`). Adobe Standard profiles do not: they leave +the base tone to the raw converter. Lightroom then applies its default base curve. Up to V17 LightCraft keeps the +photo's own tone instead: the file's DNG tone curve, or else the curve fitted to the camera JPEG +(`files::load`, `kept_tone`). Measured against Camera Raw: + +- **The base curve is a different one.** Lightroom's default curve lifts the midtones more and rolls off into white + later than a typical camera JPEG's. On 5 held-out Panasonic Lumix DC-S9 raws with the Adobe Standard profile, the + unedited V8 render is off by 5.03 in lightness (RMS, OkLab × 100), and brighter by 2.41 on average. +- **It is applied to luminance, not to the channels.** V17 scales all three channels by the curve's change in + luminance. Lightroom applies the curve to the largest and the smallest channel in linear ProPhoto RGB, and the + middle channel keeps its relative position between them. On the 327 colour patches of the neutral chart this rule + predicts Camera Raw's output within 0.26 (OkLab × 100). Scaling by luminance misses by 5.31, and the curve on each + channel by 0.86. + +## What V18 does + +For a raw whose profile has no tone curve (`SourceInfo::default_tone`, set by `files::load` when a camera profile +without `ProfileToneCurve` is chosen): + +1. The base tone map's camera curve is the fitted default curve (`default_tone::curve`): a monotone curve through 12 + fitted knots, evenly spaced in stops from the chart's darkest grey step (0.002) to its white, sampled into 32 + knots of the camera curve, the scene shifted by the camera's exposure offset. Past the last knot it rolls + off into white in stops, as V5 extends every camera curve (#1632). +2. The tone map applies hue preserving on linear ProPhoto channels (`default_tone::rgb_tone`), not by luminance. +3. Contrast and Blacks keep V4's calibrated operators, and Whites, the curves, the colour mixer and Colour Grading + follow as before ([curve-stage.md](curve-stage.md), [mixer-stage.md](mixer-stage.md), + [grading-stage.md](grading-stage.md)). + +A raw without a camera profile, a profile with a tone curve of its own, and a rendered file are unchanged. + +**The exposure offset.** The chart is a DNG with a baseline exposure of 0. For a raw of another format (RW2, ARW, NEF +and so on) Camera Raw uses an exposure offset of its own per camera, which the file does not carry and LightCraft +does not know. `default_tone::camera_ev` holds the offsets: + +| Camera | Offset (stops) | Measured on | +|---|---:|---| +| Panasonic Lumix DC-S9 (RW2) | −0.10 | 5 photos (training set; the 5 held-out photos land 0.00 lighter on average) | +| Panasonic Lumix DC-S5 (RW2) | −0.04 | 6 photos from 6 days; with the offset 0.10 darker than Lightroom on average (0.44 lighter without) | +| Panasonic Lumix DC-S5 II (DC-S5M2, RW2) | −0.03 | 6 photos from 6 days; 0.02 darker (0.32 lighter without) | +| Panasonic Lumix DC-S5 IIX (DC-S5M2X, RW2) | −0.05 | 6 photos from 6 days; 0.06 darker (0.56 lighter without) | + +Lightness differences are OkLab × 100, the mean over the central three quarters of each frame, unedited, against +Camera Raw's render through the same camera's Adobe Standard profile. Adding a camera takes about 5 photos: render +them unedited through Camera Raw and LightCraft, and pick the offset that leaves the mean lightness difference at 0 +(about 11.8 per stop). + +Other cameras get 0. Without the offset the S9 renders 1.1 lighter in lightness than Lightroom (OkLab × 100), so a +camera not measured can be off by about that much. + +## How it was measured + +`tools/lr_tone_charts.py base RENDER_DIR OUT_RS` reads Camera Raw's render of the neutral chart of +`tools/lr_tone_charts.py charts` (48 grey steps, geometric from 0.002 to 1, linear DNG, settings neutral), fits the +12 knots to its grey steps (chart value in, linear ProPhoto value out) with LightCraft's own monotone spline, and +writes only the knots, `default_tone_model.rs`. No measurement is committed. The fit ends the curve at exactly 1 at +the chart's white and minimises the error in 8-bit levels of the sRGB-encoded output: 0.29 RMS and 1.08 at most over +the 48 steps. The chart is original test data. It was rendered through Camera Raw to a 16-bit Adobe RGB (1998) TIFF, +and only that output is measured. Nothing of Adobe's is copied or shipped, and no profile's contents are read: the +only fact taken from a profile is whether it has a tone curve. + +The offset was fitted on 5 training photos of the DC-S9 and checked on 5 others held out from fitting. + +## Results + +Held-out Panasonic Lumix DC-S9 photos (RW2, Adobe Standard profile, 24 edits each plus Neutral, 1,500 px, aligned +against Camera Raw's renders), lightness RMS and mean a/b error (OkLab × 100), lower is better. "Before" is LightCraft +before the series (V7); "V18" is the whole series with every stage's fitted model, this curve included. + +| Edits | Tone: before → V18 | Colour: before → V18 | +|---|---|---| +| Unedited | 5.03 → 0.70 | 1.00 → 0.27 | +| Highlights | 6.68 → 2.16 | 0.89 → 0.27 | +| Shadows | 5.71 → 3.24 | 1.14 → 0.39 | +| Highlights and Shadows together | 8.66 → 4.03 | 1.01 → 0.43 | +| 19 presets (7 groups, equal weight) | 6.96 → 2.12 | 1.74 → 0.64 | + +With the measured grey steps instead of the fitted knots the series gives 0.69 and 0.27 unedited, and 2.418 and +0.556 over all groups against 2.424 and 0.557 with them. + +## Limits + +- Four cameras' offsets are measured (the Lumix S9, S5, S5 II and S5 IIX). Other cameras render with the chart's + curve as it is, which on these four would be 0.3 to 1.2 lighter than Lightroom. +- The curve is fitted for Camera Raw's process version 2012 (`crs:ProcessVersion` 11.0), one chart, grey steps up to + the DNG's white. Above white it rolls off as V5's camera curves do, not as measured. +- Smart previews are built without the imported camera profile, so a photo whose original is offline renders + without the profile, and so without this curve, until the original is back (as before). Building smart previews + with the selected profile would lift this; it is a change of its own. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-11 | minor | Process V18: Lightroom's default base curve for a raw whose camera profile has none | +| 2026-11-24 | minor | The base curve is 12 fitted knots instead of the measured grey steps | +| 2026-12-03 | patch | Renumbered from V9 to V17, on top of V16: main retired 9 | +| 2026-12-03 | patch | Renumbered from V17 to V18, on top of V17: main took 17 for Apple ProRAW (#4196) | diff --git a/docs/gaps.md b/docs/gaps.md index b859d9c18b3..060b4d31ec5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -17,7 +17,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app |---:|---|---|---|---:|---| | 1 B | **Camera colour is estimated, not measured** (LR-PROF-CAMERACOLOR). Raws start from a per-file fit to the camera JPEG, 10 bundled profiles, 52 spectral matrices (plus same-sensor bodies, e.g. the X-T30 through the X-T3) or chart-measured matrices (the EOS D60); others use a neutral matrix (a black-and-white camera JPEG gives its tone curve only, #577; dark JPEG tones also guide the toe, #1307) | ΔE vs camera JPEG 2.9–10 after fitting (raw-parity.md); 1 chart-calibrated model (EOS D60: its Kelvin scale and fallback colour, the look stays the JPEG fit) vs 1,500 Adobe Standard profiles | every raw shooter sees colour that is close but not Lightroom's; some get neutral-matrix colour | 50–90 | [raw-parity](raw-parity.md#colour) | | 2 B | **CR3 variants no public file uses** (LR-IMP-FORMATS): `crx.rs` refuses vertical-tile C-RAW, partial-subband and other plane coding, multi-tile 0x200 and adaptive low-frequency gains, and those files fall back to the preview. All 110 CC0 CR3s on raw.pixls.us (31 folders) decode from sensor data, so none of these variants has a public sample; 26 CR3 bodies are verified (M50 / R100 / R8 exact, R5 Mark II pinned, 22 more pinned on one CC0 file each and checked against the camera JPEG, [cr3.md](cr3.md#further-bodies-one-cc0-file-each)). HEIF stills are `.HIF` files, not CR3; no CR3 sRAW / mRAW sample exists | measured: Canon's share whose camera fully works 73% → 94% (raw-parity.md); 18 of 22 popular Canon bodies write CR3, all 18 now verified | +0.3 points of photographers; the variants surface only as user files that open as a preview | 10–25 | [raw-parity](raw-parity.md#remaining-work-ranked-by-photographers-unlocked-per-hour) | -| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632); from process V17 Apple ProRAW takes Lightroom's fitted tone chain | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; Whites remains V2 pending a follow-up | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | +| 3 B | **Render fidelity partial** (LR-BEHAV-RENDER-FIDELITY): calibrated camera-look Contrast and Blacks; other operators need measurement; from process V5 raw tone curves roll off into white in stops, so Exposure keeps recorded highlights (#1632); from process V17 Apple ProRAW takes Lightroom's fitted tone chain; from V18 Whites, the tone curves, the colour mixer and Colour Grading are measured against Camera Raw ([curve-stage.md](curve-stage.md), [mixer-stage.md](mixer-stage.md), [grading-stage.md](grading-stage.md)), and a raw whose camera profile has no tone curve gets Lightroom's measured default base curve ([default-tone.md](default-tone.md)); from V18 Highlights acts relative to the frame's tonal range, fitted on photos ([hs-range.md](hs-range.md)) | process V3 reduces held-out response error from 0.136 to 0.038 stops for Contrast and 0.424 to 0.077 for Blacks on one Sony camera; V4 to V16, and V17 except Apple ProRAW (fitted Whites in its own chain), keep V2 Whites; for other photos V18's Whites is fitted to Camera Raw's grey-step charts, not yet checked on photos per camera | imported Lightroom edits still differ, especially on uncalibrated operators and cameras | 30–60 | [calibrated Light operators](light-v3.md), [process versions](process-versions.md) | | 4 | ~~Original-pixel detail at 100%~~ (LR-VIEW-ZOOM): closed 2026-10-12, see Closed recently | checklist row ✅ | — | 0 | [ui-parity](ui-parity.md) | | 5 B | **AI masks: Subject, Sky, People, Background, Landscape** are heuristics; Object / Describe run SAM 3 but its download has no mirror configured | `crates/segment`; ai-masks.md; MASK rows 67% | masking is how most Lightroom users edit today | 40–70 + model decision | [target-app-parity](target-app-parity.md#ai) | | 6 | **Compressed ORF** (support withdrawn) | #3775 decoder removed pending provenance review; uncompressed support remains | compressed files use embedded JPEG previews when available, not sensor data | pending review | [orf-compression](orf-compression.md) | @@ -96,6 +96,11 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| +| 2026-12-03 | minor | Gap 3: from process V18 Highlights acts relative to the frame's tonal range, fitted on photos ([hs-range.md](hs-range.md)); gap not closed | +| 2026-12-03 | minor | Gap 3: from process V18 a raw whose camera profile has no tone curve gets Lightroom's measured default base curve ([default-tone.md](default-tone.md)); gap not closed | +| 2026-12-03 | minor | Gap 3: from process V18 Colour Grading is measured against Camera Raw ([grading-stage.md](grading-stage.md)); gap not closed | +| 2026-12-03 | minor | Gap 3: from process V18 the colour mixer is measured against Camera Raw ([mixer-stage.md](mixer-stage.md)); gap not closed | +| 2026-12-02 | minor | Gap 3: from V18 Whites and the parametric curve at its default splits are measured against Camera Raw, and the point curves (still LightCraft's spline) apply hue preserving as Lightroom's do ([curve-stage.md](curve-stage.md)); gap not closed | | 2026-11-26 | minor | Gap 31 added: sidebar multi-selection — the batch album, keyword and library-folder commands (#2757) have no sidebar caller yet | | 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | diff --git a/docs/grading-stage.md b/docs/grading-stage.md new file mode 100644 index 00000000000..e75ef9fbbb6 --- /dev/null +++ b/docs/grading-stage.md @@ -0,0 +1,108 @@ +# Colour Grading, measured (process V18) + +> **Changes:** [revision history](#revision-history) + +Process V18 renders Colour Grading (the shadows, midtones, highlights and global wheels with Blending and Balance) the +way Lightroom does, with LightCraft's own model fitted to measurements of Camera Raw's output. V1 to V17 are unchanged +(`docs/process-versions.md`). The code is `crates/pipeline/src/grading_stage.rs`, the model's fitted constants +`crates/pipeline/src/grading_stage_model.rs`, and the GPU kernel's `measured_grade` in +`crates/gpu/src/wgsl/finish.wgsl`. + +## What was wrong + +Up to V17 each wheel adds a fixed OkLab tint, 0.09 at saturation 100 (from V13 the global wheel 0.45 of it), in the direction of the pure sRGB colour of the +wheel's hue, weighted by smooth steps in lightness. Measured against Camera Raw on charts of grey steps and colour +patches: + +- **The tints are the wrong size and direction.** Lightroom's tint at saturation 100 is 0.08 to 0.16 depending on + the hue. Wheel hue 0 points to OkLab hue 11 to 15 in Lightroom, 29 in V17. +- **The wheels reach different tones.** At Blending 50 Lightroom's shadows wheel peaks at lightness 0.33 and gives + at least half its tint from 0.12 to 0.52, so it barely touches the deepest shadows. V17's is strongest at black and + gone by 0.6. Lightroom's global wheel peaks in the midtones (0.62, half or more from 0.23 to 0.89). V17's is the + same at every lightness. Midtones peak at 0.59 and highlights at 0.84. +- **Colours that already lean the tint's way get less of it.** A saturated colour in the tint's direction gets 62% + of the shadows tint and about 90% of the highlights and global tints. V17 adds the full tint to every colour. + +## What V18 does + +After the other colour tools, where V17 and earlier grade (`colorops::ColorOps::apply`), in OkLab: + +1. Each wheel with a saturation above 0 adds its tint times its share at the pixel's lightness, times the damping. + - The tint comes from the model (below): its direction and size around the hue circle, the wheel's size and its + saturation curve, from none at saturation 0. + - The share comes from the model's profile at the pixel's lightness, for the Blending and Balance set (the global + wheel ignores Balance). + - The damping depends on the pixel's chroma (levels 0.04, 0.08 and 0.12, from none at 0) and on the angle between + its hue and the tint's (the model sampled at the centres of bins of 30°, linear between them). +2. Each wheel's Luminance adds a lightness change by lightness, from the model. +3. The wheels act on the same input colour and their changes add. + +The earlier grading is off under V18 (`ColorOps::grading` is `None`). With Colour Grading neutral the stage does not run. + +## The model + +262 constants (`grading_stage_model.rs`): + +- **Tint.** All four wheels share one shape around the hue circle: a Fourier series of the wheel hue (4 harmonics) for + the tint's direction as an offset from the wheel hue, and one for its log size. Each wheel adds its own size and a + saturation curve `s (1 + g1 (s − 1) + g2 (s − 1)²)`, `s` = saturation / 100. 30 constants. +- **Share by lightness.** Per wheel, two bumps of the kind the curve stage uses ([curve-stage.md](curve-stage.md)), + whose gain and exponents are quadratic in Blending and in Balance. 30 constants per wheel. +- **Luminance.** Per wheel and direction, two bumps whose gain and exponents change with the amount. 24 constants + per wheel. +- **Damping.** Per wheel, `1 + (C / 0.12)^exp(e) (d0 + d1 cos a + d2 cos 2a)` for chroma `C` and angle `a` between the + colour's hue and the tint's. 4 constants per wheel. + +## How it was measured + +`tools/lr_grading_charts.py charts OUT_DIR` writes linear DNG charts with the grey steps and colour patches of +`tools/lr_tone_charts.py`, with the settings in the DNG's XMP (197 charts). It writes: + +- one neutral chart; +- each wheel at 12 hues × 3 saturations; +- each wheel's Luminance at ±50 and ±100; +- Blending 0, 25, 75 and 100, and Balance ±50 and ±100; +- two combinations used only as checks. + +The charts are original test data. Every chart was rendered through Camera Raw to a 16-bit Adobe RGB (1998) TIFF. +Only that output is measured, and nothing of Adobe's is copied or shipped. + +`tools/lr_grading_charts.py fit RENDER_DIR OUT_RS` reads each render's patches as OkLab, measures the following in +memory, fits the model to it and writes only the model's constants, `grading_stage_model.rs`. No measurement is +committed. + +- The tints and profiles are fitted on the grey steps: the profile's shape is the mean tint size over the hues, + and each tint is the least-squares scale of its grey-step change against that shape. +- The damping comes from the colour patches. +- The Luminance curves are the grey steps' lightness change. + +It needs numpy, scipy and tifffile (`tools/requirements-lr-tone-charts.txt`). Running the tool again reproduces the +committed charts byte for byte, and the constants with the pinned packages. + +How close the model is to those measurements: the tints within 0.57 RMS (OkLab × 100) of an average tint of 6.94; +the share by lightness within 0.7 to 2.6 RMS (× 100, the shadows wheel worst); Luminance within 0.01 to 0.27 RMS +(OkLab L × 100); the damping within 1.0 to 4.7 RMS (× 100). The damping's measurements do not change steadily with the +angle (the midtones wheel's at chroma 0.12 go 1.02, 0.99, 0.90, 0.92, 0.96, 1.02), so the smooth model leaves part of +that out. + +On 5 held-out Panasonic DC-S9 photos (24 edits each plus Neutral, 1,500 px, aligned against Camera Raw's renders), +the whole series with every stage's fitted model (curves, mixer, this stage, the default base curve, Highlights and +Calibration) is 2.424 in tone and 0.557 in colour (OkLab × 100, lower is better), against 2.418 and 0.556 with the +measured tables it replaces, and 6.98 and 1.52 before the series (V7). + +## Limits + +- Camera Raw's tint also changes grey steps' lightness a little. Leaving that out costs on the charts (1.26 against + 0.93 with it), but including it made photos with several strong wheels worse, so the tint leaves lightness alone. +- The damping's chroma levels are the charts' nominal chroma, and the measured hues are 30° apart. +- Camera Raw's process version 2012 controls (`crs:ProcessVersion` 11.0), one chart layout, sRGB-gamut patches. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-10 | minor | Process V18: Colour Grading measured against Lightroom | +| 2026-11-24 | minor | Colour Grading is a fitted model of 262 constants instead of measured tables | +| 2026-12-03 | patch | Renumbered from V9 to V17, on top of V16: main retired 9 | +| 2026-12-03 | patch | Renumbered from V17 to V18, on top of V17: main took 17 for Apple ProRAW (#4196) | +| 2026-12-03 | patch | The damping's chroma exponent is `exp(e)`, as the model computes it (review on #4084) | diff --git a/docs/hs-range.md b/docs/hs-range.md new file mode 100644 index 00000000000..b21e48b00fc --- /dev/null +++ b/docs/hs-range.md @@ -0,0 +1,84 @@ +# Highlights relative to the frame's tonal range (process V18) + +> **Changes:** [revision history](#revision-history) + +Process V18 makes Highlights act relative to the photo's own tonal range, as Lightroom's does. V1 to V17 are unchanged +(`docs/process-versions.md`), and Shadows keeps V17's rule. The code is `crates/pipeline/src/hs_range.rs`, the range +`local::frame_range`, and the GPU kernel's `hs_range_highlights` in `crates/gpu/src/wgsl/finish.wgsl`. + +## What was wrong + +Up to V17 Highlights moves the base layer's log luminance by a fixed weight of its absolute level: `1.7 × amount` at +the top, fading out below −1 stop from middle grey. Lightroom's Highlights depends on the photo. Measured on Camera +Raw renders of photos at Highlights −50 and −100, Lightroom's Highlights works relative to the frame's own tonal +range, anchored on its darkest tones: + +- **On a photo with a wide tonal range it works harder.** Its pull at the top grows with the span from the frame's + darkest to its brightest tones. +- **It reaches further down.** On such a photo it also darkens the upper midtones, which V17 leaves alone. + +Region size barely matters: the response follows the frame's range, not how much of the frame is bright. + +## What V18 does + +1. **The frame's range.** The base layer's 2nd and 99th percentile in log₂ luminance (`FrameRange`), plus exposure. + It comes from a render of the whole output frame at a fixed 384 px on the long edge, whatever the output's size, + built like the proxy Dehaze uses for its airlight (`local::frame_range`, `Plan::hs_range`). So a zoomed window, a + thumbnail, a preview and an export of one photo share it. The proxy goes through the same stages as the render + before its base layer: the camera's local tone map (`ProfileGainTableMap`) when the Profile option turns it on, + then the white balance. +2. **Highlights** adds `amount × a × smooth(low, 2.8, base)` to the base layer's log luminance (`FrameRange::highlights`): + - `span` is the range's width in stops, at least 0.1. + - The strength is `a = 0.7 × (span / 5)^2.4`, clamped to 0.2…8. + - It reaches down to `low = −1 − 0.8 × max(span − 5, 0)` stops. +3. **Shadows**, local Whites, Blacks, Contrast, Clarity and Texture are V17's. + +It applies to global Highlights and to Highlights in masks, except global Highlights on Apple ProRAW, which V17's +Lightroom chain applies (`crate::proraw`); Highlights in masks on ProRAW still uses the range. With Highlights at 0 (globally and in every mask) the range +is not measured and Highlights adds nothing. + +## How it was fitted + +The form comes from an earlier analysis of Camera Raw renders of photos: the response scales with the frame's range +and is anchored on its darkest tones. The five constants were fitted by coordinate descent against Camera Raw renders +of 5 training photos (Panasonic Lumix DC-S9, RW2, Adobe Standard), on Highlights −50 and −100, the Highlights and +Shadows combination and one preset of each group. They were checked on 5 other photos held out from fitting. These +renders are the contributor's own photos and are not in the repository. Unlike the curve, mixer and grading stages, +no synthetic chart is involved: a flat chart has no tonal range for the rule to act on. + +A version that also made Shadows relative to the range was measured too. It moved Shadows +100 further from Lightroom +(4.35 to 4.53) and the Highlights and Shadows combination less than Highlights alone did, so Shadows keeps V17's rule. + +## Results + +Held-out Panasonic Lumix DC-S9 photos (RW2, Adobe Standard profile, 1,500 px, aligned against Camera Raw's renders), +lightness RMS and mean a/b error (OkLab × 100), lower is better. "Before" is process V18 without this change. + +| Edits | Tone: before → this | Colour: before → this | +|---|---|---| +| Highlights −50, −100 | 3.30 → 2.17 | 0.37 → 0.27 | +| Highlights −100 with Shadows +100 | 6.59 → 4.03 | 0.62 → 0.42 | +| Shadows +50, +100 | 3.23 → 3.23 | 0.39 → 0.39 | +| 19 presets (7 groups) | 2.61 → 2.14 | 0.73 → 0.69 | +| Unedited | 0.69 → 0.69 | 0.27 → 0.27 | + +Three presets get worse: Muted (tone 4.92 → 5.35, colour 0.72 → 0.85), Sunset (tone 2.24 → 2.43) and Cool (colour +1.53 → 1.58, tone better). + +## Limits + +- Fitted on one camera's photos (10 in all) with Lightroom's renders as reference; other cameras and scenes are + unchecked. +- The percentiles come from a 384 px proxy, so a frame whose range is set by a few tiny highlights can read a + slightly different range than the full image would. +- The formula is a fit, not a measurement of Lightroom's operator: its shape matches on these photos, its constants + may not hold for very wide or very narrow ranges (the strength is clamped). + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-11 | minor | Process V18: Highlights relative to the frame's tonal range | +| 2026-12-03 | patch | Renumbered from V9 to V17, on top of V16: main retired 9 | +| 2026-12-03 | patch | Renumbered from V17 to V18, on top of V17: main took 17 for Apple ProRAW (#4196) | +| 2026-12-03 | patch | The range is measured after the camera's local tone map; ProRAW's global Highlights stays in its chain (review on #4100 and #4103) | diff --git a/docs/mixer-stage.md b/docs/mixer-stage.md new file mode 100644 index 00000000000..21a85ee2e5c --- /dev/null +++ b/docs/mixer-stage.md @@ -0,0 +1,119 @@ +# The colour mixer, measured (process V18) + +> **Changes:** [revision history](#revision-history) + +Process V18 renders the colour mixer (Hue, Saturation and Luminance of the eight bands) the way Lightroom does, with +LightCraft's own model fitted to measurements of Camera Raw's output. V1 to V17 are unchanged +(`docs/process-versions.md`). The code is `crates/pipeline/src/mixer_stage.rs`, the model's fitted constants +`crates/pipeline/src/mixer_stage_model.rs`, and the GPU kernel's `mixer_stage` in `crates/gpu/src/wgsl/finish.wgsl`. + +## What was wrong + +Up to V17 the mixer is a model: eight bands with smooth weights around fixed OkLCh hues, a hue rotation, a chroma +scale and a lightness change, linear in the slider, applied after the tone map (so after Whites) and before the output curves. Measured against Camera Raw on +fine colour charts: + +- **The bands sit in the wrong place.** V17 centres each band on the OkLab hue of the pure sRGB colour (Red 29, + Orange 82, Yellow 110, Green 142, Aqua 195, Blue 254, Purple 312, Magenta 335). Lightroom's Saturation +50 peaks + at 10, 50, 95, 140, 180, 255, 320 and 350 (5° bins). A red-orange such as skin or autumn leaves gets Lightroom's + Orange adjustment but V17's Red one. +- **The widths differ.** At half height Lightroom's Blue band is about 85° wide against V17's 59°, its Red and Magenta + bands about 20° against 54° and 39°. +- **The response is not linear.** Saturation +100 does 2.6 to 2.9 times what +50 does, Luminance +100 about 1.7 + times. At ±100 Lightroom's Hue and Saturation sliders also move lightness, by up to 3 to 17 (OkLab L × 100) + depending on the band. Its hue shift barely depends on the input's chroma (0.8 to 1.15 times between the lowest and + highest measured level), while V17 scales the shift by chroma up to 0.12, so a colour of chroma 0.04 gets a third. +- **The order differs.** Lightroom applies the mixer before Whites; V17 applies Whites in the tone map, before the mixer (below). + +## What V18 does + +After the tone map and V4's calibrated Contrast and Blacks, before the curve stage ([curve-stage.md](curve-stage.md)): + +1. Convert linear Rec.2020 to OkLCh. +2. Look up the response of every mixer slider that is set, from the model (below), sampled once per render into a + table: for the pixel's hue (72 bins of 5°), chroma and lightness, the hue shift, the relative chroma change and + the lightness change. Hue is interpolated linearly. Chroma and lightness are interpolated bilinearly between three + levels of each (lightness 0.55, 0.78 and 0.92, chroma levels lower for brighter colours), and clamped outside + them. Below the lowest chroma level the lightness change fades out, so greys stay grey. +3. All sliders act on the same input colour. Their hue and lightness changes add and their chroma changes multiply + (charts with several sliders at once: closer than adding). +4. Convert back to linear Rec.2020. + +V17's mixer in `ColorOps` is off under V18 (`ColorOps::mixer`), so the mixer applies once. With the mixer neutral the +stage does not run. Saturation, Vibrance, Point Color and B&W keep their V17 operators, +now after the curve stage (V1 to V17 run them before the output curves). Calibration stays scene linear, before the +tone map. Colour Grading also runs after the curves, through its own measured V18 stage +([grading-stage.md](grading-stage.md)). + +## The model + +168 constants (`mixer_stage_model.rs`). For slider kind `k` (Hue, Saturation, Luminance) of band `b` and output `o` +(hue shift in degrees, relative chroma change, lightness change), with `t` = amount / 100, `dc` = (C − 0.09) / 0.05 +and `dl` = (L − 0.75) / 0.15 for the colour's OkLCh chroma and lightness: + + response = amp[b][k][o] · gain[k][o](t) · band[b](h) · exp(ac dc + al dl) + gain(t) = g1 |t| + g2 t² + g3 |t|³ (g4, g5, g6 for positive amounts) + band(h) = exp(−z² / 2), z = wrap(h − centre) / e^(left or right of the centre) + +- **Per band** (24 constants): its centre on the OkLab hue circle and its width on each side, shared by the band's + Hue, Saturation and Luminance sliders. +- **Per kind and output** (72 constants): the gain over the amount, which grows faster than linearly, and the + dependence on the colour's chroma and lightness, shared by all eight bands. +- **Per band, kind and output** (72 constants): an amplitude. + +## How it was measured + +`tools/lr_mixer_charts.py charts OUT_DIR` writes linear DNG charts of OkLCh patches (72 hues × 3 chroma levels × 3 +lightness levels, patches outside sRGB left out), with the settings in the DNG's XMP. It writes one neutral chart and +each band's Hue, Saturation and Luminance at each measured amount (193 charts). The charts are original test data. +Every chart was rendered through Camera Raw to a 16-bit Adobe RGB (1998) TIFF. Only that output is measured, and +nothing of Adobe's is copied or shipped. `tools/lr_mixer_charts.py fit RENDER_DIR OUT_RS [CHART_DIR]` takes the charts' `mixer__manifest.json` from +CHART_DIR (RENDER_DIR when the renders sit beside the charts) and reads each render's +patches as OkLab, takes each setting's response against Camera Raw's own neutral chart, fits the model to it and +writes only the model's constants, `mixer_stage_model.rs`. No measurement is committed. It needs numpy, scipy and +tifffile (`tools/requirements-lr-tone-charts.txt`). Running the tool again reproduces the committed charts byte for +byte, and the constants with the pinned packages. + +Camera Raw's neutral render desaturates bright colours: patches of one nominal chroma come out about three times +less chromatic at the top lightness level than at the bottom. The model therefore takes the colour's chroma and +lightness as they are, and the table it is sampled into keeps lower chroma levels for brighter colours. + +How close the model is: predicting Camera Raw's edited charts (each slider at ±25, ±50, ±75 and ±100) from its +neutral chart with the stage's rules leaves 0.35 (Hue), 0.24 (Saturation) and 0.55 (Luminance) OkLab × 100, against +average effects of 0.68, 0.62 and 1.54. The measured responses themselves, used the same way, would leave 0.04, +0.05 and 0.12. A model with a band shape per slider and output (1,584 constants) leaves 0.15, 0.16 and 0.37, but +does no better on photos than this one. On photos: see +[Results](#results). + +The order comes from separate check charts rendered while investigating: a strong curve together with mixer +settings. Predicting them from the single-setting renders leaves 1.17 (OkLab × 100) with the mixer before the curves +and 1.66 with it after. Those check charts are not part of the tool. + +## Results + +Held-out Panasonic Lumix DC-S9 photos (5 raws, 24 edits each plus Neutral, 1,500 px, aligned against Camera Raw's +renders), with the curve stage of [curve-stage.md](curve-stage.md). Tone is RMS lightness error, colour the mean a/b +error (OkLab × 100), all edit groups weighted equally. Lower is better. + +| Mixer | Tone | Colour | +|---|---|---| +| Measured table (before) | 7.008 | 1.314 | +| This model | 7.015 | 1.288 | + +## Limits + +- Camera Raw's process version 2012 controls (`crs:ProcessVersion` 11.0), one chart layout, sRGB-gamut patches. More + saturated colours than the top measured chroma level take its response. +- Calibration is not measured in. Its measured response matched the charts better than V17's matrix, but made the + held-out photos worse (OkLab colour error 1.316 to 1.331), so V18 keeps V17's Calibration. +- Masks' Hue and Saturation keep the earlier operators. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-10 | minor | Process V18: the colour mixer measured against Lightroom, before the tone curves | +| 2026-12-03 | patch | Renumbered from V9 to V17, on top of V16: main retired 9 | +| 2026-11-11 | patch | Colour Grading under V18 has its own measured stage, not the earlier operator | +| 2026-12-03 | patch | Renumbered from V17 to V18, on top of V17: main took 17 for Apple ProRAW (#4196) | +| 2026-11-24 | minor | The mixer is a fitted model of 168 constants instead of a measured table | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 455157e4acc..451ebc62f2e 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -186,12 +186,12 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR button next to B&W in the Edit panel header, as Lightroom (Visualize HDR and the headroom limit in the Light panel while it's on, sliding open and shut with the histogram's layout change); see Q. HDR | | LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | 🟡 | `ctl:light.contrast` | From process V4, global Contrast on the camera-look path is fitted per channel in ProPhoto with the sRGB transfer. Check response error 0.136 to 0.038 stops on six held-out Sony photos. Other sources and local adjustments retain V2; broader parity remains unverified (`docs/light-v3.md`). | -| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp; from process V8 (`local::detail_free`: clamped between the median at that radius and one 3× wider) lettering keeps clean gaps (the median alone turned them into blocks of the letters' tone). Alt/Option-drag shows highlight clipping | +| LR-EDIT-LIGHT-HIGHLIGHTS | Highlights | P0 | ✅ | `ctl:light.highlights`, `crates/raw/src/highlight.rs` | sensor-clipped highlights stay neutral when Highlights (or Exposure, Whites) darkens them: fully clipped content is rebuilt to the neutral of the colour model applied after it, partly clipped content takes its colour from reliable unclipped content nearby (not from dark objects, lens fringes or another surface beside it) and white where there is none, and pale partly clipped content (a white sky) turns white on its way to clipping (#523); binned previews and thumbnails decide clipping per sample before averaging (`develop_binned_masked`, `highlight::reconstruct_masked`), so a block with one clipped specular sample keeps its mean instead of jumping to the clip level, which reconstruction turned into green speckles at 500 px (#548) From process V2 the Highlights/Shadows base is the edge-aware filter of the 0.15 %-of-long-edge median of log luminance: twigs and fine texture take their surroundings' shift, so bright areas keep their local contrast as with Exposure (V1's base kept ~0.6 of it at −100, #632); region edges stay sharp; from process V8 (`local::detail_free`: clamped between the median at that radius and one 3× wider) lettering keeps clean gaps (the median alone turned them into blocks of the letters' tone). Alt/Option-drag shows highlight clipping; from process V18 it acts relative to the frame's tonal range, stronger and reaching further down on a wide range, as Lightroom's does ([hs-range.md](hs-range.md)) | | LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | From process V2, the same base as Highlights: dark areas keep their local contrast when lifted (#632); from process V8, the gaps in dark lettering on a bright panel are not lifted into bright blocks. Alt/Option-drag shows shadow clipping (white, clipped channels in colour). From process V13 the global amount eases off as it grows: the operator's strength is `a / (1 + 1.33·abs(a))` for `a` = slider / 100 (0.43 at +100, against 1 up to V10), fitted to Lightroom exports (#523). | -| LR-EDIT-LIGHT-WHITES | Whites | P0 | 🟡 | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | V4 preserves V2 Whites for both signs. Calibration is a planned follow-up; measured V2 check response error is 0.075 stops on the Sony test photos (`docs/light-v3.md`). Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | +| LR-EDIT-LIGHT-WHITES | Whites | P0 | 🟡 | `ctl:light.whites`, `crates/pipeline/src/visualize.rs` | From process V18 Whites is measured against Camera Raw renders of synthetic grey steps and reaches into the midtones as Lightroom's does ([curve-stage.md](curve-stage.md)); not yet compared on photos per camera. V4 to V16, and V17 except Apple ProRAW, preserve V2 Whites for both signs; ProRAW uses its chain's fitted Whites from V17, under V18 too; measured V2 check response error is 0.075 stops on the Sony test photos (`docs/light-v3.md`). Alt/Option-drag shows highlight clipping (black, clipped channels in colour) | | LR-EDIT-LIGHT-BLACKS | Blacks | P0 | 🟡 | `ctl:light.blacks`, `crates/pipeline/src/visualize.rs` | From process V4, global Blacks on the camera-look path uses a fitted per-channel/luminance mix. Check response error 0.424 to 0.077 stops on six held-out Sony photos; deepest tones still differ. Other sources and local adjustments retain V2 (`docs/light-v3.md`). Alt/Option-drag shows shadow clipping (white, clipped channels in colour) | -| LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*`, `crates/pipeline/src/curve.rs` | the graph draws the renderer's own curve model; dragging the line moves the region under the pointer (one undo step); sampled selected-curve input backdrop (#987); [stage and sampling limits](tone-curve-input.md) | -| LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON; sampled input after Parametric, independent of this curve (#987); [stage and sampling limits](tone-curve-input.md) | +| LR-EDIT-LIGHT-CURVE-PARAM | Parametric curve | P0 | ✅ | `ctl:curve.highlights`, `ctl:curve.lights`, `ctl:curve.darks`, `ctl:curve.shadows`, `ctl:curve.split*`, `crates/pipeline/src/curve.rs` | from process V18 the regions are LightCraft's model fitted to Camera Raw's measured response at the default splits, broad and additive ([curve-stage.md](curve-stage.md)); the graph draws the curve the photo renders (`ParametricGraph`: the fitted regions under V18 at the default splits, else the analytic model); dragging the line moves the region under the pointer (one undo step); sampled selected-curve input backdrop (#987); [stage and sampling limits](tone-curve-input.md) | +| LR-EDIT-LIGHT-CURVE-POINT | Point curve | P0 | ✅ | `cmd:develop.curve`, `cmd:curve.reset`, `cmd:curve.presets`, `cmd:curve.applyPreset`, `cmd:curve.savePreset`, `cmd:curve.deletePreset`, `cmd:curve.importPresets`, `cmd:curve.exportPresets`, `cmd:file.importCurvePresets`, `cmd:file.exportCurvePresets`, `crates/engine/src/cmd/curves.rs`, `crates/ui-egui/src/panels/edit.rs` | click to add a point; drag a point in both axes (between its neighbours, input / output readout, one undo step per drag; ⌥-drag moves it a tenth as far for fine adjustment, issue #1363); drag empty space to add and drag; double-click removes; reset: double-click a channel selector (that channel), the Reset button under the graph (every curve incl. parametric) or right-click the graph (channel / all); Point Curve preset dropdown: own Linear / Medium Contrast / Strong Contrast, user presets (save the current point curves, delete by right-click; saved with the library), import / export as `.lccurve` JSON; from process V18 the master curve keeps hue as Lightroom's does (largest and smallest channel through the curve, the middle one in proportion), and the red, green and blue curves follow it per channel ([curve-stage.md](curve-stage.md)); sampled input after Parametric, independent of this curve (#987); [stage and sampling limits](tone-curve-input.md) | | LR-EDIT-LIGHT-CURVE-RGB | Per-channel curves | P0 | ✅ | `cmd:develop.curve` (`channel`) | sampled selected-curve input backdrop (#987); [stage and sampling limits](tone-curve-input.md) | | LR-EDIT-LIGHT-CURVE-REFINESAT | Curve saturation compensation | P1 | ✅ | `ctl:curve.refineSaturation` | | | LR-EDIT-LIGHT-CURVE-TAT | Drag-on-image curve adjust | P1 | ✅ | `cmd:develop.targeted` (`target: curve`) | | @@ -201,10 +201,10 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-COLOR-TINT | Tint | P0 | ✅ | `ctl:wb.tint`, `docs/tint-direction.md` | DNG / Lightroom sign: negative (left) adds green, positive (right) magenta; XMP `crs:Tint` values render as in Lightroom (issue #188); CPU/GPU regression tests | | LR-EDIT-COLOR-VIBRANCE | Vibrance | P0 | ✅ | `ctl:color.vibrance` | | | LR-EDIT-COLOR-SATURATION | Saturation | P0 | ✅ | `ctl:color.saturation` | | -| LR-EDIT-COLOR-MIXER-HSL | 8-band colour mixer | P0 | ✅ | `ctl:mixer.*`, `cmd:view.colorMixer`, `crates/ui-egui/src/panels/edit/mixer.rs` (`mixer`), `crates/ui-egui/src/tests/color_mixer.rs` | Lightroom Classic's layout: Mixer \| Point Color tabs, then Adjust HSL / Color; HSL shows Hue \| Saturation \| Luminance \| All (the three stacked with headings), eight sliders per group with coloured tracks and a targeted adjustment per group; Color shows one colour at a time; HSL by default, remembered | +| LR-EDIT-COLOR-MIXER-HSL | 8-band colour mixer | P0 | ✅ | `ctl:mixer.*`, `cmd:view.colorMixer`, `crates/ui-egui/src/panels/edit/mixer.rs` (`mixer`), `crates/ui-egui/src/tests/color_mixer.rs`, `crates/pipeline/src/mixer_stage.rs` | from process V18 each slider follows LightCraft's model fitted to Camera Raw's measured response on synthetic OkLCh charts (band centres, widths, the non-linear amount, side effects on lightness), applied before Whites and the tone curves ([mixer-stage.md](mixer-stage.md)); Lightroom Classic's layout: Mixer \| Point Color tabs, then Adjust HSL / Color; HSL shows Hue \| Saturation \| Luminance \| All (the three stacked with headings), eight sliders per group with coloured tracks and a targeted adjustment per group; Color shows one colour at a time; HSL by default, remembered | | LR-EDIT-COLOR-MIXER-BW | B&W mix | P1 | ✅ | `ctl:bw.*`, `cmd:develop.autoBwMix` | eight bands; Auto pushes each hue band's colourful pixels away from the mean lightness (own rule) | | LR-EDIT-COLOR-POINTCOLOR | Point colour | P1 | ✅ | `cmd:pointColor.pick`, `cmd:pointColor.delete` | | -| LR-EDIT-COLOR-GRADING | Colour grading wheels | P0 | ✅ | `ctl:grading.*`, `crates/ui-egui/src/panels/edit.rs` (`grading`) | 3-Way / Shadows / Midtones / Highlights tabs; a range tab shows one large wheel with Hue, Saturation and Luminance sliders; Blending and Balance in every tab; 3-Way shows the hovered wheel's hue and saturation; every wheel marks its neutral centre; wheel modifiers as in Lightroom: Shift-drag keeps the puck's hue and changes saturation only (the spoke is the guide; a puck at the centre has no hue, so it takes the angle where the pointer pressed), Cmd/Ctrl-drag keeps the saturation and changes hue only (the circle is the guide), Alt/Option-drag fine-adjusts at 0.1x and combines with either lock, and a hover tooltip lists them (issues #559, #1160; tests `shift_dragging_across_the_tangent_keeps_the_hue_and_moves_saturation`, `shift_drag_keeps_the_pucks_hue_wherever_the_pointer_grabs`, `cmd_drag_keeps_the_saturation_and_changes_only_the_hue`, `alt_drag_fine_adjusts_to_a_tenth_of_the_pointers_travel`, `alt_works_with_shift_and_cmd_constraints` in `crates/ui-egui/src/tests/grading.rs`); a wheel drag holds the pointer as in Lightroom: hidden while dragging (the puck follows the mouse's travel; on macOS the pointer is locked in place), back where the button went down on release, and given back at once on Esc, a lost window focus or a wheel that goes away mid-drag; the browser can't move the pointer, so there it only shows again where the drag ended (issue #1899; tests `a_held_wheel_follows_the_mouses_motion_not_where_the_pointer_sits`, `a_wheel_drag_hides_the_pointer_and_releasing_puts_it_back_where_it_was_pressed`, `escape_or_losing_focus_gives_the_pointer_back_mid_drag`, `a_wheel_that_goes_away_mid_drag_gives_the_pointer_back`); the large wheel adds 25/50/75 % saturation rings (issue #559); each wheel's eye hides its effect for viewing only (`RenderJob::with_hidden_grading`, not saved, export unaffected) (issue #737). No Global wheel tab yet; from process V13 the Global wheel tints at 0.45 of the other wheels at the same saturation, measured against Lightroom exports (`colorops::global_wheel`) | +| LR-EDIT-COLOR-GRADING | Colour grading wheels | P0 | ✅ | `ctl:grading.*`, `crates/ui-egui/src/panels/edit.rs` (`grading`), `crates/pipeline/src/grading_stage.rs` | from process V18 the wheels follow Camera Raw's measured response on synthetic charts (tint size and direction, lightness reach by Blending and Balance, less tint for colours already leaning its way; [grading-stage.md](grading-stage.md)); 3-Way / Shadows / Midtones / Highlights tabs; a range tab shows one large wheel with Hue, Saturation and Luminance sliders; Blending and Balance in every tab; 3-Way shows the hovered wheel's hue and saturation; every wheel marks its neutral centre; wheel modifiers as in Lightroom: Shift-drag keeps the puck's hue and changes saturation only (the spoke is the guide; a puck at the centre has no hue, so it takes the angle where the pointer pressed), Cmd/Ctrl-drag keeps the saturation and changes hue only (the circle is the guide), Alt/Option-drag fine-adjusts at 0.1x and combines with either lock, and a hover tooltip lists them (issues #559, #1160; tests `shift_dragging_across_the_tangent_keeps_the_hue_and_moves_saturation`, `shift_drag_keeps_the_pucks_hue_wherever_the_pointer_grabs`, `cmd_drag_keeps_the_saturation_and_changes_only_the_hue`, `alt_drag_fine_adjusts_to_a_tenth_of_the_pointers_travel`, `alt_works_with_shift_and_cmd_constraints` in `crates/ui-egui/src/tests/grading.rs`); a wheel drag holds the pointer as in Lightroom: hidden while dragging (the puck follows the mouse's travel; on macOS the pointer is locked in place), back where the button went down on release, and given back at once on Esc, a lost window focus or a wheel that goes away mid-drag; the browser can't move the pointer, so there it only shows again where the drag ended (issue #1899; tests `a_held_wheel_follows_the_mouses_motion_not_where_the_pointer_sits`, `a_wheel_drag_hides_the_pointer_and_releasing_puts_it_back_where_it_was_pressed`, `escape_or_losing_focus_gives_the_pointer_back_mid_drag`, `a_wheel_that_goes_away_mid_drag_gives_the_pointer_back`); the large wheel adds 25/50/75 % saturation rings (issue #559); each wheel's eye hides its effect for viewing only (`RenderJob::with_hidden_grading`, not saved, export unaffected) (issue #737). No Global wheel tab yet; in processes V13 to V17 the Global wheel tints at 0.45 of the other wheels at the same saturation, measured against Lightroom exports (`colorops::global_wheel`) | | LR-EDIT-EFFECTS-TEXTURE | Texture | P0 | ✅ | `ctl:effects.texture` | From process V13 a negative amount smooths at 0.67 of V6's strength, measured against full-size Lightroom exports at −27 (`finish::texture_slider`) | | LR-EDIT-EFFECTS-CLARITY | Clarity | P0 | ✅ | `ctl:effects.clarity` | | | LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | | @@ -472,7 +472,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | -| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs`, `crates/pipeline/src/proraw.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. Whites retains V2 and awaits a follow-up. Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). From process V5 a raw's tone curve rolls off into white in stops (past a camera curve's last fitted knot, or from half a stop below the generic curve's white point instead of clipping), so Exposure +1 and +2 keep the highlights the sensor recorded: on 12 CC0 corpus raws and 6 CC0 DNGs on the generic curve, unclipped pixels whose luminance renders at 254 or more fall from up to 22.5 % to 0 at +1 EV and from up to 35 % to at most 0.03 % at +2 EV, apart from one sky that is mostly at the clip (#1632). Not compared with Lightroom's output. From process V13 global Shadows eases off at large amounts (`finish::tone_slider`, +100 at 0.43 of V6), fitted to 56 Lightroom exports of real Canon portrait edits at Shadows +40 to +100; with negative Texture and the Global wheel, mean ΔE on those exports 9.5 → 9.0. Global Highlights stays linear: on those edits V6 renders the brightest tones about 5 L* too dark, but single-slider exports show Lightroom's Highlights response close to linear and dependent on the frame's content (#3923), so that coverage-dependent strength, and smaller Shadows amounts, remain open. From process V17 Apple ProRAW (Make Apple and a `ProfileToneCurve`) takes Lightroom Classic's tone chain: base operator, Highlights / Shadows on a neighbourhood of the photo, Whites, Blacks, the profile curve per channel, Contrast adapting to the image; closed-form operators fitted on one CC0 iPhone 12 Pro file against Lightroom Classic 15.6 exports, mean CIEDE2000 unedited 2.93 → 1.05 and the 12 single tone-slider renders 3.73 → 1.22 (#613). Other cameras keep the operators above | +| LR-BEHAV-RENDER-FIDELITY | Rendering matches Lightroom | P1 | 🟡 | `crates/pipeline/src/lib.rs`, `crates/pipeline/src/tone.rs`, `crates/pipeline/src/proraw.rs` | Process V4 calibrates global camera-look Contrast and Blacks against black-box Lightroom exports of Sony ILCE-7CR photos. Held-out response errors are 0.038 and 0.077 stops; V1/V2 keep their rendering. V4 to V16, and V17 except Apple ProRAW, keep V2 Whites; ProRAW uses its chain's fitted Whites from V17, and V18 measures Whites for other photos (below). Exposure, Highlights/Shadows, other operators and broader camera coverage remain open (`docs/light-v3.md`). From process V18 Whites, the parametric curve (at the default splits; moved splits keep the analytic model) and the point curves follow Camera Raw's measured response on synthetic grey steps, the master curve hue-preserving ([curve-stage.md](curve-stage.md)). From V18 the colour mixer follows Camera Raw's measured response on synthetic colour charts ([mixer-stage.md](mixer-stage.md)), and Colour Grading too ([grading-stage.md](grading-stage.md)); Calibration, Saturation and Vibrance are not measured in yet. From V18 Highlights acts relative to the frame's tonal range, fitted on Lightroom's renders of photos ([hs-range.md](hs-range.md)). From V18 a raw whose camera profile has no tone curve of its own (Adobe Standard) gets Lightroom's default base curve measured on a synthetic chart, hue preserving on linear ProPhoto channels, with a per-camera exposure offset measured for the Panasonic Lumix S9, S5, S5 II and S5 IIX only ([default-tone.md](default-tone.md)). From process V5 a raw's tone curve rolls off into white in stops (past a camera curve's last fitted knot, or from half a stop below the generic curve's white point instead of clipping), so Exposure +1 and +2 keep the highlights the sensor recorded: on 12 CC0 corpus raws and 6 CC0 DNGs on the generic curve, unclipped pixels whose luminance renders at 254 or more fall from up to 22.5 % to 0 at +1 EV and from up to 35 % to at most 0.03 % at +2 EV, apart from one sky that is mostly at the clip (#1632). Not compared with Lightroom's output. From process V13 global Shadows eases off at large amounts (`finish::tone_slider`, +100 at 0.43 of V6), fitted to 56 Lightroom exports of real Canon portrait edits at Shadows +40 to +100; with negative Texture and the Global wheel, mean ΔE on those exports 9.5 → 9.0. Global Highlights stays linear: on those edits V6 renders the brightest tones about 5 L* too dark, but single-slider exports show Lightroom's Highlights response close to linear and dependent on the frame's content (#3923), so that coverage-dependent strength, and smaller Shadows amounts, remain open. From process V17 Apple ProRAW (Make Apple and a `ProfileToneCurve`) takes Lightroom Classic's tone chain: base operator, Highlights / Shadows on a neighbourhood of the photo, Whites, Blacks, the profile curve per channel, Contrast adapting to the image; closed-form operators fitted on one CC0 iPhone 12 Pro file against Lightroom Classic 15.6 exports, mean CIEDE2000 unedited 2.93 → 1.05 and the 12 single tone-slider renders 3.73 → 1.22 (#613). Other cameras keep the operators above | | LR-BEHAV-DRAGDROP | Drag and drop | P1 | ✅ | `crates/ui-egui/src/lib.rs`, `crates/ui-egui/src/panels/grid.rs` (`drag_feedback`), `crates/ui-egui/src/panels/left.rs` (`drop_target`, `album_drag_over`, `top_level_drop_target`, `drag_auto_scroll`), `crates/ui-egui/src/tests/drag_contract.rs`, `crates/ui-egui/src/destination.rs`, `crates/ui-egui/src/widgets.rs` (`context_menu`), `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/tests/carried_right_click.rs`, `crates/ui-egui/src/tests/carried_text_field_menu.rs` | a right-click while photos are carried opens no context menu (every menu opened through `widgets::context_menu`: sidebar rows, grid cells, lists; a text field's own Cut / Copy / Paste menu too); files → app (a drop-target card while they hover, then the import review); grid photos → an album row (the dragged label says how many photos it adds, or that they are all there already, and a drop then does nothing, with no undo step; a drop that finds some there says so in its toast); a smart album, an album folder and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason, on the label and in the toast; Esc gives up any drag (photos, albums, sidebar sections, keywords) and does nothing else; sidebar album / folder rows → a folder (moves it; its name follows the pointer); a drag of albums or grid photos near the top or bottom edge of the sidebar scrolls it (faster nearer the edge, only while the pointer is over the sidebar); when another folder has the same name, the dragged label, the Move question and the toast name the folder it is in (`home (/a)`); an album drop's toast does the same for an album of that name in another album folder (two in the same place have nothing to tell them apart and keep the plain name); only the primary button drags photos and drops them: a right-button drag over a grid cell neither picks photos up nor changes the selection, and a right-button release while photos are dragged neither drops them nor ends the drag | | LR-BEHAV-TOAST | Toast notifications | P1 | ✅ | `crates/ui-egui/src/panels.rs` | | | LR-BEHAV-DIALOGS | Dialogs fit the window | P1 | ✅ | `crates/ui-egui/src/dialogs.rs` (`dialog_body`, `list_height`), `crates/ui-egui/src/tests/dialog_fit.rs`, `crates/ui-egui/src/tests/dialog_copy.rs`, `crates/ui-egui/src/tests/dialogs.rs` (`a_click_outside_closes_the_dialog_when_settings_allow_it`) | a dialog taller than the window (Export on a 1366×768 screen, issue #781) never runs off it: its options scroll while the title bar and the Cancel / confirm row stay on screen (the confirm button names its action: Create, Rename, Create Stacks, Export 3 Photos…, with "OK" kept only for a one-field prompt opened with a command that has no verb, `crates/ui-egui/src/tests/dialog_copy.rs`); lists that scroll on their own (What's New, All Metadata, shortcuts, smart-album rules, credits) get shorter first; dialogs that fit look as before; Import keeps its own resizable, scrolling window; Settings → Dialogs → Close a dialog by clicking outside it (off by default, so a stray click never throws away a dialog's choices): a click pressed and released on the dimmed backdrop closes the dialog like Esc and doesn't reach the panels below, while a drag that ends outside (a slider pulled past the edge) or a click that closes a dropdown keeps it; the import review never closes this way (`clicked_backdrop`); a one-line prompt (Rename Folder, New Folder on Disk, the preset and version names, New Library when its name can't be used, Auto-Tag from Tracklog) the engine refuses stays open with its text and shows the reason in a toast, so the name can be corrected, where it used to close without a word; a New Folder on Disk that works says so (“Created folder “Selects” in “2026/Shoot””, naming the parent by its last two folders as dialogs do) | @@ -738,7 +738,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | | | LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | | | LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets | -| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers, V8 keeps the gaps in dark lettering under Highlights and Shadows (#3460), V10 checks the Bradford white-balance fallback (craft-libs#587), V13 eases global Shadows off at large amounts and has negative Texture and the Global grading wheel act less, as measured against Lightroom exports (#523), V14 pins Heal and Remove spots to the photo on the spot's edge. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | +| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers, V8 keeps the gaps in dark lettering under Highlights and Shadows (#3460), V10 checks the Bradford white-balance fallback (craft-libs#587), V13 eases global Shadows off at large amounts and has negative Texture and the Global grading wheel act less, as measured against Lightroom exports (#523), V14 pins Heal and Remove spots to the photo on the spot's edge, V17 renders Apple ProRAW in Lightroom's fitted tone chain, V18 measures Whites, the tone curves, the colour mixer and Colour Grading against Lightroom and keeps hue through the master curve. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. | | LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ Loupe Overlay ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option | | LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders | | LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | | @@ -1117,6 +1117,12 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-17 | minor | LR-BEHAV-DRAGDROP: Esc gives up a photo drag (and only the drag); album rows say how many photos a drop adds or that they are there already (a no-op drop changes nothing); smart albums, album folders and the sidebar's Keywords rows refuse photos with the not-allowed cursor and a reason; the Keyword List says how many photos get a keyword and refuses a keyword dropped inside itself; LR-LIB-ALBUM and LRC-LIB-KEYWORDS text updated; status unchanged (✅) | | 2026-10-27 | patch | MENU-HELP-FEEDBACK: on macOS the Help menu no longer shows the system's `Send Feedback` row beside Send Feedback… | | 2026-10-17 | minor | LR-LIB-SMARTALBUM, LR-LIB-PEOPLE, LR-VIEW-FOCUSPOINT, LR-VIEW-BEFOREAFTER, LR-VIEW-SLIDESHOW, LR-BEHAV-SIDEBAR-HIDE, MENU-VIEW-PHOTOCOUNT, MENU-VIEW-SIDEBARSECTIONS, KEY-MASKCOLOR, LRC-LIB-METADATA, LRC-MAP-TRACKLOG, LRC-SS-PLAYBACK, LRC-SS-EXPORT, LRC-DEV-VIEWOPTIONS: menu bar reorganised; the rows now cite the new paths (View ▸ Loupe Overlay, Before/After, Mask Overlay, Slideshow, Sort; Window for panel toggles; Photo ▸ Metadata); no command changed and no status changed | +| 2026-11-10 | minor | LR-EDIT-LIGHT-WHITES, LR-EDIT-LIGHT-CURVE-PARAM, LR-EDIT-LIGHT-CURVE-POINT, LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V18 measures Whites and the parametric curve against Camera Raw and applies the master curve hue-preserving ([curve-stage.md](curve-stage.md)); statuses unchanged | +| 2026-11-10 | minor | LR-EDIT-COLOR-MIXER-HSL, LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V18 measures the colour mixer against Camera Raw and applies it before Whites and the tone curves ([mixer-stage.md](mixer-stage.md)); statuses unchanged | +| 2026-11-10 | minor | LR-EDIT-COLOR-GRADING, LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V18 measures Colour Grading against Camera Raw ([grading-stage.md](grading-stage.md)); statuses unchanged | +| 2026-11-11 | minor | LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V18 gives a raw whose camera profile has no tone curve Lightroom's default base curve, measured ([default-tone.md](default-tone.md)); status unchanged | +| 2026-11-11 | minor | LR-EDIT-LIGHT-HIGHLIGHTS, LR-BEHAV-RENDER-FIDELITY, LRC-DEV-PROCESS: process V18 makes Highlights relative to the frame's tonal range ([hs-range.md](hs-range.md)); statuses unchanged | +| 2026-11-11 | patch | LR-EDIT-LIGHT-CURVE-PARAM: the graph draws and drags the curve the photo renders, the measured regions under V18 at the default splits; status unchanged (✅) | ## External-profile correspondence geometry diff --git a/docs/process-versions.md b/docs/process-versions.md index 12c23e24e9f..eebdfdd0198 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -24,7 +24,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | **V14** | V13 plus: Heal spots, and Remove spots with their automatic source, are pinned to the photo on the spot's edge (`spots::pinned`, [heal-pinned.md](heal-pinned.md)). The patch is the source times `e^P`, `P` the membrane fill (`lightcraft_inpaint::membrane_fill`) of the log ratio of photo to source, known only on the ring of pixels touching the spot and blurred there over the outside only (1.5 px), so the patch meets its surroundings at the edge, takes nothing from features that don't touch it, and carries the source's texture at its contrast relative to the new light. The source's fine detail (log luminance minus a 1.5 px blur) is scaled to the detail around the spot, by the ratio of medians around the spot (1.05 to 2 radii) and inside the source (0.9 radii), within 0.5 to 2×. Every spot, Clone included, reads its source at whole pixels (read between pixels, bilinear sampling halved the grain). V1 to V13 keep the source plus a Gaussian-weighted average of the difference around the spot (σ 0.6 radii) in linear light. A Heal or Remove spot whose working box holds more than `MAX_SPOT_SPAN² / 2` pixels (about 33.5 million; 8.4 million on the web) is too big for the pinned heal's working memory and gets the V13 averaged correction instead, still reading its source at whole pixels. Fill is unchanged. CPU and GPU branch on `spots::HealMethod`; the GPU renderer reads the image back for the spot stage on V14 photos with spots and keeps the rest of the render on the device. Renders without Heal, Remove or Clone spots are the same as V13's. | | **V15** | V14 plus: brush Flow is the coverage a stroke adds per brush radius it travels, as in Lightroom Classic (#4045): each dab adds `1 − (1 − flow)^(d / r)` for a dab `d` past the previous one (the first dab counts one radius, so a click paints its flow), `masks::travel_flow`. A point a stroke passes over for a length `L` is then covered by `1 − (1 − flow)^(L / r)` however densely the dabs lie: a straight stroke's centre by 44 % at Flow 25 and 75 % at Flow 50, where Lightroom Classic measures 41 % and 76 % on a grey card. V1 to V14 add the full flow per dab (r/4 apart on a fast drag, closer on a slow one): 90 % at Flow 25 on a fast stroke, more on a slow one. CPU (`masks::brush_dabs_within`), GPU (a flow per dab in the `shape` kernel's brush data) and the live stroke (`brush_live`, the masking and Lens Blur brushes) all branch on `masks::flow_per_radius`. Renders without brush strokes, or with Flow 100 only, are the same as V14's. | | **V16** | V15 plus: a brush stroke's edge is feathered as one dab's is. Each stroke keeps its Flow build-up (every dab that reaches a pixel adds its flow, `masks::feather_dab`) apart from its edge (the highest falloff of those dabs), and covers their product up to Density (`masks::stroke_coverage`). V1 to V15 accumulate each dab's falloff times its flow, so the soft edges of dabs r/4 apart piled up: at Feather 100 and Flow 100 a straight stroke covered 0.90 halfway out from its centre line, where one dab covers 0.50; V16 covers 0.50. Below Flow 100 the centre now builds up by Flow per radius travelled whatever the Feather (a straight stroke's 44 % at Flow 25), where V15 also weakened a soft brush's centre (25 %). CPU (`masks::rasterize_brush`), GPU (a stroke-record word in the `shape` kernel's brush data) and the live stroke (`brush_live`, the masking and Lens Blur brushes) branch on `masks::stroke_feather`. Auto Mask strokes keep V15's accumulation (their edge follows the photo's edges, not the feather). Renders without brush strokes, or with Feather 0 or Auto Mask brushes only, are the same as V15's; a saved V1 to V15 photo keeps its strokes until Update to Current Process. | -| **V17** (the latest) | V16 plus: Apple ProRAW (Make `Apple` and a DNG `ProfileToneCurve`) renders its Light sliders through Lightroom Classic's fitted tone chain (`crates/pipeline/src/proraw.rs`, #613): base operator (BaselineExposure + Exposure), Highlights / Shadows on a Gaussian neighbourhood at 6.4 % of the long edge, Whites, Blacks, the 128-knot profile tone curve per channel (hue-preserving in linear ProPhoto), then Contrast adapting to the image's key. HDR keeps the chain through the midtones and lifts highlights past white (`camera_hdr_lift`). V1 to V16 keep the 32-knot camera curve on luminance; non-ProRAW photos and older offline smart previews without the curve render identically to V16. CPU and GPU share the stage tables and Highlights / Shadows curves. | +| **V17** | V16 plus: Apple ProRAW (Make `Apple` and a DNG `ProfileToneCurve`) renders its Light sliders through Lightroom Classic's fitted tone chain (`crates/pipeline/src/proraw.rs`, #613): base operator (BaselineExposure + Exposure), Highlights / Shadows on a Gaussian neighbourhood at 6.4 % of the long edge, Whites, Blacks, the 128-knot profile tone curve per channel (hue-preserving in linear ProPhoto), then Contrast adapting to the image's key. HDR keeps the chain through the midtones and lifts highlights past white (`camera_hdr_lift`). V1 to V16 keep the 32-knot camera curve on luminance; non-ProRAW photos and older offline smart previews without the curve render identically to V16. CPU and GPU share the stage tables and Highlights / Shadows curves. | +| **V18** (the latest) | V17 plus: Whites, the parametric curve and the point curves as Lightroom applies them ([curve-stage.md](curve-stage.md), `crates/pipeline/src/curve_stage.rs`), measured on Camera Raw renders of synthetic grey steps. Whites leaves the tone map (Apple ProRAW keeps Whites in V17's chain, and the stage then applies only the curves) and, with the parametric curve at Lightroom's default splits, comes from LightCraft's model fitted to those measurements (Whites reaches into the midtones; the regions are broad and add; moved splits keep the analytic model of V1 to V17); the master curve acts hue-preserving on sRGB-encoded linear ProPhoto RGB (largest and smallest channel through the curve, the middle one in proportion in linear light), then the red, green and blue curves per channel, between the calibrated Contrast and Blacks and the colour stage. V1 to V17 keep Whites in the tone map (Apple ProRAW from V17: in its own chain) and their per-channel curves on the output. CPU (`finish::finish_with`) and GPU (`finish.wgsl::curve_stage`) share the curve tables built from the model. With Whites, the parametric curve and the point curves neutral the curve stage does not run. The colour mixer follows LightCraft's model fitted to Camera Raw's measured response on synthetic OkLCh charts ([mixer-stage.md](mixer-stage.md), `crates/pipeline/src/mixer_stage.rs`): per band and slider the hue shift, chroma change and lightness change by input hue, chroma and lightness, applied before Whites and the tone curves; V1 to V17 keep their mixer model (`ColorOps::mixer`), after Whites (in the tone map) and before the output curves. Colour Grading follows LightCraft's model fitted to Camera Raw's measured response ([grading-stage.md](grading-stage.md), `crates/pipeline/src/grading_stage.rs`): per wheel a tint by hue and saturation, a lightness profile by Blending and Balance, a damping for colours already leaning the tint's way, and Luminance as a lightness change; V1 to V17 keep their grading (`ColorOps::grading`, with V13's Global wheel). A raw whose camera profile has no tone curve of its own (a DCP without `ProfileToneCurve`, such as Adobe Standard) gets a default base curve, LightCraft's model fitted to a synthetic chart measured on Camera Raw, applied hue preserving on linear ProPhoto channels and shifted by the camera's measured exposure offset ([default-tone.md](default-tone.md), `crates/pipeline/src/default_tone.rs`); V1 to V17 keep the photo's own tone (the file's curve or the one fitted to its camera JPEG), scaled by luminance, and Apple ProRAW keeps V17's chain. Highlights acts relative to the frame's tonal range (the base layer's 2nd to 99th percentile, from a 384 px render of the whole frame): stronger and reaching further down on a wide range ([hs-range.md](hs-range.md), `crates/pipeline/src/hs_range.rs`); Shadows keeps V17's rule, and Apple ProRAW keeps its chain's Highlights. | ## The rule @@ -134,6 +135,11 @@ extra field and retain their existing cached renders. No cache-version bump is n | Date | Change | Summary | |---|---|---| +| 2026-12-03 | minor | V18: Whites and the tone curves measured against Lightroom ([curve-stage.md](curve-stage.md)); V1 to V17 keep theirs | +| 2026-12-03 | minor | V18: the colour mixer measured against Lightroom, before Whites and the tone curves ([mixer-stage.md](mixer-stage.md)); V1 to V17 keep theirs | +| 2026-12-03 | minor | V18: Colour Grading measured against Lightroom ([grading-stage.md](grading-stage.md)); V1 to V17 keep theirs | +| 2026-12-03 | minor | V18: Lightroom's default base curve for a raw whose camera profile has none ([default-tone.md](default-tone.md)); V1 to V17 keep the photo's own tone | +| 2026-12-03 | minor | V18: Highlights relative to the frame's tonal range ([hs-range.md](hs-range.md)); V1 to V17 keep theirs | | 2026-12-03 | minor | V17: fitted Apple ProRAW tone chain (#613, #4196); V1 to V16 and non-ProRAW photos remain unchanged | | 2026-12-02 | minor | V16: a brush stroke's edge is feathered as one dab's is; V1 to V15 keep the accumulated soft edges | | 2026-11-24 | minor | V15: brush Flow per brush radius travelled, as in Lightroom Classic; V1 to V14 keep the flow per dab. 12 is no longer claimed | diff --git a/docs/whats-new.md b/docs/whats-new.md index 39d5cc7e927..b09b7947f38 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,42 @@ ## Unreleased +### Highlights adapts to each photo's tonal range (process 18) +- Highlights now adapts to the photo: on a photo with a wide range from its darkest to its brightest tones it + recovers more and reaches further into the upper midtones, and on a flat photo it acts more gently. A zoomed-in + view, a preview and an export of the same photo get the same result. Shadows is unchanged. This is part of + rendering process 18: photos you already edited keep their look until you choose Photo ▸ Update to Current Process. + See [Highlights relative to the frame's range](hs-range.md). + +### A default base curve for camera profiles without one (process 18) +- A raw developed with an imported camera profile that has no tone curve of its own, such as Adobe Standard, now gets + a default base tone curve, applied hue preserving, instead of the tone of the camera's JPEG. Panasonic Lumix S9, + S5, S5 II and S5 IIX raws (RW2) have a measured exposure offset; other cameras get the same curve without one, so + they can come out a little lighter or darker. This is part of rendering process 18: photos you already edited keep + their look until you choose Photo ▸ Update to Current Process. See [The default base curve](default-tone.md). + +### Colour Grading wheels reach different tones and spare colours already leaning their way (process 18) +- The colour grading wheels now tint with a strength and direction that depend on the wheel's hue, reach different + tones (the shadows wheel spares the deepest blacks and reaches into the midtones, the global wheel acts most on the + midtones), and give less tint to colours that already lean its way, so a warm grade no longer oversaturates warm + colours. Blending, Balance and Luminance change with them. This is part of rendering process 18: photos you + already edited keep their look until you choose Photo ▸ Update to Current Process. See + [Colour Grading](grading-stage.md). + +### Colour mixer bands in new places, stronger at large amounts (process 18) +- Each band of the colour mixer now covers different colours (a red-orange such as skin answers to Orange, Blue + reaches further towards aqua and purple), and Hue, Saturation and Luminance act more strongly at large amounts + than at small ones. The mixer now works before Whites, as in Lightroom, where it used to come after it. This is part + of rendering process 18: photos you already edited keep their look until you choose Photo ▸ Update to Current + Process. See [The colour mixer](mixer-stage.md). + +### Broader Whites and parametric curve, hue-preserving tone curves (process 18) +- Whites now reaches into the upper midtones, and the Highlights, Lights, Darks and Shadows regions of the + parametric curve are broader, overlap and add up when several are set. A contrast curve no longer turns orange + towards red: the point curve keeps colours' hue, and the red, green and blue curves act on their channel after it. + This is rendering process 18: new photos (and Reset) get it, photos you already edited keep their look until you + choose Photo ▸ Update to Current Process. See [Whites and the tone curves](curve-stage.md). + ### Apple ProRAW tone chain fitted to Lightroom (process 17) - On Apple ProRAW files with a profile tone curve, the Light sliders now run through a tone chain fitted to Lightroom Classic exports of an iPhone 12 Pro ProRAW, applying the profile curve to colour as well as brightness diff --git a/tools/lr_grading_charts.py b/tools/lr_grading_charts.py new file mode 100644 index 00000000000..c65e3d8d7e6 --- /dev/null +++ b/tools/lr_grading_charts.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +"""Measure Lightroom's Colour Grading on synthetic charts (process V18, docs/grading-stage.md). + + python3 tools/lr_grading_charts.py charts OUT_DIR + Writes linear DNG charts (the grey steps and colour patches of tools/lr_tone_charts.py) with the settings + embedded as XMP: one neutral chart; each wheel (shadows, midtones, highlights, global) at 12 hues x 3 + saturations, at Luminance -100/-50/50/100, at Blending 0/25/75/100 and (not global) at Balance + -100/-50/50/100; and two combinations used only as checks. + (render every DNG through Camera Raw to a 16-bit Adobe RGB (1998) TIFF with the same file name) + python3 tools/lr_grading_charts.py fit RENDER_DIR OUT_RS + Reads the renders, fits LightCraft's model of Colour Grading to them and writes the model's constants + (`lightcraft_pipeline::grading_stage_model`). The measurements themselves are not written out. + +The charts are original test data generated here; nothing in them comes from Adobe. Only Camera Raw's output is +measured. Requires numpy, scipy and tifffile (tools/requirements-lr-tone-charts.txt). + +The model, per wheel: an OkLab tint (a, b) by wheel hue and saturation; a lightness profile (how much of the tint +each lightness gets) by Blending and Balance; a damping of the tint for colours that already lean its way, by their +chroma and the angle between their hue and the tint's; and the wheel's Luminance as a lightness change by lightness. +""" +import json +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from lr_tone_charts import ADOBE_TO_XYZ, chart, write_dng, xmp # noqa: E402 + +WHEELS = { + "shadows": ("SplitToningShadowHue", "SplitToningShadowSaturation", "ColorGradeShadowLum"), + "midtones": ("ColorGradeMidtoneHue", "ColorGradeMidtoneSat", "ColorGradeMidtoneLum"), + "highlights": ("SplitToningHighlightHue", "SplitToningHighlightSaturation", "ColorGradeHighlightLum"), + "global": ("ColorGradeGlobalHue", "ColorGradeGlobalSat", "ColorGradeGlobalLum"), +} +HUES = tuple(range(0, 360, 30)) +SATS = (25, 50, 100) +BLENDS = (0, 25, 50, 75, 100) +BALANCES = (-100, -50, 0, 50, 100) +LUMS = (-100, -50, 50, 100) +CHROMA = (0.04, 0.08, 0.12) +GRID = 65 +# the hue and saturation each wheel is measured at for Blending and Balance +REF_HUE, REF_SAT = 30, 100 + +M1 = np.array([[0.8189330101, 0.3618667424, -0.1288597137], [0.0329845436, 0.9293118715, 0.0361456387], + [0.0482003018, 0.2643662691, 0.6338517070]]) +M2 = np.array([[0.2104542553, 0.793617785, -0.0040720468], [1.9779984951, -2.428592205, 0.4505937099], + [0.0259040371, 0.7827717662, -0.808675766]]) + + +def variants(): + """Name and XMP settings of every chart (neutral, wheels, Luminance, Blending, Balance, checks).""" + v = {"neutral": {}} + for w, (kh, ks, kl) in WHEELS.items(): + for h in HUES: + for s in SATS: + v[f"{w}_h{h}_s{s}"] = {kh: h, ks: s, "ColorGradeBlending": 50} + for lum in (-50, 50): + v[f"{w}_lum{lum:+d}"] = {kl: lum, "ColorGradeBlending": 50} + split = {"SplitToningShadowHue": 52, "SplitToningShadowSaturation": 50, "SplitToningHighlightHue": 220, + "SplitToningHighlightSaturation": 50} + for b in (0, 25, 75, 100): + v[f"blend{b}"] = {**split, "ColorGradeBlending": b} + for bal in (-50, 50): + v[f"balance{bal:+d}"] = {**split, "ColorGradeBlending": 50, "SplitToningBalance": bal} + v["dm_grading"] = {"SplitToningShadowHue": 52, "SplitToningShadowSaturation": 20, "SplitToningHighlightHue": 34, + "SplitToningHighlightSaturation": 0, "SplitToningBalance": 40, "ColorGradeBlending": 100} + v["to_grading"] = {"SplitToningShadowHue": 205, "SplitToningShadowSaturation": 18, "SplitToningHighlightHue": 46, + "SplitToningHighlightSaturation": 80, "ColorGradeMidtoneHue": 45, "ColorGradeMidtoneSat": 22, + "ColorGradeGlobalHue": 46, "ColorGradeGlobalSat": 33, "ColorGradeBlending": 50} + for w, (kh, ks, kl) in WHEELS.items(): + for b in (0, 25, 75, 100): + v[f"{w}_blend{b}"] = {kh: REF_HUE, ks: REF_SAT, "ColorGradeBlending": b} + if w != "global": + for bal in (-100, -50, 50, 100): + v[f"{w}_bal{bal:+d}"] = {kh: REF_HUE, ks: REF_SAT, "ColorGradeBlending": 50, "SplitToningBalance": bal} + for lum in (-100, 100): + v[f"{w}_lum{lum:+d}"] = {kl: lum, "ColorGradeBlending": 50} + return v + + +# ---- tables ------------------------------------------------------------------------------------------------- + +def oklab_patches(path, patches): + """Mean colour of every patch of a Camera Raw render, as OkLab.""" + import tifffile + a = tifffile.imread(path).astype(np.float64) + a /= 65535.0 if a.max() > 255 else 255.0 + out = [] + for q in patches: + rgb = a[q["y"] + 8:q["y"] + q["h"] - 8, q["x"] + 8:q["x"] + q["w"] - 8].reshape(-1, 3).mean(0) + xyz = ADOBE_TO_XYZ @ (np.clip(rgb, 0, 1) ** (563 / 256)) + out.append(M2 @ np.cbrt(np.maximum(M1 @ xyz, 0))) + return np.array(out) + + +def measure(render_dir): + """Measure the Camera Raw renders in `render_dir`: tints, profiles by Blending and by Balance, Luminance curves and + damping per wheel, as dictionaries (kept in memory, never written out).""" + patches = json.load(open(os.path.join(render_dir, "manifest.json")))["patches"] + ok = np.array([p["ok"] for p in patches]) + grey = ok & np.array([p["kind"] == "grey" for p in patches]) + col = ok & np.array([p["kind"] == "colour" for p in patches]) + cache = {} + + def lab(n): + """OkLab patches of render `n`, read once.""" + if n not in cache: + cache[n] = oklab_patches(os.path.join(render_dir, f"grade__{n}.tif"), patches) + return cache[n] + + n0 = lab("neutral") + order = np.argsort(n0[grey][:, 0]) + grey_l = n0[grey][order, 0] + grid = np.linspace(0, 1, GRID) + + def offsets(n): + """(dL, da, db) of the grey steps against neutral, on the lightness grid; towards 0 below the darkest step.""" + d = (lab(n) - n0)[grey][order] + out = np.stack([np.interp(grid, grey_l, d[:, k]) for k in range(3)], 1) + low = grid < grey_l[0] + out[low] *= (grid[low] / grey_l[0])[:, None] + return out + + chroma = np.array([p.get("C", 0) for p in patches])[col] + nc = n0[col] + hue_c = np.arctan2(nc[:, 2], nc[:, 1]) + tint, pblend, pbal, lum, att = {}, {}, {}, {}, {} + for w in WHEELS: + # the profile's shape at Blending 50: mean tint size over the hues at saturation 100, peak 1 + size = np.mean([np.hypot(*offsets(f"{w}_h{h}_s100")[:, 1:].T) for h in HUES], 0) + prof = size / size.max() + for h in HUES: + for s in SATS: + tint[(w, h, s)] = (offsets(f"{w}_h{h}_s{s}") * prof[:, None]).sum(0)[1:] / (prof ** 2).sum() + ref = np.hypot(*tint[(w, REF_HUE, REF_SAT)]) + ref_name = f"{w}_h{REF_HUE}_s{REF_SAT}" + for b in BLENDS: + pblend[(w, b)] = np.hypot(*offsets(ref_name if b == 50 else f"{w}_blend{b}")[:, 1:].T) / ref + for a in BALANCES: + if w == "global": + pbal[(w, a)] = pblend[(w, 50)] + else: + pbal[(w, a)] = np.hypot(*offsets(ref_name if a == 0 else f"{w}_bal{a:+d}")[:, 1:].T) / ref + for v in LUMS: + lum[(w, v)] = offsets(f"{w}_lum{v:+d}")[:, 0] + # damping: the colour patches' change along the grey steps' tint, by chroma level and angle (6 x 30 degrees) + acc, cnt = np.zeros((3, 6)), np.zeros((3, 6)) + for h in HUES: + name = f"{w}_h{h}_s100" + d = (lab(name) - n0)[col] + g = offsets(name) + gd = np.stack([np.interp(nc[:, 0], grid, g[:, k]) for k in range(3)], 1) + mag = np.hypot(gd[:, 1], gd[:, 2]) + m = mag > 0.01 + u = gd[:, 1:] / np.maximum(mag, 1e-9)[:, None] + proj = (d[:, 1:] * u).sum(1) / np.maximum(mag, 1e-9) + ang = np.degrees(np.abs((hue_c - np.arctan2(gd[:, 2], gd[:, 1]) + np.pi) % (2 * np.pi) - np.pi)) + for i, c in enumerate(CHROMA): + for j in range(6): + k = m & (chroma == c) & (ang >= j * 30) & (ang < j * 30 + 30) + if k.any(): + acc[i, j] += np.median(proj[k]) + cnt[i, j] += 1 + att[w] = np.where(cnt > 0, acc / np.maximum(cnt, 1), 1.0) + + return tint, pblend, pbal, lum, att + + +# ---- fit ---------------------------------------------------------------------------------------------------- +# +# LightCraft's own model of Colour Grading, fitted to the measurements above. Nothing measured is written out: only +# the model's constants (docs/grading-stage.md has the formulas). +# +# - Tint: the same shape around the hue circle for every wheel, a Fourier series of the wheel hue for the tint's +# direction (offset from the wheel hue) and for its log size, times a size per wheel and a saturation curve per +# wheel: size(s) = s (1 + g1 (s - 1) + g2 (s - 1)^2), s = saturation / 100. +# - Share by lightness: two bumps (as the tone curve stage's), whose gain and exponents are quadratic in Blending and +# in Balance. +# - Luminance: two bumps per direction, gain and exponents changing with the amount. +# - Damping: 1 + (C / 0.12)^exp(e) (d0 + d1 cos a + d2 cos 2a), a the angle between the colour's hue and the tint's. + +HARMONICS = 4 +FIT_SEED = 3 +FIT_STARTS = 24 + + +def fourier(c, h): + """c0 + sum of c[2k-1] cos(k h) + c[2k] sin(k h).""" + return c[0] + sum(c[2 * k - 1] * np.cos(k * h) + c[2 * k] * np.sin(k * h) for k in range(1, (len(c) - 1) // 2 + 1)) + + +def bump(x, p, q): + """A bump of peak 1 at p / (p + q), 0 at black and white.""" + m = p / (p + q) + return np.exp(p * np.log(np.clip(x, 1e-12, 1) / m) + q * np.log(np.clip(1 - x, 1e-12, 1) / (1 - m))) + + +def tint_model(params, hue, sat): + """Tints (wheel, hue, saturation, a/b) for hues in radians and saturations 0..1.""" + n = 2 * HARMONICS + 1 + angle = hue + fourier(params[:n], hue) + size = np.exp(fourier(params[n:2 * n], hue)) + out = np.zeros((4, len(hue), len(sat), 2)) + for w in range(4): + scale, g1, g2 = np.exp(params[2 * n + w]), params[2 * n + 4 + 2 * w], params[2 * n + 5 + 2 * w] + for i, s in enumerate(sat): + m = scale * size * s * (1 + g1 * (s - 1) + g2 * (s - 1) ** 2) + out[w, :, i] = np.stack([m * np.cos(angle), m * np.sin(angle)], 1) + return out + + +def share_model(params, blend, balance, light): + """Share of the tint at lightness `light` for Blending and Balance as fractions (Blending 0.5 and Balance 0 at the default).""" + b, c = blend - 0.5, balance + out = 0.0 + for k in range(2): + q = params[15 * k:15 * k + 15] + f = lambda i: q[i] + q[i + 1] * b + q[i + 2] * b * b + q[i + 3] * c + q[i + 4] * c * c + out = out + f(0) * bump(light, np.exp(f(5)), np.exp(f(10))) + return out + + +def lum_model(params, amount, light): + """Lightness change at `light` for Luminance `amount` (-1..1).""" + a, side = abs(amount), 0 if amount < 0 else 1 + out = 0.0 + for k in range(2): + q = params[12 * side + 6 * k:12 * side + 6 * k + 6] + out = out + (q[0] * a + q[1] * a * a) * bump(light, np.exp(q[2] + q[3] * a), np.exp(q[4] + q[5] * a)) + return np.sign(amount) * out + + +def damping_model(params, chroma, angle): + """Share of the tint a colour of `chroma` gets at `angle` (radians) from the tint's direction.""" + d0, d1, d2, e = params + return 1 + (chroma / 0.12) ** np.exp(e) * (d0 + d1 * np.cos(angle) + d2 * np.cos(2 * angle)) + + +def multistart(residual, starts): + """The best least-squares solution over `starts`.""" + from scipy.optimize import least_squares + return min((least_squares(residual, s, max_nfev=4000) for s in starts), key=lambda r: r.cost).x + + +def fit_share(job): + """One wheel's share profiles (by Blending, by Balance) on the lightness grid.""" + blends, balances, light = job + def residual(p): + return np.concatenate([share_model(p, b, 0.0, light) - v for b, v in blends] + + [share_model(p, 0.5, a, light) - v for a, v in balances]) * 100 + rng = np.random.default_rng(FIT_SEED) + starts = [] + for _ in range(FIT_STARTS): + s = np.zeros(30) + for k in range(2): + s[15 * k], s[15 * k + 5], s[15 * k + 10] = rng.uniform(0.2, 1), rng.uniform(-1, 2.5), rng.uniform(-1, 2.5) + starts.append(s) + return multistart(residual, starts) + + +def fit_lum(job): + """One wheel's Luminance responses on the lightness grid.""" + lums, light = job + residual = lambda p: np.concatenate([lum_model(p, a, light) - v for a, v in lums]) * 100 + rng = np.random.default_rng(FIT_SEED) + starts = [] + for _ in range(FIT_STARTS): + s = np.zeros(24) + for side in range(2): + for k in range(2): + o = 12 * side + 6 * k + s[o], s[o + 2], s[o + 4] = rng.uniform(0, 0.1), rng.uniform(-1, 2.5), rng.uniform(-1, 2.5) + starts.append(s) + return multistart(residual, starts) + + +def fit_damping(table): + """One wheel's damping (chroma level x 6 angle bins) as 4 constants.""" + angle = np.radians(np.arange(15, 180, 30)) + c = np.array(CHROMA)[:, None] + return multistart(lambda p: (damping_model(p, c, angle[None, :]) - table).ravel() * 100, [np.zeros(4)]) + + +def fit(render_dir, out_rs): + """Fit the model to the Camera Raw renders in `render_dir` and write its constants to `out_rs`.""" + from concurrent.futures import ProcessPoolExecutor + tint, pblend, pbal, lum, att = measure(render_dir) + names = list(WHEELS) + light = np.linspace(0, 1, GRID) + hue, sat = np.radians(np.array(HUES, float)), np.array(SATS) / 100 + measured = np.array([[[tint[(w, h, s)] for s in SATS] for h in HUES] for w in names]) + n = 2 * HARMONICS + 1 + start = np.zeros(2 * n + 12) + start[n] = np.log(np.hypot(*measured.reshape(-1, 2).T).mean()) + tp = multistart(lambda p: ((tint_model(p, hue, sat) - measured) * 100).ravel(), [start]) + e = np.linalg.norm(tint_model(tp, hue, sat) - measured, axis=-1) * 100 + print(f"tint: rms {np.sqrt((e ** 2).mean()):.3f} of {np.linalg.norm(measured, axis=-1).mean() * 100:.3f} (OkLab x 100)") + share_jobs = [([(b / 100, pblend[(w, b)]) for b in BLENDS], [] if w == "global" else [(a / 100, pbal[(w, a)]) for a in BALANCES], light) + for w in names] + lum_jobs = [([(v / 100, lum[(w, v)]) for v in LUMS], light) for w in names] + with ProcessPoolExecutor() as pool: + shares = list(pool.map(fit_share, share_jobs)) + lums = list(pool.map(fit_lum, lum_jobs)) + damps = [fit_damping(att[w]) for w in names] + for i, w in enumerate(names): + blends, balances, _ = share_jobs[i] + es = np.concatenate([share_model(shares[i], b, 0.0, light) - v for b, v in blends] + + [share_model(shares[i], 0.5, a, light) - v for a, v in balances]) * 100 + el = np.concatenate([lum_model(lums[i], a, light) - v for a, v in lum_jobs[i][0]]) * 100 + ed = (damping_model(damps[i], np.array(CHROMA)[:, None], np.radians(np.arange(15, 180, 30))[None, :]) - att[w]) * 100 + print(f"{w:10s} share rms {np.sqrt((es ** 2).mean()):.2f} (x 100), Luminance rms {np.sqrt((el ** 2).mean()):.3f} (OkLab L x 100), " + f"damping rms {np.sqrt((ed ** 2).mean()):.2f} (x 100)") + num = lambda v: f"{v:.6e}" + row = lambda vs: "[" + ", ".join(num(v) for v in vs) + "]" + s = ["// Written by `tools/lr_grading_charts.py fit`: LightCraft's model of Colour Grading, fitted to the tool's charts", + "// (provenance in docs/grading-stage.md). Constants of the model only. Wheels: shadows, midtones, highlights, global.", + "", + "/// The tint's direction around the hue circle, as an offset from the wheel hue (radians): a Fourier series of the", + "/// wheel hue, `c0 + c1 cos h + c2 sin h + c3 cos 2h + ...`.", + f"pub const TINT_ANGLE: [f64; {n}] = {row(tp[:n])};", + "/// The tint's log size around the hue circle, the same kind of series.", + f"pub const TINT_SIZE: [f64; {n}] = {row(tp[n:2 * n])};", + "/// Each wheel's log size, added to [`TINT_SIZE`].", + f"pub const WHEEL_SIZE: [f64; 4] = {row(tp[2 * n:2 * n + 4])};", + "/// Each wheel's saturation curve `[g1, g2]`: size `s (1 + g1 (s - 1) + g2 (s - 1)²)` at saturation `s` (0 to 1).", + "pub const WHEEL_SAT: [[f64; 2]; 4] = [" + ", ".join(row(tp[2 * n + 4 + 2 * w:2 * n + 6 + 2 * w]) for w in range(4)) + "];", + "/// Each wheel's share of the tint by lightness: two bumps of 15 constants, `[g, gb, gb2, gc, gc2, p, pb, ..., q, ...]`,", + "/// each value quadratic in Blending (`b` = Blending / 100 - 0.5) and Balance (`c` = Balance / 100).", + "pub const SHARE: [[f64; 30]; 4] = [", + *[f" {row(p)}," for p in shares], + "];", + "/// Each wheel's Luminance, negative then positive: two bumps of `[g1, g2, p0, p1, q0, q1]` each.", + "pub const LUM: [[f64; 24]; 4] = [", + *[f" {row(p)}," for p in lums], + "];", + "/// Each wheel's damping `[d0, d1, d2, e]`: `1 + (C / 0.12)^exp(e) (d0 + d1 cos a + d2 cos 2a)`.", + "pub const DAMPING: [[f64; 4]; 4] = [" + ", ".join(row(p) for p in damps) + "];", + ""] + with open(out_rs, "w") as f: + f.write("\n".join(s)) + + +def main(): + """Command line: `charts OUT_DIR` or `fit RENDER_DIR OUT_RS`.""" + if len(sys.argv) == 3 and sys.argv[1] == "charts": + out = sys.argv[2] + os.makedirs(out, exist_ok=True) + img, patches = chart() + json.dump(dict(patches=patches), open(os.path.join(out, "manifest.json"), "w")) + for name, settings in variants().items(): + write_dng(os.path.join(out, f"grade__{name}.dng"), img, xmp(**settings)) + elif len(sys.argv) == 4 and sys.argv[1] == "fit": + fit(sys.argv[2], sys.argv[3]) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main() diff --git a/tools/lr_mixer_charts.py b/tools/lr_mixer_charts.py new file mode 100644 index 00000000000..5fe441253c4 --- /dev/null +++ b/tools/lr_mixer_charts.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Measure Lightroom's colour mixer on synthetic colour charts (process V18, docs/mixer-stage.md). + + python3 tools/lr_mixer_charts.py charts OUT_DIR + Writes linear DNG charts (OkLCh patches: 72 hues x 3 chroma x 3 lightness levels) with the settings embedded + as XMP: one neutral chart and every mixer band's Hue, Saturation and Luminance at -100, -75, -50, -25, 25, + 50, 75 and 100. + (render every DNG through Camera Raw to a 16-bit Adobe RGB (1998) TIFF with the same file name) + python3 tools/lr_mixer_charts.py fit RENDER_DIR OUT_RS [CHART_DIR] + Reads the renders (and the charts' `mixer__manifest.json` from CHART_DIR, by default RENDER_DIR), fits LightCraft's model of each mixer slider to them and writes the model's constants + (`lightcraft_pipeline::mixer_stage_model`). The measurements themselves are not written out. + +The charts are original test data generated here; nothing in them comes from Adobe. Only Camera Raw's output is +measured. Requires numpy, scipy and tifffile (tools/requirements-lr-tone-charts.txt). +""" +import json +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from lr_tone_charts import ADOBE_TO_XYZ, H, W, write_dng, xmp # noqa: E402 + +CELL = 60 +BANDS = ("Red", "Orange", "Yellow", "Green", "Aqua", "Blue", "Purple", "Magenta") +MIXER = (("Hue", "HueAdjustment"), ("Sat", "SaturationAdjustment"), ("Lum", "LuminanceAdjustment")) +AMOUNTS = (-100, -75, -50, -25, 25, 50, 75, 100) +LIGHTNESS = (0.45, 0.62, 0.78) +CHROMA = (0.04, 0.08, 0.13) +HUES = 72 + +# OkLab (Ottosson): XYZ (D65) -> LMS, cube root, -> Lab +M1 = np.array([[0.8189330101, 0.3618667424, -0.1288597137], [0.0329845436, 0.9293118715, 0.0361456387], + [0.0482003018, 0.2643662691, 0.6338517070]]) +M2 = np.array([[0.2104542553, 0.793617785, -0.0040720468], [1.9779984951, -2.428592205, 0.4505937099], + [0.0259040371, 0.7827717662, -0.808675766]]) +SRGB_TO_XYZ = np.array([[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]]) + + +def chart(): + """OkLCh patches, hue in 5 degree steps x 3 chroma x 3 lightness levels; patches outside sRGB are left out.""" + m2i, m1i, x2s = np.linalg.inv(M2), np.linalg.inv(M1), np.linalg.inv(SRGB_TO_XYZ) + cols = W // CELL + img = np.full((H, W, 3), 0.18) + patches = [] + for lightness in LIGHTNESS: + for chroma in CHROMA: + for hue in range(0, 360, 360 // HUES): + i = len(patches) + x, y = (i % cols) * CELL, (i // cols) * CELL + h = np.radians(hue) + c = x2s @ (m1i @ ((m2i @ np.array([lightness, chroma * np.cos(h), chroma * np.sin(h)])) ** 3)) + ok = bool(np.all(c >= 0) and np.all(c <= 1)) + if ok: + img[y + 6:y + CELL - 6, x + 6:x + CELL - 6] = c + patches.append(dict(y=y + 6, x=x + 6, w=CELL - 12, h=CELL - 12, L=lightness, C=chroma, hue=hue, ok=ok)) + return img, patches + + +def sliders(): + """(chart name stem, XMP key) per slider, in the table's order: mixer bands x (Hue, Sat, Lum).""" + return [(f"mix_{b}{p}", k + b) for b in BANDS for p, k in MIXER] + + +def variants(): + """Name and XMP settings of every chart: neutral, then each mixer slider at each amount.""" + v = {"neutral": {}} + for stem, key in sliders(): + for a in AMOUNTS: + v[f"{stem}{a:+d}"] = {key: a} + return v + + +# ---- table -------------------------------------------------------------------------------------------------- + +def oklab_patches(path, patches): + """Mean colour of each in-gamut patch of a Camera Raw render, as OkLab.""" + import tifffile + a = tifffile.imread(path).astype(np.float64) + a /= 65535.0 if a.max() > 255 else 255.0 + out = [] + for q in patches: + rgb = a[q["y"] + 10:q["y"] + q["h"] - 10, q["x"] + 10:q["x"] + q["w"] - 10].reshape(-1, 3).mean(0) + xyz = ADOBE_TO_XYZ @ (np.clip(rgb, 0, 1) ** (563 / 256)) + out.append(M2 @ np.cbrt(M1 @ xyz)) + return np.array(out) + + +def by_hue(hue, values): + """Mean of `values` per 5 degree hue bin, bins without a patch interpolated around the circle; and which bins had one.""" + bins = np.arange(0, 360, 360 // HUES) + centres, means, have = [], [], np.zeros(HUES, bool) + for i, b in enumerate(bins): + k = ((hue - b + 2.5) % 360) < 5 + if k.any(): + centres.append(b) + means.append(values[k].mean(0)) + have[i] = True + centres, means = np.array(centres, float), np.array(means) + return np.stack([np.interp(bins, centres, means[:, o], period=360) for o in range(3)], 1), have + + +def response(lab0, lab, light, chroma): + """Hue shift (degrees), relative chroma change and lightness change of each chart setting against neutral, + per lightness and chroma level and hue bin: shape (9, 3, 72).""" + hue0 = np.degrees(np.arctan2(lab0[:, 2], lab0[:, 1])) % 360 + c0 = np.hypot(lab0[:, 1], lab0[:, 2]) + hue = np.degrees(np.arctan2(lab[:, 2], lab[:, 1])) % 360 + r = np.stack([(hue - hue0 + 180) % 360 - 180, np.hypot(lab[:, 1], lab[:, 2]) / c0 - 1, lab[:, 0] - lab0[:, 0]], 1) + out = np.zeros((9, 3, HUES)) + for ci, cv in enumerate(CHROMA): + m = chroma == cv + base, _ = by_hue(hue0[m], r[m]) + for li, lv in enumerate(LIGHTNESS): + m2 = m & (light == lv) + if m2.sum() < 6: + out[li * 3 + ci] = base.T + continue + c, have = by_hue(hue0[m2], r[m2]) + # hue bins without an in-gamut patch at this lightness: blend smoothly towards the all-lightness curve + w = np.convolve(np.r_[have[-3:], have, have[:3]].astype(float), np.ones(7) / 7, "same")[3:-3] + out[li * 3 + ci] = (c * w[:, None] + base * (1 - w[:, None])).T + return out + + +# ---- fit ---------------------------------------------------------------------------------------------------- +# +# LightCraft's own model of the colour mixer, fitted to the measured chart responses. Nothing measured is written +# out: only the model's 168 constants. For slider `kind` (Hue, Saturation, Luminance) of band `b` and output `o` (hue +# shift in degrees, relative chroma change, lightness change), with t = amount / 100, dc = (C - 0.09) / 0.05 and +# dl = (L - 0.75) / 0.15 for an OkLCh colour: +# +# response = amp[b][kind][o] * gain[kind][o](t) * band[b](h) * exp(ac dc + al dl) +# gain(t) = g1 |t| + g2 t^2 + g3 |t|^3 (g4..g6 for positive amounts) +# band(h) = exp(-z^2 / 2), z = wrap(h - centre) / e^(left or right) +# +# Each band's centre and widths are shared by its three sliders; each kind's gain curve and level dependence are +# shared by all bands. + +FIT_C, FIT_L = (0.09, 0.05), (0.75, 0.15) +CENTRES = (10, 50, 95, 140, 180, 255, 320, 350) + + +def unpack(p): + """(bands 8 x [centre, left, right], kinds 3 x 3 x [g1..g6, ac, al], amps 8 x 3 x 3).""" + return p[:24].reshape(8, 3), p[24:96].reshape(3, 3, 8), p[96:168].reshape(8, 3, 3) + + +def model(p, t, dc, dl): + """The responses (slider, output, amount, level, hue) at amounts `t` and level coordinates `dc`, `dl`.""" + bands, kinds, amps = unpack(p) + hue = np.arange(HUES) * (360 / HUES) + at, neg = np.abs(t), t < 0 + out = np.zeros((24, 3, len(t), len(dc), HUES)) + for b in range(8): + centre, left, right = bands[b] + d = (hue - centre + 180) % 360 - 180 + shape = np.exp(-0.5 * (d / np.exp(np.where(d < 0, left, right))) ** 2) + for k in range(3): + for o in range(3): + g = kinds[k, o] + gain = np.where(neg, g[0] * at + g[1] * at ** 2 + g[2] * at ** 3, g[3] * at + g[4] * at ** 2 + g[5] * at ** 3) + level = np.exp(g[6] * dc + g[7] * dl) + out[b * 3 + k, o] = amps[b, k, o] * gain[:, None, None] * level[None, :, None] * shape[None, None, :] + return out + + +def fit_model(measured, chroma, dc, dl): + """Fit the model to the measured responses (slider, amount, level, output, hue); returns the constants.""" + from scipy.optimize import least_squares + t = np.array(AMOUNTS) / 100 + + def oklab(v, o): + """A response in OkLab x 100 at each level's chroma: hue shift and chroma change scale with chroma.""" + return (np.radians(v) * chroma[None, :, None] if o == 0 else v * chroma[None, :, None] if o == 1 else v) * 100 + + target = np.stack([np.stack([oklab(measured[s, :, :, o], o) for o in range(3)]) for s in range(24)]) + + def residual(p): + m = model(p, t, dc, dl) + return (np.stack([np.stack([oklab(m[s, o], o) for o in range(3)]) for s in range(24)]) - target).ravel() + + kinds = np.zeros((3, 3, 8)) + # starting signs and sizes: each kind's main output, then its smaller side effects + for (k, o), (neg, pos) in {(0, 0): (-40, 40), (0, 1): (0.1, 0.1), (0, 2): (0.01, 0.01), (1, 0): (1, -1), (1, 1): (-0.6, 0.6), + (1, 2): (0.01, -0.01), (2, 0): (1, -1), (2, 1): (0.1, -0.1), (2, 2): (-0.1, 0.1)}.items(): + kinds[k, o, 0], kinds[k, o, 3] = neg, pos + p0 = np.r_[np.ravel([[c, 3.0, 3.0] for c in CENTRES]), kinds.ravel(), np.ones(72)] + return least_squares(residual, p0, max_nfev=3000).x, residual + + +def fit(render_dir, out_rs, chart_dir=None): + """Fit the model to the Camera Raw renders in `render_dir` and write its constants to `out_rs`.""" + # the manifest carries the tool's prefix, as its charts do, so another chart tool's in the same folder is left alone + manifest = os.path.join(chart_dir or render_dir, "mixer__manifest.json") + patches = [p for p in json.load(open(manifest))["patches"] if p["ok"]] + tif = lambda n: os.path.join(render_dir, f"mixer__{n}.tif") + lab0 = oklab_patches(tif("neutral"), patches) + light = np.array([p["L"] for p in patches]) + chroma = np.array([p["C"] for p in patches]) + c0 = np.hypot(lab0[:, 1], lab0[:, 2]) + # each level's chroma and lightness on Camera Raw's neutral render (it desaturates bright colours), as the fit's + # coordinates of the measured rows + level_c, level_l = [], [] + for v in LIGHTNESS: + for c in CHROMA: + m = (light == v) & (chroma == c) + level_c.append(float(c0[m].mean() if m.sum() else c0[chroma == c].mean())) + level_l.append(float(lab0[light == v, 0].mean())) + level_c, level_l = np.array(level_c), np.array(level_l) + dc, dl = (level_c - FIT_C[0]) / FIT_C[1], (level_l - FIT_L[0]) / FIT_L[1] + stems = [n for n, _ in sliders()][:24] + measured = np.stack([np.stack([response(lab0, oklab_patches(tif(f"{stem}{a:+d}"), patches), light, chroma) for a in AMOUNTS]) + for stem in stems]) + params, residual = fit_model(measured, level_c, dc, dl) + e = residual(params).reshape(24, 3, -1) + for i, stem in enumerate(stems): + print(f"{stem:22s} rms " + " ".join(f"{np.sqrt((e[i, o] ** 2).mean()):.3f}" for o in range(3)) + " (hue, chroma, lightness; OkLab x 100)") + bands, kinds, amps = unpack(params) + num = lambda v: f"{v:.6e}" + row = lambda vs: "[" + ", ".join(num(v) for v in vs) + "]" + s = ["// Written by `tools/lr_mixer_charts.py fit`: LightCraft's model of the colour mixer, fitted to the tool's OkLCh", + "// charts (provenance in docs/mixer-stage.md). Constants of the model only.", + "", + "/// The model's reference chroma and lightness: `dc = (C - centre) / scale`, `dl` likewise.", + f"pub const REF_CHROMA: (f64, f64) = ({FIT_C[0]}, {FIT_C[1]});", + f"pub const REF_LIGHT: (f64, f64) = ({FIT_L[0]}, {FIT_L[1]});", + "", + "/// Per band (Red, Orange, Yellow, Green, Aqua, Blue, Purple, Magenta): centre (OkLab hue, degrees), and the log", + "/// width below and above it.", + "pub const BANDS: [[f64; 3]; 8] = [" + ", ".join(row(b) for b in bands) + "];", + "/// Per kind of slider (Hue, Saturation, Luminance) and output (hue shift, chroma change, lightness change):", + "/// `[g1, g2, g3, g4, g5, g6, ac, al]`, the gain over the amount and the dependence on chroma and lightness.", + "pub const KINDS: [[[f64; 8]; 3]; 3] = [", + *[f" [{', '.join(row(o) for o in k)}]," for k in kinds], + "];", + "/// Per band, kind and output: the amplitude.", + "pub const AMPS: [[[f64; 3]; 3]; 8] = [", + *[f" [{', '.join(row(k) for k in a)}]," for a in amps], + "];", + ""] + with open(out_rs, "w") as f: + f.write("\n".join(s)) + + +def main(): + """Command line: `charts OUT_DIR` or `fit RENDER_DIR OUT_RS [CHART_DIR]`.""" + if len(sys.argv) == 3 and sys.argv[1] == "charts": + out = sys.argv[2] + os.makedirs(out, exist_ok=True) + img, patches = chart() + json.dump(dict(patches=patches), open(os.path.join(out, "mixer__manifest.json"), "w")) + for name, settings in variants().items(): + write_dng(os.path.join(out, f"mixer__{name}.dng"), img, xmp(**settings)) + elif len(sys.argv) in (4, 5) and sys.argv[1] == "fit": + fit(*sys.argv[2:]) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main() diff --git a/tools/lr_tone_charts.py b/tools/lr_tone_charts.py new file mode 100644 index 00000000000..85bb6656c1b --- /dev/null +++ b/tools/lr_tone_charts.py @@ -0,0 +1,367 @@ +#!/usr/bin/env python3 +"""Measure Lightroom's Whites and parametric curve on synthetic grey steps (process V18, docs/curve-stage.md). + + python3 tools/lr_tone_charts.py charts OUT_DIR + Writes linear DNG charts (48 grey steps plus colour patches) with the settings embedded as XMP: + one neutral chart, Whites at +-25/50/100 and each parametric region at +-25/50/75/100 (default splits). + (render every DNG through Camera Raw to a 16-bit Adobe RGB (1998) TIFF with the same file name) + python3 tools/lr_tone_charts.py fit RENDER_DIR OUT_RS [CHART_DIR] + Reads the renders (and the charts' `curve__manifest.json` from CHART_DIR, by default RENDER_DIR), fits LightCraft's model of each setting to them and writes the model's constants + (`lightcraft_pipeline::curve_stage_model`). The measurements themselves are not written out. + python3 tools/lr_tone_charts.py base RENDER_DIR OUT_RS [CHART_DIR] + Reads the neutral render (and the manifest, as `fit` does), fits the default base curve's knots to its grey steps and writes them + (`lightcraft_pipeline::default_tone_model`, docs/default-tone.md). The grey steps are not written out. + +The charts are original test data generated here; nothing in them comes from Adobe. Only Camera Raw's output is +measured. Requires numpy, scipy and tifffile (tools/requirements-lr-tone-charts.txt). +""" +import json +import os +import struct +import sys + +import numpy as np + +W, H = 2400, 1600 +CELL = 60 +# linear sRGB -> XYZ (D65) inverse, stored as the DNG's ColorMatrix1 so the chart decodes as scene-linear sRGB +XYZ_TO_SRGB = [[3.2404542, -1.5371385, -0.4985314], [-0.969266, 1.8760108, 0.041556], [0.0556434, -0.2040259, 1.0572252]] +WHITES = (-100, -50, -25, 25, 50, 100) +REGIONS = ("Shadows", "Darks", "Lights", "Highlights") +REGION_AMOUNTS = (-100, -75, -50, -25, 25, 50, 75, 100) + + +def xmp(**settings): + """Camera Raw settings with everything else neutral (no sharpening, noise reduction, lens or vignette correction).""" + d = dict(CameraProfile="Embedded", WhiteBalance="As Shot", Exposure2012="0.00", Contrast2012="0", Highlights2012="0", + Shadows2012="0", Whites2012="0", Blacks2012="0", ToneCurveName2012="Linear", Sharpness="0", LuminanceSmoothing="0", + ColorNoiseReduction="0", LensProfileEnable="0", PostCropVignetteAmount="0", VignetteAmount="0", Texture="0", + Clarity2012="0", Dehaze="0", Vibrance="0", Saturation="0") + d.update({k: str(v) for k, v in settings.items()}) + attrs = " ".join(f'crs:{k}="{v}"' for k, v in d.items()) + return ('' + '').encode("utf8") + + +def write_dng(path, img, xm): + """A minimal linear (LinearRaw) DNG: `img` is scene-linear RGB 0..1, height x width x 3.""" + h, w = img.shape[:2] + px = (np.clip(img, 0, 1) * 65535 + 0.5).astype(" linear sRGB as the exact inverse of the sRGB primaries' matrix (the patches' colours) + x2s = np.linalg.inv(np.array([[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]])) + img = np.full((H, W, 3), 0.18) + patches = [] + + def put(c, **k): + """Place patch colour `c` in the next cell; a colour outside 0..1 is listed but left black.""" + i = len(patches) + x, y = (i % (W // CELL)) * CELL, (i // (W // CELL)) * CELL + ok = bool(np.all(c >= 0) and np.all(c <= 1)) + if ok: + img[y + 6:y + CELL - 6, x + 6:x + CELL - 6] = c + patches.append(dict(y=y + 6, x=x + 6, w=CELL - 12, h=CELL - 12, ok=ok, **k)) + + for g in np.geomspace(0.002, 1, 48): + put(np.array([g, g, g]), kind="grey", v=float(g)) + for lightness in (0.25, 0.4, 0.55, 0.7, 0.82, 0.92): + for chroma in (0.04, 0.08, 0.12): + for hue in range(0, 360, 15): + lab = np.array([lightness, chroma * np.cos(np.radians(hue)), chroma * np.sin(np.radians(hue))]) + put(x2s @ (m1i @ ((m2i @ lab) ** 3)), kind="colour", L=lightness, C=chroma, hue=hue) + return img, patches + + +def variants(): + """Name and XMP settings of every chart: neutral, each Whites amount, each region amount.""" + v = {"neutral": {}} + for a in WHITES: + v[f"whites{a:+d}"] = {"Whites2012": a} + for r in REGIONS: + for a in REGION_AMOUNTS: + v[f"par_{r.lower()}{a:+d}"] = {"Parametric" + r: a} + return v + + +# ---- measuring ---------------------------------------------------------------------------------------------- + +ADOBE_TO_XYZ = np.array([[0.5767309, 0.1855540, 0.1881852], [0.2973769, 0.6273491, 0.0752741], [0.0270343, 0.0706872, 0.9911085]]) +# XYZ (D65) -> linear ProPhoto RGB (D50, Bradford), as `RgbSpace::to_space` +XYZ_TO_PROPHOTO = (np.array([[1.3459433, -0.2556075, -0.0511118], [-0.5445989, 1.5081673, 0.0205351], [0.0, 0.0, 1.2118128]]) + @ np.array([[1.0478112, 0.0228866, -0.0501270], [0.0295424, 0.9904844, -0.0170491], + [-0.0092345, 0.0150436, 0.7521316]])) + + +def srgb_encode(v): + """Linear to sRGB-encoded values.""" + v = np.clip(v, 0, None) + return np.where(v <= 0.0031308, v * 12.92, 1.055 * v ** (1 / 2.4) - 0.055) + + +ADOBE_RGB_NAME = "Adobe RGB (1998)" + + +def read_render(path): + """A Camera Raw render as RGB 0..1, after checking it is the 16-bit Adobe RGB (1998) TIFF the fit assumes. + + Another export setting would still give plausible numbers, but wrong ones, so it is refused. + """ + import tifffile + with tifffile.TiffFile(path) as t: + page = t.pages[0] + icc = page.tags.get(34675) # InterColorProfile + profile = bytes(icc.value) if icc is not None else b"" + a = page.asarray() + if a.dtype != np.uint16 or a.ndim != 3 or a.shape[2] != 3: + raise SystemExit(f"{path}: expected a 16-bit RGB TIFF, got {a.dtype} {a.shape}") + # the profile's description: ASCII in ICC v2, UTF-16 in v4 + if not any(n in profile for n in (ADOBE_RGB_NAME.encode(), ADOBE_RGB_NAME.encode("utf-16-be"))): + raise SystemExit(f"{path}: expected an embedded {ADOBE_RGB_NAME} profile (export from Camera Raw in that colour space)") + return a.astype(np.float64) / 65535.0 + + +def grey_levels(path, patches): + """The grey steps of a Camera Raw render as sRGB-encoded linear ProPhoto values (the curve stage's domain).""" + a = read_render(path) + out = [] + for q in patches: + if q["kind"] != "grey" or not q["ok"]: + continue + rgb = a[q["y"] + 8:q["y"] + q["h"] - 8, q["x"] + 8:q["x"] + q["w"] - 8].reshape(-1, 3).mean(0) + xyz = ADOBE_TO_XYZ @ (np.clip(rgb, 0, 1) ** (563 / 256)) + out.append(srgb_encode((XYZ_TO_PROPHOTO @ xyz)[1])) + return np.array(out) + + +def delta_table(neutral, edited): + """Output minus input over 257 evenly spaced inputs, from matched grey steps; zero at both ends.""" + o = np.argsort(neutral) + x, y = neutral[o], np.maximum.accumulate(edited[o]) + grid = np.linspace(0, 1, 257) + d = np.interp(grid, x, y - x) + lo, hi = grid < x[0], grid > x[-1] + d[lo] = np.interp(grid[lo], [0, x[0]], [0, d[~lo][0]]) + d[hi] = np.interp(grid[hi], [x[-1], 1], [d[~hi][-1], 0]) + return d + + +# ---- fit ---------------------------------------------------------------------------------------------------- +# +# LightCraft's own model of each setting, fitted to the measured grey steps. Nothing measured is written out: only +# the model's constants. Per slider direction (negative, positive) the response (output minus input) is the sum of +# two bumps, each with a gain over the amount and a shape whose position and width change with the amount: +# +# t = |amount| / 100 +# response(x) = sum over the two bumps of (a1 t + a2 t^2 + a3 t^3) * bump(x, e^(p0 + p1 t), e^(q0 + q1 t)) +# bump(x, p, q) = (x / m)^p ((1 - x) / (1 - m))^q with m = p / (p + q): 0 at black and white, 1 at its peak m +# +# The fit keeps every response growing with the amount at every input, and never acting against the slider. + +FIT_SEED = 7 +FIT_STARTS = 16 +FIT_AMOUNTS = np.linspace(0, 1, 21) +GRID = np.linspace(0, 1, 257) + + +def bump(x, p, q): + """A bump of peak 1 at p / (p + q), 0 at black and white.""" + m = p / (p + q) + return np.exp(p * np.log(np.clip(x, 1e-12, 1) / m) + q * np.log(np.clip(1 - x, 1e-12, 1) / (1 - m))) + + +def response(params, t, x=GRID): + """The model's response of one slider direction at amount `t` (0..1) for inputs `x`.""" + out = 0.0 + for a1, a2, a3, p0, p1, q0, q1 in np.reshape(params, (2, 7)): + out = out + (a1 * t + a2 * t * t + a3 * t ** 3) * bump(x, np.exp(p0 + p1 * t), np.exp(q0 + q1 * t)) + return out + + +def fit_direction(amounts, deltas, sign): + """Fit one slider direction to its measured deltas (257 inputs each); returns the constants and the error.""" + from scipy.optimize import least_squares + rows = [(abs(a) / 100, d) for a, d in zip(amounts, deltas) if np.sign(a) == sign] + + def err(params): + """Error of the rendered curve in 8-bit levels, both sides clamped to 0..1 as the stage clamps.""" + return np.concatenate([(np.clip(GRID + response(params, t), 0, 1) - np.clip(GRID + d, 0, 1)) * 255 for t, d in rows]) + + def residual(params): + grow = np.array([sign * response(params, t) for t in FIT_AMOUNTS]) + return np.concatenate([err(params), 30 * 255 * np.minimum(np.diff(grow, axis=0), 0).ravel(), + 30 * 255 * np.minimum(grow, 0).ravel()]) + + rng = np.random.default_rng(FIT_SEED) + starts = [np.ravel([[sign * rng.uniform(0, 0.3), 0, 0, rng.uniform(-1.5, 2.5), 0, rng.uniform(-1.5, 2.5), 0] + for _ in range(2)]) for _ in range(FIT_STARTS)] + best = min((least_squares(residual, s, max_nfev=3000) for s in starts), key=lambda r: r.cost) + e = err(best.x) + return best.x, float(np.sqrt((e ** 2).mean())), float(np.abs(e).max()) + + +def fit(render_dir, out_rs, chart_dir=None): + """Fit the model to the Camera Raw renders in `render_dir` and write its constants to `out_rs`.""" + # the manifest carries the tool's prefix, as its charts do, so another chart tool's in the same folder is left alone + patches = json.load(open(os.path.join(chart_dir or render_dir, "curve__manifest.json")))["patches"] + tif = lambda n: os.path.join(render_dir, f"curve__{n}.tif") + n0 = grey_levels(tif("neutral"), patches) + rows = lambda names: [delta_table(n0, grey_levels(tif(n), patches)) for n in names] + sets = [("Whites", WHITES, rows([f"whites{a:+d}" for a in WHITES]))] + sets += [(r, REGION_AMOUNTS, rows([f"par_{r.lower()}{a:+d}" for a in REGION_AMOUNTS])) for r in REGIONS] + from concurrent.futures import ProcessPoolExecutor + jobs = [(name, sign, amounts, deltas) for name, amounts, deltas in sets for sign in (-1, 1)] + with ProcessPoolExecutor() as pool: + done = list(pool.map(fit_direction, *zip(*[(a, d, s) for _, s, a, d in jobs]))) + fitted = {} + for (name, sign, _, _), (params, rms, worst) in zip(jobs, done): + fitted[name, sign] = params + print(f"{name:10s} {'+' if sign > 0 else '-'} rms {rms:.2f} max {worst:.2f} (8-bit levels)") + num = lambda v: f"{v:.6e}" + resp = lambda name, sign: "[" + ", ".join("[" + ", ".join(num(v) for v in b) + "]" for b in np.reshape(fitted[name, sign], (2, 7))) + "]" + pair = lambda name: f"[{resp(name, -1)}, {resp(name, 1)}]" + s = ["// Written by `tools/lr_tone_charts.py fit`: LightCraft's model of Whites and the parametric regions, fitted to the", + "// tool's grey-step charts (provenance in docs/curve-stage.md). Constants of the model only.", + "", + "/// One bump of a response: `[a1, a2, a3, p0, p1, q0, q1]`, gain `a1 t + a2 t² + a3 t³` (t = |amount| / 100), shape", + "/// exponents `e^(p0 + p1 t)` and `e^(q0 + q1 t)` ([`crate::curve_stage`]).", + "pub type Bump = [f64; 7];", + "/// A slider direction's response: two bumps, added.", + "pub type Response = [Bump; 2];", + "", + "/// Whites: negative, positive.", + f"pub const WHITES: [Response; 2] = {pair('Whites')};", + "", + "/// Shadows, Darks, Lights, Highlights at the default splits (25, 50, 75): negative, positive.", + "pub const REGIONS: [[Response; 2]; 4] = [", + *[f" {pair(r)}," for r in REGIONS], + "];", + ""] + with open(out_rs, "w") as f: + f.write("\n".join(s)) + + +BASE_KNOTS = 12 + + +def monotone(xs, ys): + """`lightcraft_color::spline::MonotoneCurve`: the same tangents and Fritsch-Carlson limiter, as a function.""" + n = len(xs) + d = np.diff(ys) / np.diff(xs) + ms = np.zeros(n) + ms[0], ms[-1] = d[0], d[-1] + for i in range(1, n - 1): + ms[i] = 0 if d[i - 1] * d[i] <= 0 else (d[i - 1] + d[i]) / 2 + for i in range(n - 1): + if d[i] == 0: + ms[i] = ms[i + 1] = 0 + continue + a, b = ms[i] / d[i], ms[i + 1] / d[i] + if a * a + b * b > 9: + t = 3 / np.sqrt(a * a + b * b) + ms[i], ms[i + 1] = t * a * d[i], t * b * d[i] + + def at(q): + q = np.asarray(q, float) + i = np.clip(np.searchsorted(xs, q) - 1, 0, n - 2) + h = xs[i + 1] - xs[i] + t = (q - xs[i]) / h + v = ((2 * t ** 3 - 3 * t ** 2 + 1) * ys[i] + (t ** 3 - 2 * t ** 2 + t) * h * ms[i] + (-2 * t ** 3 + 3 * t ** 2) * ys[i + 1] + + (t ** 3 - t ** 2) * h * ms[i + 1]) + return np.where(q <= xs[0], ys[0], np.where(q >= xs[-1], ys[-1], v)) + return at + + +def base(render_dir, out_rs, chart_dir=None): + """Fit the default base curve's knots to the neutral render's grey steps (chart value in, linear ProPhoto out) and + write them to `out_rs`: 12 knots evenly spaced in stops from the darkest step (0) to white (1).""" + from scipy.optimize import least_squares + patches = json.load(open(os.path.join(chart_dir or render_dir, "curve__manifest.json")))["patches"] + steps = np.array([q["v"] for q in patches if q["kind"] == "grey" and q["ok"]]) + enc = grey_levels(os.path.join(render_dir, "curve__neutral.tif"), patches) + lin = np.where(enc <= 0.04045, enc / 12.92, ((enc + 0.055) / 1.055) ** 2.4) + lin = np.maximum.accumulate(np.clip(lin, 0, 1)) + stops = np.log2(steps) + kx = np.linspace(stops.min(), 0.0, BASE_KNOTS) + + def knots(p): + """Increasing knots from 0 at the darkest step to exactly 1 at white.""" + w = np.exp(p) + return np.concatenate([[0.0], np.cumsum(w) / w.sum()]) + + err = lambda p: (srgb_encode(monotone(kx, knots(p))(stops)) - srgb_encode(lin)) * 255 + p0 = np.log(np.maximum(np.diff(np.interp(kx, stops, lin)), 1e-5)) + ky = knots(least_squares(err, p0, max_nfev=20000).x) + e = (srgb_encode(monotone(kx, ky)(stops)) - srgb_encode(lin)) * 255 + print(f"base curve: rms {np.sqrt((e ** 2).mean()):.2f} max {np.abs(e).max():.2f} (8-bit levels)") + row = lambda vs: "[" + ", ".join(f"{v:.6e}" for v in vs) + "]" + s = ["// Written by `tools/lr_tone_charts.py base`: LightCraft's default base curve, fitted to the tool's neutral", + "// grey-step chart (provenance in docs/default-tone.md). Knots of the curve only.", + "", + "/// The knots' range in stops of the chart's linear value: from the darkest grey step to white.", + f"pub const STOPS: (f64, f64) = ({kx[0]:.6e}, 0.0);", + "/// The curve's linear ProPhoto output at the knots, evenly spaced over [`STOPS`].", + f"pub const KNOTS: [f64; {BASE_KNOTS}] = {row(ky)};", + ""] + with open(out_rs, "w") as f: + f.write("\n".join(s)) + + +def main(): + """Command line: `charts OUT_DIR`, `fit RENDER_DIR OUT_RS [CHART_DIR]` or `base RENDER_DIR OUT_RS [CHART_DIR]`.""" + if len(sys.argv) == 3 and sys.argv[1] == "charts": + out = sys.argv[2] + os.makedirs(out, exist_ok=True) + img, patches = chart() + json.dump(dict(patches=patches), open(os.path.join(out, "curve__manifest.json"), "w")) + for name, settings in variants().items(): + write_dng(os.path.join(out, f"curve__{name}.dng"), img, xmp(**settings)) + elif len(sys.argv) in (4, 5) and sys.argv[1] == "fit": + fit(*sys.argv[2:]) + elif len(sys.argv) in (4, 5) and sys.argv[1] == "base": + base(*sys.argv[2:]) + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main() diff --git a/tools/requirements-lr-tone-charts.txt b/tools/requirements-lr-tone-charts.txt new file mode 100644 index 00000000000..3828d64e39c --- /dev/null +++ b/tools/requirements-lr-tone-charts.txt @@ -0,0 +1,8 @@ +# Python packages for tools/lr_tone_charts.py (crates/pipeline/src/curve_stage_model.rs, docs/curve-stage.md), +# tools/lr_mixer_charts.py (crates/pipeline/src/mixer_stage_model.rs, docs/mixer-stage.md) and +# tools/lr_grading_charts.py (crates/pipeline/src/grading_stage_model.rs, docs/grading-stage.md). +# Needs Python 3.12 or newer (numpy 2.5); use a matching interpreter, e.g. python3.12 -m venv. +# python3.12 -m venv .venv-lr-tone && .venv-lr-tone/bin/pip install -r tools/requirements-lr-tone-charts.txt +numpy==2.5.4 +scipy==1.18.1 +tifffile==2026.11.8