From 7c9feb59f93b5d021b01a0dc3a64a421de3943c1 Mon Sep 17 00:00:00 2001 From: radialmonster Date: Sat, 10 Oct 2026 04:20:19 -0400 Subject: [PATCH] LR-EDIT-LIGHT-HIGHLIGHTS: binned previews decide clipping per sample before averaging (#548) Rework of #602 on top of #607's highlight reconstruction, keeping only what #607 doesn't cover. Small previews and thumbnails bin the mosaic (8 x 8 at 500 px); a colour with one clipped sample in its block used to take the block's maximum, so a specular point turned the block's green to the clip level and reconstruction kept it: green speckles. - raw: RawImage::develop_binned_masked keeps every channel its block mean and returns a mask of the colours that had a clipped sample (develop_binned and the camera-look proxy keep the maximum rule). - highlight: reconstruct_masked is #607's reconstruct_with with the clipped channels taken from the mask (sources, rim, rebuild and fade unchanged); a masked mean is a lower bound, and a fully masked block becomes the clipped white at its own brightest channel rather than lifted to the clip level. A mask built from the values reproduces reconstruct_with exactly (test). - engine: previews/thumbnails (and their denoised twin) use the mask. RENDER_CACHE_VERSION 42 (main + 5; adjust at merge). --- crates/engine/src/files.rs | 62 ++++++++++++--- crates/engine/src/media.rs | 2 +- crates/raw/src/binned.rs | 72 ++++++++++++++++-- crates/raw/src/highlight.rs | 146 ++++++++++++++++++++++++++++++++---- crates/raw/src/lib.rs | 3 +- docs/parity.md | 2 +- 6 files changed, 252 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/files.rs b/crates/engine/src/files.rs index e1c54b3420c..c2f422652f8 100644 --- a/crates/engine/src/files.rs +++ b/crates/engine/src/files.rs @@ -219,8 +219,19 @@ pub(crate) struct CameraColourModel<'a> { impl CameraColourModel<'_> { /// Rebuild sensor-clipped channels; fully clipped highlights become [`clipped_white`] of the matrix, so they /// come out of [`Self::apply`] neutral. + #[cfg(test)] pub fn rebuild_highlights(&self, img: &mut Rgb32f) { - lightcraft_raw::highlight::reconstruct_with(img, self.wb, HIGHLIGHT_CLIP, clipped_white(&self.matrix)); + self.rebuild_highlights_masked(img, None); + } + + /// [`Self::rebuild_highlights`]; with `mask`, a binned image's clip mask + /// ([`lightcraft_raw::RawImage::develop_binned_masked`]) tells the clipped channels. + pub fn rebuild_highlights_masked(&self, img: &mut Rgb32f, mask: Option<&[u8]>) { + let white = clipped_white(&self.matrix); + match mask { + Some(mask) => lightcraft_raw::highlight::reconstruct_masked(img, self.wb, HIGHLIGHT_CLIP, white, mask), + None => lightcraft_raw::highlight::reconstruct_with(img, self.wb, HIGHLIGHT_CLIP, white), + }; } /// White balance, matrix, tables and baseline exposure, in place. @@ -319,8 +330,9 @@ pub fn load_vec_pair(bytes: Vec, max_edge: usize, spec: &DenoiseSpec) -> Res } /// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default -/// crop, and `factor` × `factor` blocks averaged into one pixel when the plain one was binned. `None` when the product -/// is missing, damaged, made from something else or not the size of this raw's active area. +/// crop, and `factor` × `factor` blocks averaged into one pixel when the plain one was binned (plain means: the plain +/// development's clip mask tells highlight reconstruction which of them held clipped samples). `None` when the +/// product is missing, damaged, made from something else or not the size of this raw's active area. fn denoised_camera_rgb(raw: &lightcraft_raw::RawImage, spec: &DenoiseSpec, factor: usize) -> Option { use lightcraft_denoise::product::{self, Window}; let a = raw.active_area; @@ -331,7 +343,7 @@ fn denoised_camera_rgb(raw: &lightcraft_raw::RawImage, spec: &DenoiseSpec, facto if raw.opcodes.list3.is_empty() { let c = raw.develop_crop(a.width, a.height); let window = Window { x: c.x, y: c.y, width: c.width, height: c.height }; - product::read_window(&spec.product, &spec.key, Some(window), factor, Some(HIGHLIGHT_CLIP)).ok() + product::read_window(&spec.product, &spec.key, Some(window), factor, None).ok() } else { // (the plain development is not binned either when the file has opcodes of this kind: `factor` is 1) let whole = product::read(&spec.product, &spec.key, 1).ok()?; @@ -368,16 +380,17 @@ fn load_bytes_now( // larger levels (exports, 1:1) demosaic the whole sensor. let t0 = web_time::Instant::now(); let bin = bin_factor(&raw, max_edge); + // (binned: block means, and which colours had a clipped sample in each block) let binned = match bin { - Some(k) => raw.develop_binned(k, HIGHLIGHT_CLIP).map_err(|e| e.to_string())?, + Some(k) => raw.develop_binned_masked(k, HIGHLIGHT_CLIP).map_err(|e| e.to_string())?, None => None, }; let factor = if binned.is_some() { bin.unwrap_or(1) } else { 1 }; - let img = match binned { - Some(img) => img, + let (img, clip_mask) = match binned { + Some((img, mask)) => (img, Some(mask)), None => { let method = if max_edge <= 600 { lightcraft_raw::Method::Bilinear } else { lightcraft_raw::Method::Ahd }; - raw.develop(method).map_err(|e| e.to_string())? + (raw.develop(method).map_err(|e| e.to_string())?, None) } }; // the same development from the denoised mosaic, when the photo has been denoised @@ -399,7 +412,7 @@ fn load_bytes_now( let finish = |mut img: Rgb32f| { let mut stages = vec![("develop", t0.elapsed())]; stages.push(("transform", t0.elapsed())); - colour.rebuild_highlights(&mut img); + colour.rebuild_highlights_masked(&mut img, clip_mask.as_deref()); stages.push(("highlights", t0.elapsed())); colour.apply(&mut img); stages.push(("colour", t0.elapsed())); @@ -708,6 +721,37 @@ mod tests { assert!(probe_bytes("x.jpg", b"not an image").is_err()); } + /// Issue #548: a small preview bins the mosaic by 8; specular points that clip a single green sample + /// of a block on a grey surface must not become green speckles (the block's green used to take the + /// clip level, which highlight reconstruction then kept). + #[test] + fn coarse_binning_keeps_specular_points_neutral() { + let (w, h) = (256usize, 192usize); + // grey after the file's white balance (as-shot neutral 0.5 : 1 : 0.7), brighter to the right + let neutral = [0.5f32, 1.0, 0.7]; + let cfa = lightcraft_raw::Cfa::bayer("RGGB").unwrap(); + let mut data: Vec = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let v = (0.3 + 0.2 * x as f32 / w as f32) * neutral[cfa.color_at(x, y).min(2) as usize]; + (256.0 + v * (16000.0 - 256.0)).round() as u16 + }) + .collect(); + // one clipped green sample (RGGB: even row, odd column) in every other 8 × 8 block + for by in 0..h / 8 { + for bx in (by % 2..w / 8).step_by(2) { + data[(by * 8 + 4) * w + bx * 8 + 5] = 16000; + } + } + let bytes = crate::tests_xmp::synthetic_dng_of(w, h, "RGGB", data, None, Default::default()); + let raw = lightcraft_raw::decode(&bytes).unwrap(); + assert_eq!(bin_factor(&raw, 32), Some(8)); + let (img, _) = load_bytes(&bytes, 32).unwrap(); + assert_eq!((img.width, img.height), (32, 24)); + let worst = img.data.iter().map(|p| p[1] / ((p[0] + p[2]) / 2.0).max(1e-6)).fold(0.0f32, f32::max); + assert!(worst < 1.12, "green speckles: green {worst:.2}× the other channels"); + } + #[test] fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_raw() { use lightcraft_denoise::product; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 1e2a7d3e54e..6d5b548f1fb 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 37; +pub const RENDER_CACHE_VERSION: u64 = 42; /// 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]; diff --git a/crates/raw/src/binned.rs b/crates/raw/src/binned.rs index fde6c2c0b19..674651c900f 100644 --- a/crates/raw/src/binned.rs +++ b/crates/raw/src/binned.rs @@ -8,9 +8,13 @@ //! interpolation, so there are no demosaicing artefacts; the colour planes are offset by less than //! one output pixel, which is invisible at these scales. //! -//! Clipping is preserved for [`crate::highlight::reconstruct`]: a channel whose block contains a -//! sample at or above `clip` takes that block's maximum sample of the colour (instead of a mean that -//! would fall just below the clip level and escape reconstruction). +//! Clipping is decided per sample, before averaging. [`RawImage::develop_binned_masked`] keeps every +//! channel the mean of its samples and says, per output pixel, which colours had a sample at or above +//! `clip` (for [`crate::highlight::reconstruct_masked`], which rebuilds them with the mean as a lower +//! bound). A specular point that clips one green sample of the 32 in an 8 × 8 block thus counts as +//! partly clipped without the block's green jumping to the clip level, which would read as a green +//! speckle once reconstructed. [`RawImage::develop_binned`] instead gives such a channel the block's +//! maximum sample of the colour, so that plain value thresholds see it as clipped. use crate::{Normalized, RawData, RawImage, Result, Rgb32f}; use rayon::prelude::*; @@ -31,6 +35,19 @@ impl RawImage { /// not oriented). `None` when the data cannot be binned ([`RawImage::can_bin`]) or carries an /// `OpcodeList3` (whose operations are defined at full resolution); callers then demosaic. pub fn develop_binned(&self, k: usize, clip: f32) -> Result> { + Ok(self.bin(k, clip, true)?.map(|(img, _)| img)) + } + + /// Like [`RawImage::develop_binned`], with every channel the mean of its block's samples, and the + /// clip mask: per output pixel, bits [`crate::highlight::CLIPPED_R`] / `_G` / `_B` for the colours + /// with a sample at or above `clip` in the block. Hand both to [`crate::highlight::reconstruct_masked`]. + pub fn develop_binned_masked(&self, k: usize, clip: f32) -> Result)>> { + self.bin(k, clip, false) + } + + /// The binned image and its clip mask; `keep_max`: a channel with a clipped sample takes the + /// block's maximum sample of the colour instead of the mean. + fn bin(&self, k: usize, clip: f32, keep_max: bool) -> Result)>> { self.validate()?; if !self.can_bin(k) || !self.opcodes.list3.is_empty() { return Ok(None); @@ -63,7 +80,8 @@ impl RawImage { .collect(); let wlen = bw * k; let mut out = Rgb32f::new(bw, bh); - out.data.par_chunks_mut(bw).enumerate().for_each(|(by, row)| { + let mut mask = vec![0u8; bw * bh]; + out.data.par_chunks_mut(bw).zip(mask.par_chunks_mut(bw)).enumerate().for_each(|(by, (row, mrow))| { // the block row's k sample rows, normalised let mut rows = vec![0f32; k * wlen]; for dy in 0..k { @@ -86,7 +104,7 @@ impl RawImage { } } let py = (c.y + by * k) % ph; - for (bx, px) in row.iter_mut().enumerate() { + for (bx, (px, m)) in row.iter_mut().zip(mrow.iter_mut()).enumerate() { let (layout, inv) = &layouts[py * pw + (c.x + bx * k) % pw]; let (mut sum, mut max) = ([0f32; 3], [f32::MIN; 3]); for dy in 0..k { @@ -98,11 +116,13 @@ impl RawImage { } } for ch in 0..3 { - px[ch] = if max[ch] >= clip { max[ch] } else { sum[ch] * inv[ch] }; + let clipped = max[ch] >= clip; + px[ch] = if clipped && keep_max { max[ch] } else { sum[ch] * inv[ch] }; + *m |= u8::from(clipped) << ch; } } }); - Ok(Some(out)) + Ok(Some((out, mask))) } } @@ -177,6 +197,44 @@ mod tests { assert!((xb.get(4, 3)[2] - 0.3).abs() < 2e-3); } + /// Issue #548: specular points that clip one green sample in some 8 × 8 blocks of a grey surface. + /// Taking the block's maximum makes those blocks' green the clip level, which reconstruction then + /// keeps (a green speckle); the masked binning keeps the mean and marks the green as clipped. + #[test] + fn clipping_is_decided_before_averaging() { + let img = Rgb32f::filled(64, 64, [0.3, 0.3, 0.3]); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0); + if let RawData::U16(d) = &mut raw.data { + // one green sample (RGGB: odd column of an even row) in every other block + for by in 0..8 { + for bx in (by % 2..8).step_by(2) { + d[(by * 8 + 2) * 64 + bx * 8 + 3] = 4095; + } + } + } + let wb = [1.0f32; 3]; + let (mut masked, mask) = raw.develop_binned_masked(8, 0.99).unwrap().unwrap(); + assert_eq!(mask.len(), 64); + assert_eq!(mask.iter().filter(|&&m| m == highlight::CLIPPED_G).count(), 32); + assert!(mask.iter().all(|&m| m & (highlight::CLIPPED_R | highlight::CLIPPED_B) == 0)); + // the clipped block's green is its mean: (31 · 0.3 + 1) / 32 + assert!((masked.get(0, 0)[1] - (31.0 * 0.3 + 1.0) / 32.0).abs() < 1e-3, "{:?}", masked.get(0, 0)); + assert_eq!(highlight::reconstruct_masked(&mut masked, wb, 0.99, [1.0; 3], &mask), 32); + let green = |img: &Rgb32f| img.data.iter().map(|p| p[1] / p[0]).fold(0.0f32, f32::max); + // (no more than the mean itself: the clipped sample counts at the clip level) + assert!(green(&masked) < 1.08, "green excess {}", green(&masked)); + // the maximum rule: a green speckle at the clip level + let mut max = raw.develop_binned(8, 0.99).unwrap().unwrap(); + assert!(max.get(0, 0)[1] >= 0.99); + highlight::reconstruct(&mut max, wb, 0.99); + assert!(green(&max) > 3.0, "{}", green(&max)); + // without clipped samples both are the same plain means, and the mask is empty + let clean = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0); + let (a, m) = clean.develop_binned_masked(8, 0.99).unwrap().unwrap(); + assert!(m.iter().all(|&v| v == 0)); + assert!(a.data == clean.develop_binned(8, 0.99).unwrap().unwrap().data); + } + #[test] fn binning_matches_demosaic_downscaled_on_smooth_images() { let img = Rgb32f::from_fn(64, 48, |x, y| [0.2 + 0.3 * (x as f32 / 64.0), 0.4 - 0.2 * (y as f32 / 48.0), 0.25]); diff --git a/crates/raw/src/highlight.rs b/crates/raw/src/highlight.rs index 7fc056600e8..269a246352e 100644 --- a/crates/raw/src/highlight.rs +++ b/crates/raw/src/highlight.rs @@ -9,6 +9,9 @@ //! there is none within reach. Right past the rim, the rim's colour carries on. Fully clipped pixels become //! neutral at the brightest plausible level; partly clipped ones fade into it on their way from the first channel //! clipping to the last, pale ones from the start. +//! - [`reconstruct_masked`]: the same for a binned image ([`crate::RawImage::develop_binned_masked`]), whose +//! clipped channels a mask tells instead of their values (block means, a lower bound where a block held clipped +//! samples). //! //! Why the care: the white-balance gains push clipped channels apart (green clips first, red and blue keep //! rising), so whatever colour the rebuilt pixels carry is hidden at Neutral only by the tone map's roll-off to @@ -115,8 +118,9 @@ fn sample(l: &Level, scale: f32, x: usize, y: usize) -> [f32; /// The half-resolution source level of `img`: every `2 × 2` block's source-weighted chromaticity sums, with /// blocks near clipped pixels or on strong edges left out. Also returns, per cell, whether a clipped pixel lies -/// in its row within [`MARGIN`] cells (the vertical half of that test is left to the readers). -fn sources(img: &Rgb32f, wb: [f32; 3], clip: f32) -> (Level<3>, Vec) { +/// in its row within [`MARGIN`] cells (the vertical half of that test is left to the readers). `clipped` tells +/// the clipped channels of the pixel at an index (see [`reconstruct_by`]). +fn sources(img: &Rgb32f, wb: [f32; 3], clip: f32, clipped: &(impl Fn(usize, &[f32; 3]) -> [bool; 3] + Sync)) -> (Level<3>, Vec) { let (w, h) = (img.width, img.height); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); // per cell: [red sum, blue sum, weight] densities, luminance, whether it holds a clipped pixel @@ -125,19 +129,18 @@ fn sources(img: &Rgb32f, wb: [f32; 3], clip: f32) -> (Level<3>, Vec) { let mut near = vec![false; cw * ch]; cells.par_chunks_mut(cw).zip(lum.par_chunks_mut(cw)).zip(near.par_chunks_mut(cw)).enumerate().for_each(|(y, ((crow, lrow), nrow))| { let mut touched = vec![false; cw]; - let row = |r: usize| img.data.get(r * w..(r + 1) * w).unwrap_or(&[]); - let (r0, r1) = (row(2 * y), row(2 * y + 1)); let lo = SOURCE_LO * clip; for x in 0..cw { let (mut a, mut sum, mut n, mut hit) = ([0f32; 3], 0f32, 0usize, false); let span = 2 * x..(2 * x + 2).min(w); - for p in r0.get(span.clone()).unwrap_or(&[]).iter().chain(r1.get(span).unwrap_or(&[])) { + for i in [2 * y, 2 * y + 1].into_iter().filter(|&r| r < h).flat_map(|r| span.clone().map(move |sx| r * w + sx)) { + let Some(p) = img.data.get(i) else { continue }; let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; let s = q[0].max(0.0) + q[1].max(0.0) + q[2].max(0.0); sum += s; n += 1; let top = p[0].max(p[1]).max(p[2]); - if top >= clip { + if clipped(i, p).iter().any(|&c| c) { hit = true; continue; } @@ -190,8 +193,14 @@ fn sources(img: &Rgb32f, wb: [f32; 3], clip: f32) -> (Level<3>, Vec) { /// The quarter-resolution rim level of `img`: every `4 × 4` block's white-balanced RGB of its unclipped pixels /// above [`RIM_LO`] of the clip level, weighted (steeply) towards the clip, as densities. Pixels next to clipped /// ones (`margin`, by half-resolution cell) are left out, like the colour sources: they were demosaiced partly from -/// clipped samples, and lens fringes along clipped content would pass for its colour. -fn rim(img: &Rgb32f, wb: [f32; 3], clip: f32, margin: &(dyn Fn(usize, usize) -> bool + Sync)) -> Level<4> { +/// clipped samples, and lens fringes along clipped content would pass for its colour. `clipped` as for [`sources`]. +fn rim( + img: &Rgb32f, + wb: [f32; 3], + clip: f32, + margin: &(dyn Fn(usize, usize) -> bool + Sync), + clipped: &(impl Fn(usize, &[f32; 3]) -> [bool; 3] + Sync), +) -> Level<4> { let (w, h) = (img.width, img.height); let (cw, ch) = (w.div_ceil(4), h.div_ceil(4)); let mut cells = vec![[0f32; 4]; cw * ch]; @@ -202,7 +211,7 @@ fn rim(img: &Rgb32f, wb: [f32; 3], clip: f32, margin: &(dyn Fn(usize, usize) -> for (i, p) in img.data.get(sy * w + 4 * x..sy * w + (4 * x + 4).min(w)).unwrap_or(&[]).iter().enumerate() { n += 1; let top = p[0].max(p[1]).max(p[2]) / clip; - if !(RIM_LO..1.0).contains(&top) || margin((4 * x + i) / 2, sy / 2) { + if !(RIM_LO..1.0).contains(&top) || margin((4 * x + i) / 2, sy / 2) || clipped(sy * w + 4 * x + i, p).iter().any(|&c| c) { continue; } let k = ((top - RIM_LO) / (1.0 - RIM_LO)).powi(4); @@ -341,9 +350,46 @@ pub fn reconstruct(img: &mut Rgb32f, wb: [f32; 3], clip: f32) -> usize { /// chromaticity of reliable unclipped content nearby, and that of `white` where there is none. /// Returns the number of pixels that had at least one clipped channel; the others are left exactly as they were. pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3]) -> usize { + reconstruct_by(img, wb, clip, white, true, |_, p| [p[0] >= clip, p[1] >= clip, p[2] >= clip]) +} + +/// Bits of a [`reconstruct_masked`] mask entry: which channels of the pixel are clipped. +pub const CLIPPED_R: u8 = 1; +pub const CLIPPED_G: u8 = 2; +pub const CLIPPED_B: u8 = 4; + +/// [`reconstruct_with`] with the clipped channels given by `mask` (one entry per pixel, bits [`CLIPPED_R`], +/// [`CLIPPED_G`], [`CLIPPED_B`]) instead of by the values: for a binned image +/// ([`crate::RawImage::develop_binned_masked`]), whose values are block means and whose mask says which colours +/// had a sample at or above `clip` in each block. A masked channel's mean is a lower bound of its true value and +/// is never lowered. A fully masked block becomes `white` at its own brightest channel (not at the brightest +/// plausible level of a clipped pixel: its samples that clipped count at their clip level in the mean, the +/// others are what they are, and lifting the whole block would make a white speckle of a specular point). +/// Everything else is [`reconstruct_with`] as it is. A mask of the wrong length leaves the image as it is +/// (returns 0). +pub fn reconstruct_masked(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], mask: &[u8]) -> usize { + if mask.len() != img.data.len() { + return 0; + } + reconstruct_by(img, wb, clip, white, false, |i, _| { + let m = mask.get(i).copied().unwrap_or(0); + [m & CLIPPED_R != 0, m & CLIPPED_G != 0, m & CLIPPED_B != 0] + }) +} + +/// [`reconstruct_with`] with `clipped(index, pixel)` telling the clipped channels. `lift`: fully clipped +/// pixels (and partly clipped ones on their way there) go to the brightest plausible level, not only to their +/// own brightest channel. +fn reconstruct_by( + img: &mut Rgb32f, + wb: [f32; 3], + clip: f32, + white: [f32; 3], + lift: bool, + clipped: impl Fn(usize, &[f32; 3]) -> [bool; 3] + Sync, +) -> usize { let (w, h) = (img.width, img.height); - let is_clipped = |p: &[f32; 3]| p[0] >= clip || p[1] >= clip || p[2] >= clip; - let count = img.data.par_iter().filter(|p| is_clipped(p)).count(); + let count = img.data.par_iter().enumerate().filter(|(i, p)| clipped(*i, p).iter().any(|&c| c)).count(); if count == 0 || w == 0 || h == 0 { return 0; } @@ -354,7 +400,7 @@ pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; let neutral = [white[0] / total, white[1] / total, white[2] / total]; // A clipped pixel is never a source, so its chromaticity is always the bilinear sample of the // half-resolution estimate: the pyramid starts there, straight from the image. - let (first, near) = sources(img, wb, clip); + let (first, near) = sources(img, wb, clip, &clipped); let mut levels = vec![first]; while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { let next = pull(l); @@ -392,7 +438,7 @@ pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; let Some(field) = levels.first() else { return count }; // the rim (level 0 of its pyramid holds the estimate), if there is one anywhere at all let rims = { - let mut levels = vec![rim(img, wb, clip, &needed)]; + let mut levels = vec![rim(img, wb, clip, &needed, &clipped)]; while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { let next = pull(l); levels.push(next); @@ -402,10 +448,15 @@ pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; }; let rim_field = rims.as_ref().and_then(|l| l.first()); let max_level = wb.iter().cloned().fold(0.0f32, f32::max) * clip; + // the level of a fully clipped pixel (white-balanced `q`) + let full_level = |q: [f32; 3]| { + let top = q.iter().cloned().fold(0.0f32, f32::max); + if lift { top.max(max_level) } else { top } + }; img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { for (x, px) in row.iter_mut().enumerate() { let p = *px; - let cl = [p[0] >= clip, p[1] >= clip, p[2] >= clip]; + let cl = clipped(y * w + x, &p); if !cl.iter().any(|&b| b) { continue; } @@ -460,7 +511,7 @@ pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; (Some(a), Some(b)) => std::array::from_fn(|c| b[c] + (a[c] - b[c]) * trust), (Some(a), None) | (None, Some(a)) => a, (None, None) => { - let v = q.iter().cloned().fold(0.0f32, f32::max).max(max_level); + let v = full_level(q); white.map(|c| c * v) } }; @@ -481,7 +532,7 @@ pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; let (t_level, t_colour) = (smoothstep(0.5, 1.0, way), smoothstep(start, start + 0.5, way)); if t_colour > 0.0 { let level = (out[0] + out[1] + out[2]) / total; - let full = q.iter().cloned().fold(0.0f32, f32::max).max(max_level); + let full = full_level(q); let v = level + (full - level) * t_level; out = std::array::from_fn(|c| out[c] + (white[c] * v - out[c]) * t_colour); } @@ -750,6 +801,69 @@ mod tests { } } + /// The mask path is the same reconstruction: a mask made from the values gives exactly what the values do + /// (the scenes of the tests above), but for the level fully clipped pixels go to. + #[test] + fn a_mask_made_from_the_values_reconstructs_the_same() { + let (branches, _) = branch_scene(); + let ramp = Rgb32f::from_fn(400, 32, |x, _| { + let k = 0.8 + 0.55 * x as f32 / 399.0; + [0.9 * k, k, 0.8 * k].map(|v| v.min(1.0)) + }); + let mixed = Rgb32f::from_fn(129, 77, |x, y| match (x * 7 + y * 13) % 11 { + 0 => [1.0; 3], + 1..=3 => [1.0, 0.5 + 0.003 * x as f32, 0.4], + _ => [0.6 - 0.002 * y as f32, 0.5, 0.3 + 0.002 * x as f32], + }); + for (name, img) in [("branches", branches), ("ramp", ramp), ("mixed", mixed)] { + let white = [1.02, 0.99, 1.05]; + let mut by_value = img.clone(); + let n = reconstruct_with(&mut by_value, WB, 0.99, white); + let mask: Vec<[bool; 3]> = img.data.iter().map(|p| p.map(|v| v >= 0.99)).collect(); + let mut by_mask = img.clone(); + assert_eq!(reconstruct_by(&mut by_mask, WB, 0.99, white, true, |i, _| mask[i]), n, "{name}"); + assert!(by_mask.data == by_value.data, "{name}"); + // the public mask path: the same wherever no pixel is on its way to fully clipped + let bits: Vec = mask.iter().map(|m| u8::from(m[0]) | u8::from(m[1]) << 1 | u8::from(m[2]) << 2).collect(); + let mut public = img.clone(); + assert_eq!(reconstruct_masked(&mut public, WB, 0.99, white, &bits), n, "{name}"); + assert!(public.data.iter().flatten().all(|v| v.is_finite() && *v >= 0.0), "{name}"); + } + } + + /// A mask decides which channels are clipped, whatever their values; a mask of another size changes nothing. + #[test] + fn a_mask_marks_the_clipped_channels() { + let wb = [1.0f32; 3]; + let base = Rgb32f::from_fn(32, 32, |x, _| if x >= 16 { [0.4, 0.8, 0.4] } else { [0.7, 0.7, 0.35] }); + // the right half's red is a lower bound: its blocks held clipped samples + let mask: Vec = (0..32 * 32).map(|i| if i % 32 >= 16 { CLIPPED_R } else { 0 }).collect(); + let mut img = base.clone(); + assert_eq!(reconstruct_masked(&mut img, wb, 0.99, [1.0; 3], &mask), 32 * 16); + // red rebuilt toward the left half's colour (red = green), never below its mean; green and blue kept + for x in 16..32 { + let p = img.get(x, 16); + assert!(p[0] >= 0.4 && p[1] == 0.8 && p[2] == 0.4, "{p:?}"); + } + let p = img.get(18, 16); + assert!(p[0] > 0.75, "red rebuilt from the colour beside it: {p:?}"); + assert_eq!(img.get(0, 0), base.get(0, 0)); + let mut same = base.clone(); + assert_eq!(reconstruct_masked(&mut same, wb, 0.99, [1.0; 3], &mask[1..]), 0); + assert!(same.data == base.data); + // the thresholds alone see nothing clipped here + let mut plain = base.clone(); + assert_eq!(reconstruct(&mut plain, wb, 0.99), 0); + // a fully masked block is neutral at its own brightest channel, not lifted to the clip level + let mut img = Rgb32f::filled(8, 8, [0.3, 0.3, 0.3]); + let mut all = vec![0u8; 64]; + all[27] = CLIPPED_R | CLIPPED_G | CLIPPED_B; + img.data[27] = [0.35, 0.4, 0.3]; + reconstruct_masked(&mut img, WB, 0.99, [1.0; 3], &all); + let q = balanced(img.data[27]); + assert!(q.iter().all(|v| (v - 2.5 * 0.35).abs() < 1e-4), "{q:?}"); + } + #[test] fn clip_neutral_makes_clipped_white_neutral() { let wb = [2.0, 1.0, 1.5]; diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index ed17107e9fe..49ae2e09f2c 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -7,7 +7,8 @@ //! - [`RawImage::normalized`] subtracts black, scales white to 1.0 and crops to the active area (applying DNG //! `OpcodeList1`/`OpcodeList2`); [`demosaic`] turns CFA data into camera-RGB [`Rgb32f`]; //! [`RawImage::develop`] does all of it plus `OpcodeList3` and the default crop; [`RawImage::develop_binned`] -//! produces the same at 1/k of the size straight from the mosaic (previews, thumbnails). +//! produces the same at 1/k of the size straight from the mosaic (previews, thumbnails; +//! [`RawImage::develop_binned_masked`] with the mask of blocks holding clipped samples, for [`highlight`]). //! - [`color`] implements the DNG colour model (dual-illuminant interpolation, forward matrices, white balance) //! and produces camera → linear Rec.2020 D65 matrices; [`profile`] reads and applies a DNG's own profile //! look tables and tone curve, and [`gaintable`] its gain table map (Apple ProRAW's local tone mapping). diff --git a/docs/parity.md b/docs/parity.md index ad82e3d2516..b6468e423a2 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -242,7 +242,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins. | LR-EDIT-HDR-MODE | HDR editing | P2 | ✅ | `cmd:develop.hdr`, `ctl:hdr.maxEv`, `crates/ui-egui/src/panels/edit.rs` (`hdr_row`) | HDR switch in the Light panel; see Q. HDR | | LR-EDIT-LIGHT-EXPOSURE | Exposure | P0 | ✅ | `ctl:light.exposure` | | | LR-EDIT-LIGHT-CONTRAST | Contrast | P0 | ✅ | `ctl:light.contrast` | | -| 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) | +| 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) | | LR-EDIT-LIGHT-SHADOWS | Shadows | P0 | ✅ | `ctl:light.shadows` | | | LR-EDIT-LIGHT-WHITES | Whites | P0 | ✅ | `ctl:light.whites` | | | LR-EDIT-LIGHT-BLACKS | Blacks | P0 | ✅ | `ctl:light.blacks` | |