Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Limit tone-curve steps between pixel populations in the camera look fit (#1904)

radialmonster3335fffb872a
diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs
index 1fc172548..d39bcf230 100644
--- a/crates/engine/src/camera_preview.rs
+++ b/crates/engine/src/camera_preview.rs
@@ -79,7 +79,8 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights};
/// a tone-only fallback for near-black scenes with too few colour pairs (#1587); DNG tone fitting uses a
/// lens-corrected proxy when the file carries lens opcodes; validated A7CR distortion, including the lens data
/// stored with each smart preview.
-pub const LOOK_VERSION: u32 = 12;
+/// 13: tone curves no steeper than a log-log slope of 4 between knots (#1904).
+pub const LOOK_VERSION: u32 = 13;
#[derive(Clone, Debug)]
pub(crate) struct CameraLook {
diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs
index d8442589d..b084bb062 100644
--- a/crates/engine/src/camera_preview/tests.rs
+++ b/crates/engine/src/camera_preview/tests.rs
@@ -1,3 +1,4 @@
+use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity};
use super::*;
fn steep_toe_scene() -> (Rgb32f, Rgb32f) {
@@ -26,6 +27,51 @@ fn camera_tone_follows_the_jpegs_deep_shadows() {
assert_eq!(look.matrix, Mat3::IDENTITY);
}
+/// Issue #1904: two populations the camera renders at different brightness for the same scene luminance (saturated
+/// blue at 1.7x, red at 2.64x) made quantile matching join them with a near-vertical step.
+#[test]
+fn tone_fit_does_not_step_between_two_pixel_populations() {
+ let mut pairs = Vec::new();
+ for i in 0..620 {
+ let x = 0.040 + 0.012 * f64::from(i) / 620.0;
+ pairs.push((x, 1.7 * x));
+ }
+ for i in 0..380 {
+ let x = 0.02 * (10.0f64).powf(f64::from(i) / 380.0);
+ pairs.push((x, 2.64 * x));
+ }
+ let elasticity = |k: &[[f32; 2]; 32]| {
+ k.windows(2)
+ .map(|w| {
+ ((f64::from(w[1][1]) + ELASTICITY_BLACK) / (f64::from(w[0][1]) + ELASTICITY_BLACK)).ln()
+ / (f64::from(w[1][0]) / f64::from(w[0][0])).ln()
+ })
+ .fold(0.0, f64::max)
+ };
+ let mut xs: Vec<f64> = pairs.iter().map(|p| p.0).collect();
+ let mut ys: Vec<f64> = pairs.iter().map(|p| p.1).collect();
+ xs.sort_by(f64::total_cmp);
+ ys.sort_by(f64::total_cmp);
+ let raw: [[f32; 2]; 32] = std::array::from_fn(|i| {
+ let mid = (i * xs.len() / 32 + (i + 1) * xs.len() / 32) / 2;
+ [xs[mid] as f32, ys[mid] as f32]
+ });
+ assert!(elasticity(&raw) > 10.0, "the synthetic scene must reproduce the step: {}", elasticity(&raw));
+ let tone = fit_tone(pairs).unwrap();
+ let knots = tone.knots();
+ assert!(elasticity(knots) <= MAX_TONE_ELASTICITY + 1e-3, "{}", elasticity(knots));
+ assert!(knots.iter().zip(&raw).all(|(a, b)| a[0] == b[0]), "only the outputs move");
+ for w in knots.windows(2) {
+ assert!(w[1][1] >= w[0][1]);
+ }
+ // A curve within the bound is left alone.
+ let smooth: [[f32; 2]; 32] = std::array::from_fn(|i| {
+ let x = 0.01 * 1.15f32.powi(i as i32);
+ [x, 0.9 * (x / (x + 0.18))]
+ });
+ assert_eq!(limit_elasticity(smooth, &[]), Some(smooth));
+}
+
#[test]
fn colour_holdouts_stay_out_of_the_wider_tone_training() {
let (sensor, reference) = steep_toe_scene();
diff --git a/crates/engine/src/camera_preview/tone.rs b/crates/engine/src/camera_preview/tone.rs
index f16b8e899..52598d35c 100644
--- a/crates/engine/src/camera_preview/tone.rs
+++ b/crates/engine/src/camera_preview/tone.rs
@@ -133,7 +133,106 @@ pub(super) fn fit_tone(pairs: Vec<(f64, f64)>) -> Option<CameraTone> {
if knots[31][0] < knots[0][0] * MIN_TONE_RANGE {
return None;
}
- CameraTone::new(knots)
+ CameraTone::new(limit_elasticity(knots, &pairs)?)
+}
+
+/// Largest log-log slope (elasticity, d ln y / d ln x with [`ELASTICITY_BLACK`] added to y) a fitted tone curve may
+/// have between two knots. A much steeper segment is not a camera curve but two pixel populations the camera renders at
+/// different brightness for the same scene luminance (by hue): quantile matching puts all of one population's scene
+/// range below the other's JPEG range and joins them with a near-vertical step, which amplifies the luminance noise of
+/// every pixel on it and renders as contours and blotches. On a dark ISO 1100 D3400 frame of saturated blue and red
+/// (issue #1904; reds 1.55x brighter in the JPEG than blues of the same scene luminance) the step had elasticity 12-28,
+/// and the render's fine luminance noise in the blue area was 1.46x that of Adobe's DNG of the same frame; with the
+/// bound it is 0.99x. Of 514 fitted looks on the user samples the median curve's steepest segment is 2.1 and the 95th
+/// percentile 3.6. The smoothed window ends where its end-to-end slope is first under the bound, so a looser bound
+/// (5 or 6) only spreads the D3400 step over a few knots and leaves the noise as it was.
+pub(super) const MAX_TONE_ELASTICITY: f64 = 4.0;
+/// Log-log slope of a curve end left free by [`limit_elasticity`]: about the median steepest segment of fitted looks
+/// (2.1), so the knots past the step follow an ordinary camera curve. At the bound itself (4) the D3400 frame's fine
+/// luminance noise stays 1.2x Adobe's; at 2 it is 0.99x.
+pub(super) const TONE_REPAIR_ELASTICITY: f64 = 2.0;
+/// Display level added to both ends of a segment's elasticity, so a toe rising from black is not counted as infinitely
+/// steep.
+pub(super) const ELASTICITY_BLACK: f64 = 0.002;
+
+/// `knots` with every segment steeper than [`MAX_TONE_ELASTICITY`] smoothed. The knots inside the smallest window
+/// around the segment (widened a knot on each side at a time) whose end-to-end elasticity is under the bound move onto
+/// the straight log-log line between the window's ends, so the step is spread over the scene range of the populations it
+/// joined. A window that reaches an end of the curve is pinned there, which can drag most of the curve onto one line
+/// (a step at the top of a Coolpix P340 curve pulled knots 3-29 up, held-out error +4 dE00), so it is weighed against
+/// leaving that end free: the knots past the segment on that side move onto [`TONE_REPAIR_ELASTICITY`] from the
+/// segment's other knot instead. Of the two the one closer to `pairs` (absolute error) is kept. The curve outside the
+/// window and its monotonicity are kept. `None` when nothing brings the curve under the bound. Knots within the bound are returned as
+/// they are.
+pub(super) fn limit_elasticity(mut knots: [[f32; 2]; 32], pairs: &[(f64, f64)]) -> Option<[[f32; 2]; 32]> {
+ let (bound, repair) = (MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY);
+ let at = |k: &[[f32; 2]; 32], i: usize| (f64::from(k[i][0]).ln(), (f64::from(k[i][1]) + ELASTICITY_BLACK).ln());
+ let slope = |k: &[[f32; 2]; 32], a: usize, b: usize| {
+ let ((ua, va), (ub, vb)) = (at(k, a), at(k, b));
+ (vb - va) / (ub - ua)
+ };
+ let level = |v: f64| (v.exp() - ELASTICITY_BLACK).max(0.0) as f32;
+ let error = |k: &[[f32; 2]; 32]| {
+ let tone = CameraTone::new(*k)?;
+ Some(pairs.iter().map(|&(x, y)| (f64::from(tone.apply(x as f32)) - y).abs()).sum::<f64>())
+ };
+ for _ in 0..64 {
+ let Some(i) = (0..31).find(|&i| slope(&knots, i, i + 1) > bound) else { return Some(knots) };
+ let (mut lo, mut hi) = (i, i + 1);
+ while slope(&knots, lo, hi) > bound && !(lo == 0 && hi == 31) {
+ lo = lo.saturating_sub(1);
+ hi = (hi + 1).min(31);
+ }
+ let mut pinned = knots;
+ let pinned_ok = slope(&knots, lo, hi) <= bound;
+ if pinned_ok {
+ let ((ua, va), (ub, vb)) = (at(&knots, lo), at(&knots, hi));
+ for k in lo + 1..hi {
+ pinned[k][1] = level(va + (vb - va) * (f64::from(knots[k][0]).ln() - ua) / (ub - ua));
+ }
+ }
+ // A window that reaches an end of the curve can leave that end free instead: the knots below the segment rise
+ // onto the repair slope down from knot i + 1, or the knots above it drop onto it up from knot i.
+ let mut free = None;
+ if lo == 0 || hi == 31 {
+ let mut k2 = knots;
+ if lo == 0 {
+ let (ub, vb) = at(&knots, i + 1);
+ for k in 0..=i {
+ let (u, v) = at(&knots, k);
+ k2[k][1] = level(v.max(vb - repair * (ub - u)));
+ }
+ } else {
+ let (ua, va) = at(&knots, i);
+ for k in i + 1..32 {
+ let (u, v) = at(&knots, k);
+ k2[k][1] = level(v.min(va + repair * (u - ua)));
+ }
+ }
+ free = Some(k2);
+ }
+ let next = match (pinned_ok, free) {
+ (true, Some(free)) => {
+ if error(&free).unwrap_or(f64::INFINITY) < error(&pinned).unwrap_or(f64::INFINITY) {
+ free
+ } else {
+ pinned
+ }
+ }
+ (true, None) => pinned,
+ (false, Some(free)) => free,
+ (false, None) => return None,
+ };
+ if lightcraft_pipeline::profiling() {
+ let moved: Vec<usize> = (0..32).filter(|&k| next[k][1] != knots[k][1]).collect();
+ eprintln!("[profile] camera tone: elasticity {:.1} at scene {:.4}, knots {moved:?} moved", slope(&knots, i, i + 1), knots[i][0]);
+ }
+ if next == knots {
+ return None;
+ }
+ knots = next;
+ }
+ None
}
fn median(values: &mut [f64]) -> Option<f64> {
@@ -182,5 +281,5 @@ pub(super) fn fit_tone_conditional(mut pairs: Vec<(f64, f64)>) -> Option<CameraT
}
i += n;
}
- CameraTone::new(knots)
+ CameraTone::new(limit_elasticity(knots, &pairs)?)
}
diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs
index 8f6a9c28c..8490d2ee2 100644
--- a/crates/engine/src/media/source.rs
+++ b/crates/engine/src/media/source.rs
@@ -1,7 +1,7 @@
use super::{Arc, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
-pub const RENDER_CACHE_VERSION: u64 = 70;
+pub const RENDER_CACHE_VERSION: u64 = 71;
/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];