diff --git a/crates/develop/src/sensor/demosaic.rs b/crates/develop/src/sensor/demosaic.rs index 8a0a96fd4..b0f825818 100644 --- a/crates/develop/src/sensor/demosaic.rs +++ b/crates/develop/src/sensor/demosaic.rs @@ -11,7 +11,7 @@ //! Every method reproduces a constant-colour mosaic exactly. mod ahd; -mod bilinear; +pub(super) mod bilinear; mod ppg; mod xtrans; @@ -26,6 +26,10 @@ pub enum Method { Ahd, } +pub(super) fn mosaic_method(cfa: &Cfa, w: usize, h: usize, method: Method) -> Method { + if (w < 4 || h < 4) && cfa.is_bayer() { Method::Bilinear } else { method } +} + /// Mirror-reflected access to a single-plane mosaic (reflection keeps Bayer parity: −k → k, w−1+k → w−1−k). #[derive(Clone, Copy)] pub(crate) struct Mosaic<'a> { @@ -96,17 +100,9 @@ pub fn demosaic(n: &Normalized, method: Method) -> Rgb32f { (None, _) => Rgb32f { width: w, height: h, data: n.data.iter().map(|&v| [v; 3]).collect() }, (Some(cfa), _) => { let m = Mosaic { w, h, data: &n.data, cfa }; - if !cfa.is_bayer() { - return match method { - Method::Bilinear => bilinear::bilinear(&m), - _ => xtrans::directional(&m), - }; - } - if w < 4 || h < 4 { - return bilinear::bilinear(&m); - } - match method { + match mosaic_method(cfa, w, h, method) { Method::Bilinear => bilinear::bilinear(&m), + _ if !cfa.is_bayer() => xtrans::directional(&m), Method::Ppg => ppg::ppg(&m), Method::Ahd => ahd::ahd(&m), } diff --git a/crates/develop/src/sensor/demosaic/bilinear.rs b/crates/develop/src/sensor/demosaic/bilinear.rs index b47528023..268b0bd6f 100644 --- a/crates/develop/src/sensor/demosaic/bilinear.rs +++ b/crates/develop/src/sensor/demosaic/bilinear.rs @@ -1,12 +1,15 @@ //! Bilinear demosaicing for any CFA pattern: each missing colour is the mean of the same-colour samples in the //! 3×3 neighbourhood (5×5 when the 3×3 has none, as happens in some non-Bayer layouts). -use super::super::Rgb32f; use super::Mosaic; use crate::raster::par_rows; +use crate::sensor::highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; +use crate::sensor::{Rect, Rgb32f}; + +type PhaseTaps = [Vec<(isize, isize)>; 3]; /// Offsets (dx, dy) of same-colour neighbours for each pattern position and colour. -pub(crate) fn neighbour_table(m: &Mosaic) -> Vec<[Vec<(isize, isize)>; 3]> { +fn neighbour_table(m: &Mosaic) -> Vec { let cfa = m.cfa; let mut table = Vec::with_capacity(cfa.width * cfa.height); for py in 0..cfa.height { @@ -33,6 +36,34 @@ pub(crate) fn neighbour_table(m: &Mosaic) -> Vec<[Vec<(isize, isize)>; 3]> { table } +/// Visit the samples that contribute to a missing channel, in interpolation order. +#[inline] +fn for_each_tap(m: &Mosaic, table: &[PhaseTaps], x: usize, y: usize, c: usize, mut visit: impl FnMut(f32)) { + let cfa = m.cfa; + if x >= 2 && y >= 2 && x + 2 < m.w && y + 2 < m.h { + let entry = &table[(y % cfa.height) * cfa.width + (x % cfa.width)]; + for &(dx, dy) in &entry[c] { + visit(m.data[(y as isize + dy) as usize * m.w + (x as isize + dx) as usize]); + } + return; + } + for r in [1isize, 2] { + let mut found = false; + for dy in -r..=r { + for dx in -r..=r { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if m.color(nx, ny) as usize == c { + visit(m.get(nx, ny)); + found = true; + } + } + } + if found { + break; + } + } +} + pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f { let (w, h) = (m.w, m.h); let table = neighbour_table(m); @@ -41,38 +72,44 @@ pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f { par_rows(&mut out.data, w, |y, row| { for (x, px) in row.iter_mut().enumerate() { let own = cfa.color_at(x, y) as usize; - let interior = x >= 2 && y >= 2 && x + 2 < w && y + 2 < h; - let entry = &table[(y % cfa.height) * cfa.width + (x % cfa.width)]; - for c in 0..3 { + for (c, channel) in px.iter_mut().enumerate() { if c == own { - px[c] = m.data[y * w + x]; + *channel = m.data[y * w + x]; continue; } let (mut s, mut n) = (0.0f32, 0u32); - if interior { - for &(dx, dy) in &entry[c] { - s += m.data[(y as isize + dy) as usize * w + (x as isize + dx) as usize]; - n += 1; - } - } else { - for r in [1isize, 2] { - for dy in -r..=r { - for dx in -r..=r { - let (nx, ny) = (x as isize + dx, y as isize + dy); - if m.color(nx, ny) as usize == c { - s += m.get(nx, ny); - n += 1; - } - } - } - if n > 0 { - break; - } - } - } - px[c] = if n > 0 { s / n as f32 } else { m.data[y * w + x] }; + for_each_tap(m, &table, x, y, c, |v| { + s += v; + n += 1; + }); + *channel = if n > 0 { s / n as f32 } else { m.data[y * w + x] }; } } }); out } + +pub(in crate::sensor) fn clip_mask(m: &Mosaic, crop: Rect, clip: f32) -> Vec { + let table = neighbour_table(m); + let mut mask = vec![0; crop.width * crop.height]; + par_rows(&mut mask, crop.width, |oy, row| { + let y = crop.y + oy; + for (ox, bits) in row.iter_mut().enumerate() { + let x = crop.x + ox; + let own = m.cfa.color_at(x, y) as usize; + if m.data[y * m.w + x] >= clip { + *bits = CLIPPED_BITS[own]; + continue; + } + // Each channel uses only its own taps, so leave the measured-colour field unset. + for (c, bit) in FROM_CLIPPED_BITS.into_iter().enumerate().filter(|&(c, _)| c != own) { + for_each_tap(m, &table, x, y, c, |v| { + if v >= clip { + *bits |= bit; + } + }); + } + } + }); + mask +} diff --git a/crates/develop/src/sensor/highlight.rs b/crates/develop/src/sensor/highlight.rs index 7849e4fc8..50732bf38 100644 --- a/crates/develop/src/sensor/highlight.rs +++ b/crates/develop/src/sensor/highlight.rs @@ -9,8 +9,7 @@ //! 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, whose clipped channels a mask tells (block means with a -//! clipped sample among them). +//! - [`reconstruct_masked`]: also uses clipping information from the original mosaic, for binned and full-size images. //! //! 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 @@ -82,6 +81,10 @@ const AGREE: (f32, f32) = (0.15, 0.4); /// colour left in a pale sky once a channel clipped is as much the estimate's error as the sky's, and darkening /// shows it. const PALE: (f32, f32) = (0.2, 0.4); +/// Minimum brightness ratio against reconstruction by value. Its inverse limits brightening in saturated colours. +const CONTINUITY: f32 = 0.8; +/// Weights for comparing white-balanced brightness. +const LUMA: [f32; 3] = [0.2126, 0.7152, 0.0722]; #[inline] fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { @@ -296,15 +299,17 @@ fn bound(p: [f32; 3], cl: [bool; 3], clip: f32, c: usize) -> f32 { if cl[c] { 1.0 } else { smoothstep(FLOOR_LO, 1.0, p[c] / clip) } } -/// How many stops the channels of a partly clipped pixel (sensor values `p`, white-balanced `q`, clipped channels -/// `cl`) contradict chromaticity `r`: how far the levels they imply spread, where a clipped channel's only bounds the -/// level from below (see [`bound`]). 0 for the pixel's own colour, whatever its level. -fn contradiction(p: [f32; 3], q: [f32; 3], cl: [bool; 3], r: [f32; 3], clip: f32) -> f32 { +/// How many stops a pixel's channels contradict chromaticity `r`. A saturated channel sets a lower bound. +/// Channels with unknown values do not constrain the estimate. +fn contradiction(p: [f32; 3], q: [f32; 3], clipping: Clipping, r: [f32; 3], clip: f32) -> f32 { let (mut lo, mut hi) = (f32::INFINITY, 0f32); for c in 0..3 { + if clipping.unknown(c) { + continue; + } let level = q[c] / r[c].max(1e-3); hi = hi.max(level); - let w = bound(p, cl, clip, c); + let w = bound(p, clipping.clipped, clip, c); if r[c] > 1e-3 && w < 1.0 { lo = lo.min(level / (1.0 - w)); } @@ -312,15 +317,14 @@ fn contradiction(p: [f32; 3], q: [f32; 3], cl: [bool; 3], r: [f32; 3], clip: f32 if hi > 0.0 && lo > 0.0 && lo.is_finite() { (hi / lo).log2().max(0.0) } else { 0.0 } } -/// The white-balanced colour of a partly clipped pixel (sensor values `p`, white-balanced `q`, clipped channels -/// `cl`) whose colour is estimated at chromaticity `r`: clipped channels rebuilt, unclipped ones kept. `None` -/// when no unclipped channel can tell the level. -fn rebuild(p: [f32; 3], q: [f32; 3], cl: [bool; 3], r: [f32; 3], clip: f32, max_level: f32) -> Option<[f32; 3]> { +/// Rebuild a pixel at chromaticity `r` using its known, unclipped channels to estimate the level. +/// Keep those channels and use saturated values as lower bounds. +fn rebuild(p: [f32; 3], q: [f32; 3], clipping: Clipping, r: [f32; 3], clip: f32, max_level: f32) -> Option<[f32; 3]> { // The white-balanced channel sum the unclipped channels imply: their mean, except that a channel about to clip // counts more and more as the floor it is about to become (continuous with the neighbours where it has). let (mut sum, mut near_clip, mut k) = (0f32, 0f32, 0usize); for c in 0..3 { - if !cl[c] && r[c] > 1e-3 { + if !clipping.clipped[c] && r[c] > 1e-3 { let s = q[c] / r[c]; sum += s; near_clip = near_clip.max(s * smoothstep(FLOOR_LO, 1.0, p[c] / clip)); @@ -334,10 +338,14 @@ fn rebuild(p: [f32; 3], q: [f32; 3], cl: [bool; 3], r: [f32; 3], clip: f32, max_ // clips first), and the pair would show as magenta or red. They keep the estimate's ratio instead, at the level // that lifts each to its clip (no channel above the clipped neutral), and so does a channel about to clip (the // same floor, so nothing jumps where it clips). - let floor = (0..3).filter(|&c| cl[c]).map(|c| q[c] / r[c].max(1e-3)).fold(0.0f32, f32::max); + let floor = (0..3).filter(|&c| clipping.saturated[c]).map(|c| q[c] / r[c].max(1e-3)).fold(0.0f32, f32::max); let top = r[0].max(r[1]).max(r[2]).max(1e-3); let sum = (sum / k as f32).max(near_clip.max(floor).min(max_level / top)); - Some(std::array::from_fn(|c| if cl[c] { q[c].max(sum * r[c]) } else { q[c] })) + Some(std::array::from_fn(|c| match (clipping.clipped[c], clipping.saturated[c]) { + (true, true) => q[c].max(sum * r[c]), + (true, false) => sum * r[c], + _ => q[c], + })) } /// Reconstruct partially clipped channels, with a neutral that is neutral in camera RGB. See @@ -354,43 +362,87 @@ 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 { - rebuild_clipped(img, wb, clip, white, &|_, p| by_value(p, clip)) + rebuild_clipped(img, wb, clip, white, &|_, p| Clipping::from_values(p, clip)) } -/// Bits of a [`reconstruct_masked`] mask entry: which channels of the pixel had a clipped sample. +/// Bits of a [`reconstruct_masked`] mask entry: which channels of the pixel had a clipped sample (saturated: their +/// value is a lower bound of the true one). pub const CLIPPED_R: u8 = 1; pub const CLIPPED_G: u8 = 2; pub const CLIPPED_B: u8 = 4; +/// Bits of a [`reconstruct_masked`] mask entry for the colours of nearby clipped samples that can affect interpolation. +/// In a directional mask, a clipped sample of the measured colour can still affect the interpolated channels. +pub const FROM_CLIPPED_R: u8 = 8; +pub const FROM_CLIPPED_G: u8 = 16; +pub const FROM_CLIPPED_B: u8 = 32; +/// Bits 6 and 7 of a directional [`reconstruct_masked`] mask entry: the measured colour plus one. +/// Binned and bilinear masks leave this field at zero. +pub const MEASURED_SHIFT: u8 = 6; -/// [`reconstruct_with`] for a binned image ([`crate::RawImage::develop_binned_masked`]): its values are block +pub(super) const CLIPPED_BITS: [u8; 3] = [CLIPPED_R, CLIPPED_G, CLIPPED_B]; +pub(super) const FROM_CLIPPED_BITS: [u8; 3] = [FROM_CLIPPED_R, FROM_CLIPPED_G, FROM_CLIPPED_B]; + +/// [`reconstruct_with`] for a binned image ([`super::RawDevelopExt::develop_binned_masked`]): its values are block /// means, and `mask` (one entry per pixel, bits [`CLIPPED_R`], [`CLIPPED_G`], [`CLIPPED_B`]) says which colours /// had a clipped sample in the block. Those channels count as clipped with their mean as the lower bound of their /// true value, so one clipped specular sample among many unclipped ones neither escapes reconstruction nor /// (as the block's maximum would) lifts the channel to the clip level, which reads as a coloured speckle (#548). +/// +/// For a full-size demosaic ([`super::RawDevelopExt::develop_balanced_masked`]), the mask records the colours +/// of clipped samples that can affect interpolation. In a directional mask, it also records the measured +/// colour so reconstruction can treat only the interpolated channels below clip as unknown. A dependency on the +/// measured colour alone triggers that treatment when every channel is below clip. This preserves partly clipped +/// detail when another channel is already saturated. A bilinear mask marks each interpolated channel separately. +/// Interpolated values at or above clip still count as lower bounds. +/// Reconstruction uses the known channels and limits brightness changes near strongly coloured highlights. +/// /// A mask of the wrong length is ignored (clipping is then told by the values alone). 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 reconstruct_with(img, wb, clip, white); } - rebuild_clipped(img, wb, clip, white, &|i, p| { - let m = mask.get(i).copied().unwrap_or(0); - let v = by_value(p, clip); - [v[0] || m & CLIPPED_R != 0, v[1] || m & CLIPPED_G != 0, v[2] || m & CLIPPED_B != 0] - }) + rebuild_clipped(img, wb, clip, white, &|i, p| masked(mask[i], p, clip)) } -/// Which channels of pixel `i` (values `p`) are clipped. +#[derive(Clone, Copy)] +struct Clipping { + /// Channels to rebuild, including saturated channels and interpolated values of unknown accuracy. + clipped: [bool; 3], + saturated: [bool; 3], +} + +impl Clipping { + fn from_values(p: &[f32; 3], clip: f32) -> Self { + let saturated = p.map(|v| v >= clip); + Self { clipped: saturated, saturated } + } + + fn unknown(self, c: usize) -> bool { + self.clipped[c] && !self.saturated[c] + } +} + +#[inline] +fn masked(m: u8, p: &[f32; 3], clip: f32) -> Clipping { + let bit = |b: u8| m & b != 0; + let saturated = std::array::from_fn(|c| p[c] >= clip || bit(CLIPPED_BITS[c])); + let mut unknown: [bool; 3] = std::array::from_fn(|c| bit(FROM_CLIPPED_BITS[c]) && !saturated[c]); + if let Some(own) = ((m >> MEASURED_SHIFT) as usize).checked_sub(1).filter(|&c| !saturated[c]) { + let from_measured_colour = std::mem::take(&mut unknown[own]); + if unknown.iter().any(|&u| u) || (from_measured_colour && !saturated.iter().any(|&c| c)) { + unknown = std::array::from_fn(|c| c != own && !saturated[c]); + } + } + Clipping { clipped: std::array::from_fn(|c| saturated[c] || unknown[c]), saturated } +} + +/// Which channels of pixel `i` (values `p`) need to be rebuilt. trait Clipped: Fn(usize, &[f32; 3]) -> [bool; 3] + Sync {} impl [bool; 3] + Sync> Clipped for F {} -#[inline] -fn by_value(p: &[f32; 3], clip: f32) -> [bool; 3] { - [p[0] >= clip, p[1] >= clip, p[2] >= clip] -} - -/// [`reconstruct_with`], with `clipped` telling the clipped channels. -fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], clipped: &impl Clipped) -> usize { +fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], classify: &(impl Fn(usize, &[f32; 3]) -> Clipping + Sync)) -> usize { let (w, h) = (img.width, img.height); + let clipped = |i, p: &[f32; 3]| classify(i, p).clipped; #[cfg(not(target_arch = "wasm32"))] let count = img.data.par_iter().enumerate().filter(|(i, p)| clipped(*i, p).iter().any(|&c| c)).count(); #[cfg(target_arch = "wasm32")] @@ -405,7 +457,7 @@ fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], c 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, clipped); + 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); @@ -443,7 +495,7 @@ fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], c 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, clipped, &needed)]; + let mut levels = vec![rim(img, wb, clip, &clipped, &needed)]; while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { let next = pull(l); levels.push(next); @@ -453,88 +505,123 @@ fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], c }; let rim_field = rims.as_ref().and_then(|l| l.first()); let max_level = wb.iter().cloned().fold(0.0f32, f32::max) * clip; + let solve = |x: usize, y: usize, p: [f32; 3], clipping: Clipping| -> [f32; 3] { + let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; + let known_top = || (0..3).filter(|&c| !clipping.unknown(c)).map(|c| q[c]).fold(0.0f32, f32::max); + // rebuilt with the colour of the reliable content around, and with neutral, blended by how much of it + // there is and how well the pixel agrees with it (blending the results, not the colours, keeps the + // estimate consistent with the pixel's own unclipped channels all the way) + let e = sample(field, 2.0, x, y); + let borrowed = [e[0], 1.0 - e[0] - e[1], e[1]]; + let edge = rim_field.map(|rim| sample(rim, 4.0, x, y)); + let mut trust = e[2].clamp(0.0, 1.0); + if trust > 0.0 { + let mut off = contradiction(p, q, clipping, borrowed, clip); + if off > AGREE.0 { + off = off.min(edge.map_or(0.0, |edge| { + let s = edge[0] + edge[1] + edge[2]; + if s > 1e-6 { unlike([edge[0] / s, edge[1] / s, edge[2] / s], borrowed) } else { 0.0 } + })); + } + trust *= 1.0 - smoothstep(AGREE.0, AGREE.1, off); + } + // either applies only as far as the pixel lies past the rim nearest its clip (in any channel); nearer, the + // pixel is rebuilt with the rim's colour + let at_rim = edge.and_then(|edge| { + // stops between pixel and rim in each channel; a clipped channel's true value lies at least as far + // above the rim's as its clip, and no further below (see [`bound`]) + let ratio = (0..3) + .map(|c| { + if clipping.unknown(c) { + return 1.0; + } + let (a, b) = (q[c].max(1e-12), edge[c].max(1e-12)); + if a >= b { + return a / b; + } + match bound(p, clipping.clipped, clip, c) { + w if w <= 0.0 => b / a, + w if w >= 1.0 => 1.0, + w => (b / a).powf(1.0 - w), + } + }) + .fold(1.0f32, f32::max); + let past = ratio.log2().min(64.0); + let k = smoothstep(NEAR_RIM, NEAR_RIM + DEPTH, past); + let s = edge[0] + edge[1] + edge[2]; + (k < 1.0 && s > 1e-6).then(|| rebuild(p, q, clipping, [edge[0] / s, edge[1] / s, edge[2] / s], clip, max_level)).flatten().map(|a| (a, k)) + }); + let past_rim = |b: [f32; 3]| -> [f32; 3] { + let Some((a, k)) = at_rim else { return b }; + std::array::from_fn(|c| a[c] + (b[c] - a[c]) * k) + }; + let local = (trust > 0.0).then(|| rebuild(p, q, clipping, borrowed, clip, max_level)).flatten().map(past_rim); + let plain = (trust < 1.0).then(|| rebuild(p, q, clipping, neutral, clip, max_level)).flatten().map(past_rim); + let mut out = match (local, plain) { + (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 = known_top().max(max_level); + white.map(|c| c * v) + } + }; + // Fade into the fully clipped neutral on the way from the first channel clipping (no change: continuous + // with the unclipped neighbours) to the last one clipping (all of it: continuous with the fully clipped + // ones). The way is measured in stops: how far the rebuilt clipped channels lie above their clip, + // against how far the lowest unclipped channel still lies below its own. + let above = (0..3).filter(|&c| clipping.saturated[c]).map(|c| (out[c] / q[c].max(1e-9)).max(1.0).log2()).fold(0.0f32, f32::max); + let lowest = (0..3).filter(|&c| !clipping.clipped[c]).map(|c| p[c]).fold(f32::MAX, f32::min); + let below = (clip / lowest.max(1e-6)).log2().max(0.0); + let way = if above > 0.0 && lowest < clip { above / (above + below) } else { 0.0 }; + // The brightness goes over in the second half of the way, and so does the colour of a strongly coloured + // pixel; a pale one's goes over from the start ([`PALE`]). + let u = [out[0] / white[0], out[1] / white[1], out[2] / white[2]]; + let (lo, hi) = (u[0].min(u[1]).min(u[2]), u[0].max(u[1]).max(u[2])); + let saturation = if hi > 0.0 && hi.is_finite() { 1.0 - lo.max(0.0) / hi } else { 1.0 }; + let start = 0.5 * smoothstep(PALE.0, PALE.1, saturation); + 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 = known_top().max(max_level); + let v = level + (full - level) * t_level; + out = std::array::from_fn(|c| out[c] + (white[c] * v - out[c]) * t_colour); + } + out + }; par_rows(&mut img.data, w, |y, row| { for (x, px) in row.iter_mut().enumerate() { let p = *px; - let cl = clipped(y * w + x, &p); - if !cl.iter().any(|&b| b) { + let clipping = classify(y * w + x, &p); + if !clipping.clipped.iter().any(|&b| b) { continue; } - let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; - // rebuilt with the colour of the reliable content around, and with neutral, blended by how much of it - // there is and how well the pixel agrees with it (blending the results, not the colours, keeps the - // estimate consistent with the pixel's own unclipped channels all the way) - let e = sample(field, 2.0, x, y); - let borrowed = [e[0], 1.0 - e[0] - e[1], e[1]]; - let edge = rim_field.map(|rim| sample(rim, 4.0, x, y)); - let mut trust = e[2].clamp(0.0, 1.0); - if trust > 0.0 { - let mut off = contradiction(p, q, cl, borrowed, clip); - if off > AGREE.0 { - off = off.min(edge.map_or(0.0, |edge| { - let s = edge[0] + edge[1] + edge[2]; - if s > 1e-6 { unlike([edge[0] / s, edge[1] / s, edge[2] / s], borrowed) } else { 0.0 } + let mut out = solve(x, y, p, clipping); + if (0..3).any(|c| clipping.unknown(c)) { + // Rebuilding a highlight from its weakest channel can make its rim too dark. + // Use the value-based estimate when the mask causes a large brightness drop. + // Also limit brightening, with more room in pale areas where the mask removes colour fringes. + let by_value = Clipping::from_values(&p, clip); + let alt = if by_value.clipped.iter().any(|&b| b) { solve(x, y, p, by_value) } else { [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]] }; + let luma = |c: [f32; 3]| LUMA[0] * c[0] + LUMA[1] * c[1] + LUMA[2] * c[2]; + let ratio = luma(out) / luma(alt).max(1e-9); + let coloured = || { + // how strongly coloured the reliable content around is, and the rim nearest the clip + let e = sample(field, 2.0, x, y); + let around = [[e[0], 1.0 - e[0] - e[1], e[1]]].into_iter().chain(rim_field.map(|rim| { + let e = sample(rim, 4.0, x, y); + [e[0], e[1], e[2]] })); + around + .map(|c| { + let u = [c[0] / white[0], c[1] / white[1], c[2] / white[2]]; + let (lo, hi) = (u[0].min(u[1]).min(u[2]), u[0].max(u[1]).max(u[2])); + if hi > 1e-9 && hi.is_finite() { smoothstep(PALE.0, PALE.1, 1.0 - lo.max(0.0) / hi) } else { 0.0 } + }) + .fold(0.0f32, f32::max) + }; + if !ratio.is_finite() || ratio < CONTINUITY || (ratio > 1.0 / CONTINUITY && ratio.log2() * coloured() > -CONTINUITY.log2()) { + out = alt; } - trust *= 1.0 - smoothstep(AGREE.0, AGREE.1, off); - } - // either applies only as far as the pixel lies past the rim nearest its clip (in any channel); nearer, the - // pixel is rebuilt with the rim's colour - let at_rim = edge.and_then(|edge| { - // stops between pixel and rim in each channel; a clipped channel's true value lies at least as far - // above the rim's as its clip, and no further below (see [`bound`]) - let ratio = (0..3) - .map(|c| { - let (a, b) = (q[c].max(1e-12), edge[c].max(1e-12)); - if a >= b { - return a / b; - } - match bound(p, cl, clip, c) { - w if w <= 0.0 => b / a, - w if w >= 1.0 => 1.0, - w => (b / a).powf(1.0 - w), - } - }) - .fold(1.0f32, f32::max); - let past = ratio.log2().min(64.0); - let k = smoothstep(NEAR_RIM, NEAR_RIM + DEPTH, past); - let s = edge[0] + edge[1] + edge[2]; - (k < 1.0 && s > 1e-6).then(|| rebuild(p, q, cl, [edge[0] / s, edge[1] / s, edge[2] / s], clip, max_level)).flatten().map(|a| (a, k)) - }); - let past_rim = |b: [f32; 3]| -> [f32; 3] { - let Some((a, k)) = at_rim else { return b }; - std::array::from_fn(|c| a[c] + (b[c] - a[c]) * k) - }; - let local = (trust > 0.0).then(|| rebuild(p, q, cl, borrowed, clip, max_level)).flatten().map(past_rim); - let plain = (trust < 1.0).then(|| rebuild(p, q, cl, neutral, clip, max_level)).flatten().map(past_rim); - let mut out = match (local, plain) { - (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); - white.map(|c| c * v) - } - }; - // Fade into the fully clipped neutral on the way from the first channel clipping (no change: continuous - // with the unclipped neighbours) to the last one clipping (all of it: continuous with the fully clipped - // ones). The way is measured in stops: how far the rebuilt clipped channels lie above their clip, - // against how far the lowest unclipped channel still lies below its own. - let above = (0..3).filter(|&c| cl[c]).map(|c| (out[c] / q[c].max(1e-9)).max(1.0).log2()).fold(0.0f32, f32::max); - let lowest = (0..3).filter(|&c| !cl[c]).map(|c| p[c]).fold(f32::MAX, f32::min); - let below = (clip / lowest.max(1e-6)).log2().max(0.0); - let way = if above > 0.0 && lowest < clip { above / (above + below) } else { 0.0 }; - // The brightness goes over in the second half of the way, and so does the colour of a strongly coloured - // pixel; a pale one's goes over from the start ([`PALE`]). - let u = [out[0] / white[0], out[1] / white[1], out[2] / white[2]]; - let (lo, hi) = (u[0].min(u[1]).min(u[2]), u[0].max(u[1]).max(u[2])); - let saturation = if hi > 0.0 && hi.is_finite() { 1.0 - lo.max(0.0) / hi } else { 1.0 }; - let start = 0.5 * smoothstep(PALE.0, PALE.1, saturation); - 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 v = level + (full - level) * t_level; - out = std::array::from_fn(|c| out[c] + (white[c] * v - out[c]) * t_colour); } *px = [out[0] / wb[0], out[1] / wb[1], out[2] / wb[2]]; } diff --git a/crates/develop/src/sensor/mod.rs b/crates/develop/src/sensor/mod.rs index 4429ad9d5..f7f20ab0a 100644 --- a/crates/develop/src/sensor/mod.rs +++ b/crates/develop/src/sensor/mod.rs @@ -15,8 +15,10 @@ pub use craft_raw::opcodes::{Opcode, OpcodeLists}; pub use craft_raw::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, RawData, RawError, RawFormat, RawImage, RawInfo, Rect, Result, stretched_height}; pub use demosaic::{Method, demosaic}; -use crate::raster::Rgb32f; use crate::raster::resample::{Filter, resize}; +use crate::raster::{Rgb32f, par_rows}; +#[cfg(not(target_arch = "wasm32"))] +use rayon::prelude::*; /// Checked product of input-derived dimensions, in u64 so it cannot wrap on 32-bit or 64-bit /// targets. Returns `None` on overflow, zero, or when the product exceeds [`MAX_SAMPLES`]. @@ -55,7 +57,19 @@ pub trait RawDevelopExt { fn validate(&self) -> Result<()>; fn white_at(&self, s: usize) -> f32; fn normalized(&self) -> Result; + /// Develop camera RGB with the demosaic on the sensor's original colour scale. fn develop(&self, method: Method) -> Result; + /// Demosaic after applying white balance `wb` to the mosaic, with gains relative to green. + /// Directional interpolation then sees little colour difference across a neutral edge. + /// The returned RGB is back on the sensor's scale for highlight reconstruction and colour conversion. + /// Bilinear, monochrome and already demosaiced data use the same path as [`Self::develop`]. + /// Unusable gains or samples also fall back to that path. + fn develop_balanced(&self, method: Method, wb: [f32; 3]) -> Result; + /// [`Self::develop_balanced`] with a per-pixel sensor clip mask for [`highlight::reconstruct_masked`]. + /// The mask uses the normalised sensor threshold `clip` and covers the default crop. + /// The mask is absent for an unclipped mosaic, data without a single-plane CFA, `OpcodeList3`, + /// or a pixel-aspect correction that changes the output grid. + fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)>; fn finish_demosaiced(&self, rgb: Rgb32f) -> Rgb32f; fn develop_crop(&self, width: usize, height: usize) -> Rect; fn can_bin(&self, k: usize) -> bool; @@ -145,17 +159,17 @@ impl RawDevelopExt for RawImage { } fn develop(&self, method: Method) -> Result { + Ok(develop_full(self, self.normalized()?, method, None)) + } + + fn develop_balanced(&self, method: Method, wb: [f32; 3]) -> Result { + Ok(develop_full(self, self.normalized()?, method, Some(wb))) + } + + fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)> { let n = self.normalized()?; - if self.opcodes.list3.is_empty() && method == Method::Ahd { - let c = self.develop_crop(n.width, n.height); - if let Some(rgb) = demosaic::ahd_window(&n, c) { - drop(n); - return Ok(stretched(self, rgb)); - } - } - let rgb = demosaic(&n, method); - drop(n); - Ok(self.finish_demosaiced(rgb)) + let mask = clip_mask(self, &n, method, clip); + Ok((develop_full(self, n, method, Some(wb)), mask)) } fn finish_demosaiced(&self, mut rgb: Rgb32f) -> Rgb32f { @@ -184,6 +198,119 @@ impl RawDevelopExt for RawImage { } } +fn develop_full(raw: &RawImage, mut n: Normalized, method: Method, wb: Option<[f32; 3]>) -> Rgb32f { + let gains = wb.and_then(balance_gains).filter(|&gains| scale_mosaic(&mut n, method, gains)); + let window = + if raw.opcodes.list3.is_empty() && method == Method::Ahd { demosaic::ahd_window(&n, raw.develop_crop(n.width, n.height)) } else { None }; + let windowed = window.is_some(); + let mut rgb = window.unwrap_or_else(|| demosaic(&n, method)); + drop(n); + if let Some(gains) = gains { + par_rows(&mut rgb.data, rgb.width, |_, row| { + for p in row { + p[0] /= gains[0]; + p[2] /= gains[2]; + } + }); + } + if windowed { stretched(raw, rgb) } else { raw.finish_demosaiced(rgb) } +} + +fn balance_gains(wb: [f32; 3]) -> Option<[f32; 3]> { + // A factor of 64 in either direction is already wider than camera white balances. + const MAX_GAIN: f32 = 64.0; + if !wb.iter().all(|v| v.is_finite() && *v > 0.0) { + return None; + } + let gains = [wb[0] / wb[1], 1.0, wb[2] / wb[1]]; + (gains != [1.0; 3] && gains.iter().all(|g| (1.0 / MAX_GAIN..=MAX_GAIN).contains(g))).then_some(gains) +} + +fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool { + let Some(cfa) = n.cfa.as_ref().filter(|_| n.cpp == 1) else { return false }; + if demosaic::mosaic_method(cfa, n.width, n.height, method) == Method::Bilinear { + return false; + } + + // Leave room for demosaic arithmetic and the division back to camera RGB, even for float DNGs. + // Check the whole mosaic before scaling it so the fallback can reuse the normalised data. + let largest_factor = gains.into_iter().map(|g| g.max(1.0 / g)).fold(1.0f32, f32::max); + let limit = 1e30 / largest_factor; + let fits = |v: &f32| v.abs() <= limit; + #[cfg(not(target_arch = "wasm32"))] + let safe = n.data.par_iter().all(fits); + #[cfg(target_arch = "wasm32")] + let safe = n.data.iter().all(fits); + if !safe { + return false; + } + par_rows(&mut n.data, n.width, |y, row| { + let period: Vec = (0..cfa.width).map(|x| gains[cfa.color_at(x, y) as usize]).collect(); + for (sample, gain) in row.iter_mut().zip(period.iter().cycle()) { + *sample *= gain; + } + }); + true +} + +fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { + use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; + + // This radius covers samples read directly by the directional interpolators. Estimates + // that build on interpolated green can depend on samples farther away. + const REACH: usize = 2; + + let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?; + let (w, h) = (n.width, n.height); + let crop = raw.develop_crop(w, h); + if !clip.is_finite() || clip <= 0.0 || !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + return None; + } + let is_clipped = |v: &f32| *v >= clip; + #[cfg(not(target_arch = "wasm32"))] + let has_clip = n.data.par_iter().any(is_clipped); + #[cfg(target_arch = "wasm32")] + let has_clip = n.data.iter().any(is_clipped); + if !has_clip { + return None; + } + if demosaic::mosaic_method(cfa, w, h, method) == Method::Bilinear { + let mosaic = demosaic::Mosaic { w, h, data: &n.data, cfa }; + return Some(demosaic::bilinear::clip_mask(&mosaic, crop, clip)); + } + + // Collect clipped colours within reach horizontally, then combine those rows for each output pixel. + let mut rows = vec![0u8; w * h]; + par_rows(&mut rows, w, |y, row| { + let samples = &n.data[y * w..(y + 1) * w]; + let clipped: Vec = + samples.iter().enumerate().map(|(x, v)| if is_clipped(v) { FROM_CLIPPED_BITS[cfa.color_at(x, y) as usize] } else { 0 }).collect(); + for (x, bits) in row.iter_mut().enumerate() { + *bits = clipped[x.saturating_sub(REACH)..=(x + REACH).min(w - 1)].iter().fold(0, |a, b| a | b); + } + }); + let mut mask = vec![0u8; crop.width * crop.height]; + par_rows(&mut mask, crop.width, |oy, out| { + let y = crop.y + oy; + for yy in y.saturating_sub(REACH)..=(y + REACH).min(h - 1) { + let start = yy * w + crop.x; + out.iter_mut().zip(&rows[start..start + crop.width]).for_each(|(o, s)| *o |= s); + } + for (ox, bits) in out.iter_mut().enumerate() { + let x = crop.x + ox; + let colour = cfa.color_at(x, y); + if is_clipped(&n.data[y * w + x]) { + // Keep the interpolated values around a clipped measurement. They can carry thin dark detail. + *bits = CLIPPED_BITS[colour as usize]; + } else if *bits != 0 { + // A same-colour sample can affect the other channels through the green estimates. + *bits |= (colour + 1) << highlight::MEASURED_SHIFT; + } + } + }); + Some(mask) +} + fn stretched(raw: &RawImage, rgb: Rgb32f) -> Rgb32f { let h = stretched_height(rgb.height, raw.pixel_aspect); if h == rgb.height { diff --git a/crates/develop/tests/it/balanced.rs b/crates/develop/tests/it/balanced.rs new file mode 100644 index 000000000..4c8584304 --- /dev/null +++ b/crates/develop/tests/it/balanced.rs @@ -0,0 +1,655 @@ +//! Original synthetic RAW scenes from storytold/lightcraft#1463, generated in these tests. + +use craft_develop::raster::Rgb32f; +use craft_develop::sensor::{Method, RawDevelopExt, highlight}; +use craft_raw::opcodes::{Opcode, OpcodeLists}; +use craft_raw::{BlackLevel, Cfa, ColorData, Orientation, RawData, RawFormat, RawImage, Rect}; + +/// Daylight-like as-shot multipliers (a Sony body's are about 2.6 : 1 : 1.85). +const DAYLIGHT: [f32; 3] = [2.5, 1.0, 1.6]; +const CLIP: f32 = 0.99; + +/// A floating-point raw (black 0, white 1) whose mosaic samples `scene` (white-balanced RGB) through `cfa`, divided +/// by `wb` as a sensor records it, and clipped at the white level. +fn raw_of(w: usize, h: usize, cfa: &Cfa, wb: [f32; 3], scene: impl Fn(usize, usize) -> [f32; 3]) -> RawImage { + let data = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let c = cfa.color_at(x, y) as usize; + (scene(x, y)[c] / wb[c]).min(1.0) + }) + .collect(); + RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::F32(data), + cfa: Some(cfa.clone()), + bits: 16, + black: BlackLevel::uniform(0.0), + white: vec![1.0], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::Normal, + color: ColorData::default(), + wb_multipliers: None, + linearized: true, + pixel_aspect: 1.0, + lens_metadata: Default::default(), + opcodes: OpcodeLists::default(), + linearization_table: None, + camera: Default::default(), + cinema: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + } +} + +/// What the decode does after the demosaic, up to the colour matrix: clipped highlights rebuilt, white balance. +fn finish(mut img: Rgb32f, wb: [f32; 3]) -> Rgb32f { + highlight::reconstruct(&mut img, wb, CLIP); + finish_wb(img, wb) +} + +fn layouts() -> Vec<(String, Cfa, Method)> { + let mut v = Vec::new(); + for name in ["RGGB", "BGGR", "GRBG", "GBRG"] { + for m in [Method::Ahd, Method::Ppg] { + v.push((format!("{name} {m:?}"), Cfa::bayer(name).unwrap(), m)); + } + } + v.push(("X-Trans directional".into(), Cfa::xtrans(), Method::Ahd)); + v.push(("X-Trans directional (shifted)".into(), Cfa::xtrans().shifted(2, 3), Method::Ahd)); + v +} + +#[test] +fn balanced_demosaic_returns_constant_colour_on_the_sensor_scale() { + let colours = [[0.3f32, 0.55, 0.8], [0.02, 0.9, 0.4], [0.7, 0.7, 0.7]]; + let wbs = [DAYLIGHT, [1.3, 1.0, 3.1], [2.0, 1.2, 1.5], [1.0; 3]]; + let mut cases = layouts(); + for name in ["RGGB", "GBRG"] { + cases.push((format!("{name} Bilinear"), Cfa::bayer(name).unwrap(), Method::Bilinear)); + } + for (name, cfa, method) in &cases { + for colour in colours { + for wb in wbs { + // the colour as camera RGB, i.e. what the mosaic holds + let raw = raw_of(23, 19, cfa, [1.0; 3], |_, _| colour); + let out = raw.develop_balanced(*method, wb).unwrap(); + for p in &out.data { + for c in 0..3 { + assert!((p[c] - colour[c]).abs() <= 1e-6 * colour[c].max(1.0), "{name} wb {wb:?}: {p:?} for {colour:?}"); + } + } + } + } + } +} + +#[test] +fn every_sample_keeps_its_own_value() { + let cfa = Cfa::bayer("GRBG").unwrap(); + let raw = raw_of(40, 32, &cfa, [1.0; 3], |x, y| { + let v = 0.05 + 0.9 * (((x * 7 + y * 13) % 17) as f32 / 17.0); + [v * 0.6, v, v * 0.8] + }); + let n = raw.normalized().unwrap(); + for m in [Method::Ahd, Method::Ppg] { + let out = raw.develop_balanced(m, DAYLIGHT).unwrap(); + for y in 0..32 { + for x in 0..40 { + let (c, s) = (cfa.color_at(x, y) as usize, n.data[y * 40 + x]); + assert!((out.get(x, y)[c] - s).abs() <= 1e-6, "{m:?} ({x}, {y})"); + } + } + } +} + +#[test] +fn unsupported_white_balance_inputs_keep_the_plain_develop_result() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let raw = raw_of(30, 22, &cfa, DAYLIGHT, |x, y| { + let v = if (x / 5 + y / 4) % 2 == 0 { 0.08 } else { 0.9 }; + [v, v * 0.9, v * 1.1] + }); + for method in [Method::Ahd, Method::Ppg] { + let plain = raw.develop(method).unwrap(); + // multipliers count relative to green: equal ones are no white balance at all + // (and finite multipliers whose ratios would overflow the scaled mosaic or the division back, review of #1328) + for wb in [ + [1.0; 3], + [2.0; 3], + [f32::NAN, 1.0, 1.0], + [0.0, 1.0, 1.5], + [2.0, -1.0, 1.5], + [f32::INFINITY, 1.0, 1.0], + [f32::MAX, 1.0, 1.0], + [1e-40, 1.0, 1.0], + [f32::MIN_POSITIVE, 1.0, 1.0], + [1e20, 1.0, 1e-20], + [f32::MAX, f32::MIN_POSITIVE, 1.0], + ] { + assert_eq!(raw.develop_balanced(method, wb).unwrap(), plain, "{method:?} {wb:?}"); + } + // Strong finite gains still balance when the samples fit. + for wb in [[16.0, 1.0, 1.0 / 16.0], [2.0, 4.0, 3.0]] { + let out = raw.develop_balanced(method, wb).unwrap(); + assert_ne!(out, plain, "{method:?} {wb:?}"); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{method:?} {wb:?}"); + } + } + // bilinear interpolates each colour on its own: nothing to balance + assert_eq!(raw.develop_balanced(Method::Bilinear, DAYLIGHT).unwrap(), raw.develop(Method::Bilinear).unwrap()); + // already demosaiced and monochrome data are left alone + let mut mono = raw.clone(); + mono.cfa = None; + assert_eq!(mono.develop_balanced(Method::Ahd, DAYLIGHT).unwrap(), mono.develop(Method::Ahd).unwrap()); + + let mut linear = mono; + linear.cpp = 3; + linear.data = RawData::F32([0.2, 0.6, 0.8].repeat(linear.width * linear.height)); + assert_eq!(linear.develop_balanced(Method::Ahd, DAYLIGHT).unwrap(), linear.develop(Method::Ahd).unwrap()); +} + +/// What the lens makes of a sharp `scene` (white-balanced level, sampled at sub-pixel positions): each pixel the +/// mean of 4 × 4 points of its area, then a blur of about one pixel (binomial [1 4 6 4 1] / 16 each way: a good lens +/// and the sensor's microlenses). Any sharper and a single sample holds detail no demosaic can place. +fn photograph(w: usize, h: usize, scene: impl Fn(f32, f32) -> f32) -> Vec { + let area: Vec = (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + (0..16).map(|k| scene(x + ((k % 4) as f32 + 0.5) / 4.0, y + ((k / 4) as f32 + 0.5) / 4.0)).sum::() / 16.0 + }) + .collect(); + let blur = |v: &[f32], dx: isize, dy: isize| -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as isize, (i / w) as isize); + let at = |k: isize| v[(y + k * dy).clamp(0, h as isize - 1) as usize * w + (x + k * dx).clamp(0, w as isize - 1) as usize]; + (at(-2) + 4.0 * at(-1) + 6.0 * at(0) + 4.0 * at(1) + at(2)) / 16.0 + }) + .collect() + }; + blur(&blur(&area, 1, 0), 0, 1) +} + +/// Issue #1328: on a dark neutral surface, neutral specular points of 1 to 3 px bright enough to clip green (the +/// brightest clip every channel). Around them, the pixels with nothing clipped must stay neutral after highlight +/// reconstruction and white balance: no channel below half the pixel's mean, none negative. Demosaiced from the +/// unbalanced mosaic, red (or blue) beside a point fell to about zero or below: green and cyan rims, on 16 to 38 % +/// of these pixels. +#[test] +fn specular_points_have_no_coloured_rims() { + let (w, h) = (96usize, 72usize); + // (x, y, size, white-balanced level): green clips at 1, blue at 1.6, red at 2.5 + let mut points = Vec::new(); + for (i, level) in [2.0f32, 4.0, 8.0].into_iter().enumerate() { + for (j, size) in [1.0f32, 2.0, 3.0].into_iter().enumerate() { + for k in 0..2 { + points.push((8.0 + j as f32 * 30.0 + k as f32 * 12.6, 9.0 + i as f32 * 22.0 + k as f32 * 7.3, size, level)); + } + } + } + let light = + photograph(w, h, |x, y| points.iter().find(|&&(px, py, s, _)| (px..px + s).contains(&x) && (py..py + s).contains(&y)).map_or(0.04, |p| p.3)); + let near = |x: usize, y: usize| { + let (x, y) = (x as f32, y as f32); + points.iter().any(|&(px, py, s, _)| x + 3.0 > px && x < px + s + 2.0 && y + 3.0 > py && y < py + s + 2.0) + }; + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + // what the scene is about: green clipped at most points, every channel at the brightest + let n = raw.normalized().unwrap(); + let clipped = |c: u8| (0..w * h).filter(|&i| cfa.color_at(i % w, i / w) == c && n.data[i] >= 1.0).count(); + assert!(clipped(1) >= 20 && clipped(0) >= 2 && clipped(2) >= 4, "{name}: clipped R G B {} {} {}", clipped(0), clipped(1), clipped(2)); + let developed = raw.develop_balanced(method, DAYLIGHT).unwrap(); + let unclipped: Vec = developed.data.iter().map(|p| p.iter().all(|&v| v < CLIP)).collect(); + let out = finish(developed, DAYLIGHT); + // X-Trans: its directional weights already keep colour differences from crossing an edge, and it has the + // same few pale pixels (a channel at 0.3 to 0.5 of the mean) either way + let floor = if cfa.is_bayer() { 0.5 } else { 0.25 }; + let (mut rim, mut bad) = (0, Vec::new()); + for y in 0..h { + for x in 0..w { + if !near(x, y) || !unclipped[y * w + x] { + continue; + } + rim += 1; + let p = out.get(x, y); + let mean = (p[0] + p[1] + p[2]) / 3.0; + if p.iter().any(|&v| v < 0.0 || v < floor * mean) { + bad.push((x, y, p)); + } + } + } + assert!(rim > 0, "{name}: {rim} rim pixels"); + assert!(bad.is_empty(), "{name}: {} of {rim} rim pixels coloured, e.g. {:?}", bad.len(), &bad[..bad.len().min(4)]); + } +} + +/// Issue #1328: sharp neutral white-on-dark edges with nothing clipped (straight, diagonal, round, a 1 px line). +/// The pixels along them must stay nearly neutral after white balance. From the unbalanced mosaic their colour +/// spread (largest minus smallest channel) averaged 6 % of the edge's contrast on Bayer layouts (0.2 % to 0.7 % +/// balanced), with yellow, green, cyan or magenta outlines up to 36 %. +#[test] +fn sharp_neutral_edges_stay_neutral() { + let (w, h) = (96usize, 80usize); + let (dark, bright) = (0.03f32, 0.85f32); + let shape = |x: f32, y: f32| { + let disc = (x - 70.0).powi(2) + (y - 24.0).powi(2) < 13.5f32.powi(2); + let bar = (10.0..30.0).contains(&x) && (8.0..40.0).contains(&y); + let slant = y > 46.0 && x * 0.6 + y > 70.0 && x < 60.0; + let line = (80.0..81.0).contains(&x) && y > 46.0; + disc || bar || slant || line + }; + let light = photograph(w, h, |x, y| if shape(x, y) { bright } else { dark }); + // pixels within 1 px of an edge + let inside = |x: usize, y: usize| shape(x as f32 + 0.5, y as f32 + 0.5); + let edge = |x: usize, y: usize| (x - 1..=x + 1).any(|xx| (y - 1..=y + 1).any(|yy| inside(xx, yy) != inside(x, y))); + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let out = finish(raw.develop_balanced(method, DAYLIGHT).unwrap(), DAYLIGHT); + let (mut n, mut worst, mut sum) = (0, 0f32, 0f32); + for y in 2..h - 2 { + for x in 2..w - 2 { + if !edge(x, y) { + continue; + } + let p = out.get(x, y); + assert!(p.iter().all(|&v| v >= 0.0), "{name}: negative channel at ({x}, {y}): {p:?}"); + let spread = (p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2])) / (bright - dark); + worst = worst.max(spread); + sum += spread; + n += 1; + } + } + let mean = sum / n as f32; + assert!(n > 0, "{name}: {n} edge pixels"); + // X-Trans: our directional method's own green interpolation softens edges (mean 9 %, worst 43 %, and + // negative channels, unbalanced) + let (mean_max, worst_max) = if cfa.is_bayer() { (0.02, 0.15) } else { (0.085, 0.35) }; + assert!(mean < mean_max && worst < worst_max, "{name}: edge colour spread mean {mean:.3}, worst {worst:.3}"); + } +} + +/// Large clipped areas on bright and dark neutral surfaces can leave magenta rims. The mask lets highlight +/// reconstruction rebuild the unknown interpolated channels and keep the surrounding pixels neutral. +#[test] +fn clipped_areas_have_no_coloured_rims() { + let (w, h) = (96usize, 72usize); + let lamp = |x: f32, y: f32| (x - 30.0).powi(2) + (y - 36.0).powi(2) < 14.0f32.powi(2) || ((62.0..80.0).contains(&x) && (20.0..52.0).contains(&y)); + let light = photograph(w, h, |x, y| { + if lamp(x, y) { + 6.0 + } else if x < 48.0 { + 0.7 + } else { + 0.05 + } + }); + // within 3 px of the clipped area, unclipped in the scene + let rim = |x: usize, y: usize| { + !lamp(x as f32 + 0.5, y as f32 + 0.5) + && (x.saturating_sub(3)..=(x + 3).min(w - 1)) + .any(|xx| (y.saturating_sub(3)..=(y + 3).min(h - 1)).any(|yy| lamp(xx as f32 + 0.5, yy as f32 + 0.5))) + }; + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let img = finish_wb(img, DAYLIGHT); + let (mut n, mut worst, mut sum) = (0, 0f32, 0f32); + for y in 2..h - 2 { + for x in 2..w - 2 { + if !rim(x, y) { + continue; + } + let p = img.get(x, y); + let mean = (p[0] + p[1] + p[2]) / 3.0; + let spread = (p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2])) / mean.max(1e-3); + worst = worst.max(spread); + sum += spread; + n += 1; + } + } + let mean = sum / n as f32; + assert!(n > 0, "{name}: {n} rim pixels"); + // (told by value: mean 7 to 17 %, worst 80 %; demosaiced unbalanced, channels below zero). X-Trans: a few + // pixels at the lamp's edge where green interpolates just above the clip and red overshoots + let worst_max = if cfa.is_bayer() { 0.6 } else { 0.8 }; + assert!( + mean < 0.03 && worst < worst_max, + "{name}: colour spread around the clipped area mean {mean:.3}, worst {worst:.3} of the pixel's mean" + ); + } +} + +#[test] +fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let (w, h) = (16usize, 12usize); + let mut raw = raw_of(w, h, &cfa, [1.0; 3], |_, _| [0.3; 3]); + // Place clipped green and red samples at known CFA sites, then develop with an offset crop. + if let RawData::F32(d) = &mut raw.data { + d[4 * w + 5] = 1.0; + d[8 * w + 10] = 1.0; + } + raw.crop = Rect::new(1, 1, 14, 10); + let (img, mask) = raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap(); + assert_eq!(img, raw.develop_balanced(Method::Ahd, DAYLIGHT).unwrap(), "the same picture"); + let mask = mask.unwrap(); + assert_eq!(mask.len(), img.data.len()); + let at = |x: usize, y: usize| mask[(y - raw.crop.y) * img.width + x - raw.crop.x]; + assert_eq!(at(5, 4), highlight::CLIPPED_G, "the saturated green site"); + assert_eq!(at(10, 8), highlight::CLIPPED_R, "the saturated red site"); + assert_eq!(at(4, 4), highlight::FROM_CLIPPED_G | (1 << highlight::MEASURED_SHIFT), "red beside saturated green"); + assert_eq!(at(11, 8), highlight::FROM_CLIPPED_R | (2 << highlight::MEASURED_SHIFT), "green beside saturated red"); + assert_ne!(at(5, 6) & highlight::FROM_CLIPPED_G, 0, "clipped green can affect the other channels at this green site"); + assert_eq!(at(2, 8), 0, "a site away from both clipped samples"); + // An unclipped mosaic or an OpcodeList3 needs no mask. + let clean = raw_of(w, h, &cfa, [1.0; 3], |_, _| [0.3; 3]); + assert!(clean.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); + raw.opcodes.list3.push(Opcode::FixVignetteRadial { k: [0.0; 5], center: [0.5, 0.5] }); + assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); +} + +#[test] +fn ppg_clip_mask_marks_same_colour_dependencies() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let wb = [1.0; 3]; + let mut raw = raw_of(16, 12, &cfa, wb, |x, y| { + let level = match (x, y) { + (5, 4) | (6, 3) => 0.26, + (7, 4) => 0.35, + (8, 4) => 0.4, + (6, 5) => 0.49, + _ => 0.3, + }; + [level; 3] + }); + let clean = raw.develop(Method::Ppg).unwrap().get(6, 4); + if let RawData::F32(samples) = &mut raw.data { + samples[4 * raw.width + 4] = 1.0; + } + let (mut image, mask) = raw.develop_balanced_masked(Method::Ppg, wb, CLIP).unwrap(); + let changed = image.get(6, 4); + assert!(changed[1] > clean[1] && changed.iter().all(|&v| v < CLIP)); + let mask = mask.unwrap(); + let entry = mask[4 * image.width + 6]; + assert_ne!(entry & highlight::FROM_CLIPPED_R, 0, "the clipped red sample changed interpolated green"); + assert_eq!(entry >> highlight::MEASURED_SHIFT, cfa.color_at(6, 4) + 1); + assert_eq!(mask[4 * image.width + 10], 0, "no clipped sample is within reach"); + highlight::reconstruct_masked(&mut image, wb, CLIP, wb, &mask); + assert_eq!(image.get(6, 4)[0], clean[0], "reconstruction keeps measured red"); + assert_ne!(image.get(6, 4)[1], changed[1], "reconstruction can use measured red to rebuild green"); +} + +#[test] +fn bilinear_clip_mask_marks_only_actual_taps() { + let cfa = Cfa::bayer("RGGB").unwrap(); + for (width, method) in [(16, Method::Bilinear), (3, Method::Ahd), (3, Method::Ppg)] { + let raw = raw_of(width, 10, &cfa, [1.0; 3], |x, y| if (x, y) == (0, 2) { [1.0; 3] } else { [0.21, 0.15, 0.11] }); + let (mut image, mask) = raw.develop_balanced_masked(method, [1.0; 3], CLIP).unwrap(); + let mask = mask.unwrap(); + let clean = image.get(2, 3); + let blue = image.get(1, 2)[2]; + highlight::reconstruct_masked(&mut image, [1.0; 3], CLIP, [1.0; 3], &mask); + assert_eq!(image.get(2, 3), clean, "the clipped red sample is outside these bilinear taps"); + assert_eq!(mask[3 * width + 2], 0); + assert_eq!(mask[2 * width + 1] & highlight::FROM_CLIPPED_R, highlight::FROM_CLIPPED_R); + assert_eq!(image.get(1, 2)[2], blue, "blue interpolation uses its own samples"); + } +} + +#[test] +fn bilinear_clip_mask_keeps_the_wider_taps_for_sparse_cfas() { + let cfa = Cfa { width: 6, height: 1, pattern: vec![0, 1, 1, 1, 2, 1], origin_x: 0, origin_y: 0 }; + let raw = raw_of(12, 10, &cfa, [1.0; 3], |x, y| if (x, y) == (0, 2) { [1.0; 3] } else { [0.21, 0.15, 0.11] }); + let (_, mask) = raw.develop_balanced_masked(Method::Bilinear, DAYLIGHT, CLIP).unwrap(); + let mask = mask.unwrap(); + assert_ne!(mask[2 * raw.width + 2] & highlight::FROM_CLIPPED_R, 0, "the closest red taps are two columns away"); +} + +/// Review of #1328: dark twigs and wires against a clipped sky (every channel clipped around them) keep their level. +/// A pixel's own CFA sample is measured: a clipped neighbour of the same colour says nothing about it, and the colours +/// interpolated from clipped samples are unknown, not lower bounds. Taken as lower bounds (with the pixel's own colour +/// marked as clipped by its neighbours), the line's pixels were rebuilt as the brightest neutral and the lines vanished. +#[test] +fn dark_lines_against_a_clipped_sky_keep_their_level() { + let (w, h) = (96usize, 72usize); + let sky = 3.0f32; + // lines 3, 4 and 6 px wide (across, down, slanted) and a blob, at the level of dark bark + let dark = |x: f32, y: f32| { + (20.0..23.0).contains(&x) + || (30.0..34.0).contains(&y) + || ((x - y * 0.5 - 50.0).abs() < 3.0 && y < 60.0) + || (x - 78.0).powi(2) + (y - 56.0).powi(2) < 25.0 + }; + let light = photograph(w, h, |x, y| if dark(x, y) { 0.05 } else { sky }); + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let out = finish_wb(img, DAYLIGHT); + let (mut n, mut lifted, mut worst) = (0, Vec::new(), 0f32); + for y in 3..h - 3 { + for x in 3..w - 3 { + // what the lens let through is well below green's clip: the sensor measured it + let level = light[y * w + x]; + if level > 0.5 { + continue; + } + n += 1; + let p = out.get(x, y); + let mean = (p[0] + p[1] + p[2]) / 3.0; + worst = worst.max(mean / level); + if mean > 2.0 * level + 0.05 { + lifted.push((x, y, level, p)); + } + } + } + assert!(n > 0, "{name}: {n} line pixels"); + assert!( + lifted.is_empty(), + "{name}: {} of {n} dark pixels lifted (worst {worst:.1}x), e.g. {:?}", + lifted.len(), + &lifted[..lifted.len().min(3)] + ); + } +} + +/// White balance only (what [`finish`] does after the reconstruction it runs itself). +fn finish_wb(mut img: Rgb32f, wb: [f32; 3]) -> Rgb32f { + img.data.iter_mut().for_each(|p| *p = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]); + img +} + +/// Review of #1328: twigs a pixel or two wide against a clipped sky stay continuous lines at about the level the lens +/// let through. Their pixels are partly clipped (green clips at the twig's centre, red and blue don't), so marking the +/// interpolated channels of the pixels whose own sample clipped as unknown broke them into dots: those pixels were +/// rebuilt as clipped white between dark ones (0.44 stop from one twig pixel to the next, unbalanced 0.04). +#[test] +fn thin_twigs_against_a_clipped_sky_stay_continuous() { + let (w, h) = (96usize, 72usize); + let dark = |x: f32, y: f32| { + (20.0..21.0).contains(&x) + || (40.0..41.5).contains(&x) + || (60.0..62.0).contains(&x) + || (30.0..31.5).contains(&y) + || (x - y * 0.4 - 70.0).abs() < 0.8 + }; + let light = photograph(w, h, |x, y| if dark(x, y) { 0.05 } else { 3.0 }); + let level = |p: [f32; 3]| ((p[0] + p[1] + p[2]) / 3.0).min(3.0); + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let out = finish_wb(img, DAYLIGHT); + // twig pixels (the lens let through less than 2 of the sky's 3): the error of their level, and the change from + // one to the next along the twig + let (mut n, mut err, mut jump, mut nj) = (0, 0f32, 0f32, 0); + for y in 4..h - 4 { + for x in 4..w - 4 { + let l = light[y * w + x]; + if l >= 2.0 { + continue; + } + let m = level(out.get(x, y)).max(1e-3); + err += (m / l).log2().abs(); + n += 1; + for (xx, yy) in [(x + 1, y), (x, y + 1)] { + let l2 = light[yy * w + xx]; + if l2 < 2.0 && (l2 / l - 1.0).abs() < 0.1 { + jump += (level(out.get(xx, yy)).max(1e-3) / m).log2().abs(); + nj += 1; + } + } + } + } + let (err, jump) = (err / n as f32, jump / nj as f32); + assert!(n > 0 && nj > 0, "{name}: {n} twig pixels, {nj} pairs"); + // (unbalanced: 0.19 / 0.04 stop on Bayer, 0.29 / 0.17 on X-Trans) + let (err_max, jump_max) = if cfa.is_bayer() { (0.25, 0.12) } else { (0.35, 0.25) }; + assert!(err < err_max && jump < jump_max, "{name}: twig level off by {err:.3} stop, {jump:.3} stop from pixel to pixel"); + } +} + +/// Round 2 review of #1328: strongly coloured highlights (a warm sun clipping red, or red and green, or every +/// channel at its core; red, yellow and green light tubes) keep their brightness just inside their bright edges. +/// Rebuilding a pixel's interpolated channels from its measured one alone (blue, at an orange sun's edge) with the +/// colour of the content around made a dark checkerboard line there: a CC0 sunset's pixel went from Y 0.87 to 0.21. +#[test] +fn coloured_highlights_keep_their_brightness_at_the_edges() { + let (w, h) = (96usize, 80usize); + // (tint, white-balanced level): an orange sun clipping red only, red and green, and every channel; light tubes + let suns = [([1.0f32, 0.3, 0.06], 3.0f32), ([1.0, 0.45, 0.08], 4.0), ([1.0, 0.5, 0.12], 40.0)]; + let tubes = [([1.0f32, 0.15, 0.1], 3.5f32), ([1.0, 0.85, 0.15], 2.6), ([0.25, 1.0, 0.4], 2.0)]; + let scenes = suns.map(|(tint, level)| (tint, level, true)).into_iter().chain(tubes.map(|(tint, level)| (tint, level, false))); + let lum = |p: [f32; 3]| 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; + for (tint, level, sun) in scenes { + let scene_name = if sun { "sun" } else { "tube" }; + let scene = |x: f32, y: f32| { + if sun { + let radius = ((x - 48.0).powi(2) + (y - 40.0).powi(2)).sqrt(); + let k = if radius < 16.0 { 1.0 } else { (-(radius - 16.0) / 3.0).exp() }; + (k, 0.03) + } else { + let distance = (x - 30.0).abs().min((x - 0.5 * y - 45.0).abs() / 1.118); + let k = if distance < 2.0 { 1.0 } else { 0.15 * (-(distance - 2.0) / 2.0).exp() }; + (k, 0.02) + } + }; + let lights: [Vec; 3] = std::array::from_fn(|c| { + photograph(w, h, |x, y| { + let (strength, background) = scene(x, y); + tint[c] * level * strength + background + }) + }); + let truth = |x: usize, y: usize| -> [f32; 3] { std::array::from_fn(|c| lights[c][y * w + x]) }; + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, truth); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + let mut by_value = img.clone(); + highlight::reconstruct(&mut by_value, DAYLIGHT, CLIP); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let (out, by_value) = (finish_wb(img, DAYLIGHT), finish_wb(by_value, DAYLIGHT)); + // pixels the sensor measured in every channel (well below each clip), within 3 px of a clipped sample: + // their brightness must stay near what the lens let through + let clipped = |x: usize, y: usize| (0..3).any(|c| truth(x, y)[c] / DAYLIGHT[c] >= 1.0); + let (mut n, mut dark, mut dark_by_value) = (0, Vec::new(), 0); + for y in 3..h - 3 { + for x in 3..w - 3 { + let t = truth(x, y); + if (0..3).any(|c| t[c] / DAYLIGHT[c] > 0.9) || !(x - 3..=x + 3).any(|xx| (y - 3..=y + 3).any(|yy| clipped(xx, yy))) { + continue; + } + n += 1; + let ratio = |p: [f32; 3]| lum(p) / lum(t).max(1e-4); + let masked_ratio = ratio(out.get(x, y)); + let value_ratio = ratio(by_value.get(x, y)); + assert!( + masked_ratio.is_finite() && value_ratio.is_finite(), + "{scene_name} {tint:?} x{level}, {name} at ({x}, {y}): masked ratio {masked_ratio}, by-value ratio {value_ratio}" + ); + if masked_ratio < 0.6 { + dark.push((x, y, masked_ratio)); + } + if value_ratio < 0.6 { + dark_by_value += 1; + } + } + } + assert!(n > 0, "{scene_name} {tint:?} x{level}, {name}: {n} edge pixels"); + if !cfa.is_bayer() { + // X-Trans darkens a few pixels inside thin red and yellow tubes told by value too (as main does); the + // mask may add a few more, never many + assert!( + dark.len() <= dark_by_value + n / 30, + "{scene_name} {tint:?} x{level}, {name}: {} of {n} edge pixels darkened ({dark_by_value} by value)", + dark.len() + ); + continue; + } + assert!( + dark.is_empty(), + "{scene_name} {tint:?} x{level}, {name}: {} of {n} edge pixels darkened ({dark_by_value} by value), e.g. {:?}", + dark.len(), + &dark[..dark.len().min(3)] + ); + } + } +} + +/// Round 2 review of #1328: finite but huge samples (a floating-point DNG holding 1e37) must not overflow once +/// balanced: the gains are applied only when every sample times the largest of them, and divided back by the +/// smallest, stays far inside `f32`; otherwise the mosaic is demosaiced unbalanced, as `develop` does (finite here). +/// Just inside that bound the gains apply, and every demosaic stays finite. +#[test] +fn huge_float_samples_develop_unbalanced_rather_than_overflow() { + let mut raw = raw_of(24, 20, &Cfa::bayer("RGGB").unwrap(), [1.0; 3], |_, _| [0.1; 3]); + raw.data = RawData::F32(vec![1e37; 24 * 20]); + raw.bits = 32; + let bytes = craft_raw::write_dng(&raw, &craft_raw::DngWriteOptions::default()).unwrap(); + let decoded = craft_raw::decode(&bytes).unwrap(); + for method in [Method::Ahd, Method::Ppg] { + let plain = decoded.develop(method).unwrap(); + assert!(plain.data.iter().flatten().all(|v| v.is_finite()), "{method:?} unbalanced"); + for wb in [[64.0, 1.0, 1.0], [1.0, 1.0, 1.0 / 64.0], DAYLIGHT] { + let out = decoded.develop_balanced(method, wb).unwrap(); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{method:?} {wb:?}"); + assert_eq!(out, plain, "{method:?} {wb:?}: develops unbalanced"); + } + } + // just inside the bound the gains apply, and every demosaic stays finite on samples that large + for (name, cfa, method) in layouts() { + let (w, h) = (36usize, 36usize); + let mut raw = raw_of(w, h, &cfa, [1.0; 3], |_, _| [0.1; 3]); + raw.data = RawData::F32((0..w * h).map(|i| if (i % w + 2 * (i / w)) % 5 < 2 { 1.5e28 } else { 0.0 }).collect()); + let plain = raw.develop(method).unwrap(); + for wb in [[64.0, 1.0, 1.0], [1.0, 1.0, 1.0 / 64.0]] { + let out = raw.develop_balanced(method, wb).unwrap(); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{name} {wb:?}"); + assert_ne!(out, plain, "{name} {wb:?}: balanced"); + } + } +} + +/// Pixel-aspect correction changes the developed grid, so mosaic positions cannot mark it. +#[test] +fn non_square_pixels_keep_the_stretched_grid_without_a_mosaic_clip_mask() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut raw = raw_of(24, 18, &cfa, DAYLIGHT, |_, _| [3.0; 3]); + let (square, mask) = raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap(); + assert_eq!(mask.unwrap().len(), square.data.len()); + for aspect in [2.0, 0.5] { + raw.pixel_aspect = aspect; + let (image, mask) = raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap(); + assert_eq!(image.width, square.width); + assert_eq!(image.height > square.height, aspect > 1.0); + assert_ne!(image.height, square.height); + assert!(mask.is_none(), "the mosaic grid is not the stretched grid"); + assert_eq!(image, raw.develop_balanced(Method::Ahd, DAYLIGHT).unwrap()); + } +} diff --git a/crates/develop/tests/it/main.rs b/crates/develop/tests/it/main.rs new file mode 100644 index 000000000..3812b39e2 --- /dev/null +++ b/crates/develop/tests/it/main.rs @@ -0,0 +1 @@ +mod balanced;