From 542bb59fbf7684abce2ba1d370e7ecf6c520fc28 Mon Sep 17 00:00:00 2001 From: robmdunn <1900604+robmdunn@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:25 -0400 Subject: [PATCH] LR-PROF-CAMERACOLOR: continuing a photo's curve keeps it where its JPEG taught it To make room for the pooled extension in the curve's 32 knots, extend_tone kept every n-th knot of the photo's own curve, which could move the curve inside the range its JPEG showed (a sharp toe most). It now drops the knots the curve needs least, one at a time, within one 8-bit code (thinned_knots); with fewer extension knots if needed, or the photo's curve as fitted when even two don't fit. On a D750 bracket renders move by at most dE 0.09. LOOK_VERSION 13. Found by CodeRabbit on #2093. --- crates/engine/src/camera_preview.rs | 84 +++++++++++++++++++++++++++-- docs/camera-preview-colour.md | 2 +- 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index b1cdee5890..f5e7d26baa 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -37,7 +37,8 @@ use lightcraft_raw::{ /// 10: a photo no look fits keeps its camera profile's colour instead of the neutral fallback. /// 11: a camera profile's pooled tone curve continues a photo's own past what its JPEG showed. /// 12: only a look with the profile's colour continues along its pooled tone curve. -pub const LOOK_VERSION: u32 = 12; +/// 13: continuing a photo's curve keeps it as it was where its JPEG taught it (`thinned_knots`). +pub const LOOK_VERSION: u32 = 13; #[derive(Clone, Debug)] pub(crate) struct CameraLook { @@ -916,14 +917,25 @@ fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { if !(span.is_finite() && span > 0.2) { return *photo; } - let extra = ((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16); + // the photo's own knots, the ones its curve needs least dropped to make room: as many extension knots as keep the + // curve within `THIN_TOLERANCE` where the JPEG taught it, at least 2, else the photo keeps its curve as it is + let Some((extra, own)) = + (2..=((span * EXTEND_KNOTS_PER_EV).round() as usize).clamp(2, 16)).rev().find_map(|extra| thinned_knots(own, 32 - extra).map(|k| (extra, k))) + else { + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: the photo's curve can't make room for the pooled one, kept as fitted"); + } + return *photo; + }; + if lightcraft_pipeline::profiling() { + eprintln!("[profile] camera look: pooled tone curve joined with {extra} knots past the photo's"); + } let at_end = pooled.apply(end[0]); let ratio = if at_end > 0.0 && end[1] > 0.0 { end[1] / at_end } else { 1.0 }; let mut knots = [[0.0f32; 2]; 32]; - // the photo's own knots, evenly thinned to make room, always keeping its first and last let kept = 32 - extra; - for (i, knot) in knots.iter_mut().take(kept).enumerate() { - *knot = own[i * 31 / (kept - 1)]; + for (knot, own) in knots.iter_mut().zip(&own) { + *knot = *own; } for k in 1..=extra { let ev = span * k as f32 / extra as f32; @@ -941,6 +953,37 @@ fn extend_tone(photo: &CameraTone, pooled: &CameraTone) -> CameraTone { CameraTone::new(knots).and_then(|tone| tone.with_chroma(*photo.chroma())).unwrap_or(*photo) } +/// Largest change, in gamma-encoded display values (1/2.2), that thinning a photo's curve for [`extend_tone`] may make +/// where its JPEG taught it: one 8-bit code. +const THIN_TOLERANCE: f32 = 1.0 / 255.0; + +/// `knots` thinned to `keep` (first and last kept), dropping one at a time the knot whose removal changes the curve +/// least (`CameraTone::apply` interpolates linearly, so the change peaks at a dropped knot); `None` when that change +/// would exceed [`THIN_TOLERANCE`]. +fn thinned_knots(knots: &[[f32; 2]; 32], keep: usize) -> Option> { + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // the change from leaving out every knot strictly between kept indices `a` and `b` + let gap = |a: usize, b: usize| { + let ([x0, y0], [x1, y1]) = (knots[a], knots[b]); + (a + 1..b) + .map(|i| { + let [x, y] = knots[i]; + let t = if x1 > x0 { (x - x0) / (x1 - x0) } else { 0.0 }; + (encoded(y0 + t * (y1 - y0)) - encoded(y)).abs() + }) + .fold(0.0f32, f32::max) + }; + let mut kept: Vec = (0..knots.len()).collect(); + while kept.len() > keep.max(2) { + let (i, change) = (1..kept.len() - 1).map(|i| (i, gap(kept[i - 1], kept[i + 1]))).min_by(|a, b| a.1.total_cmp(&b.1))?; + if change > THIN_TOLERANCE { + return None; + } + kept.remove(i); + } + Some(kept.into_iter().map(|i| knots[i]).collect()) +} + /// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table) /// fitted to pairs pooled from many photos. pub(crate) fn fit_profile(pairs: &[([f64; 3], [f64; 3])]) -> Option<(Mat3, Option)> { @@ -4157,6 +4200,37 @@ mod tests { assert_eq!(extend_tone(&bright, &pooled), bright); } + #[test] + fn extending_a_photos_curve_keeps_it_where_its_jpeg_taught_it() { + let pooled = sampled(camera_curve, 0.0005, 0.9); + let encoded = |v: f32| v.max(0.0).powf(1.0 / 2.2); + // a smooth dark curve, and one with a sharp toe (flat, then a steep rise over two knots) + let smooth = sampled(|x| 0.9 * camera_curve(x), 0.0005, 0.02); + let toe = CameraTone::new(std::array::from_fn(|i| { + let x = 0.0005 * 40f32.powf(i as f32 / 31.0); + [ + x, + if i < 9 { + 0.001 + 0.0001 * i as f32 + } else if i < 11 { + 0.004 + 0.012 * (i - 8) as f32 + } else { + 0.03 + 0.004 * (i - 10) as f32 + }, + ] + })) + .unwrap(); + for photo in [smooth, toe] { + let tone = extend_tone(&photo, &pooled); + for [x, _] in photo.knots() { + let change = (encoded(tone.apply(*x)) - encoded(photo.apply(*x))).abs(); + assert!(change <= THIN_TOLERANCE + 1e-5, "{x}: {} vs {} ({change})", tone.apply(*x), photo.apply(*x)); + } + } + // the smooth one still goes on along the pooled curve + assert!((extend_tone(&smooth, &pooled).apply(0.3) - pooled.apply(0.3)).abs() < 0.01); + } + #[test] fn a_pooled_tone_curve_spans_dark_and_bright_photos() { // camera RGB grey (white balanced): a dark photo's pixels and a bright one's, through one camera curve diff --git a/docs/camera-preview-colour.md b/docs/camera-preview-colour.md index c9ba6e90cb..db9844e12a 100644 --- a/docs/camera-preview-colour.md +++ b/docs/camera-preview-colour.md @@ -195,7 +195,7 @@ When no look fits a photo of a profiled model (step 2 and 3 both fail: a black-a Before this, such a photo fell to 4 or 5 and the profile did nothing for it. Measured on two bracketed bursts of one NIKON D780 scene (a colourful woven runner in low sun, ISO 100, f/8, frames 1.1 to 3.7 EV under the burst's brightest, each rendered with Exposure raised by its measured offset and compared with the brightest frame, CIEDE2000 and chroma of the colourful areas), with a local profile pooled from 255 of the photographer's D780 photos: the five frames 2.8 EV or more under have no look (their camera JPEGs are nearly black) and rendered at 35-48% of the reference's chroma with hue off by up to 9° whether or not the profile existed; with the profile's colour kept they render at 88-99% of it, hue within 5°. Frames up to 2.3 EV under fit a look and are unchanged. The pushed frames remain 4-7 L\* darker than the reference: a dark photo's tone curve is fitted to its shadows only (or is the default curve), which the profile's colour doesn't change (the pooled tone curve, next, does). -**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. +**A pooled tone curve.** A photo's tone curve only reaches as far as its JPEG's own pixels: a dark photo's ends in the shadows, and past its last knot `CameraTone::apply` goes on as a bounded shoulder whose rate comes from the last two knots. Push such a photo's exposure up and most of it lands on that shoulder. `lightcraft-cli calibrate` therefore also pools tone samples (white-balanced camera RGB → the camera JPEG's luminance, every proxy pixel whose channels are above 0.0001 and whose JPEG luminance is in 0.0003-0.85, at most 4,000 per photo; a photo too dark or colourless for colour pairs still gives these, without counting toward the profile's photos, and a black-and-white camera JPEG gives none), and after fitting the matrix fits one curve through it by quantile matching (`fit_profile_tone`): every photo went through the same camera curve, so the pooled scene and JPEG distributions are still one monotone map apart, and dark photos supply the shadows while bright ones supply the highlights (picture styles and Active D-Lighting are averaged). The profile stores it as `tone` (absent in profiles fitted before; the bundled ones have none yet). A photo of the model whose look takes the profile's colour keeps its own curve up to its last knot and from there follows the pooled curve, faded from its own level over 1 EV (`extend_tone`; to make room in the curve's 32 knots it drops the photo's knots its curve needs least, by at most one 8-bit code where the JPEG taught it, using fewer extension knots or keeping the photo's curve as fitted otherwise: `thinned_knots`, `LOOK_VERSION` 13); a look fitted with the photo's own matrix (the profile's colour rejected) keeps its curve as fitted, since the pooled one maps luminance through the profile's matrix (`with_pooled_tone`, `LOOK_VERSION` 12); a photo no look fits takes the pooled curve whole instead of the default one. On the same D780 brackets with the profile refitted with its tone curve (255 photos), the pushed frames match the reference's lightness: ΔL\* −0.2 to +0.5 for every frame (−1 to −7 before), median CIEDE2000 in the L\* 40-70 band 0.9-2.6 (2.0-13.5 before), hue within 5°. Colourfulness in the second burst comes out 16-28% above the reference in midtones. On 40 D780 photos the profile never saw, rendered unedited and compared with their camera JPEGs, the curve changes nothing that matters: mean ΔE 2.67 with the colour-only profile, 2.68 with the curve (2.77 without a profile), mean ΔL\* +0.71 → +0.73, one photo worse by more than 0.25 (0.38).