From 7631ed550ef6b1abcc90a095dd7338e1b2c67c26 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 22 Nov 2026 05:26:27 -0500 Subject: [PATCH] craft-develop: extract sensor and local_tone stages (#587) (#3021) * craft-develop: extract sensor and local_tone stages (#587) * craft-develop: fix sensor chart_table/color/binned compilation * craft-develop: factor OffsetList alias in xtrans demosaic for clippy * craft-develop: remove unused Bayer test helper All sensor fixtures already call Cfa::bayer directly. Remove the unused wrapper so strict test lint can pass without suppressing warnings. AI-assisted: OpenAI Boris. * craft-develop: keep binned feasibility checks allocation-free Reject blocks that cannot fit the active area. Check each CFA phase over one period rather than allocating per-block layouts during preflight. Keep the existing path for valid rendered bins and cover both the fitting and non-fitting cases with a small synthetic crop. AI-assisted: OpenAI Boris. --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- Cargo.lock | 1 + crates/develop/Cargo.toml | 1 + crates/develop/README.md | 2 + crates/develop/src/lib.rs | 2 + crates/develop/src/local_tone.rs | 42 ++ crates/develop/src/sensor/binned.rs | 292 ++++++++++ crates/develop/src/sensor/chart_table.rs | 30 + crates/develop/src/sensor/color.rs | 454 +++++++++++++++ crates/develop/src/sensor/demosaic.rs | 400 +++++++++++++ crates/develop/src/sensor/demosaic/ahd.rs | 190 ++++++ .../develop/src/sensor/demosaic/bilinear.rs | 78 +++ crates/develop/src/sensor/demosaic/ppg.rs | 89 +++ crates/develop/src/sensor/demosaic/xtrans.rs | 283 +++++++++ crates/develop/src/sensor/gaintable.rs | 267 +++++++++ crates/develop/src/sensor/highlight.rs | 546 ++++++++++++++++++ crates/develop/src/sensor/highlight/tests.rs | 346 +++++++++++ crates/develop/src/sensor/mod.rs | 207 +++++++ crates/develop/src/sensor/opcodes.rs | 333 +++++++++++ crates/develop/src/sensor/opcodes/tests.rs | 471 +++++++++++++++ 19 files changed, 4034 insertions(+) create mode 100644 crates/develop/src/local_tone.rs create mode 100644 crates/develop/src/sensor/binned.rs create mode 100644 crates/develop/src/sensor/chart_table.rs create mode 100644 crates/develop/src/sensor/color.rs create mode 100644 crates/develop/src/sensor/demosaic.rs create mode 100644 crates/develop/src/sensor/demosaic/ahd.rs create mode 100644 crates/develop/src/sensor/demosaic/bilinear.rs create mode 100644 crates/develop/src/sensor/demosaic/ppg.rs create mode 100644 crates/develop/src/sensor/demosaic/xtrans.rs create mode 100644 crates/develop/src/sensor/gaintable.rs create mode 100644 crates/develop/src/sensor/highlight.rs create mode 100644 crates/develop/src/sensor/highlight/tests.rs create mode 100644 crates/develop/src/sensor/mod.rs create mode 100644 crates/develop/src/sensor/opcodes.rs create mode 100644 crates/develop/src/sensor/opcodes/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 87927b418..31917c408 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1813,6 +1813,7 @@ dependencies = [ "craft-color-transform", "craft-develop-model", "craft-geom", + "craft-raw", "craft-render-parity", "proptest", "rayon", diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index 9d217b149..c66c81faa 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -15,6 +15,7 @@ craft-color = { workspace = true } craft-color-transform = { workspace = true } craft-develop-model = { workspace = true } craft-geom = { workspace = true } +craft-raw = { workspace = true } serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] diff --git a/crates/develop/README.md b/crates/develop/README.md index 38401e19e..f610a0899 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -20,10 +20,12 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "` (`Rgb32f`, `Rgba8`, `Plane`), separable blur, resampling, point sampling, morphology, and `Histogram`. | +| `sensor` | `crates/raw` | Sensor normalization, DNG opcodes (`OpcodeList1/2/3`), Bayer (AHD/PPG/Bilinear) & X-Trans demosaicing, highlight reconstruction, DNG colour matrices (`color`), `ProfileGainTableMap` evaluation (`gaintable`), and binned preview development. | | `tone` | `crates/pipeline` | Global tone mapping (`ToneMap` and `CameraTone`) from scene luminance to display-linear luminance, SDR and HDR. | | `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. | diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index 2c97222a1..c29723503 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -15,10 +15,12 @@ pub mod light_v3; #[rustfmt::skip] pub mod light_v3_params; pub mod local; +pub mod local_tone; pub mod lut; pub mod nrc_joint; #[cfg(test)] mod nrc_joint_reference; pub mod profiles; pub mod raster; +pub mod sensor; pub mod tone; diff --git a/crates/develop/src/local_tone.rs b/crates/develop/src/local_tone.rs new file mode 100644 index 000000000..1d1847456 --- /dev/null +++ b/crates/develop/src/local_tone.rs @@ -0,0 +1,42 @@ +//! The camera's local tone mapping: a raw's DNG `ProfileGainTableMap` (Apple ProRAW), rendered +//! when the photo's Profile option "Camera local tone mapping" is on. Off by default: Lightroom +//! Classic renders ProRAW without it (see `lightcraft_raw::gaintable`). +//! +//! The map is a per-pixel gain that depends on the pixel's position in the raw's active area and +//! on its colour after the baseline exposure (linear ProPhoto). The source the pipeline gets is +//! exactly that colour (scene-linear Rec.2020 after the baseline exposure), so the gain is +//! evaluated here, on the resampled source at output resolution: a preview colours only the pixels +//! it shows. A gain multiplies R, G and B alike, so it commutes with the white balance (a matrix) +//! that follows. Files that also carry a `ProfileLookTable` get the gain after the table instead of +//! before it (DNG 1.7.1); Apple ProRAW has none. + +use craft_color_transform::{D50, D65, PROPHOTO, REC2020, bradford}; + +use crate::raster::{Rgb32f, par_rows}; +use crate::sensor::gaintable::{GainTableMap, GainTableMapApply, SourcePlacement}; + +/// A raw's gain table map and where its developed source sits in the active area. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct LocalTone { + pub map: GainTableMap, + pub placement: SourcePlacement, +} + +/// Multiply the resampled, not yet white-balanced source `img` by the local tone gain at each +/// pixel, where `active_uv(x, y)` maps an output pixel `(x, y)` to normalised active-area +/// coordinates `(ax, ay)` (`None` leaves blank canvas alone). +pub fn apply(img: &mut Rgb32f, lt: &LocalTone, active_uv: impl Fn(usize, usize) -> Option<(f64, f64)> + Sync) { + let Some(eval) = lt.map.evaluator() else { return }; + let w = img.width; + let to_prophoto = PROPHOTO.from_xyz().mul(&bradford(D65, D50)).mul(&REC2020.to_xyz()).to_f32(); + par_rows(&mut img.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let Some((u, v)) = active_uv(x, y) else { continue }; + let (ax, ay) = lt.placement.active(u, v); + let m = &to_prophoto; + let q: [f32; 3] = std::array::from_fn(|i| m[i][0] * px[0] + m[i][1] * px[1] + m[i][2] * px[2]); + let g = eval.gain(q, ax, ay); + *px = px.map(|c| c * g); + } + }); +} diff --git a/crates/develop/src/sensor/binned.rs b/crates/develop/src/sensor/binned.rs new file mode 100644 index 000000000..a005278b1 --- /dev/null +++ b/crates/develop/src/sensor/binned.rs @@ -0,0 +1,292 @@ +//! Reduced-size development straight from the mosaic ("superpixel" binning). +//! +//! When the caller needs an image at most half (or a third, a quarter…) of the sensor size — a +//! 2560 px loupe preview or a grid thumbnail of a 24 MP raw — demosaicing the full mosaic and then +//! downscaling throws most of the work away. Instead every `k × k` block of CFA samples becomes one +//! output pixel whose channels are the means of the block's samples of that colour. Every block must +//! contain all three colours (Bayer: `k` even; X-Trans: `k` a multiple of 3). There is no +//! 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 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 super::{Normalized, RawData, RawDevelopExt, RawImage, Rect, Result, Rgb32f, cfa_valid}; + +/// Does at least one `k × k` block fit the active area, with single-plane CFA data and R, G +/// and B present in every block phase? Bayer also requires an even `k`. +pub fn can_bin(raw: &RawImage, k: usize) -> bool { + if k < 2 || k > raw.active_area.width || k > raw.active_area.height { + return false; + } + let Some(cfa) = &raw.cfa else { return false }; + if raw.cpp != 1 || (raw.pixel_aspect - 1.0).abs() >= 0.01 || !cfa_valid(cfa) || (cfa.is_bayer() && !k.is_multiple_of(2)) { + return false; + } + // Repeating a CFA period cannot add a colour to the phase's coverage. + (0..cfa.height).all(|j| { + (0..cfa.width).all(|i| { + let mut colours = 0u8; + for dy in 0..k.min(cfa.height) { + for dx in 0..k.min(cfa.width) { + colours |= 1 << cfa.color_at(i + dx, j + dy).min(2); + } + } + colours == 0b111 + }) + }) +} + +/// Like [`RawDevelopExt::develop`] at `1/k` of the size (camera RGB, white = 1.0, default crop applied, +/// not oriented). +pub fn develop_binned(raw: &RawImage, k: usize, clip: f32) -> Result> { + Ok(bin(raw, k, clip, true)?.map(|(img, _)| img)) +} + +/// Like [`develop_binned`], with every channel the mean of its block's samples, and the clip mask. +pub fn develop_binned_masked(raw: &RawImage, k: usize, clip: f32) -> Result)>> { + bin(raw, 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(raw: &RawImage, k: usize, clip: f32, keep_max: bool) -> Result)>> { + raw.validate()?; + if !can_bin(raw, k) || !raw.opcodes.list3.is_empty() { + return Ok(None); + } + let Some(cfa) = &raw.cfa else { return Ok(None) }; + let a = raw.active_area; + // bin the default crop (relative to the active area) only + let c = raw.crop.clipped(a.width, a.height); + let c = if c.width < k || c.height < k { Rect::new(0, 0, a.width, a.height) } else { c }; + let (bw, bh) = (c.width / k, c.height / k); + if bw == 0 || bh == 0 { + return Ok(None); + } + // Opcode lists 1/2 need the normalised copy; plain files are normalised row by row. + let norm: Option = if raw.opcodes.list1.is_empty() && raw.opcodes.list2.is_empty() { None } else { Some(raw.normalized()?) }; + let cfa = cfa.shifted(a.x, a.y); + let range = raw.white_at(0) - raw.black.mean(); + let scale = if range > 0.0 { 1.0 / range } else { 1.0 }; + let uniform_black = raw.black.delta_h.is_empty() && raw.black.delta_v.is_empty() && raw.black.values.iter().all(|&v| v == raw.black.values[0]); + let black0 = raw.black.at(0, 0, 0, 1); + // colour of every sample of a block, per pattern phase of the block's corner + let (pw, ph) = (cfa.width, cfa.height); + let layouts: Vec<(Vec, [f32; 3])> = (0..ph) + .flat_map(|j| (0..pw).map(move |i| (i, j))) + .map(|(i, j)| { + let (l, n) = block_layout(&cfa, i, j, k); + (l, n.map(|n| 1.0 / n.max(1) as f32)) + }) + .collect(); + let wlen = bw * k; + let mut out = Rgb32f::new(bw, bh); + let mut mask = vec![0u8; bw * bh]; + let process_row = |by: usize, row: &mut [[f32; 3]], mrow: &mut [u8]| { + // the block row's k sample rows, normalised + let mut rows = vec![0f32; k * wlen]; + for dy in 0..k { + let y = c.y + by * k + dy; + let dst = &mut rows[dy * wlen..(dy + 1) * wlen]; + match (&norm, &raw.data) { + (Some(nm), _) => dst.copy_from_slice(&nm.data[y * nm.width + c.x..][..wlen]), + (None, RawData::U16(d)) if uniform_black => { + let src = &d[(a.y + y) * raw.width + a.x + c.x..][..wlen]; + for (o, &v) in dst.iter_mut().zip(src) { + *o = (v as f32 - black0) * scale; + } + } + (None, data) => { + let base = (a.y + y) * raw.width + a.x + c.x; + for (x, o) in dst.iter_mut().enumerate() { + *o = (data.get(base + x) - raw.black.at(c.x + x, y, 0, 1)) * scale; + } + } + } + } + let py = (c.y + by * k) % ph; + 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 { + let src = &rows[dy * wlen + bx * k..][..k]; + for (&v, &col) in src.iter().zip(&layout[dy * k..(dy + 1) * k]) { + let col = col as usize; + sum[col] += v; + max[col] = max[col].max(v); + } + } + for ch in 0..3 { + let clipped = max[ch] >= clip; + px[ch] = if clipped && keep_max { max[ch] } else { sum[ch] * inv[ch] }; + *m |= u8::from(clipped) << ch; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.data.par_chunks_mut(bw).zip(mask.par_chunks_mut(bw)).enumerate().for_each(|(by, (row, mrow))| process_row(by, row, mrow)); + } + #[cfg(target_arch = "wasm32")] + { + for (by, (row, mrow)) in out.data.chunks_mut(bw).zip(mask.chunks_mut(bw)).enumerate() { + process_row(by, row, mrow); + } + } + Ok(Some((out, mask))) +} + +/// Colours of the `k × k` samples of a block whose corner sits at pattern position `(i, j)` +/// (row-major) and the count of each colour. +fn block_layout(cfa: &super::Cfa, i: usize, j: usize, k: usize) -> (Vec, [u32; 3]) { + let mut n = [0u32; 3]; + let l: Vec = (0..k * k) + .map(|t| { + let c = cfa.color_at(i + t % k, j + t / k).min(2); + n[c as usize] += 1; + c + }) + .collect(); + (l, n) +} + +#[cfg(test)] +mod tests { + use super::super::demosaic::mosaic_from_rgb; + use super::super::*; + use super::*; + + fn raw_from(n: &Normalized, black: f32, white: f32) -> RawImage { + let data = n.data.iter().map(|&v| (v * (white - black) + black).round() as u16).collect(); + RawImage { + format: RawFormat::Dng, + width: n.width, + height: n.height, + cpp: 1, + data: RawData::U16(data), + cfa: n.cfa.clone(), + bits: 14, + black: BlackLevel::uniform(black), + white: vec![white], + active_area: Rect::new(0, 0, n.width, n.height), + crop: Rect::new(0, 0, n.width, n.height), + orientation: craft_raw::Orientation::Normal, + color: ColorData::default(), + wb_multipliers: None, + linearized: false, + linearization_table: None, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + camera: Default::default(), + cinema: Default::default(), + lens_metadata: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + } + } + + #[test] + fn binning_matches_block_means_and_keeps_clipping() { + let img = Rgb32f::from_fn(24, 18, |x, y| [0.1 + x as f32 * 0.01, 0.2 + y as f32 * 0.01, 0.3]); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("GRBG").unwrap()), 512.0, 16383.0); + assert!(raw.can_bin(2) && raw.can_bin(4) && !raw.can_bin(3)); + let b = raw.develop_binned(2, 0.99).unwrap().unwrap(); + assert_eq!((b.width, b.height), (12, 9)); + let p = b.get(3, 2); + // red sample of block (3,2) under GRBG is at (7,4); blue at (6,5); greens average (6,4)+(7,5) + assert!((p[0] - img.get(7, 4)[0]).abs() < 1e-3, "{p:?}"); + assert!((p[2] - 0.3).abs() < 1e-3); + assert!((p[1] - (img.get(6, 4)[1] + img.get(7, 5)[1]) / 2.0).abs() < 1e-3); + // a single clipped green sample keeps the block's green clipped + if let RawData::U16(d) = &mut raw.data { + d[4 * 24 + 6] = 16383; + } + assert!(raw.develop_binned(2, 0.99).unwrap().unwrap().get(3, 2)[1] >= 0.99); + // default crop is honoured at the binned scale + raw.crop = Rect::new(2, 2, 20, 12); + let c = raw.develop_binned(2, 0.99).unwrap().unwrap(); + assert_eq!((c.width, c.height), (10, 6)); + // X-Trans: 3×3 blocks hold all colours, 2×2 don't + let x = raw_from(&mosaic_from_rgb(&img, &Cfa::xtrans()), 0.0, 1000.0); + assert!(x.can_bin(3) && x.can_bin(6) && !x.can_bin(2)); + let xb = x.develop_binned(3, 0.99).unwrap().unwrap(); + assert_eq!((xb.width, xb.height), (8, 6)); + assert!((xb.get(4, 3)[2] - 0.3).abs() < 2e-3); + } + + #[test] + fn binning_requires_a_complete_block_in_the_active_area() { + let img = Rgb32f::filled(12, 10, [0.25, 0.5, 0.75]); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4096.0); + raw.active_area = Rect::new(2, 2, 8, 6); + raw.crop = Rect::new(0, 0, 8, 6); + assert!(raw.can_bin(6)); + let binned = raw.develop_binned(6, 0.99).unwrap().unwrap(); + assert_eq!((binned.width, binned.height), (1, 1)); + assert_eq!(binned.data, vec![[0.25, 0.5, 0.75]]); + assert!(!can_bin(&raw, 8)); + assert!(!raw.can_bin(8)); + assert!(raw.develop_binned(8, 0.99).unwrap().is_none()); + assert!(raw.develop_binned_masked(8, 0.99).unwrap().is_none()); + } + + /// 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]); + let raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0); + let b = raw.develop_binned(2, 0.99).unwrap().unwrap(); + let full = crate::raster::resample::half(&raw.develop(Method::Ahd).unwrap()); + for y in 2..b.height - 2 { + for x in 2..b.width - 2 { + for c in 0..3 { + assert!((b.get(x, y)[c] - full.get(x, y)[c]).abs() < 0.01, "({x},{y})"); + } + } + } + } +} diff --git a/crates/develop/src/sensor/chart_table.rs b/crates/develop/src/sensor/chart_table.rs new file mode 100644 index 000000000..a1a9f6401 --- /dev/null +++ b/crates/develop/src/sensor/chart_table.rs @@ -0,0 +1,30 @@ +// Camera colour matrices fitted to our own photographs of a ColorChecker Classic (post-November-2014 formulation), +// for cameras with no published spectral sensitivities. Kept by hand: each row's capture, fit and checks are in +// clean-room/crw/10-chart-calibration.md (scripts local-only). Reference colours: X-Rite's published L*a*b* (D50) for +// the chart, as packaged by colour-science (BSD-3-Clause). No number comes from Adobe or from a GPL raw decoder. +use craft_color_transform::Mat3; + +/// Measured dual-illuminant colour calibration for a camera model. +#[derive(Clone, Copy, Debug)] +pub struct Camera { + pub make: &'static str, + pub model: &'static str, + pub illuminant: [u16; 2], + pub color_matrix: [Mat3; 2], + pub forward_matrix: [Mat3; 2], +} + +#[rustfmt::skip] +pub const CAMERAS: &[Camera] = &[ + // Canon EOS D60 (CRW), the maintainer's body, ISO 100. Matrix 1: one ~2,900 K tungsten bulb, 11 frames, filed as + // Standard Illuminant A; matrix 2: direct afternoon sun, ~4,850 K, 20 frames, filed as D50 (both temperatures from + // the camera's own white-balance presets). Fitted on chromaticity with neutral held at D50 (the sunlit chart was + // unevenly lit): CIEDE2000 mean 2.42 / 1.70 on the 24 patches, 2.74 / 1.97 leaving each patch out. + Camera { + make: "Canon", + model: "EOS D60", + illuminant: [17, 23], + color_matrix: [Mat3([[0.950961, -0.345297, 0.112165], [-0.545579, 1.400621, 0.558365], [-0.123107, 0.222004, 1.026236]]), Mat3([[0.609694, -0.127035, -0.045387], [-0.461201, 1.16644, 0.337283], [-0.115992, 0.229363, 0.791647]])], + forward_matrix: [Mat3([[0.763921, 0.183562, 0.016813], [0.268545, 0.944022, -0.212567], [0.100742, -0.431647, 1.15601]]), Mat3([[0.757277, 0.190573, 0.016446], [0.291782, 1.009128, -0.300909], [0.026419, -0.264451, 1.063137]])], + }, +]; diff --git a/crates/develop/src/sensor/color.rs b/crates/develop/src/sensor/color.rs new file mode 100644 index 000000000..480a97d9d --- /dev/null +++ b/crates/develop/src/sensor/color.rs @@ -0,0 +1,454 @@ +//! DNG colour model (Adobe DNG Specification 1.7, chapter 6 "Mapping Camera Color Space to CIE XYZ Space"). +//! +//! - `ColorMatrix1/2` (XYZ → reference camera) and `CameraCalibration1/2` / `ForwardMatrix1/2` are interpolated +//! between the two calibration illuminants by inverse correlated colour temperature of the white point. +//! - `XYZtoCamera = AnalogBalance · CameraCalibration · ColorMatrix`. +//! - White balance multipliers are the reciprocal of the camera neutral for the chosen white. +//! - Camera → XYZ(D50): through `ForwardMatrix` when present, else the inverse of `XYZtoCamera` followed by +//! Bradford adaptation from the white to D50. +//! - The as-shot white comes from `AsShotWhiteXY`, or `AsShotNeutral` converted to xy by the spec's iteration. +//! +//! Cameras without a colour matrix (non-DNG files until our own calibration DB exists) use a generic +//! "camera RGB ≈ linear sRGB" model and are flagged with `matrix_is_fallback`. + +use super::{ColorData, Mat3, RawImage}; +use craft_color_transform::{D50, D65, REC2020, SRGB, Xy, bradford, cct}; +use craft_raw::Matrix3; +use serde::{Deserialize, Serialize}; + +/// Correlated colour temperature (K) of an Exif `LightSource` / DNG `CalibrationIlluminant` code. +pub fn illuminant_temperature(code: u16) -> Option { + Some(match code { + 1 | 4 | 9 => 5500.0, + 2 | 14 => 4150.0, + 3 => 2850.0, + 10 => 6500.0, + 11 => 7500.0, + 12 => 6430.0, + 13 => 5000.0, + 15 => 3450.0, + 16 => 2940.0, + 17 => 2856.0, + 18 => 4874.0, + 19 => 6774.0, + 20 => 5503.0, + 21 => 6504.0, + 22 => 7504.0, + 23 => 5003.0, + 24 => 3200.0, + _ => return None, + }) +} + +fn lerp(a: &Mat3, b: &Mat3, g: f64) -> Mat3 { + let mut r = [[0.0; 3]; 3]; + for i in 0..3 { + for j in 0..3 { + r[i][j] = g * a.0[i][j] + (1.0 - g) * b.0[i][j]; + } + } + Mat3(r) +} + +/// Weight of calibration 1 for white `xy` (1 = use matrix 1 only). +pub fn illuminant_weight(color: &ColorData, white: Xy) -> f64 { + let t = cct::xy_to_temp_tint(white).0; + let (t1, t2) = (illuminant_temperature(color.illuminant[0]).unwrap_or(2856.0), illuminant_temperature(color.illuminant[1]).unwrap_or(6504.0)); + if (t1 - t2).abs() < 1.0 { + return 1.0; + } + let g = (1.0 / t - 1.0 / t2) / (1.0 / t1 - 1.0 / t2); + g.clamp(0.0, 1.0) +} + +fn interp(pair: &[Option; 2], g: f64) -> Option { + match pair { + [Some(a), Some(b)] => Some(lerp(&Mat3(*a), &Mat3(*b), g)), + [Some(a), None] | [None, Some(a)] => Some(Mat3(*a)), + [None, None] => None, + } +} + +/// `AnalogBalance · CameraCalibration` for white `xy`. +fn ab_cc(color: &ColorData, g: f64) -> Mat3 { + let ab = color.analog_balance.map(|a| Mat3::diag(a[0], a[1], a[2])).unwrap_or(Mat3::IDENTITY); + let cc = interp(&color.camera_calibration, g).unwrap_or(Mat3::IDENTITY); + ab.mul(&cc) +} + +/// Whether the file carries a usable colour matrix. +pub fn has_matrix(color: &ColorData) -> bool { + color.color_matrix.iter().any(|m| m.is_some()) +} + +/// `XYZtoCamera` for white `xy` (fallback: XYZ → linear sRGB). +pub fn xyz_to_camera(color: &ColorData, white: Xy) -> Mat3 { + let g = illuminant_weight(color, white); + match interp(&color.color_matrix, g) { + Some(cm) => ab_cc(color, g).mul(&cm), + None => SRGB.from_xyz(), + } +} + +/// Camera neutral (raw camera values of a neutral surface under white `xy`), normalised to max 1. +pub fn camera_neutral(color: &ColorData, white: Xy) -> [f64; 3] { + let Some(xyz) = white.to_xyz() else { return [1.0; 3] }; + let n = xyz_to_camera(color, white).apply(xyz); + let mx = n.iter().cloned().fold(f64::MIN, f64::max); + if mx > 0.0 { n.map(|v| v / mx) } else { [1.0; 3] } +} + +/// White-balance multipliers for white `xy` (reciprocal camera neutral, minimum 1). +pub fn wb_multipliers(color: &ColorData, white: Xy) -> [f64; 3] { + let n = camera_neutral(color, white); + let m = n.map(|v| if v > 1e-9 { 1.0 / v } else { 1.0 }); + let mn = m.iter().cloned().fold(f64::MAX, f64::min); + m.map(|v| v / mn) +} + +/// Convert a camera neutral to a white xy (DNG spec iteration: xy → XYZtoCamera(xy) → xy until stable). +pub fn neutral_to_xy(color: &ColorData, neutral: [f64; 3]) -> Xy { + let mut xy = D50; + for _ in 0..50 { + let Some(inv) = xyz_to_camera(color, xy).inverse() else { return xy }; + let xyz = inv.apply(neutral); + let Some(next) = Xy::from_xyz(xyz) else { return xy }; + if !(next.x.is_finite() && next.y.is_finite()) || next.y <= 0.0 { + return xy; + } + let next = Xy::new(next.x.clamp(0.1, 0.7), next.y.clamp(0.1, 0.7)); + let done = (next.x - xy.x).abs() < 1e-9 && (next.y - xy.y).abs() < 1e-9; + xy = next; + if done { + break; + } + } + xy +} + +/// The as-shot white point: `AsShotWhiteXY`, `AsShotNeutral`, vendor multipliers, else D65. +pub fn as_shot_white_xy(raw: &RawImage) -> Xy { + as_shot_white(&raw.color, raw.wb_multipliers) +} + +/// [`as_shot_white_xy`] from a header-only [`super::RawInfo`]. +pub fn as_shot_white_xy_of(info: &super::RawInfo) -> Xy { + as_shot_white(&info.color, info.wb_multipliers) +} + +/// The as-shot white from colour tags and vendor multipliers alone (see [`as_shot_white_xy`]). +pub fn as_shot_white_of(c: &ColorData, wb_multipliers: Option<[f32; 3]>) -> Xy { + as_shot_white(c, wb_multipliers) +} + +fn as_shot_white(c: &ColorData, wb_multipliers: Option<[f32; 3]>) -> Xy { + if let Some([x, y]) = c.as_shot_white_xy { + return Xy::new(x, y); + } + if let Some(n) = c.as_shot_neutral { + return neutral_to_xy(c, n); + } + if let Some(m) = wb_multipliers.filter(|m| m.iter().all(|v| *v > 0.0 && v.is_finite())) { + return neutral_to_xy(c, [1.0 / m[0] as f64, 1.0 / m[1] as f64, 1.0 / m[2] as f64]); + } + D65 +} + +/// Camera (raw, not white balanced) → XYZ relative to D50, for scene white `xy`. +pub fn camera_to_xyz_d50(color: &ColorData, white: Xy) -> Mat3 { + let g = illuminant_weight(color, white); + if has_matrix(color) + && let Some(fm) = interp(&color.forward_matrix, g) + { + let abcc = ab_cc(color, g); + if let Some(abcc_inv) = abcc.inverse() { + let n = camera_neutral(color, white); + let rn = abcc_inv.apply(n); + if rn.iter().all(|v| *v > 1e-9) { + return fm.mul(&Mat3::diag(1.0 / rn[0], 1.0 / rn[1], 1.0 / rn[2])).mul(&abcc_inv); + } + } + } + let cam_to_xyz = xyz_to_camera(color, white).inverse().unwrap_or(Mat3::IDENTITY); + bradford(white, D50).mul(&cam_to_xyz) +} + +/// Everything the pipeline needs to go from raw camera RGB to the working space. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct CameraTransform { + /// White-balanced camera RGB → linear Rec.2020 D65; maps (1, 1, 1) to (1, 1, 1). + pub matrix: Mat3, + /// Per-channel white-balance multipliers applied before `matrix` (minimum 1). + pub wb: [f32; 3], + pub white_xy: Xy, + /// No colour matrix was available: a generic camera ≈ sRGB model was used. + pub matrix_is_fallback: bool, + pub baseline_exposure: f64, +} + +/// Camera transform for white `wb_xy`: `rec2020 = matrix · (wb ⊙ camera)`. +pub fn camera_transform(raw: &RawImage, wb_xy: Xy) -> CameraTransform { + camera_transform_of(&raw.color, wb_xy) +} + +/// [`camera_transform`] from the colour tags alone. +pub fn camera_transform_of(color: &ColorData, wb_xy: Xy) -> CameraTransform { + let fallback = !has_matrix(color); + let wb = wb_multipliers(color, wb_xy); + let to_d50 = camera_to_xyz_d50(color, wb_xy); + let m = REC2020.from_xyz().mul(&bradford(D50, D65)).mul(&to_d50).mul(&Mat3::diag(1.0 / wb[0], 1.0 / wb[1], 1.0 / wb[2])); + let white = m.apply([1.0; 3]); + let k = (white[0] + white[1] + white[2]) / 3.0; + let matrix = if k.abs() > 1e-12 { Mat3(m.0.map(|r| r.map(|v| v / k))) } else { m }; + CameraTransform { matrix, wb: wb.map(|v| v as f32), white_xy: wb_xy, matrix_is_fallback: fallback, baseline_exposure: color.baseline_exposure } +} + +/// Linear Rec.2020 → linear Rec.2020 matrix that re-develops pixels developed with the camera +/// transform for white `from` as if developed for white `to`: the camera's own colour model is +/// evaluated at the new white (camera-space white balance, DNG spec ch. 6), as Lightroom does, so +/// a neutral lit by `to` comes out neutral. `None` when the tags have no colour matrix or the +/// transform is singular. +pub fn rebalance(color: &ColorData, from: Xy, to: Xy) -> Option { + if !has_matrix(color) { + return None; + } + let (a, b) = (camera_transform_of(color, from), camera_transform_of(color, to)); + let ratio = Mat3::diag(f64::from(b.wb[0] / a.wb[0]), f64::from(b.wb[1] / a.wb[1]), f64::from(b.wb[2] / a.wb[2])); + Some(b.matrix.mul(&ratio).mul(&a.matrix.inverse()?)) +} + +/// The white under which `rgb` (linear Rec.2020, developed with the camera transform for white +/// `developed_for`) is a neutral: the white [`rebalance`] must re-develop for to make it neutral +/// (white-balance picker, auto white balance). `None` without a colour matrix, or when `rgb` maps +/// to a non-positive camera value. +pub fn neutral_white(color: &ColorData, developed_for: Xy, rgb: [f64; 3]) -> Option { + if !has_matrix(color) { + return None; + } + let a = camera_transform_of(color, developed_for); + let balanced = a.matrix.inverse()?.apply(rgb); + let camera: [f64; 3] = std::array::from_fn(|i| balanced[i] / f64::from(a.wb[i])); + camera.iter().all(|v| v.is_finite() && *v > 0.0).then(|| neutral_to_xy(color, camera)) +} + +/// `(matrix, multipliers)` with `rec2020 = matrix · (multipliers ⊙ camera)`, linear Rec.2020 D65. +pub fn camera_to_rec2020(raw: &RawImage, wb_xy: Xy) -> (Mat3, [f32; 3]) { + let t = camera_transform(raw, wb_xy); + (t.matrix, t.wb) +} + +/// Grey-world white balance estimate (multipliers, min 1) from camera RGB, ignoring clipped and very dark pixels. +pub fn grey_world(img: &crate::raster::Rgb32f) -> [f32; 3] { + let mut s = [0f64; 3]; + let step = (img.data.len() / 200_000).max(1); + for p in img.data.iter().step_by(step) { + if p.iter().all(|&v| v > 0.02 && v < 0.95) { + for c in 0..3 { + s[c] += p[c] as f64; + } + } + } + if s.iter().any(|&v| v <= 0.0) { + return [1.0; 3]; + } + let m = [s[1] / s[0], 1.0, s[1] / s[2]]; + let mn = m.iter().cloned().fold(f64::MAX, f64::min); + m.map(|v| (v / mn) as f32) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A plausible camera: XYZ → camera matrix (rows sum to something sensible), invertible. + fn cam_a() -> Matrix3 { + [[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]] + } + fn cam_b() -> Matrix3 { + [[0.7, 0.3, -0.1], [-0.35, 1.3, 0.1], [0.05, -0.2, 1.0]] + } + + fn color_single(m: Matrix3, ill: u16) -> ColorData { + ColorData { illuminant: [ill, 0], color_matrix: [Some(m), None], ..Default::default() } + } + + fn raw_with(color: ColorData) -> RawImage { + RawImage { + format: super::super::RawFormat::Dng, + width: 1, + height: 1, + cpp: 1, + data: super::super::RawData::U16(vec![0]), + cfa: None, + bits: 16, + black: Default::default(), + white: vec![65535.0], + active_area: super::super::Rect::new(0, 0, 1, 1), + crop: super::super::Rect::new(0, 0, 1, 1), + orientation: Default::default(), + color, + wb_multipliers: None, + linearized: false, + linearization_table: None, + pixel_aspect: 1.0, + opcodes: Default::default(), + camera: Default::default(), + cinema: Default::default(), + lens_metadata: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + } + } + + fn close(a: [f64; 3], b: [f64; 3], tol: f64) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < tol) + } + + #[test] + fn neutral_maps_to_white_and_primaries_are_recovered() { + let raw = raw_with(color_single(cam_a(), 21)); + let t = camera_transform(&raw, D65); + assert!(!t.matrix_is_fallback); + // a surface with XYZ = Rec.2020 red primary under D65, seen by the camera + let red_xyz = REC2020.to_xyz().apply([1.0, 0.0, 0.0]); + let cam = Mat3(cam_a()).apply(red_xyz); + let wbd = [cam[0] * t.wb[0] as f64, cam[1] * t.wb[1] as f64, cam[2] * t.wb[2] as f64]; + let out = t.matrix.apply(wbd); + let k = out[0]; + assert!(close([out[0] / k, out[1] / k, out[2] / k], [1.0, 0.0, 0.0], 1e-6), "{out:?}"); + // white + let n = Mat3(cam_a()).apply(D65.to_xyz().unwrap()); + let wbd = [n[0] * t.wb[0] as f64, n[1] * t.wb[1] as f64, n[2] * t.wb[2] as f64]; + let out = t.matrix.apply(wbd); + assert!((out[0] - out[1]).abs() < 1e-6 && (out[1] - out[2]).abs() < 1e-6, "{out:?}"); + assert!(close(t.matrix.apply([1.0; 3]), [1.0; 3], 1e-12)); + assert!(t.wb.iter().cloned().fold(f32::MAX, f32::min) == 1.0); + } + + #[test] + fn dual_illuminant_interpolation() { + let color = ColorData { illuminant: [17, 21], color_matrix: [Some(cam_a()), Some(cam_b())], ..Default::default() }; + assert!((illuminant_weight(&color, cct::temp_tint_to_xy(2856.0, 0.0)) - 1.0).abs() < 0.01); + assert!(illuminant_weight(&color, cct::temp_tint_to_xy(6504.0, 0.0)) < 0.01); + assert_eq!(illuminant_weight(&color, cct::temp_tint_to_xy(10000.0, 0.0)), 0.0); + let mid = cct::temp_tint_to_xy(4000.0, 0.0); + let g = illuminant_weight(&color, mid); + let expect = (1.0 / 4000.0 - 1.0 / 6504.0) / (1.0 / 2856.0 - 1.0 / 6504.0); + assert!((g - expect).abs() < 0.02, "{g} vs {expect}"); + let m = xyz_to_camera(&color, mid); + let l = lerp(&Mat3(cam_a()), &Mat3(cam_b()), g); + assert!(close(m.0[0], l.0[0], 1e-12)); + } + + #[test] + fn neutral_xy_roundtrip() { + let color = ColorData { + illuminant: [17, 21], + color_matrix: [Some(cam_a()), Some(cam_b())], + analog_balance: Some([1.0, 1.05, 0.98]), + ..Default::default() + }; + for t in [2600.0, 3200.0, 4500.0, 5500.0, 7000.0, 9000.0] { + for tint in [-10.0, 0.0, 15.0] { + let xy = cct::temp_tint_to_xy(t, tint); + let n = camera_neutral(&color, xy); + let back = neutral_to_xy(&color, n); + assert!((back.x - xy.x).abs() < 1e-6 && (back.y - xy.y).abs() < 1e-6, "{t} {tint}: {back:?} vs {xy:?}"); + } + } + let mut raw = raw_with(color.clone()); + raw.color.as_shot_neutral = Some(camera_neutral(&color, cct::temp_tint_to_xy(3300.0, 5.0))); + let xy = as_shot_white_xy(&raw); + let (t, tint) = cct::xy_to_temp_tint(xy); + assert!((t - 3300.0).abs() < 5.0 && (tint - 5.0).abs() < 0.5, "{t} {tint}"); + raw.color.as_shot_white_xy = Some([D50.x, D50.y]); + assert_eq!(as_shot_white_xy(&raw), D50); + } + + #[test] + fn forward_matrix_path_agrees_with_color_matrix_path() { + let a = Mat3(cam_a()); + let n = a.apply(D65.to_xyz().unwrap()); + let fm = bradford(D65, D50).mul(&a.inverse().unwrap()).mul(&Mat3::diag(n[0], n[1], n[2])); + // DNG forward matrices map (1,1,1) to D50 white (with Y=1): normalise like a real file would + let w = fm.apply([1.0; 3]); + let s = D50.to_xyz().unwrap()[1] / w[1]; + let fm = fm.0.map(|r| r.map(|v| v * s)); + let cm_only = camera_transform(&raw_with(color_single(cam_a(), 21)), D65); + let mut with_fm = color_single(cam_a(), 21); + with_fm.forward_matrix = [Some(fm), None]; + let fm_t = camera_transform(&raw_with(with_fm), D65); + for i in 0..3 { + assert!(close(cm_only.matrix.0[i], fm_t.matrix.0[i], 1e-9), "{:?} vs {:?}", cm_only.matrix, fm_t.matrix); + } + assert_eq!(cm_only.wb, fm_t.wb); + } + + #[test] + fn camera_calibration_and_analog_balance_are_respected() { + // AB · CC scales channels: the neutral must scale accordingly + let mut c = color_single(cam_a(), 21); + let base = camera_neutral(&c, D65); + c.camera_calibration = [Some(Mat3::diag(1.0, 0.5, 1.0).0), None]; + let n = camera_neutral(&c, D65); + assert!((n[1] / n[0] - 0.5 * base[1] / base[0]).abs() < 1e-9); + } + + #[test] + fn fallback_without_matrix() { + let mut raw = raw_with(ColorData::default()); + raw.wb_multipliers = Some([2.0, 1.0, 1.5]); + let xy = as_shot_white_xy(&raw); + let t = camera_transform(&raw, xy); + assert!(t.matrix_is_fallback); + assert!((t.wb[0] / t.wb[1] - 2.0).abs() < 1e-3 && (t.wb[2] / t.wb[1] - 1.5).abs() < 1e-3, "{:?}", t.wb); + let t = camera_transform(&raw, D65); + let expect = SRGB.to_space(&REC2020); + for i in 0..3 { + assert!(close(t.matrix.0[i], expect.0[i], 1e-6)); + } + assert_eq!(camera_to_rec2020(&raw, D65).1, [1.0, 1.0, 1.0]); + } + + #[test] + fn illuminant_codes() { + assert_eq!(illuminant_temperature(21), Some(6504.0)); + assert_eq!(illuminant_temperature(17), Some(2856.0)); + assert_eq!(illuminant_temperature(0), None); + assert_eq!(illuminant_temperature(255), None); + } + + /// Camera-space white balance: re-developing for another white turns a neutral lit by that + /// white neutral (the camera's own matrices, interpolated for the new white, say how); the same + /// white is the identity; without a colour matrix there is nothing to re-evaluate. + #[test] + fn rebalance_redevelops_for_the_new_white() { + let color = ColorData { illuminant: [17, 21], color_matrix: [Some(cam_a()), Some(cam_b())], ..Default::default() }; + let (from, to) = (cct::temp_tint_to_xy(5500.0, 0.0), cct::temp_tint_to_xy(3200.0, 10.0)); + let a = camera_transform_of(&color, from); + // a grey card lit by `to`, as the camera records it, developed for `from`: warm + let n = camera_neutral(&color, to); + let developed = a.matrix.apply(std::array::from_fn(|i| n[i] * a.wb[i] as f64)); + assert!(developed[0] > 1.2 * developed[2], "{developed:?}"); + let out = rebalance(&color, from, to).unwrap().apply(developed); + assert!(close(out.map(|v| v / out[1]), [1.0; 3], 1e-6), "{out:?}"); + let same = rebalance(&color, from, from).unwrap(); + assert!((0..3).all(|r| close(same.0[r], Mat3::IDENTITY.0[r], 1e-9)), "{same:?}"); + assert!(rebalance(&ColorData::default(), from, to).is_none()); + // and back: the developed grey card names the white it was lit by + let white = neutral_white(&color, from, developed).unwrap(); + assert!((white.x - to.x).abs() < 1e-6 && (white.y - to.y).abs() < 1e-6, "{white:?} vs {to:?}"); + assert!(neutral_white(&color, from, [-1.0, 0.5, 0.5]).is_none()); + assert!(neutral_white(&ColorData::default(), from, developed).is_none()); + } + + #[test] + fn grey_world_balances() { + let img = crate::raster::Rgb32f::from_fn(20, 20, |x, _| { + let v = 0.2 + 0.02 * x as f32; + [v * 0.5, v, v * 0.8] + }); + let m = grey_world(&img); + assert!((m[0] - 2.0).abs() < 1e-3 && (m[1] - 1.0).abs() < 1e-6 && (m[2] - 1.25).abs() < 1e-3, "{m:?}"); + } +} diff --git a/crates/develop/src/sensor/demosaic.rs b/crates/develop/src/sensor/demosaic.rs new file mode 100644 index 000000000..8a0a96fd4 --- /dev/null +++ b/crates/develop/src/sensor/demosaic.rs @@ -0,0 +1,400 @@ +//! Demosaicing: CFA mosaic → camera RGB ([`Rgb32f`]), values as normalised (white = 1.0). +//! +//! Methods (all from published descriptions, see the README): +//! - [`Method::Bilinear`] — average of same-colour neighbours (drafts / thumbnails); works for any pattern. +//! - [`Method::Ppg`] — Patterned Pixel Grouping (Chuan-kai Lin): gradient-selected green, colour-difference R/B. +//! - [`Method::Ahd`] — Adaptive Homogeneity-Directed (Hirakawa & Parks, IEEE TIP 2005): horizontal/vertical +//! candidates chosen per pixel by CIELab homogeneity. The quality default for Bayer sensors. +//! - Non-Bayer patterns (X-Trans, …) always use `xtrans::directional`, our own edge-weighted colour-difference +//! interpolation. +//! +//! Every method reproduces a constant-colour mosaic exactly. + +mod ahd; +mod bilinear; +mod ppg; +mod xtrans; + +use super::{Cfa, Normalized, Rect, Rgb32f}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Method { + Bilinear, + Ppg, + #[default] + Ahd, +} + +/// 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> { + pub w: usize, + pub h: usize, + pub data: &'a [f32], + pub cfa: &'a Cfa, +} + +#[inline] +pub(crate) fn reflect(i: isize, n: usize) -> usize { + if i >= 0 && (i as usize) < n { + return i as usize; + } + let n = n as isize; + if n == 1 { + return 0; + } + let period = 2 * (n - 1); + let mut i = i.rem_euclid(period); + if i >= n { + i = period - i; + } + i as usize +} + +/// `v` clamped between `a` and `b`: `v.clamp(a.min(b), a.max(b))`, except that it returns `v` as is when both +/// bounds are NaN (NaN samples in a float raw), where `f32::clamp` panics. +#[inline] +pub(crate) fn clamp_between(v: f32, a: f32, b: f32) -> f32 { + let (lo, hi) = (a.min(b), a.max(b)); + if lo <= hi { v.clamp(lo, hi) } else { v } +} + +impl Mosaic<'_> { + #[inline] + pub fn get(&self, x: isize, y: isize) -> f32 { + self.data[reflect(y, self.h) * self.w + reflect(x, self.w)] + } + #[inline] + pub fn color(&self, x: isize, y: isize) -> u8 { + self.cfa.color_at(reflect(x, self.w), reflect(y, self.h)) + } +} + +/// Demosaic normalised raw data. `cpp == 3` data is returned as is; monochrome data is replicated to grey. +pub fn demosaic(n: &Normalized, method: Method) -> Rgb32f { + let (w, h) = (n.width, n.height); + if w == 0 || h == 0 { + return Rgb32f::new(w, h); + } + match (&n.cfa, n.cpp) { + (_, 3) => Rgb32f { width: w, height: h, data: n.data.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect() }, + // four colours develop from their first three; narrower data (refused by `RawImage::validate`, issue #1511) + // repeats its last sample instead of reading past the pixel + (_, cpp) if cpp != 1 => Rgb32f { + width: w, + height: h, + data: n + .data + .chunks_exact(cpp.max(1)) + .map(|c| { + let s = |i: usize| c.get(i).or(c.last()).copied().unwrap_or(0.0); + [s(0), s(1), s(2)] + }) + .collect(), + }, + (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 { + Method::Bilinear => bilinear::bilinear(&m), + Method::Ppg => ppg::ppg(&m), + Method::Ahd => ahd::ahd(&m), + } + } + } +} + +/// [`demosaic`] with [`Method::Ahd`] of the window `r` alone, for Bayer mosaics (`None` for any other data, or a +/// window not inside the mosaic): the same pixels as demosaicing it all and cropping that to `r`, without +/// demosaicing the rest or copying the window out of it. +pub(crate) fn ahd_window(n: &Normalized, r: Rect) -> Option { + let (w, h) = (n.width, n.height); + let cfa = n.cfa.as_ref()?; + let inside = r.x.checked_add(r.width).is_some_and(|e| e <= w) && r.y.checked_add(r.height).is_some_and(|e| e <= h); + if n.cpp != 1 || !cfa.is_bayer() || w < 4 || h < 4 || n.data.len() != w * h || r.width == 0 || r.height == 0 || !inside { + return None; + } + let m = Mosaic { w, h, data: &n.data, cfa }; + Some(ahd::ahd_window(&m, r.x, r.y, r.width, r.height)) +} + +/// Build a mosaic from an RGB image by sampling each pixel's CFA colour (for tests and synthetic data). +pub fn mosaic_from_rgb(img: &Rgb32f, cfa: &Cfa) -> Normalized { + let data = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.get(x, y)[cfa.color_at(x, y) as usize]).collect(); + Normalized { width: img.width, height: img.height, cpp: 1, data, cfa: Some(cfa.clone()) } +} + +/// Peak signal-to-noise ratio (dB, peak 1.0) between two images over an interior region (`border` pixels excluded). +pub fn psnr(a: &Rgb32f, b: &Rgb32f, border: usize) -> f64 { + let mut se = 0.0f64; + let mut n = 0usize; + for y in border..a.height.saturating_sub(border) { + for x in border..a.width.saturating_sub(border) { + let (p, q) = (a.get(x, y), b.get(x, y)); + for c in 0..3 { + se += ((p[c] - q[c]) as f64).powi(2); + n += 1; + } + } + } + if n == 0 || se == 0.0 { + return f64::INFINITY; + } + 10.0 * (1.0 / (se / n as f64)).log10() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn smooth_scene(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32); + [0.2 + 0.6 * fx * fy, 0.3 + 0.4 * (fx * 3.0).sin().abs() * 0.5 + 0.2 * fy, 0.1 + 0.5 * (1.0 - fx) * (0.5 + 0.5 * (fy * 5.0).cos())] + }) + } + + /// A photo-like scene: sharp luminance structure (disc, stripes, diagonal edge, fine texture) modulating a + /// smoothly varying colour — edges are mostly luminance edges, as in natural images. + fn edgy_scene(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let (fx, fy) = (x as f32, y as f32); + let d = ((fx - w as f32 * 0.35).powi(2) + (fy - h as f32 * 0.4).powi(2)).sqrt(); + let lum = if d < w as f32 * 0.18 { + 0.85 + } else if x > w * 2 / 3 && (y / 3) % 2 == 0 { + 0.15 + } else if fx + fy * 0.5 > w as f32 * 1.1 { + 0.7 + } else { + 0.35 + 0.1 * ((fx * 0.7).sin() * (fy * 0.9).cos()) + }; + let tint = [0.9 + 0.1 * (fx / w as f32), 0.8, 0.55 + 0.3 * (fy / h as f32)]; + [lum * tint[0], lum * tint[1], lum * tint[2]] + }) + } + + fn run(img: &Rgb32f, cfa: &Cfa, m: Method) -> Rgb32f { + demosaic(&mosaic_from_rgb(img, cfa), m) + } + + #[test] + fn constant_colour_is_exact_for_all_methods_and_phases() { + let img = Rgb32f::filled(17, 13, [0.3, 0.55, 0.8]); + for pat in ["RGGB", "BGGR", "GRBG", "GBRG"] { + let cfa = Cfa::bayer(pat).unwrap(); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = run(&img, &cfa, m); + for p in &out.data { + for c in 0..3 { + assert!((p[c] - img.data[0][c]).abs() < 1e-5, "{pat} {m:?} {p:?}"); + } + } + } + } + let out = run(&Rgb32f::filled(19, 14, [0.3, 0.55, 0.8]), &Cfa::xtrans(), Method::Ahd); + assert!(out.data.iter().all(|p| (p[0] - 0.3).abs() < 1e-5 && (p[1] - 0.55).abs() < 1e-5 && (p[2] - 0.8).abs() < 1e-5)); + } + + /// A window demosaiced alone is the same, bit for bit, as that part of the whole picture: at the edges and + /// corners (where the mosaic is reflected), in the middle, across tile seams, at every CFA phase. + #[test] + fn ahd_window_is_the_crop_of_the_whole() { + let img = edgy_scene(300, 270); + for pat in ["RGGB", "GBRG"] { + let n = mosaic_from_rgb(&img, &Cfa::bayer(pat).unwrap()); + let whole = demosaic(&n, Method::Ahd); + for r in + [Rect::new(0, 0, 300, 270), Rect::new(0, 0, 7, 5), Rect::new(1, 3, 298, 266), Rect::new(121, 130, 140, 9), Rect::new(293, 263, 7, 7)] + { + let part = ahd_window(&n, r).unwrap(); + let want = whole.clone().into_crop(r.x, r.y, r.width, r.height); + assert_eq!((part.width, part.height), (r.width, r.height)); + assert!(part.data.iter().zip(&want.data).all(|(a, b)| a.map(f32::to_bits) == b.map(f32::to_bits)), "{pat} {r:?}"); + } + assert!(ahd_window(&n, Rect::new(1, 0, 300, 270)).is_none(), "a window past the mosaic is refused"); + } + } + + #[test] + fn known_samples_are_preserved() { + let img = edgy_scene(40, 32); + let cfa = Cfa::bayer("GRBG").unwrap(); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = run(&img, &cfa, m); + for y in 0..32 { + for x in 0..40 { + let c = cfa.color_at(x, y) as usize; + assert!((out.get(x, y)[c] - img.get(x, y)[c]).abs() < 1e-6, "{m:?}"); + } + } + } + } + + #[test] + fn psnr_thresholds_and_ranking() { + let smooth = smooth_scene(96, 80); + let edgy = edgy_scene(96, 80); + let cfa = Cfa::bayer("RGGB").unwrap(); + let p = |img: &Rgb32f, m| psnr(img, &run(img, &cfa, m), 4); + let (sb, sp, sa) = (p(&smooth, Method::Bilinear), p(&smooth, Method::Ppg), p(&smooth, Method::Ahd)); + assert!(sb > 38.0 && sp > 38.0 && sa > 38.0, "smooth: bilinear {sb:.1} ppg {sp:.1} ahd {sa:.1}"); + let (eb, ep, ea) = (p(&edgy, Method::Bilinear), p(&edgy, Method::Ppg), p(&edgy, Method::Ahd)); + eprintln!("smooth: bilinear {sb:.1} ppg {sp:.1} ahd {sa:.1}; edgy: bilinear {eb:.1} ppg {ep:.1} ahd {ea:.1}"); + assert!(eb > 20.0, "edgy bilinear {eb:.1}"); + assert!(ep > eb + 6.0, "ppg {ep:.1} vs bilinear {eb:.1}"); + assert!(ea > eb + 6.0, "ahd {ea:.1} vs bilinear {eb:.1}"); + let xt = Cfa::xtrans(); + let xp = psnr(&edgy, &run(&edgy, &xt, Method::Ahd), 6); + let xb = psnr(&edgy, &run(&edgy, &xt, Method::Bilinear), 6); + assert!(xp > 20.0 && xp >= xb - 0.5, "xtrans directional {xp:.1} bilinear {xb:.1}"); + } + + /// Mean anisotropy of a demosaiced picture's fine luminance detail: per pixel, how much more its 3 × 3 high-pass + /// correlates with its horizontal neighbours than with its vertical ones (or the reverse). Noise has none; the + /// short horizontal and vertical strokes of a maze pattern have a lot. + fn anisotropy(img: &Rgb32f) -> f64 { + let (w, h) = (img.width, img.height); + let lum: Vec = img.data.iter().map(|p| 0.25 * p[0] + 0.5 * p[1] + 0.25 * p[2]).collect(); + let mean3 = |x: usize, y: usize| (0..9).map(|k| lum[(y + k / 3 - 1) * w + x + k % 3 - 1]).sum::() / 9.0; + let hp: Vec = + (0..w * h).map(|i| if i % w == 0 || i % w == w - 1 || i < w || i >= w * (h - 1) { 0.0 } else { lum[i] - mean3(i % w, i / w) }).collect(); + let (mut sum, mut n) = (0f64, 0f64); + for y in 2..h - 2 { + for x in 2..w - 2 { + let i = y * w + x; + sum += f64::from((hp[i] * (hp[i - 1] + hp[i + 1] - hp[i - w] - hp[i + w])).abs()); + n += 1.0; + } + } + sum / n + } + + #[test] + fn flat_noise_does_not_turn_into_a_maze() { + // a flat grey patch with sensor-like noise: AHD picked horizontal or vertical candidates per pixel by a + // homogeneity count that noise alone decides, so the picture became short horizontal and vertical strokes + let (w, h) = (192, 160); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut noise = || { + // sum of four uniforms ≈ Gaussian, σ ≈ 0.02 + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5 + }) + .sum::() + * 0.035 + }; + let cfa = Cfa::bayer("RGGB").unwrap(); + let data = (0..w * h).map(|_| 0.2 + noise()).collect(); + let n = Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + let (ahd, bilinear) = (anisotropy(&demosaic(&n, Method::Ahd)), anisotropy(&demosaic(&n, Method::Bilinear))); + eprintln!("anisotropy: ahd {ahd:.3e}, bilinear {bilinear:.3e}"); + // the hard choice gave about 11 times bilinear's, the blend about 7.5 times + assert!(ahd < 9.0 * bilinear, "ahd {ahd:.3e} bilinear {bilinear:.3e}"); + } + + #[test] + fn tiny_and_degenerate_inputs() { + let cfa = Cfa::bayer("RGGB").unwrap(); + for (w, h) in [(1, 1), (2, 2), (3, 5), (5, 3), (1, 7)] { + let img = Rgb32f::filled(w, h, [0.5; 3]); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = run(&img, &cfa, m); + assert_eq!((out.width, out.height), (w, h)); + assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()))); + } + } + let n = Normalized { width: 2, height: 1, cpp: 1, data: vec![0.2, 0.4], cfa: None }; + assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.2; 3], [0.4; 3]]); + let n = Normalized { width: 1, height: 1, cpp: 3, data: vec![0.1, 0.2, 0.3], cfa: None }; + assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.1, 0.2, 0.3]]); + } + + #[test] + fn a_nan_sample_spreads_no_further_than_the_chosen_candidate_takes_it() { + // vertical stripes: the vertical candidate wins outright beside them, and the horizontal one, which reads two + // samples to each side, is the only one that sees a NaN two columns away + let img = Rgb32f::from_fn(32, 24, |x, _| if (x / 2) % 2 == 0 { [0.2, 0.3, 0.25] } else { [0.7, 0.8, 0.6] }); + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut n = mosaic_from_rgb(&img, &cfa); + n.data[12 * 32 + 16] = f32::NAN; + let out = demosaic(&n, Method::Ahd); + let bad = out.data.iter().filter(|p| p.iter().any(|v| !v.is_finite())).count(); + // the pixels that read the NaN sample themselves, as many as the outright pick gave; the blend made it 33 + assert!(bad <= 9, "{bad} pixels not finite"); + } + + #[test] + fn non_finite_samples_do_not_panic() { + // regression: NaN samples (a float DNG) gave AHD and PPG NaN bounds for `f32::clamp`, which panics + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut patchy = mosaic_from_rgb(&edgy_scene(24, 20), &cfa); + for (i, v) in patchy.data.iter_mut().enumerate() { + let (x, y) = (i % 24, i / 24); + if (8..12).contains(&x) && (6..10).contains(&y) { + *v = f32::NAN; + } else if i % 7 == 0 { + *v = if i % 2 == 0 { f32::INFINITY } else { f32::NEG_INFINITY }; + } + } + let all_nan = Normalized { width: 9, height: 7, cpp: 1, data: vec![f32::NAN; 63], cfa: Some(cfa) }; + for n in [&patchy, &all_nan] { + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = demosaic(n, m); + assert_eq!((out.width, out.height), (n.width, n.height), "{m:?}"); + } + } + // without NaN bounds it is the `f32::clamp` it replaced, bit for bit (finite results stay identical) + let vals = [f32::NEG_INFINITY, -3e38, -2.5, -0.0, 0.0, 1e-40, 0.5, 1.0, 3e38, f32::INFINITY]; + for v in vals { + for a in vals { + for b in vals { + assert_eq!(clamp_between(v, a, b).to_bits(), v.clamp(a.min(b), a.max(b)).to_bits(), "{v} {a} {b}"); + } + } + } + } + + #[test] + fn reflect_indices() { + assert_eq!(reflect(-1, 5), 1); + assert_eq!(reflect(-2, 5), 2); + assert_eq!(reflect(5, 5), 3); + assert_eq!(reflect(6, 5), 2); + assert_eq!(reflect(3, 1), 0); + assert_eq!(reflect(-7, 2), 1); + } + + #[test] + #[ignore] + fn throughput() { + let (w, h) = (6000, 4000); + let img = smooth_scene(w, h); + let cfa = Cfa::bayer("RGGB").unwrap(); + let n = mosaic_from_rgb(&img, &cfa); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let t = std::time::Instant::now(); + let _ = demosaic(&n, m); + let s = t.elapsed().as_secs_f64(); + println!("{m:?}: {:.1} MP/s ({:.0} ms for 24 MP)", (w * h) as f64 / 1e6 / s, s * 1e3); + } + let n = mosaic_from_rgb(&img, &Cfa::xtrans()); + let t = std::time::Instant::now(); + let _ = demosaic(&n, Method::Ahd); + println!("X-Trans directional: {:.1} MP/s", (w * h) as f64 / 1e6 / t.elapsed().as_secs_f64()); + } +} diff --git a/crates/develop/src/sensor/demosaic/ahd.rs b/crates/develop/src/sensor/demosaic/ahd.rs new file mode 100644 index 000000000..6960573e3 --- /dev/null +++ b/crates/develop/src/sensor/demosaic/ahd.rs @@ -0,0 +1,190 @@ +//! Adaptive Homogeneity-Directed demosaicing (K. Hirakawa, T. W. Parks, "Adaptive homogeneity-directed +//! demosaicing algorithm", IEEE Trans. Image Processing 14(3), 2005), implemented from the paper: +//! +//! 1. Interpolate green horizontally and vertically (5-tap filter [−¼ ½ ½ ½ −¼] across the missing site, +//! clamped to the two adjacent greens), giving two candidate green planes. +//! 2. Complete each candidate with red/blue by colour-difference (C − G) interpolation. +//! 3. Convert both candidates to CIELab and measure, per pixel, how many of its 4 neighbours lie within the +//! adaptive luminance / chrominance tolerances (ε_L, ε_C from the paper) — the homogeneity. +//! 4. Sum homogeneity over a 3×3 window and pick the more homogeneous candidate. The paper picks one outright; +//! we blend the two by how far apart their sums are (see [`BLEND`]), so a clear edge still takes one candidate. +//! +//! Work is done in overlapping tiles (bounded memory, rayon-parallel), one band of tiles at a time written +//! straight into the output. Each step runs only where the tile's output depends on it: the choice reads the +//! homogeneity 1 pixel around the tile, which reads Lab 2 pixels around, the candidates read the greens 3 +//! pixels around, and those read the mosaic 5 pixels around, inside the `MARGIN`. + +use super::super::Rgb32f; +use super::Mosaic; + +const TILE: usize = 128; +const MARGIN: usize = 6; +/// Difference of the two candidates' 3×3 homogeneity sums (each 0–36) from which the more homogeneous one is taken +/// alone; closer sums blend the two linearly, equal sums half and half. In a flat, noisy area noise alone decides +/// which sum is larger, and picking outright turned the noise into short horizontal and vertical strokes (a maze, +/// coloured where white balance is strong). 12 keeps the PSNR of the outright pick on the edge tests. +const BLEND: f32 = 12.0; + +pub(crate) fn ahd(m: &Mosaic) -> Rgb32f { + ahd_window(m, 0, 0, m.w, m.h) +} + +/// The `w × h` pixels at (`x`, `y`) of [`ahd`]'s picture (inside the mosaic), demosaiced alone: every pixel comes +/// from the mosaic around it, so they are the same as when the whole picture is demosaiced and then cropped. +pub(crate) fn ahd_window(m: &Mosaic, x: usize, y: usize, w: usize, h: usize) -> Rgb32f { + let mut out = Rgb32f::new(w, h); + if w == 0 || h == 0 { + return out; + } + // one row of tiles per task, its tiles in parallel too, written straight into the picture + let process_band = |ty: usize, band: &mut [[f32; 3]]| { + let (y0, th) = (y + ty * TILE, band.len() / w.max(1)); + #[cfg(not(target_arch = "wasm32"))] + let tiles: Vec<(usize, usize, Vec<[f32; 3]>)> = { + use rayon::prelude::*; + (0..w.div_ceil(TILE)) + .into_par_iter() + .map(|tx| { + let (x0, tw) = (tx * TILE, TILE.min(w - tx * TILE)); + (x0, tw, tile(m, x + x0, y0, tw, th)) + }) + .collect() + }; + #[cfg(target_arch = "wasm32")] + let tiles: Vec<(usize, usize, Vec<[f32; 3]>)> = (0..w.div_ceil(TILE)) + .map(|tx| { + let (x0, tw) = (tx * TILE, TILE.min(w - tx * TILE)); + (x0, tw, tile(m, x + x0, y0, tw, th)) + }) + .collect(); + for (x0, tw, px) in tiles { + for (row, src) in band.chunks_exact_mut(w).zip(px.chunks_exact(tw)) { + row[x0..x0 + tw].copy_from_slice(src); + } + } + }; + crate::raster::par_rows(&mut out.data, (w * TILE).max(1), process_band); + out +} + +/// Linear camera RGB (treated as sRGB/D65 primaries for the homogeneity metric only) → CIELab. +#[inline] +fn lab(p: [f32; 3]) -> [f32; 3] { + let x = (0.4124 * p[0] + 0.3576 * p[1] + 0.1805 * p[2]) / 0.95047; + let y = 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; + let z = (0.0193 * p[0] + 0.1192 * p[1] + 0.9505 * p[2]) / 1.08883; + #[inline] + fn f(t: f32) -> f32 { + if t > 0.008856 { t.cbrt() } else { 7.787 * t + 16.0 / 116.0 } + } + let (fx, fy, fz) = (f(x), f(y), f(z)); + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] +} + +fn tile(m: &Mosaic, x0: usize, y0: usize, tw: usize, th: usize) -> Vec<[f32; 3]> { + let (bw, bh) = (tw + 2 * MARGIN, th + 2 * MARGIN); + let n = bw * bh; + let (ox, oy) = (x0 as isize - MARGIN as isize, y0 as isize - MARGIN as isize); + let mut mos = vec![0f32; n]; + let mut col = vec![0u8; n]; + for (y, (mrow, crow)) in mos.chunks_exact_mut(bw).zip(col.chunks_exact_mut(bw)).enumerate() { + let ry = super::reflect(oy + y as isize, m.h); + if ox >= 0 && ox as usize + bw <= m.w { + // inside the image: the row as it is, and its colours repeating with the pattern + let x0 = ry * m.w + ox as usize; + mrow.copy_from_slice(&m.data[x0..x0 + bw]); + let period: Vec = (0..m.cfa.width).map(|k| m.cfa.color_at(ox as usize + k, ry)).collect(); + for (c, &p) in crow.iter_mut().zip(period.iter().cycle()) { + *c = p; + } + } else { + for x in 0..bw { + mrow[x] = m.get(ox + x as isize, oy + y as isize); + crow[x] = m.color(ox + x as isize, oy + y as isize); + } + } + } + // flat indices of the pixels `d` or more from the buffer's edge, row by row + let inner = |d: usize| (d..bh - d).flat_map(move |y| y * bw + d..y * bw + bw - d); + // 1. directional greens + let mut gh = vec![0f32; n]; + let mut gv = vec![0f32; n]; + for i in inner(MARGIN - 3) { + let c = mos[i]; + if col[i] == 1 { + gh[i] = c; + gv[i] = c; + continue; + } + let (l, r) = (mos[i - 1], mos[i + 1]); + let est = (l + r) * 0.5 + (2.0 * c - mos[i - 2] - mos[i + 2]) * 0.25; + gh[i] = super::clamp_between(est, l, r); + let (u, d) = (mos[i - bw], mos[i + bw]); + let est = (u + d) * 0.5 + (2.0 * c - mos[i - 2 * bw] - mos[i + 2 * bw]) * 0.25; + gv[i] = super::clamp_between(est, u, d); + } + // 2. full candidates, and 3. their Lab + // (`p` with channel `c` set to `v`, in registers: writing channels through an index and reading the pixel + // back for its Lab stalled on store forwarding) + let set = |p: [f32; 3], c: u8, v: f32| [if c == 0 { v } else { p[0] }, if c == 1 { v } else { p[1] }, if c >= 2 { v } else { p[2] }]; + let complete = |g: &[f32]| -> (Vec<[f32; 3]>, Vec<[f32; 3]>) { + let mut rgb = vec![[0f32; 3]; n]; + let mut lab_of = vec![[0f32; 3]; n]; + for i in inner(MARGIN - 2) { + let own = col[i]; + let gvv = g[i]; + let d = |j: usize| mos[j] - g[j]; + let p = if own == 1 { + let p = set([0.0, gvv, 0.0], col[i + 1], gvv + (d(i - 1) + d(i + 1)) * 0.5); + set(p, col[i + bw], gvv + (d(i - bw) + d(i + bw)) * 0.5) + } else { + let p = set([0.0, gvv, 0.0], own, mos[i]); + set(p, 2 - own, gvv + (d(i - bw - 1) + d(i - bw + 1) + d(i + bw - 1) + d(i + bw + 1)) * 0.25) + }; + rgb[i] = p; + lab_of[i] = lab(p); + } + (rgb, lab_of) + }; + let (rh, lh) = complete(&gh); + let (rv, lv) = complete(&gv); + // homogeneity + let dl = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).abs(); + let dc = |a: &[f32; 3], b: &[f32; 3]| (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2); + let mut hh = vec![0u8; n]; + let mut hv = vec![0u8; n]; + for i in inner(MARGIN - 1) { + // left, right, up, down + let (l, r, u, d) = (i - 1, i + 1, i - bw, i + bw); + let (a, b) = (lh[i], lv[i]); + let dlh = [dl(&a, &lh[l]), dl(&a, &lh[r]), dl(&a, &lh[u]), dl(&a, &lh[d])]; + let dch = [dc(&a, &lh[l]), dc(&a, &lh[r]), dc(&a, &lh[u]), dc(&a, &lh[d])]; + let dlv = [dl(&b, &lv[l]), dl(&b, &lv[r]), dl(&b, &lv[u]), dl(&b, &lv[d])]; + let dcv = [dc(&b, &lv[l]), dc(&b, &lv[r]), dc(&b, &lv[u]), dc(&b, &lv[d])]; + let eps_l = dlh[0].max(dlh[1]).min(dlv[2].max(dlv[3])); + let eps_c = dch[0].max(dch[1]).min(dcv[2].max(dcv[3])); + hh[i] = (0..4).map(|k| u8::from(dlh[k] <= eps_l && dch[k] <= eps_c)).sum(); + hv[i] = (0..4).map(|k| u8::from(dlv[k] <= eps_l && dcv[k] <= eps_c)).sum(); + } + // 4. choose + let mut out = Vec::with_capacity(tw * th); + for i in inner(MARGIN) { + let (mut sh, mut sv) = (0u32, 0u32); + for j in [i - bw - 1, i - bw, i - bw + 1, i - 1, i, i + 1, i + bw - 1, i + bw, i + bw + 1] { + sh += hh[j] as u32; + sv += hv[j] as u32; + } + let wh = (0.5 + (sh as f32 - sv as f32) / (2.0 * BLEND)).clamp(0.0, 1.0); + // a candidate taken alone is copied, and one that isn't finite (beside a float raw's NaN sample) is left out, + // so the other's value doesn't become 0 · NaN + let finite = |p: &[f32; 3]| p.iter().all(|v| v.is_finite()); + out.push(if wh >= 1.0 || !finite(&rv[i]) { + rh[i] + } else if wh <= 0.0 || !finite(&rh[i]) { + rv[i] + } else { + [0, 1, 2].map(|c| rh[i][c] * wh + rv[i][c] * (1.0 - wh)) + }); + } + out +} diff --git a/crates/develop/src/sensor/demosaic/bilinear.rs b/crates/develop/src/sensor/demosaic/bilinear.rs new file mode 100644 index 000000000..b47528023 --- /dev/null +++ b/crates/develop/src/sensor/demosaic/bilinear.rs @@ -0,0 +1,78 @@ +//! 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; + +/// 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]> { + let cfa = m.cfa; + let mut table = Vec::with_capacity(cfa.width * cfa.height); + for py in 0..cfa.height { + for px in 0..cfa.width { + let mut per: [Vec<(isize, isize)>; 3] = Default::default(); + for (c, list) in per.iter_mut().enumerate() { + for r in [1isize, 2] { + for dy in -r..=r { + for dx in -r..=r { + let (x, y) = (px as isize + dx + 6 * cfa.width as isize, py as isize + dy + 6 * cfa.height as isize); + if cfa.color_at(x as usize, y as usize) as usize == c { + list.push((dx, dy)); + } + } + } + if !list.is_empty() { + break; + } + } + } + table.push(per); + } + } + table +} + +pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let table = neighbour_table(m); + let cfa = m.cfa; + let mut out = Rgb32f::new(w, h); + 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 { + if c == own { + px[c] = 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] }; + } + } + }); + out +} diff --git a/crates/develop/src/sensor/demosaic/ppg.rs b/crates/develop/src/sensor/demosaic/ppg.rs new file mode 100644 index 000000000..e3eb16743 --- /dev/null +++ b/crates/develop/src/sensor/demosaic/ppg.rs @@ -0,0 +1,89 @@ +//! Patterned Pixel Grouping (after Chuan-kai Lin's published description of the method). +//! +//! 1. Green at red/blue sites: four directional gradients (same-colour difference ×2 plus the green difference +//! across the site); the estimate along the flattest direction is the nearer green weighted 3:1 with the far +//! one plus a same-colour Laplacian correction, clamped to the two greens of that direction. +//! 2. Red/blue at green sites: colour-difference (C − G) average of the two same-colour neighbours. +//! 3. Blue at red sites (and red at blue): colour-difference average along the diagonal with the smaller +//! gradient (both diagonals when equal). + +use super::super::Rgb32f; +use super::Mosaic; +use crate::raster::par_rows; + +/// Green plane with PPG estimates at non-green sites. +pub(crate) fn green_plane(m: &Mosaic) -> Vec { + let (w, h) = (m.w, m.h); + let mut g = vec![0f32; w * h]; + par_rows(&mut g, w, |y, row| { + let y = y as isize; + for (x, o) in row.iter_mut().enumerate() { + let x = x as isize; + let c = m.get(x, y); + if m.color(x, y) == 1 { + *o = c; + continue; + } + let (gn, gs, gw, ge) = (m.get(x, y - 1), m.get(x, y + 1), m.get(x - 1, y), m.get(x + 1, y)); + let (cn, cs, cw, ce) = (m.get(x, y - 2), m.get(x, y + 2), m.get(x - 2, y), m.get(x + 2, y)); + let dv = (gn - gs).abs(); + let dh = (gw - ge).abs(); + let grads = [(cn - c).abs() * 2.0 + dv, (cs - c).abs() * 2.0 + dv, (cw - c).abs() * 2.0 + dh, (ce - c).abs() * 2.0 + dh]; + let mut best = 0; + for i in 1..4 { + if grads[i] < grads[best] { + best = i; + } + } + let (near, far, cfar) = match best { + 0 => (gn, gs, cn), + 1 => (gs, gn, cs), + 2 => (gw, ge, cw), + _ => (ge, gw, ce), + }; + let est = (near * 3.0 + far + c - cfar) * 0.25; + *o = super::clamp_between(est, near, far); + } + }); + g +} + +pub(crate) fn ppg(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let g = green_plane(m); + let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; + let mut out = Rgb32f::new(w, h); + par_rows(&mut out.data, w, |y, row| { + let y = y as isize; + for (x, px) in row.iter_mut().enumerate() { + let x = x as isize; + let own = m.color(x, y) as usize; + let gv = gg(x, y); + px[1] = gv; + if own == 1 { + // horizontal neighbours carry one colour, vertical the other + let ch = m.color(x + 1, y) as usize; + let cv = m.color(x, y + 1) as usize; + let hval = gv + ((m.get(x - 1, y) - gg(x - 1, y)) + (m.get(x + 1, y) - gg(x + 1, y))) * 0.5; + let vval = gv + ((m.get(x, y - 1) - gg(x, y - 1)) + (m.get(x, y + 1) - gg(x, y + 1))) * 0.5; + px[ch] = hval; + px[cv] = vval; + } else { + px[own] = m.get(x, y); + let other = 2 - own; + let d = |dx: isize, dy: isize| m.get(x + dx, y + dy) - gg(x + dx, y + dy); + let ne = (m.get(x + 1, y - 1) - m.get(x - 1, y + 1)).abs() + (gg(x + 1, y - 1) - gv).abs() + (gg(x - 1, y + 1) - gv).abs(); + let nw = (m.get(x - 1, y - 1) - m.get(x + 1, y + 1)).abs() + (gg(x - 1, y - 1) - gv).abs() + (gg(x + 1, y + 1) - gv).abs(); + let diff = if ne < nw { + (d(1, -1) + d(-1, 1)) * 0.5 + } else if nw < ne { + (d(-1, -1) + d(1, 1)) * 0.5 + } else { + (d(1, -1) + d(-1, 1) + d(-1, -1) + d(1, 1)) * 0.25 + }; + px[other] = gv + diff; + } + } + }); + out +} diff --git a/crates/develop/src/sensor/demosaic/xtrans.rs b/crates/develop/src/sensor/demosaic/xtrans.rs new file mode 100644 index 000000000..f12ab4b8e --- /dev/null +++ b/crates/develop/src/sensor/demosaic/xtrans.rs @@ -0,0 +1,283 @@ +//! Demosaicing for non-Bayer patterns (Fujifilm X-Trans and others): our own edge-weighted colour-difference +//! interpolation. +//! +//! 1. Green at non-green sites: robust weighted mean of the green samples in the 3×3 neighbourhood (5×5 if +//! none), each weighted by `1 / (ε + |g − median|)` so samples across an edge contribute little. +//! 2. Red and blue everywhere: `G(p) + Σ w_q (C(q) − G(q)) / Σ w_q` over same-colour samples `q` in the 5×5 +//! neighbourhood, with `w_q = 1 / (d²(p, q) · (ε + |G(q) − G(p)|))` — spatially close samples on the same +//! side of an edge dominate. + +use super::super::Rgb32f; +use super::Mosaic; +use crate::raster::par_rows; + +const EPS: f32 = 1e-3; + +type OffsetList = Vec<(isize, isize)>; + +/// Same-colour neighbour offsets for every pattern phase, in scan order (so sums run in the same +/// order as a plain 2-D loop and interior pixels match border pixels bit for bit). +struct Offsets { + pw: usize, + ph: usize, + /// Per phase: green offsets at radius 1, then those at radius 2 (ring order as the loop below). + green: Vec<(OffsetList, OffsetList)>, + /// Per phase and colour (0 = red, 1 = blue): 5×5 offsets of that colour. + rb: Vec<[OffsetList; 2]>, +} + +impl Offsets { + fn new(m: &Mosaic) -> Offsets { + let (pw, ph) = (m.cfa.width.max(1), m.cfa.height.max(1)); + // phases are evaluated far from the borders (pattern coordinates wrap) + let col = |x: isize, y: isize| m.cfa.color_at(x.rem_euclid(pw as isize) as usize, y.rem_euclid(ph as isize) as usize); + let mut green = Vec::new(); + let mut rb = Vec::new(); + for py in 0..ph as isize { + for px in 0..pw as isize { + let ring = |r: isize| { + let mut v = Vec::new(); + for dy in -r..=r { + for dx in -r..=r { + if (dx != 0 || dy != 0) && col(px + dx, py + dy) == 1 { + v.push((dx, dy)); + } + } + } + v + }; + green.push((ring(1), ring(2))); + let of = |c: u8| { + let mut v = Vec::new(); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if col(px + dx, py + dy) == c { + v.push((dx, dy)); + } + } + } + v + }; + rb.push([of(0), of(2)]); + } + } + Offsets { pw, ph, green, rb } + } + #[inline] + fn phase(&self, x: usize, y: usize) -> usize { + (y % self.ph) * self.pw + x % self.pw + } +} + +/// Robust weighted mean of `vals` around their median. +#[inline] +fn robust_mean(vals: &[f32]) -> f32 { + let mut sorted = [0f32; 24]; + let sorted = &mut sorted[..vals.len()]; + sorted.copy_from_slice(vals); + sorted.sort_unstable_by(|a, b| a.total_cmp(b)); + let med = sorted[sorted.len() / 2]; + let (mut s, mut ws) = (0.0f32, 0.0f32); + for &v in vals { + let wt = 1.0 / (EPS + (v - med).abs()); + s += wt * v; + ws += wt; + } + s / ws +} + +fn green(m: &Mosaic, off: &Offsets) -> Vec { + let (w, h) = (m.w, m.h); + let mut g = vec![0f32; w * h]; + par_rows(&mut g, w, |y, row| { + let interior_y = y >= 2 && y + 2 < h; + let yi = y as isize; + let mut vals: Vec = Vec::with_capacity(24); + for (x, o) in row.iter_mut().enumerate() { + if interior_y && x >= 2 && x + 2 < w { + // fast path: precomputed offsets, no reflection + let ph = off.phase(x, y); + let i = y * w + x; + if m.cfa.color_at(x, y) == 1 { + *o = m.data[i]; + continue; + } + let (r1, r2) = &off.green[ph]; + let ring = if r1.is_empty() { r2 } else { r1 }; + if ring.is_empty() { + *o = m.data[i]; + continue; + } + vals.clear(); + vals.extend(ring.iter().map(|&(dx, dy)| m.data[(i as isize + dy * w as isize + dx) as usize])); + *o = robust_mean(&vals); + continue; + } + let x = x as isize; + if m.color(x, yi) == 1 { + *o = m.get(x, yi); + continue; + } + vals.clear(); + for r in [1isize, 2] { + for dy in -r..=r { + for dx in -r..=r { + if (dx != 0 || dy != 0) && m.color(x + dx, yi + dy) == 1 { + vals.push(m.get(x + dx, yi + dy)); + } + } + } + if !vals.is_empty() { + break; + } + } + if vals.is_empty() { + *o = m.get(x, yi); + continue; + } + *o = robust_mean(&vals); + } + }); + g +} + +pub(crate) fn directional(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let off = Offsets::new(m); + let g = green(m, &off); + let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; + let mut out = Rgb32f::new(w, h); + par_rows(&mut out.data, w, |y, row| { + let interior_y = y >= 2 && y + 2 < h; + let yi = y as isize; + for (x, px) in row.iter_mut().enumerate() { + if interior_y && x >= 2 && x + 2 < w { + let i = y * w + x; + let own = m.cfa.color_at(x, y) as usize; + let gp = g[i]; + px[1] = gp; + let lists = &off.rb[off.phase(x, y)]; + for (li, c) in [0usize, 2].into_iter().enumerate() { + if c == own { + px[c] = m.data[i]; + continue; + } + let (mut s, mut ws) = (0.0f32, 0.0f32); + for &(dx, dy) in &lists[li] { + let j = (i as isize + dy * w as isize + dx) as usize; + let gq = g[j]; + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.data[j] - gq); + ws += wt; + } + px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + } + continue; + } + let x = x as isize; + let own = m.color(x, yi) as usize; + let gp = gg(x, yi); + px[1] = gp; + for c in [0usize, 2] { + if c == own { + px[c] = m.get(x, yi); + continue; + } + let (mut s, mut ws) = (0.0f32, 0.0f32); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if m.color(x + dx, yi + dy) as usize != c { + continue; + } + let gq = gg(x + dx, yi + dy); + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.get(x + dx, yi + dy) - gq); + ws += wt; + } + } + px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + } + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::super::Cfa; + use super::*; + + /// The straightforward per-pixel formulation (reflection at every access): the precomputed + /// interior path must match it bit for bit. + fn reference(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let mut g = vec![0f32; w * h]; + for y in 0..h as isize { + for x in 0..w as isize { + let o = &mut g[y as usize * w + x as usize]; + if m.color(x, y) == 1 { + *o = m.get(x, y); + continue; + } + let mut vals = Vec::new(); + for r in [1isize, 2] { + for dy in -r..=r { + for dx in -r..=r { + if (dx != 0 || dy != 0) && m.color(x + dx, y + dy) == 1 { + vals.push(m.get(x + dx, y + dy)); + } + } + } + if !vals.is_empty() { + break; + } + } + *o = if vals.is_empty() { m.get(x, y) } else { robust_mean(&vals) }; + } + } + let gg = |x: isize, y: isize| g[super::super::reflect(y, h) * w + super::super::reflect(x, w)]; + Rgb32f::from_fn(w, h, |x, y| { + let (x, y) = (x as isize, y as isize); + let own = m.color(x, y) as usize; + let gp = gg(x, y); + let mut px = [0f32, gp, 0.0]; + for c in [0usize, 2] { + if c == own { + px[c] = m.get(x, y); + continue; + } + let (mut s, mut ws) = (0.0f32, 0.0f32); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if m.color(x + dx, y + dy) as usize == c { + let gq = gg(x + dx, y + dy); + let wt = 1.0 / ((dx * dx + dy * dy) as f32 * (EPS + (gq - gp).abs())); + s += wt * (m.get(x + dx, y + dy) - gq); + ws += wt; + } + } + } + px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + } + px + }) + } + + #[test] + fn fast_path_is_bit_exact() { + let cfa = Cfa::xtrans().shifted(1, 2); + let (w, h) = (37, 29); + let mut seed = 12345u32; + let data: Vec = (0..w * h) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }) + .collect(); + let m = Mosaic { w, h, data: &data, cfa: &cfa }; + let (a, b) = (directional(&m), reference(&m)); + assert!(a.data.iter().zip(&b.data).all(|(p, q)| p.map(f32::to_bits) == q.map(f32::to_bits))); + } +} diff --git a/crates/develop/src/sensor/gaintable.rs b/crates/develop/src/sensor/gaintable.rs new file mode 100644 index 000000000..7156ddc6d --- /dev/null +++ b/crates/develop/src/sensor/gaintable.rs @@ -0,0 +1,267 @@ +//! DNG `ProfileGainTableMap` (tag 52525, DNG 1.6) and `ProfileGainTableMap2` (tag 52544, DNG 1.7): +//! a coarse grid of 1D gain tables carrying the maker's local tone mapping. Apple ProRAW has one. +//! +//! We read and write the tag (a DNG export keeps it) but don't render it by default: Lightroom +//! Classic renders Apple ProRAW without the map (see [`crate::profile`]), and so do we. The photo's +//! "camera local tone mapping" option renders it ([`GainTableMap::gain`], applied by the pipeline), +//! as the camera itself does. +//! +//! Applying it (DNG 1.7.1, `ProfileGainTableMap` → "Description"): +//! +//! - the four tables around a position are interpolated bilinearly; outside the grid the edge +//! tables are replicated. Positions are relative to the active area at pixel centres; +//! - the table input `clamp((R, G, B, min, max) · weights, 0, 1) ^ gamma` is computed in linear +//! RIMM (ProPhoto) after the baseline exposure; +//! - the gain is the table looked up linearly at `input × MapPointsN` ("multiply the table input +//! value by MapPointsN to compute the floating-point table index"), clamped to the last point, +//! and multiplies R, G and B. Results may exceed 1 and aren't clipped. +//! +//! - The grid has `MapPointsV × MapPointsH` tables of `MapPointsN` gains. Its origin and spacing +//! are relative to the active area (1.0 = the active area's height or width). +//! - The table input is the dot product of (R, G, B, min, max) with the tag's five weights; +//! version 2 then raises it to the tag's `Gamma`. +//! - Version 2 stores gains as u8 or u16 (mapped linearly onto `GainMin..=GainMax`), f16 or f32. +//! It takes precedence over version 1 when both are present. +//! +//! Malformed tags are ignored: a wrong size, zero or huge dimensions, non-finite or negative gains, +//! non-positive spacing, or gamma outside 0.25..=4. +//! +//! Byte order: the tag's fields are TIFF types (LONG, DOUBLE, FLOAT, …), and neither DNG 1.6 nor +//! 1.7.1 gives this tag a byte order of its own, as they do for opcode lists and +//! `OriginalRawFileData` (always big-endian). What applies is the general rule of the DNG 1.6 +//! specification ("DNG Format Overview" → "Byte Order", worded the same in 1.7.1): +//! +//! > DNG readers are required to support either byte order, even for files from a particular +//! > camera model. +//! +//! (, "DNG Specification".) So we read +//! the fields in the file's byte order, and fall back to big-endian for writers that followed the +//! opcode-list convention. A read in the wrong order can't pass for a valid map: one of +//! `MapPointsV` / `MapPointsH` is below 256 (their product is at most [`MAX_TABLES`]), so swapped +//! it is at least 2^24 and the size checks reject it. We write in the file's byte order. + +pub use craft_raw::gaintable::GainTableMap; +use serde::{Deserialize, Serialize}; + +/// Applying a gain table map (the map, and reading and writing its tag, is `craft-raw`'s). +pub trait GainTableMapApply { + /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) + /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, + /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. + fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32; + /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). + fn evaluator(&self) -> Option>; +} + +/// Applying the map (see the module docs). Index arithmetic saturates and every lookup is +/// checked: the fields are public and the struct is deserializable, so a hand-built or damaged map +/// must not overflow or panic, whatever it holds. +impl GainTableMapApply for GainTableMap { + /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) + /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, + /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. + fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { + self.evaluator().map_or(1.0, |e| e.gain(p, x, y)) + } + + /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). + fn evaluator(&self) -> Option> { + let n = self.points_n; + let tables = self.points_v.saturating_mul(self.points_h); + if n == 0 || tables == 0 || tables.saturating_mul(n) != self.gains.len() { + return None; + } + let axis = |points: usize, origin: f64, spacing: f64| Axis { + last: points.saturating_sub(1), + origin, + // (a degenerate axis replicates its first table) + inv: if points > 1 && spacing.is_finite() && spacing > 0.0 { 1.0 / spacing } else { 0.0 }, + }; + Some(GainEval { map: self, v: axis(self.points_v, self.origin_v, self.spacing_v), h: axis(self.points_h, self.origin_h, self.spacing_h) }) + } +} + +/// One grid axis, prepared: last table index, origin and inverse spacing (0: one table). +#[derive(Clone, Copy, Debug)] +struct Axis { + last: usize, + origin: f64, + inv: f64, +} + +impl Axis { + /// The cell at relative position `pos`: (first table, second table, weight of the second). + /// Outside the grid the edge table is replicated. + #[inline] + fn cell(self, pos: f64) -> (usize, usize, f32) { + if self.last == 0 || self.inv == 0.0 { + return (0, 0, 0.0); + } + let f = (pos - self.origin) * self.inv; + let f = if f.is_nan() { 0.0 } else { f.clamp(0.0, self.last as f64) }; + // (≥ 0: `as` truncates like `floor`, which isn't inlined on baseline x86-64) + let i0 = (f as usize).min(self.last); + let i1 = i0.saturating_add(1).min(self.last); + (i0, i1, (f - i0 as f64) as f32) + } +} + +/// Grid cell along one axis (see [`Axis::cell`]). +#[cfg(test)] +fn cell(pos: f64, origin: f64, spacing: f64, points: usize) -> (usize, usize, f32) { + let inv = if points > 1 && spacing.is_finite() && spacing > 0.0 { 1.0 / spacing } else { 0.0 }; + Axis { last: points.saturating_sub(1), origin, inv }.cell(pos) +} + +/// A [`GainTableMap`] prepared for evaluating many pixels. +#[derive(Clone, Copy, Debug)] +pub struct GainEval<'a> { + map: &'a GainTableMap, + v: Axis, + h: Axis, +} + +impl GainEval<'_> { + /// [`GainTableMapApply::gain`]. + #[inline] + pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { + let m = self.map; + let (v0, v1, fv) = self.v.cell(y); + let (h0, h1, fh) = self.h.cell(x); + // one fractional index for the four tables (≥ 0, so `as` truncates) + let n = m.points_n; + let last = n - 1; + let idx = (input(m, p) * n as f32).min(last as f32); + let i0 = (idx as usize).min(last); + let i1 = i0.saturating_add(1).min(last); + let t = idx - i0 as f32; + // (v ≤ points_v − 1, h ≤ points_h − 1 and i ≤ n − 1, with points_v·points_h·n = gains.len() + // checked by `evaluator`: none of this overflows, and `get` still guards each read) + let at = |v: usize, h: usize| { + let table = m.gains.get((v * m.points_h + h) * n..).unwrap_or(&[]); + let g0 = table.get(i0).copied().unwrap_or(1.0); + let g1 = table.get(i1).copied().unwrap_or(1.0); + g0 + (g1 - g0) * t + }; + let (a, b, c, d) = (at(v0, h0), at(v0, h1), at(v1, h0), at(v1, h1)); + let top = a + (b - a) * fh; + let bottom = c + (d - c) * fh; + let g = top + (bottom - top) * fv; + if g.is_finite() { g.max(0.0) } else { 1.0 } + } +} + +/// The table input for `p` (linear ProPhoto, after the baseline exposure). +#[inline] +fn input(m: &GainTableMap, p: [f32; 3]) -> f32 { + let w = &m.weights; + let lo = p[0].min(p[1]).min(p[2]); + let hi = p[0].max(p[1]).max(p[2]); + let x = w[0] * p[0] + w[1] * p[1] + w[2] * p[2] + w[3] * lo + w[4] * hi; + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; + if m.gamma == 1.0 { x } else { x.powf(m.gamma) } +} + +/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMapApply::gain`]. +/// The source is the default crop of the active area (`rect`, relative to the active area), +/// then EXIF-`orientation`ed. Resolution independent. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct SourcePlacement { + /// x, y, width, height of the developed crop, relative to the active area. + pub rect: [f64; 4], + /// The EXIF orientation applied to the developed crop. + pub orientation: craft_geom::Orientation, +} + +impl SourcePlacement { + /// Relative active-area position of normalized (0..1) coordinates of the oriented source. + pub fn active(&self, u: f64, v: f64) -> (f64, f64) { + let (u, v) = self.orientation.inverse().map(u, v, 1.0, 1.0); + let [x, y, w, h] = self.rect; + (x + u * w, y + v * h) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn map(dims: [usize; 3], spacing: [f64; 2], origin: [f64; 2], weights: [f32; 5], gains: Vec) -> GainTableMap { + let [points_v, points_h, points_n] = dims; + let [spacing_v, spacing_h] = spacing; + let [origin_v, origin_h] = origin; + GainTableMap { points_v, points_h, points_n, spacing_v, spacing_h, origin_v, origin_h, weights, gamma: 1.0, gains } + } + + const LUMA: [f32; 5] = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0, 0.0]; + + #[test] + fn gain_follows_the_table_input_at_input_times_n() { + // one table of 3 points: index = input × 3 (DNG 1.7.1), clamped to the last point + let m = map([1, 1, 3], [1.0, 1.0], [0.0, 0.0], LUMA, vec![1.0, 2.0, 3.0]); + assert_eq!(m.gain([0.0; 3], 0.5, 0.5), 1.0); + assert!((m.gain([1.0 / 3.0; 3], 0.5, 0.5) - 2.0).abs() < 1e-5, "index 1"); + assert!((m.gain([1.0 / 6.0; 3], 0.5, 0.5) - 1.5).abs() < 1e-5, "index 0.5: linear in the table"); + assert!((m.gain([0.9; 3], 0.5, 0.5) - 3.0).abs() < 1e-5, "index 2.7 clamps to the last point"); + // min/max weights and gamma: input = max(R, G, B)², two points + let mut m = map([1, 1, 2], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0], vec![1.0, 3.0]); + m.gamma = 2.0; + // max 0.5 → 0.25 → index 0.5 → ×2 + assert!((m.gain([0.1, 0.5, 0.2], 0.0, 0.0) - 2.0).abs() < 1e-5); + } + + #[test] + fn tables_interpolate_across_the_grid_and_replicate_at_the_edges() { + // 1 × 2 constant tables at x = 0.25 (×1) and x = 0.75 (×3) + let m = map([1, 2, 1], [1.0, 0.5], [0.0, 0.25], LUMA, vec![1.0, 3.0]); + let g = |x: f64| m.gain([0.2; 3], x, 0.5); + assert!((g(0.25) - 1.0).abs() < 1e-5 && (g(0.5) - 2.0).abs() < 1e-5 && (g(0.75) - 3.0).abs() < 1e-5); + assert!((g(0.0) - 1.0).abs() < 1e-5 && (g(1.0) - 3.0).abs() < 1e-5); + assert!((g(-10.0) - 1.0).abs() < 1e-5 && (g(10.0) - 3.0).abs() < 1e-5); + // vertically too: 2 × 1 at y = 0 (×1) and y = 1 (×2) + let m = map([2, 1, 1], [1.0, 1.0], [0.0, 0.0], LUMA, vec![1.0, 2.0]); + assert!((m.gain([0.2; 3], 0.5, 0.25) - 1.25).abs() < 1e-5); + } + + #[test] + fn hand_built_maps_never_panic() { + // review on #273: `(i0 + 1).min(points - 1)` overflowed for points_v = usize::MAX at +inf + let mut m = map([usize::MAX, 1, 1], [1.0, 1.0], [0.0, 0.0], LUMA, vec![2.0]); + assert_eq!(m.gain([0.5; 3], 0.5, f64::INFINITY), 1.0, "inconsistent sizes: no gain"); + for (v, h, n, len) in [(usize::MAX, 1, 1, 1), (1, usize::MAX, usize::MAX, 3), (0, 0, 0, 0), (2, 2, 0, 0), (1, 1, 2, 1)] { + m.points_v = v; + m.points_h = h; + m.points_n = n; + m.gains = vec![2.0; len]; + for spacing in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e-300] { + m.spacing_v = spacing; + m.spacing_h = spacing; + for p in [[0.5; 3], [f32::NAN; 3], [f32::INFINITY, 0.0, -1.0], [1e30; 3]] { + for (x, y) in [(0.5, 0.5), (f64::INFINITY, f64::NEG_INFINITY), (f64::NAN, f64::NAN)] { + assert!(m.gain(p, x, y).is_finite()); + } + } + } + } + // the grid cell itself saturates (the reviewer's case, reached directly) + assert_eq!(cell(f64::INFINITY, 0.0, 1.0, usize::MAX), (usize::MAX - 1, usize::MAX - 1, 0.0)); + assert_eq!(cell(f64::NEG_INFINITY, 0.0, 1.0, usize::MAX).0, 0); + // a consistent map with a huge grid and positions far outside it + let m = map([1, 1, 2], [1e-300, 1e-300], [0.0, 0.0], [f32::MAX; 5], vec![1.0, 4.0]); + assert!(m.gain([1e30; 3], f64::INFINITY, -f64::INFINITY).is_finite()); + } + + #[test] + fn placement_undoes_crop_and_orientation() { + // the source is the right half of the active area, rotated 90° clockwise + let p = SourcePlacement { rect: [0.5, 0.0, 0.5, 1.0], orientation: craft_geom::Orientation::Rotate90 }; + // the oriented source's top-left came from the crop's bottom-left + let (x, y) = p.active(0.0, 0.0); + assert!((x - 0.5).abs() < 1e-12 && (y - 1.0).abs() < 1e-12, "{x} {y}"); + // its top-right came from the crop's top-left + let (x, y) = p.active(1.0, 0.0); + assert!((x - 0.5).abs() < 1e-12 && y.abs() < 1e-12, "{x} {y}"); + let plain = SourcePlacement { rect: [0.0, 0.0, 1.0, 1.0], orientation: craft_geom::Orientation::Normal }; + assert_eq!(plain.active(0.25, 0.75), (0.25, 0.75)); + } +} diff --git a/crates/develop/src/sensor/highlight.rs b/crates/develop/src/sensor/highlight.rs new file mode 100644 index 000000000..7849e4fc8 --- /dev/null +++ b/crates/develop/src/sensor/highlight.rs @@ -0,0 +1,546 @@ +//! Clip-aware highlight handling on demosaiced camera RGB (before white balance, white level = 1.0). +//! +//! - [`clip_neutral`]: white-balance-aware clipping so that sensor-clipped areas render neutral instead of +//! magenta/cyan (each channel limited to the smallest white-balanced clip level). +//! - [`reconstruct`] / [`reconstruct_with`]: where only some channels are clipped, rebuild them from the +//! unclipped channels using the chromaticity of reliable unclipped content nearby (bright, away from edges and +//! from the clipped pixels themselves; diffused into the clipped region coarse to fine) unless both the pixel's +//! own channels and the clipped surface's colour just below its clip (the rim) contradict it, and neutral where +//! 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). +//! +//! 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 +//! white. Any darkening (Highlights, negative Exposure or Whites) brings it out. Three things used to leak colour +//! in: the chromaticity of whatever unclipped pixel happened to be nearest (dark foliage, purple and green +//! fringes along branches, pixels demosaiced from clipped neighbours); a colour model that does not render the +//! camera's white-balanced neutral as neutral (a look fitted to the camera's JPEG, a camera profile); and, in a +//! pale partly clipped sky, the colour of another reliable surface (bright foliage) and the sky's own faint +//! colour, which darkening and a camera profile turned teal. + +use crate::raster::{Rgb32f, par_rows}; +#[cfg(not(target_arch = "wasm32"))] +use rayon::prelude::*; + +/// Clip every channel of `wb ⊙ img` at `min_c(wb_c) · clip` — i.e. at the lowest channel's clip level after WB — +/// then divide the multipliers back out. `clip` is the sensor clip in normalised units (≈ 1.0). +pub fn clip_neutral(img: &mut Rgb32f, wb: [f32; 3], clip: f32) { + let limit = wb.iter().cloned().fold(f32::MAX, f32::min) * clip; + for p in &mut img.data { + for c in 0..3 { + p[c] = (p[c] * wb[c]).min(limit) / wb[c]; + } + } +} + +/// Unclipped pixels lend their chromaticity in proportion to how close they come to clipping (their largest +/// channel, relative to the clip level): from nothing below `SOURCE_LO` to fully above `SOURCE_HI`. Dark content +/// (foliage, branches, buildings against a clipped sky) says nothing about the sky's colour. +const SOURCE_LO: f32 = 0.25; +const SOURCE_HI: f32 = 0.6; +/// Sources on a strong edge (a 3 × 3 half-resolution neighbour brighter or darker by this many stops) are +/// left out, fading from `EDGE_LO` to `EDGE_HI`: edge pixels mix two surfaces and carry lens fringes. +const EDGE_LO: f32 = 0.15; +const EDGE_HI: f32 = 0.4; +/// Source cells within this many half-resolution cells of a clipped pixel are left out: their channels were +/// demosaiced partly from clipped samples. (At least 1: the same neighbourhood tells which cells clipped +/// pixels sample.) +const MARGIN: usize = 1; +/// Weight of the coarser estimate against a cell's own sources when the pyramid is pushed back down (in units +/// of source density: a cell half covered by full-weight sources counts 0.5). +const PRIOR: f32 = 0.01; +/// The rebuilt colour fades to neutral where reliable content covers less than `SUPPORT` of the surroundings at +/// every scale up to `REACH` of the long edge (so previews and exports agree), gradually, as the coverage of the +/// widest one falls: a clipped sky between bare branches is better white than the colour of a river far away. +const REACH: f32 = 1.0 / 4.0; +const SUPPORT: f32 = 0.05; +/// An unclipped channel above `FLOOR_LO` of its clip level counts more and more as the clip floor it is about to +/// become (see [`reconstruct_with`]). +const FLOOR_LO: f32 = 0.75; +/// A clipped pixel takes its estimated colour (reliable colour around, or the neutral guess) only as far as it is +/// brighter (or otherwise unlike) the unclipped pixels nearest its clip: the "rim", unclipped pixels above `RIM_LO` +/// of the clip level, weighted towards the clip, the clipped surface's own colour just below it. Up to `NEAR_RIM` +/// stops past the rim (the rim is an average, a little below the clip) it is rebuilt with the rim's colour, and +/// over the next `DEPTH` stops it goes over to the estimate, so a surface runs into clipping without a step +/// whatever its colour and whatever lent the estimate; well past it, or where the rim is another surface (its +/// colour differs; a clipped channel differs by at least as much as it lies above the rim's), the estimate applies. +const RIM_LO: f32 = 0.85; +const NEAR_RIM: f32 = 0.03; +const DEPTH: f32 = 0.2; +/// Reliable colour counts less and less as both the pixel's own channels (see [`contradiction`]) and the rim's +/// colour contradict it, by `AGREE.0` to `AGREE.1` stops: it is another surface's, like bright foliage below a pale +/// sky, whose green would turn the sky teal. (Either alone can be wrong: a pixel's own channels are noisy and +/// can't speak for the channels that clipped, and the rim can be another surface, like a white window frame +/// around a bright view.) +const AGREE: (f32, f32) = (0.15, 0.4); +/// On the way from the first channel clipping to the last, a partly clipped pixel's brightness goes over to the +/// clipped neutral's in the second half, and so does the colour of a strongly coloured one (saturation relative to +/// the white above `PALE.1`). A pale one's colour (below `PALE.0`) goes over from the start: the few per cent of +/// 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); + +#[inline] +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// One level of a pyramid, `w × h` cells of `N - 1` values and a weight. Pulled: per cell the weighted sums of +/// the values and the weight, as densities (per pixel of the cell). Pushed: the estimated values, and still the +/// weight. The chromaticity pyramid holds red and blue chromaticity, the rim pyramid white-balanced RGB. +struct Level { + w: usize, + h: usize, + cells: Vec<[f32; N]>, +} + +/// Bilinear sample of a level at the centre of pixel `(x, y)` of a grid `scale` times finer. +#[inline] +fn sample(l: &Level, scale: f32, x: usize, y: usize) -> [f32; N] { + let (cv, cw, ch) = (&l.cells, l.w, l.h); + let fx = ((x as f32 + 0.5) / scale - 0.5).clamp(0.0, cw.saturating_sub(1) as f32); + let fy = ((y as f32 + 0.5) / scale - 0.5).clamp(0.0, ch.saturating_sub(1) as f32); + let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); + let (x1, y1) = ((x0 + 1).min(cw.saturating_sub(1)), (y0 + 1).min(ch.saturating_sub(1))); + let (tx, ty) = (fx - x0 as f32, fy - y0 as f32); + let g = |xx: usize, yy: usize| cv.get(yy * cw + xx).copied().unwrap_or([0.0; N]); + let (a, b, c, d) = (g(x0, y0), g(x1, y0), g(x0, y1), g(x1, y1)); + std::array::from_fn(|k| { + let top = a[k] + (b[k] - a[k]) * tx; + let bot = c[k] + (d[k] - c[k]) * tx; + top + (bot - top) * ty + }) +} + +/// 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, clipped: &impl Clipped) -> (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 + let mut cells = vec![[0f32; 3]; cw * ch]; + let mut lum = vec![0f32; cw * ch]; + let mut near = vec![false; cw * ch]; + let process_row = |y: usize, crow: &mut [[f32; 3]], lrow: &mut [f32], nrow: &mut [bool]| { + 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); + let (i0, i1) = (2 * y * w + 2 * x, (2 * y + 1) * w + 2 * x); + let pixels = r0.get(span.clone()).unwrap_or(&[]).iter().zip(i0..).chain(r1.get(span).unwrap_or(&[]).iter().zip(i1..)); + for (p, i) in pixels { + 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 clipped(i, p).iter().any(|&c| c) { + hit = true; + continue; + } + if top > lo && s > 1e-4 { + let b = smoothstep(SOURCE_LO, SOURCE_HI, top / clip) / s; + a[0] += b * q[0].max(0.0); + a[1] += b * q[2].max(0.0); + a[2] += b * s; + } + } + let k = 1.0 / n.max(1) as f32; + crow[x] = a.map(|v| v * k); + lrow[x] = (sum * k).max(1e-6); + touched[x] = hit; + } + for (x, nr) in nrow.iter_mut().enumerate() { + *nr = touched.get(x.saturating_sub(MARGIN)..=(x + MARGIN).min(cw - 1)).is_some_and(|t| t.iter().any(|&t| t)); + } + }; + #[cfg(not(target_arch = "wasm32"))] + cells.par_chunks_mut(cw).zip(lum.par_chunks_mut(cw)).zip(near.par_chunks_mut(cw)).enumerate().for_each(|(y, ((crow, lrow), nrow))| { + process_row(y, crow, lrow, nrow); + }); + #[cfg(target_arch = "wasm32")] + for (y, ((crow, lrow), nrow)) in cells.chunks_mut(cw).zip(lum.chunks_mut(cw)).zip(near.chunks_mut(cw)).enumerate() { + process_row(y, crow, lrow, nrow); + } + // leave out cells near clipped pixels and on strong edges (luminance ratios to the neighbours) + let (lum, near_ref) = (&lum, &near); + let (edge_lo, edge_hi) = (EDGE_LO.exp2(), EDGE_HI.exp2()); + par_rows(&mut cells, cw, |y, row| { + let (ya, yb) = (y.saturating_sub(MARGIN), (y + MARGIN).min(ch - 1)); + let (ea, eb) = (y.saturating_sub(1), (y + 1).min(ch - 1)); + for (x, cell) in row.iter_mut().enumerate() { + if cell[2] <= 0.0 { + continue; + } + if (ya..=yb).any(|yy| near_ref.get(yy * cw + x).copied().unwrap_or(false)) { + *cell = [0.0; 3]; + continue; + } + let l = lum.get(y * cw + x).copied().unwrap_or(1.0); + let (xa, xb) = (x.saturating_sub(1), (x + 1).min(cw - 1)); + let (mut lo, mut hi) = (l, l); + for yy in ea..=eb { + for &v in lum.get(yy * cw + xa..=yy * cw + xb).unwrap_or(&[]) { + lo = lo.min(v); + hi = hi.max(v); + } + } + let keep = 1.0 - smoothstep(edge_lo, edge_hi, (hi / l).max(l / lo)); + *cell = cell.map(|v| v * keep); + } + }); + (Level { w: cw, h: ch, cells }, near) +} + +/// 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, clipped: &impl Clipped, margin: &(dyn Fn(usize, usize) -> bool + 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]; + par_rows(&mut cells, cw, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + let (mut a, mut n) = ([0f32; 4], 0usize); + for sy in 4 * y..(4 * y + 4).min(h) { + 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) || clipped(sy * w + 4 * x + i, p).iter().any(|&c| c) { + continue; + } + let k = ((top - RIM_LO) / (1.0 - RIM_LO)).powi(4); + for c in 0..3 { + a[c] += k * p[c] * wb[c]; + } + a[3] += k; + } + } + *cell = a.map(|v| v / n.max(1) as f32); + } + }); + Level { w: cw, h: ch, cells } +} + +/// The next coarser level: each `2 × 2` block's mean densities. +fn pull(l: &Level) -> Level { + let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); + let mut cells = vec![[0f32; N]; w * h]; + par_rows(&mut cells, w, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + let (mut s, mut n) = ([0f32; N], 0usize); + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if let Some(c) = (sx < l.w && sy < l.h).then(|| l.cells.get(sy * l.w + sx)).flatten() { + for k in 0..N { + s[k] += c[k]; + } + n += 1; + } + } + *cell = s.map(|v| v / n.max(1) as f32); + } + }); + Level { w, h, cells } +} + +/// The estimated values of the cells of `levels[0]` that `needed` marks (all of them when `None`), and of every +/// cell of the coarser levels: each level's own sources blended with the next coarser estimate. The top level is +/// its own sources' weighted mean (normalised: however sparse they are in a large empty picture, the empty part +/// never pulls the estimate anywhere), and `empty` (at zero weight) when it has none at all. +fn push(levels: &mut [Level], empty: [f32; N], needed: Option<&(dyn Fn(usize, usize) -> bool + Sync)>) { + let estimate = |cell: [f32; N], prior: [f32; N]| -> [f32; N] { + let weight = cell[N - 1]; + let d = weight + PRIOR; + std::array::from_fn(|k| if k + 1 == N { weight } else { (cell[k] + PRIOR * prior[k]) / d }) + }; + let Some(last) = levels.last_mut() else { return }; + last.cells.iter_mut().for_each(|c| { + let weight = c[N - 1]; + *c = if weight > 0.0 { std::array::from_fn(|k| if k + 1 == N { weight } else { c[k] / weight }) } else { empty }; + }); + for i in (0..levels.len().saturating_sub(1)).rev() { + let (fine, coarse) = levels.split_at_mut(i + 1); + let (Some(fine), Some(coarse)) = (fine.last_mut(), coarse.first()) else { continue }; + let w = fine.w; + let needed = needed.filter(|_| i == 0); + par_rows(&mut fine.cells, w, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + if needed.is_some_and(|f| !f(x, y)) { + continue; + } + *cell = estimate(*cell, sample(coarse, 2.0, x, y)); + } + }); + } +} + +/// How many stops two chromaticities differ by in any channel ratio. +fn unlike(a: [f32; 3], b: [f32; 3]) -> f32 { + let ratio = |i: usize, j: usize| (a[i].max(1e-6) * b[j].max(1e-6)) / (a[j].max(1e-6) * b[i].max(1e-6)); + [(0, 1), (0, 2), (1, 2)].iter().map(|&(i, j)| ratio(i, j).log2().abs()).fold(0.0f32, f32::max) +} + +/// How far channel `c` of a pixel (sensor values `p`, clipped channels `cl`) only bounds its true value from below: +/// fully once clipped, and increasingly from `FLOOR_LO` of the clip on, so that nothing compared with it jumps where +/// it clips. +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 { + let (mut lo, mut hi) = (f32::INFINITY, 0f32); + for c in 0..3 { + let level = q[c] / r[c].max(1e-3); + hi = hi.max(level); + let w = bound(p, cl, clip, c); + if r[c] > 1e-3 && w < 1.0 { + lo = lo.min(level / (1.0 - w)); + } + } + 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]> { + // 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 { + let s = q[c] / r[c]; + sum += s; + near_clip = near_clip.max(s * smoothstep(FLOOR_LO, 1.0, p[c] / clip)); + k += 1; + } + } + if k == 0 { + return None; + } + // Two clipped channels must not be left at their clip levels: those differ by the white-balance gains (green + // 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 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] })) +} + +/// Reconstruct partially clipped channels, with a neutral that is neutral in camera RGB. See +/// [`reconstruct_with`]. +pub fn reconstruct(img: &mut Rgb32f, wb: [f32; 3], clip: f32) -> usize { + reconstruct_with(img, wb, clip, [1.0; 3]) +} + +/// Reconstruct partially clipped channels. `clip` is the sensor clip level in normalised units (use slightly +/// below 1.0, e.g. 0.99), `wb` the white-balance multipliers that will be applied afterwards, `white` the +/// white-balanced camera RGB that the colour model applied afterwards renders neutral (`[1, 1, 1]` for a model +/// that maps the white-balanced neutral to neutral), scaled to the brightness that `[1, 1, 1]` renders at. +/// Fully clipped pixels become `white` times the brightest plausible level; partly clipped ones take the +/// 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)) +} + +/// Bits of a [`reconstruct_masked`] mask entry: which channels of the pixel had a clipped sample. +pub const CLIPPED_R: u8 = 1; +pub const CLIPPED_G: u8 = 2; +pub const CLIPPED_B: u8 = 4; + +/// [`reconstruct_with`] for a binned image ([`crate::RawImage::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). +/// 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] + }) +} + +/// Which channels of pixel `i` (values `p`) are clipped. +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 { + let (w, h) = (img.width, img.height); + #[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")] + let count = img.data.iter().enumerate().filter(|(i, p)| clipped(*i, p).iter().any(|&c| c)).count(); + if count == 0 || w == 0 || h == 0 { + return 0; + } + // a white far from the camera's neutral (or not a number) is a broken colour model: keep the camera's + let plausible = white.iter().all(|v| v.is_finite() && (1.0 / 16.0..=16.0).contains(v)); + let white = if plausible { white } else { [1.0; 3] }; + let total = white[0] + white[1] + white[2]; + 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 mut levels = vec![first]; + while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { + let next = pull(l); + levels.push(next); + } + // a clipped pixel samples the cells within one of its own, which are within one of a clipped cell + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let needed = |x: usize, y: usize| (y.saturating_sub(1)..=(y + 1).min(ch - 1)).any(|yy| near.get(yy * cw + x).copied().unwrap_or(false)); + push(&mut levels, [neutral[0], neutral[2], 0.0], Some(&needed)); + // How much reliable content lies around each needed cell: its density at any scale up to [`REACH`] (level + // i's cells span 2^i cells of level 0). Near reliable content some fine level is dense with it; far from it + // only the widest one may still hold a little, and the trust fades with that. Kept in the third entry of the + // level 0 estimates, which clipped pixels sample with their colour. + let reach = REACH * w.max(h) as f32 / 2.0; + let widest = (0..levels.len()).find(|&i| (1u64 << i.min(62)) as f32 >= reach).unwrap_or(levels.len().saturating_sub(1)); + if let Some((first, coarser)) = levels.split_first_mut() { + let support: Vec<(&Level<3>, f32)> = coarser.iter().take(widest).enumerate().map(|(i, l)| (l, (1u64 << (i + 1).min(62)) as f32)).collect(); + let fw = first.w; + par_rows(&mut first.cells, fw, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + if !needed(x, y) { + continue; + } + let mut t = 0f32; + for &(l, scale) in &support { + t = t.max(smoothstep(0.0, SUPPORT, sample(l, scale, x, y)[2])); + if t >= 1.0 { + break; + } + } + cell[2] = t; + } + }); + } + 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)]; + while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { + let next = pull(l); + levels.push(next); + } + push(&mut levels, [0.0; 4], None); + Some(levels).filter(|levels| levels.last().is_some_and(|top| top.cells.iter().any(|c| c[3] > 0.0))) + }; + let rim_field = rims.as_ref().and_then(|l| l.first()); + let max_level = wb.iter().cloned().fold(0.0f32, f32::max) * clip; + 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) { + 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 } + })); + } + 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]]; + } + }); + count +} + +#[cfg(test)] +mod tests; diff --git a/crates/develop/src/sensor/highlight/tests.rs b/crates/develop/src/sensor/highlight/tests.rs new file mode 100644 index 000000000..3386e5d73 --- /dev/null +++ b/crates/develop/src/sensor/highlight/tests.rs @@ -0,0 +1,346 @@ +use super::*; + +/// Daylight-like multipliers: green clips first, red and blue keep rising. +const WB: [f32; 3] = [2.5, 1.0, 1.6]; + +fn balanced(p: [f32; 3]) -> [f32; 3] { + [p[0] * WB[0], p[1] * WB[1], p[2] * WB[2]] +} + +fn sensor(q: [f32; 3]) -> [f32; 3] { + [q[0] / WB[0], q[1] / WB[1], q[2] / WB[2]].map(|v| v.min(1.0)) +} + +fn chroma(q: [f32; 3]) -> [f32; 3] { + let s = q[0] + q[1] + q[2]; + q.map(|v| v / s) +} + +/// A pale blue sky whose green channel clipped, an unclipped strip of the same sky along the top, and a dark +/// branch with purple fringes on both sides standing in the clipped part (white-balanced sky colour returned). +fn branch_scene() -> (Rgb32f, [f32; 3]) { + let sky = [1.10, 1.25, 1.45]; + let img = Rgb32f::from_fn(192, 128, |x, y| { + sensor(if y < 24 { + sky.map(|v| v * 0.7) + } else if (90..100).contains(&x) && y >= 40 { + [0.06, 0.05, 0.03] + } else if (x == 89 || x == 100) && y >= 40 { + [0.75, 0.25, 0.96] + } else { + sky + }) + }); + (img, sky) +} + +/// How far chromaticity `got` lies off the way from `from` to neutral (largest channel difference to the +/// nearest point of that way). +fn off_the_way_to_neutral(got: [f32; 3], from: [f32; 3]) -> f32 { + let d: [f32; 3] = std::array::from_fn(|c| 1.0 / 3.0 - from[c]); + let len = d.iter().map(|v| v * v).sum::(); + let t = if len > 0.0 { ((0..3).map(|c| (got[c] - from[c]) * d[c]).sum::() / len).clamp(0.0, 1.0) } else { 0.0 }; + (0..3).map(|c| (got[c] - (from[c] + d[c] * t)).abs()).fold(0.0, f32::max) +} + +/// Issue #523: the clipped sky beside a branch took the colour of the branch's fringes and of the branch +/// itself (magenta, green), which any darkening of the highlights then showed. Beside the branch it is now the +/// clipped sky away from it: the sky's colour, on its way to neutral. +#[test] +fn fringes_and_dark_branches_do_not_tint_a_clipped_sky() { + let (mut img, sky) = branch_scene(); + assert!(reconstruct(&mut img, WB, 0.99) > 0); + let mut worst = 0f32; + for y in 40..128 { + let away = chroma(balanced(img.get(30, y))); + assert!(away == chroma(balanced(img.get(170, y))), "row {y}"); + let off = off_the_way_to_neutral(away, chroma(sky)); + assert!(off < 0.005, "row {y}: the clipped sky {away:?} is not the sky's colour on its way to neutral ({off})"); + for x in [84, 86, 88, 101, 103, 105] { + let got = chroma(balanced(img.get(x, y))); + worst = worst.max((0..3).map(|c| (got[c] - away[c]).abs()).fold(0.0, f32::max)); + } + } + assert!(worst < 0.01, "clipped sky beside the branch is off the sky away from it by {worst}"); +} + +/// A warm light with red and green clipped: left at their clip levels the pair reads red-magenta (the white +/// balance multiplies red's clip level by 2.5, green's by 1). +#[test] +fn two_clipped_channels_are_not_left_at_their_clip_levels() { + let light = [3.5, 2.6, 0.8]; + let mut img = Rgb32f::from_fn(64, 64, |x, y| { + let d = ((x as f32 - 32.0).powi(2) + (y as f32 - 32.0).powi(2)).sqrt(); + if d < 20.0 { sensor(light) } else { [0.02; 3] } + }); + reconstruct(&mut img, WB, 0.99); + let q = balanced(img.get(32, 32)); + assert!((q[2] - 0.8).abs() < 0.1, "the unclipped channel is about kept: {q:?}"); + let ratio = q[1] / q[0]; + assert!((0.6..=1.05).contains(&ratio), "green / red {ratio} ({q:?}): not a warm white"); +} + +#[test] +fn fully_clipped_pixels_follow_the_colour_model_white() { + let white = [1.03, 0.98, 1.06]; + let mut img = Rgb32f::filled(8, 8, [1.0; 3]); + img.data[0] = [0.3, 0.6, 0.4]; + reconstruct_with(&mut img, WB, 0.99, white); + let q = balanced(img.get(4, 4)); + let k = q[1] / white[1]; + assert!((0..3).all(|c| (q[c] - white[c] * k).abs() < 1e-4 * k), "{q:?} is not along {white:?}"); + assert!(k >= 2.5 * 0.99 - 1e-4, "clipped neutral at least as bright as the highest clip level: {k}"); + assert_eq!(img.data[0], [0.3, 0.6, 0.4]); + // a white that cannot be right falls back to camera neutral, and nothing overflows + for bad in [[f32::NAN, 1.0, 1.0], [2.5e38, 0.74, 0.74], [1.0, 0.0, 1.0], [40.0, 1.0, 1.0]] { + let mut img = Rgb32f::filled(4, 4, [1.0; 3]); + img.data[0] = [1.0, 1.0, 0.5]; + reconstruct_with(&mut img, WB, 0.99, bad); + let q = balanced(img.get(1, 1)); + assert!((q[0] - q[1]).abs() < 1e-4 && (q[2] - q[1]).abs() < 1e-4, "{bad:?}: {q:?}"); + assert!(img.data.iter().flatten().all(|v| v.is_finite()), "{bad:?}"); + } +} + +/// Red rises through its clip level across a sky whose green and blue clipped: the rebuilt colour changes +/// smoothly (no edge where red clips too) and arrives at the clipped neutral. +#[test] +fn rebuilt_colour_is_continuous_as_more_channels_clip() { + let blue = [1.0, 1.3, 1.9]; + let img0 = Rgb32f::from_fn(240, 40, |x, y| { + if y < 8 { + return sensor(blue.map(|v| v * 0.5)); // unclipped sky: the source of colour + } + let level = 0.6 + 2.2 * x as f32 / 239.0; // red at 0.24 to 1.12 of its clip level + sensor([level * WB[0] * 0.4, 1.6, 2.0]) + }); + let mut img = img0.clone(); + reconstruct(&mut img, WB, 0.99); + let row: Vec<[f32; 3]> = (0..240).map(|x| chroma(balanced(img.get(x, 30)))).collect(); + let step = row.windows(2).map(|w| (0..3).map(|c| (w[1][c] - w[0][c]).abs()).fold(0.0, f32::max)).fold(0.0, f32::max); + assert!(step < 0.01, "largest chromaticity step between neighbours {step}"); + let end = row[239]; + assert!(end.iter().all(|v| (v - 1.0 / 3.0).abs() < 1e-3), "fully clipped end {end:?}"); +} + +/// A smooth pink ramp (`[0.9k, k, 0.8k]`, k from 0.8 to 1.35) whose green clips first, then red, then blue, +/// in `rows` of a `h`-row picture that is otherwise near black: the rebuilt middle row, and where green first +/// clips on it. +fn rebuilt_ramp(rows: std::ops::Range, h: usize) -> (Vec<[f32; 3]>, usize) { + let (w, k0, k1) = (1600usize, 0.8f32, 1.35f32); + let k = |x: usize| k0 + (k1 - k0) * x as f32 / (w - 1) as f32; + let img0 = Rgb32f::from_fn(w, h, |x, y| if rows.contains(&y) { [0.9 * k(x), k(x), 0.8 * k(x)].map(|v| v.min(1.0)) } else { [0.01; 3] }); + let mut img = img0.clone(); + reconstruct(&mut img, WB, 0.99); + let y = (rows.start + rows.end) / 2; + let row: Vec<[f32; 3]> = (0..w).map(|x| balanced(img.get(x, y))).collect(); + (row, (0..w).find(|&x| img0.get(x, y)[1] >= 0.99).unwrap_or(0)) +} + +/// No channel changes by more than `at_clip` (relative) where green first clips, nor by 3 % anywhere. +fn assert_continuous(row: &[[f32; 3]], first: usize, at_clip: f32, case: &str) { + // across the first clip the colour carries on as it was (the sensor's own colour, not a fade) + let (a, b) = (row[first - 1], row[first]); + assert!((0..3).all(|c| (b[c] / a[c] - 1.0).abs() < at_clip), "{case}, first clip: {a:?} then {b:?}"); + let worst = row.windows(2).map(|p| (0..3).map(|c| (p[1][c] / p[0][c] - 1.0).abs()).fold(0.0, f32::max)).fold(0.0, f32::max); + // (a smooth ramp moves 0.04 % per pixel here; the rebuilt colour turns faster where it leaves the colour of + // the unclipped part for neutral, but never by a step) + assert!(worst < 0.03, "{case}: largest relative step between neighbours {worst}"); +} + +/// The rebuilt colour has no step anywhere along the ramp: not where green first clips (the neutral fade starts +/// from nothing there), nor where red does, nor where the last channel clips (the fade ends at the fully +/// clipped neutral). +#[test] +fn rebuilt_ramp_is_continuous_from_the_first_clip_to_the_last() { + let (row, first) = rebuilt_ramp(0..32, 32); + assert_continuous(&row, first, 0.002, "full ramp"); +} + +/// The same ramp as a thin line on near black has no reliable colour around (every pixel of it is on a strong +/// edge), so its clipped part falls back to the neutral guess. That guess only applies as far as the line runs +/// past its own unclipped part: no step where it first clips, however thin the line and however much dark +/// background surrounds it. +#[test] +fn thin_line_without_reliable_colour_is_continuous_where_it_clips() { + for height in [32usize, 512, 1024] { + for width in [1usize, 4, 16] { + let top = (height - width) / 2; + let (row, first) = rebuilt_ramp(top..top + width, height); + assert_continuous(&row, first, 0.002, &format!("{width} rows of {height}")); + // and well past the first clip the neutral guess has taken over (green as high as red and blue imply) + let far = row[1500]; + assert!(far[1] > 0.95 * far[2], "{width} rows of {height}: {far:?}"); + } + } +} + +/// Issue #523 (a river photo darkened by Highlights -75): a pale cyan-blue sky (`[1, 1.07, 1.2]` white-balanced) +/// brightening from left to right through the point where green clips (and later blue), above bright +/// yellow-green foliage, with thin dark branches standing in its lower half. Its rebuilt colour used to lean +/// green to teal: the foliage lent its colour to the sky (green rebuilt from it), with a step where green first +/// clips, and the sky kept its own pale colour where Lightroom shows white. +#[test] +fn pale_sky_by_dark_branches_and_foliage_is_not_tinted() { + let sky = [1.0, 1.07, 1.2]; + let (w, h) = (320usize, 96usize); + let k = |x: usize| 0.7 * (1.2 * x as f32 / (w - 1) as f32).exp2(); + let branches = [150usize, 200, 250]; + let on_branch = |x: usize| branches.iter().any(|&b| (b.saturating_sub(1)..=b + 2).contains(&x)); + let img0 = Rgb32f::from_fn(w, h, |x, y| { + sensor(if y >= 72 { + [0.5, 0.6, 0.22] + } else if y >= 40 && branches.iter().any(|&b| x == b || x == b + 1) { + [0.1, 0.09, 0.04] + } else { + sky.map(|v| v * k(x)) + }) + }); + let mut img = img0.clone(); + reconstruct(&mut img, WB, 0.99); + let at = |x: usize, y: usize| chroma(balanced(img.get(x, y))); + let first = (0..w).find(|&x| img0.get(x, 20)[1] >= 0.99).unwrap_or(0); + assert!(first > 0 && first < 150); + let diff = |a: [f32; 3], b: [f32; 3]| (0..3).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max); + for y in [20, 50] { + // no step where green clips + let step = diff(at(first - 1, y), at(first, y)); + assert!(step < 0.001, "row {y}: step of {step} where green clips"); + for x in first..w { + // nothing but the sky's colour on its way to neutral (no green from the foliage)... + let off = off_the_way_to_neutral(at(x, y), chroma(sky)); + assert!(on_branch(x) || off < 0.005, "row {y}, x {x}: {:?} is off the sky's way to neutral by {off}", at(x, y)); + // ... the same beside the branches as above them ... + let beside = diff(at(x, y), at(x, 20)); + assert!(on_branch(x) || beside < 0.005, "row {y}, x {x}: {:?} beside a branch, {:?} above", at(x, y), at(x, 20)); + } + // ... and neutral well before the last channel clips (the sky is 0.7 stops past green's clip there) + let end = at(w - 1, y); + assert!(end.iter().all(|v| (v - 1.0 / 3.0).abs() < 0.002), "row {y}: {end:?} at the end"); + } +} + +#[test] +fn unclipped_pixels_are_left_exactly() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / (1u64 << 24) as f32 + }; + for (w, h) in [(1, 1), (3, 1), (7, 5), (64, 48), (129, 77)] { + let noise: Vec = (0..w * h).map(|_| rnd()).collect(); + let img = Rgb32f::from_fn(w, h, |x, y| { + let t = ((x as f32 * 0.21).sin() + (y as f32 * 0.17).cos()) * 0.5; + let base = [0.5 + 0.4 * t, 0.45 - 0.2 * t, 0.3 + 0.1 * t]; + match noise[y * w + x] { + r if r < 0.1 => [1.0; 3], + r if r < 0.4 => [1.0, base[1] * 1.6, base[2]], + r if r > 0.995 => [0.0, 0.0, 0.00001], + _ => base, + } + }); + let mut out = img.clone(); + let n = reconstruct_with(&mut out, [2.1, 1.0, 1.6], 0.99, [1.02, 0.99, 1.05]); + let clipped = img.data.iter().filter(|p| p.iter().any(|&v| v >= 0.99)).count(); + assert_eq!(n, clipped); + for (a, b) in img.data.iter().zip(&out.data) { + if a.iter().all(|&v| v < 0.99) { + assert_eq!(a, b, "{w}×{h}"); + } else { + assert!(b.iter().all(|v| v.is_finite() && *v >= 0.0), "{w}×{h}: {b:?}"); + } + } + } +} + +#[test] +fn clip_neutral_makes_clipped_white_neutral() { + let wb = [2.0, 1.0, 1.5]; + let mut img = Rgb32f::filled(2, 1, [1.0, 1.0, 1.0]); + img.data[1] = [0.2, 0.3, 0.4]; + clip_neutral(&mut img, wb, 1.0); + let p = img.data[0]; + let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; + assert!((q[0] - q[1]).abs() < 1e-6 && (q[1] - q[2]).abs() < 1e-6); + assert_eq!(img.data[1], [0.2, 0.3, 0.4]); +} + +#[test] +fn reconstruct_restores_clipped_channel() { + // a warm gradient whose red channel clips at its bright end + let truth = Rgb32f::from_fn(256, 16, |x, _| { + let v = 0.3 + 1.0 * x as f32 / 255.0; + [v * 1.0, v * 0.6, v * 0.35] + }); + let mut img = truth.map(|p| p.map(|v| v.min(1.0))); + let first = (0..256).find(|&x| img.get(x, 8)[0] >= 0.999).unwrap(); + // near the unclipped gradient (within the reach of its colour) red is rebuilt from it + let err = |img: &Rgb32f| -> f32 { (first..first + 12).map(|x| (img.get(x, 8)[0] - truth.get(x, 8)[0]).abs()).sum() }; + let before = err(&img); + let n = reconstruct(&mut img, [1.0, 1.0, 1.0], 0.999); + assert!(n > 0); + let after = err(&img); + assert!(after < before * 0.2, "before {before} after {after}"); + // unclipped pixels untouched + assert_eq!(img.get(0, 0), truth.get(0, 0)); + assert_eq!(img.get(first - 1, 8), truth.get(first - 1, 8)); +} + +#[test] +fn fully_clipped_and_no_clipping() { + let mut img = Rgb32f::filled(4, 4, [1.0; 3]); + assert_eq!(reconstruct(&mut img, [2.0, 1.0, 1.5], 0.99), 16); + let p = img.data[0]; + assert!((p[0] * 2.0 - p[1]).abs() < 1e-5 && (p[2] * 1.5 - p[1]).abs() < 1e-5); + let mut img = Rgb32f::filled(4, 4, [0.5; 3]); + assert_eq!(reconstruct(&mut img, [2.0, 1.0, 1.5], 0.99), 0); + let mut empty = Rgb32f::new(0, 0); + assert_eq!(reconstruct(&mut empty, [1.0; 3], 0.99), 0); +} + +/// `cargo test --release -p lightcraft-raw --lib -- --ignored bench_reconstruct --nocapture` +#[test] +#[ignore] +fn bench_reconstruct() { + let img = Rgb32f::from_fn(6000, 4000, |x, y| { + let v = 0.4 + 0.8 * ((x as f32 * 0.003).sin() * (y as f32 * 0.002).cos()).abs(); + [v.min(1.0), (v * 0.7).min(1.0), (v * 0.5).min(1.0)] + }); + let ms = (0..3) + .map(|_| { + let mut i = img.clone(); + let t = std::time::Instant::now(); + reconstruct(&mut i, [2.0, 1.0, 1.5], 0.99); + t.elapsed().as_secs_f64() * 1e3 + }) + .fold(f64::MAX, f64::min); + eprintln!("reconstruct 24 MP: {ms:.0} ms"); +} + +/// A mask decides which channels are clipped (their values are lower bounds), whatever their values; the +/// unmarked pixels are left as they were; a mask of another size leaves clipping to the values. +#[test] +fn a_mask_marks_the_clipped_channels() { + let base = Rgb32f::from_fn(32, 32, |x, _| if x >= 16 { [0.2, 0.5, 0.25] } else { [0.5, 0.5, 0.5] }); + 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, [1.0; 3], 0.99, [1.0; 3], &mask), 512); + for (p, b) in img.data.iter().zip(&base.data) { + assert!(p.iter().all(|v| v.is_finite()), "{p:?}"); + if b[0] == 0.5 { + assert_eq!(p, b); + } else { + // red rebuilt from at least its mean, the others kept + assert!(p[0] >= 0.2 && p[1] == 0.5 && p[2] == 0.25, "{p:?}"); + } + } + // red is rebuilt above its mean, towards the neighbours' neutral (as far as the pixel's own blue agrees) + assert!(img.get(24, 16)[0] > 0.3, "{:?}", img.get(24, 16)); + // the values alone see nothing clipped here, nor does a mask of another size + let mut plain = base.clone(); + assert_eq!(reconstruct(&mut plain, [1.0; 3], 0.99), 0); + assert_eq!(reconstruct_masked(&mut plain, [1.0; 3], 0.99, [1.0; 3], &mask[1..]), 0); + assert!(plain.data == base.data); +} diff --git a/crates/develop/src/sensor/mod.rs b/crates/develop/src/sensor/mod.rs new file mode 100644 index 000000000..bf3c7f47f --- /dev/null +++ b/crates/develop/src/sensor/mod.rs @@ -0,0 +1,207 @@ +//! Sensor-stage RAW development over [`craft_raw::RawImage`]: black/white normalization, +//! DNG `OpcodeList1/2/3`, Bayer (AHD, PPG, Bilinear) & X-Trans demosaicing, clip-aware highlight +//! reconstruction, DNG colour matrices, `ProfileGainTableMap` evaluation, and binned previews. + +pub mod binned; +pub mod chart_table; +pub mod color; +pub mod demosaic; +pub mod gaintable; +pub mod highlight; +pub mod opcodes; + +pub use craft_color_transform::Mat3; +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}; + +/// 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`]. +pub fn checked_pixel_count(width: u64, height: u64) -> Option { + width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_SAMPLES as u64) +} + +/// A CFA pattern this crate can address: 1 to 16 sites a side, one colour index per site. +pub fn cfa_valid(c: &Cfa) -> bool { + c.width > 0 && c.height > 0 && c.width <= 16 && c.height <= 16 && c.pattern.len() == c.width * c.height +} + +/// Black-subtracted, white-normalised data covering the active area. +#[derive(Clone, Debug, PartialEq)] +pub struct Normalized { + pub width: usize, + pub height: usize, + pub cpp: usize, + /// Nominal range [0, 1] (values may exceed 1 above white or be negative from noise). + pub data: Vec, + /// CFA anchored at (0, 0) of this buffer. + pub cfa: Option, +} + +/// Sensor development operations on [`craft_raw::RawImage`]. +pub trait RawDevelopExt { + fn validate(&self) -> Result<()>; + fn white_at(&self, s: usize) -> f32; + fn normalized(&self) -> Result; + fn develop(&self, method: Method) -> Result; + fn finish_demosaiced(&self, rgb: Rgb32f) -> Rgb32f; + fn develop_crop(&self, width: usize, height: usize) -> Rect; + fn can_bin(&self, k: usize) -> bool; + fn develop_binned(&self, k: usize, clip: f32) -> Result>; + fn develop_binned_masked(&self, k: usize, clip: f32) -> Result)>>; +} + +impl RawDevelopExt for RawImage { + fn validate(&self) -> Result<()> { + if self.width == 0 || self.height == 0 || !(1..=4).contains(&self.cpp) { + return Err(RawError::Corrupt("bad dimensions".into())); + } + if self.cpp == 2 { + return Err(RawError::Unsupported("2 samples per pixel".into())); + } + let expected = checked_pixel_count(self.width as u64, self.height as u64) + .and_then(|n| n.checked_mul(self.cpp as u64)) + .ok_or_else(|| RawError::Corrupt("data length mismatch".into()))?; + let actual = u64::try_from(self.data.len()).map_err(|_| RawError::Corrupt("data length mismatch".into()))?; + if actual != expected { + return Err(RawError::Corrupt("data length mismatch".into())); + } + if let Some(c) = &self.cfa + && (!cfa_valid(c) || c.pattern.iter().any(|&p| p > 2)) + { + return Err(RawError::Unsupported(format!("CFA pattern {}", c.name()))); + } + let a = self.active_area; + let fits = |x: usize, len: usize, limit: usize| x.checked_add(len).is_some_and(|end| end <= limit); + if a.width == 0 || a.height == 0 || !fits(a.x, a.width, self.width) || !fits(a.y, a.height, self.height) { + return Err(RawError::Corrupt("active area outside image".into())); + } + Ok(()) + } + + fn white_at(&self, s: usize) -> f32 { + self.white.get(s).or_else(|| self.white.first()).copied().unwrap_or(65535.0) + } + + fn normalized(&self) -> Result { + self.validate()?; + let (w, cpp) = (self.width, self.cpp); + let a = self.active_area; + let stage1: Option> = if self.opcodes.list1.is_empty() { + None + } else { + let mut v: Vec = (0..self.data.len()).map(|i| self.data.get(i)).collect(); + opcodes::apply_list(&self.opcodes.list1, &mut v, self.width, self.height, cpp, self.cfa.as_ref(), 65535.0); + Some(v) + }; + let src = |i: usize| match &stage1 { + Some(v) => v[i], + None => self.data.get(i), + }; + let scale: Vec = (0..cpp) + .map(|s| { + let range = self.white_at(s) - self.black.mean(); + if range > 0.0 { 1.0 / range } else { 1.0 } + }) + .collect(); + let mut out = vec![0f32; a.width * a.height * cpp]; + let row_len = a.width * cpp; + crate::raster::par_rows(&mut out, row_len, |y, row| { + let base = ((a.y + y) * w + a.x) * cpp; + for x in 0..a.width { + for s in 0..cpp { + let v = src(base + x * cpp + s); + let b = self.black.at(x, y, s, cpp); + let n = (v - b) * scale[s]; + row[x * cpp + s] = if n.is_finite() { n } else { 0.0 }; + } + } + }); + let cfa = self.cfa.as_ref().map(|c| c.shifted(a.x, a.y)); + opcodes::apply_list(&self.opcodes.list2, &mut out, a.width, a.height, cpp, cfa.as_ref(), 1.0); + Ok(Normalized { width: a.width, height: a.height, cpp, data: out, cfa }) + } + + fn develop(&self, method: Method) -> Result { + 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)) + } + + fn finish_demosaiced(&self, mut rgb: Rgb32f) -> Rgb32f { + opcodes::apply_list3(&self.opcodes.list3, &mut rgb); + let c = self.develop_crop(rgb.width, rgb.height); + let rgb = + if c.x == 0 && c.y == 0 && c.width == rgb.width && c.height == rgb.height { rgb } else { rgb.into_crop(c.x, c.y, c.width, c.height) }; + stretched(self, rgb) + } + + fn develop_crop(&self, width: usize, height: usize) -> Rect { + let c = self.crop.clipped(width, height); + if c.width == 0 || c.height == 0 { Rect::new(0, 0, width, height) } else { c } + } + + fn can_bin(&self, k: usize) -> bool { + binned::can_bin(self, k) + } + + fn develop_binned(&self, k: usize, clip: f32) -> Result> { + binned::develop_binned(self, k, clip) + } + + fn develop_binned_masked(&self, k: usize, clip: f32) -> Result)>> { + binned::develop_binned_masked(self, k, clip) + } +} + +fn stretched(raw: &RawImage, rgb: Rgb32f) -> Rgb32f { + let h = stretched_height(rgb.height, raw.pixel_aspect); + if h == rgb.height { + return rgb; + } + resize(&rgb, rgb.width, h, Filter::Mitchell) +} + +#[cfg(test)] +mod checked_arithmetic_tests { + use super::*; + + #[test] + fn checked_pixel_count_wrap_inputs_rejected() { + assert_eq!(checked_pixel_count(65536, 65536), None); + assert_eq!(checked_pixel_count(65536, 65537), None); + assert_eq!(checked_pixel_count(u64::from(u32::MAX), 2), None); + assert_eq!(checked_pixel_count(1 << 40, 1 << 40), None); + } + + #[test] + fn checked_pixel_count_over_cap_rejected() { + assert_eq!(checked_pixel_count((1 << 30) + 1, 1), None); + assert_eq!(checked_pixel_count(1, (1 << 30) + 1), None); + } + + #[test] + fn checked_pixel_count_at_cap_accepted() { + assert_eq!(checked_pixel_count(1 << 30, 1), Some(1 << 30)); + assert_eq!(checked_pixel_count(1 << 15, 1 << 15), Some(1 << 30)); + } + + #[test] + fn checked_pixel_count_small_accepted() { + assert_eq!(checked_pixel_count(100, 100), Some(10_000)); + assert_eq!(checked_pixel_count(1, 1), Some(1)); + assert_eq!(checked_pixel_count(0, 100), None); + assert_eq!(checked_pixel_count(100, 0), None); + } +} diff --git a/crates/develop/src/sensor/opcodes.rs b/crates/develop/src/sensor/opcodes.rs new file mode 100644 index 000000000..0ef3cefa0 --- /dev/null +++ b/crates/develop/src/sensor/opcodes.rs @@ -0,0 +1,333 @@ +//! DNG opcode lists (`OpcodeList1/2/3`, DNG 1.7 chapter 7). Opcode lists are always big-endian. +//! +//! Parsed (by `craft-raw`): every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`, +//! `WarpRectilinear2` (opcode 14, DNG 1.6; see [`Opcode::WarpRectilinear2`]), `FixVignetteRadial`, +//! `FixBadPixelsConstant`, `FixBadPixelsList`, `MapTable`, `MapPolynomial`, `GainMap`, `DeltaPerRow/Column`, +//! `ScalePerRow/Column`. `TrimBounds` and `WarpFisheye` are recorded but not applied. +//! +//! Opcodes run in list order, except for the DNG 1.6 skip rule ([`applied_ops`]): a `WarpRectilinear` or +//! `WarpFisheye` that immediately follows an *optional* `WarpRectilinear2` is skipped (the older opcode is the +//! fallback for readers that don't know opcode 14). +//! +//! Value convention: list 1 runs on raw sample values (16-bit scale), lists 2 and 3 on values normalised to +//! [0, 1]; table/polynomial/delta opcodes are defined on the normalised range and are rescaled accordingly. + +pub use craft_raw::opcodes::{Area, Opcode, OpcodeLists, WR2_LEN, applied_ops, parse_list, wr2_factor, write_list}; + +use super::{Cfa, Rgb32f}; + +/// Whether [`apply_list`] / [`apply_list3`] implement `op`. +pub fn is_applied(op: &Opcode) -> bool { + !matches!(op, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. }) +} + +fn area_iter(a: &Area, w: usize, h: usize, cpp: usize) -> impl Iterator + '_ { + let (t, l) = (a.top as usize, a.left as usize); + let (b, r) = ((a.bottom as usize).min(h), (a.right as usize).min(w)); + let (p0, p1) = (a.plane as usize, (a.plane as usize + a.planes.max(1) as usize).min(cpp)); + (t..b.max(t)) + .step_by(a.row_pitch.max(1) as usize) + .flat_map(move |y| (l..r.max(l)).step_by(a.col_pitch.max(1) as usize).flat_map(move |x| (p0..p1.max(p0)).map(move |p| (x, y, p)))) +} + +struct GainMapGrid<'a> { + points: [usize; 2], + spacing: [f64; 2], + origin: [f64; 2], + planes: usize, + gains: &'a [f32], +} + +impl GainMapGrid<'_> { + fn sample_at(&self, position: [f64; 2], plane: usize) -> f32 { + let [pv, ph] = self.points; + let mp = self.planes; + let p = plane.min(mp - 1); + let fy = if self.spacing[0] > 0.0 { ((position[0] - self.origin[0]) / self.spacing[0]).clamp(0.0, (pv - 1) as f64) } else { 0.0 }; + let fx = if self.spacing[1] > 0.0 { ((position[1] - self.origin[1]) / self.spacing[1]).clamp(0.0, (ph - 1) as f64) } else { 0.0 }; + let (y0, x0) = (fy.floor() as usize, fx.floor() as usize); + let (y1, x1) = ((y0 + 1).min(pv - 1), (x0 + 1).min(ph - 1)); + let (ty, tx) = ((fy - y0 as f64) as f32, (fx - x0 as f64) as f32); + let g = |y: usize, x: usize| self.gains[(y * ph + x) * mp + p]; + let top = g(y0, x0) + (g(y0, x1) - g(y0, x0)) * tx; + let bot = g(y1, x0) + (g(y1, x1) - g(y1, x0)) * tx; + top + (bot - top) * ty + } +} + +/// Radius normaliser: distance from the centre to the farthest image corner. +pub(crate) fn max_radius(cx: f64, cy: f64, w: f64, h: f64) -> f64 { + [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].iter().map(|&(x, y)| (x - cx).hypot(y - cy)).fold(0.0, f64::max).max(1e-9) +} + +/// Most pixels one bad-pixel opcode repairs (the list is 64 MB, `fix_pixels`' set about twice that). Uncapped, a +/// mosaic equal to `FixBadPixelsConstant`'s constant, or one `FixBadPixelsList` rectangle over the image, lists +/// every pixel: tens of GB at [`crate::MAX_SAMPLES`]. Pixels past the cap, in list order, are left as they are. +const MAX_BAD_PIXELS: usize = 1 << 22; + +/// Apply a list to an interleaved `w × h × cpp` buffer. `cfa` (when the data is a mosaic) is used by the +/// bad-pixel opcodes. `scale` is the value of 1.0 in the buffer: 65535 for list 1 (raw 16-bit values), 1 for +/// lists 2 and 3 (normalised values). +/// Whole-image passes one opcode list may cost, all its ops together (a real DNG's list is a +/// handful of gain maps and tables). Ops past it, in list order, are left out: a list repeating a +/// full-image polynomial thousands of times was billions of evaluations on an ordinary raw. +const MAX_LIST_PASSES: usize = 32; + +/// Sample visits `op` costs on a `w × h × cpp` buffer (coefficient evaluations for a polynomial). +fn op_cost(op: &Opcode, w: usize, h: usize, cpp: usize) -> usize { + let visits = |a: &Area| { + let rows = (a.bottom as usize).min(h).saturating_sub(a.top as usize).div_ceil(a.row_pitch.max(1) as usize); + let cols = (a.right as usize).min(w).saturating_sub(a.left as usize).div_ceil(a.col_pitch.max(1) as usize); + let planes = (a.plane as usize).saturating_add(a.planes.max(1) as usize).min(cpp).saturating_sub(a.plane as usize); + rows.saturating_mul(cols).saturating_mul(planes) + }; + match op { + Opcode::MapPolynomial { area, coefficients } => visits(area).saturating_mul(coefficients.len().max(1)), + Opcode::MapTable { area, .. } + | Opcode::GainMap { area, .. } + | Opcode::DeltaPerRow { area, .. } + | Opcode::DeltaPerColumn { area, .. } + | Opcode::ScalePerRow { area, .. } + | Opcode::ScalePerColumn { area, .. } => visits(area), + // `apply_list` does nothing for these, so they spend none of the budget + Opcode::Unknown { .. } + | Opcode::TrimBounds { .. } + | Opcode::WarpFisheye { .. } + | Opcode::WarpRectilinear { .. } + | Opcode::WarpRectilinear2 { .. } => 0, + _ => w.saturating_mul(h).saturating_mul(cpp), + } +} + +pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32) { + let mut budget = w.saturating_mul(h).saturating_mul(cpp).max(1).saturating_mul(MAX_LIST_PASSES); + for op in list { + let cost = op_cost(op, w, h, cpp); + if cost > budget { + continue; + } + budget -= cost; + match op { + Opcode::MapTable { area, table } => { + let n = table.len(); + for (x, y, p) in area_iter(area, w, h, cpp) { + let v = &mut buf[(y * w + x) * cpp + p]; + let idx = ((*v / scale * 65535.0).round().max(0.0) as usize).min(n - 1); + *v = table[idx] as f32 / 65535.0 * scale; + } + } + Opcode::MapPolynomial { area, coefficients } => { + for (x, y, p) in area_iter(area, w, h, cpp) { + let v = &mut buf[(y * w + x) * cpp + p]; + let t = (*v / scale) as f64; + let r = coefficients.iter().rev().fold(0.0, |acc, &c| acc * t + c); + *v = r as f32 * scale; + } + } + Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains } => { + let grid = GainMapGrid { + points: [*points_v as usize, *points_h as usize], + spacing: *spacing, + origin: *origin, + planes: *map_planes as usize, + gains, + }; + for (x, y, p) in area_iter(area, w, h, cpp) { + let rv = y as f64 / h as f64; + let rh = x as f64 / w as f64; + let g = grid.sample_at([rv, rh], p - area.plane as usize); + buf[(y * w + x) * cpp + p] *= g; + } + } + Opcode::DeltaPerRow { area, deltas } | Opcode::DeltaPerColumn { area, deltas } => { + let per_row = matches!(op, Opcode::DeltaPerRow { .. }); + for (x, y, p) in area_iter(area, w, h, cpp) { + let i = + if per_row { (y - area.top as usize) / area.row_pitch as usize } else { (x - area.left as usize) / area.col_pitch as usize }; + if let Some(d) = deltas.get(i) { + buf[(y * w + x) * cpp + p] += d * scale; + } + } + } + Opcode::ScalePerRow { area, scales } | Opcode::ScalePerColumn { area, scales } => { + let per_row = matches!(op, Opcode::ScalePerRow { .. }); + for (x, y, p) in area_iter(area, w, h, cpp) { + let i = + if per_row { (y - area.top as usize) / area.row_pitch as usize } else { (x - area.left as usize) / area.col_pitch as usize }; + if let Some(s) = scales.get(i) { + buf[(y * w + x) * cpp + p] *= s; + } + } + } + Opcode::FixVignetteRadial { k, center } => { + let (cx, cy) = (center[0] * w as f64, center[1] * h as f64); + let m = max_radius(cx, cy, w as f64, h as f64); + for y in 0..h { + for x in 0..w { + let r2 = ((x as f64 + 0.5 - cx).powi(2) + (y as f64 + 0.5 - cy).powi(2)) / (m * m); + let g = 1.0 + r2 * (k[0] + r2 * (k[1] + r2 * (k[2] + r2 * (k[3] + r2 * k[4])))); + for p in 0..cpp { + buf[(y * w + x) * cpp + p] *= g as f32; + } + } + } + } + Opcode::FixBadPixelsConstant { constant, .. } => { + let c = (*constant as f64 / 65535.0 * scale as f64) as f32; + let bad: Vec<(usize, usize)> = + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(MAX_BAD_PIXELS).collect(); + fix_pixels(buf, w, h, cpp, cfa, &bad); + } + Opcode::FixBadPixelsList { points, rects, .. } => { + let mut bad: Vec<(usize, usize)> = + points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(MAX_BAD_PIXELS).collect(); + 'rects: for r in rects { + let [t, l, b, rr] = r.map(|v| v as usize); + for y in t..b.min(h) { + for x in l..rr.min(w) { + if bad.len() >= MAX_BAD_PIXELS { + break 'rects; + } + bad.push((x, y)); + } + } + } + fix_pixels(buf, w, h, cpp, cfa, &bad); + } + _ => {} + } + } +} + +/// Replace listed pixels with the mean of the nearest same-colour neighbours that are not themselves bad. +fn fix_pixels(buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, bad: &[(usize, usize)]) { + if bad.is_empty() { + return; + } + let mut is_bad = std::collections::HashSet::with_capacity(bad.len()); + for &b in bad { + is_bad.insert(b); + } + let step: isize = match cfa { + Some(c) if c.width == 2 && c.height == 2 => 2, + Some(c) => c.width.max(c.height) as isize, + None => 1, + }; + for &(x, y) in bad { + for p in 0..cpp { + let mut sum = 0.0; + let mut n = 0; + for (dx, dy) in [(-step, 0), (step, 0), (0, -step), (0, step), (-step, -step), (step, step), (-step, step), (step, -step)] { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if nx < 0 || ny < 0 || nx >= w as isize || ny >= h as isize || is_bad.contains(&(nx as usize, ny as usize)) { + continue; + } + sum += buf[(ny as usize * w + nx as usize) * cpp + p]; + n += 1; + } + if n > 0 { + buf[(y * w + x) * cpp + p] = sum / n as f32; + } + } + } +} + +/// Most full-image passes of one `OpcodeList3`: every warp record is a full-image allocation and resample +/// pass and every bad-pixel record a full flatten-and-rebuild, and a hostile record may repeat either +/// thousands of times. Real DNGs carry at most a couple; passes past the cap are skipped. +const MAX_LIST3_PASSES: usize = 8; + +/// Apply `OpcodeList3` (on the demosaiced RGB image, values normalised to [0, 1]). +pub fn apply_list3(list: &[Opcode], img: &mut Rgb32f) { + if list.is_empty() { + return; + } + let (w, h) = (img.width, img.height); + let mut passes = 0usize; + for op in applied_ops(list) { + match op { + Opcode::WarpRectilinear { planes, center } => { + if passes < MAX_LIST3_PASSES { + passes += 1; + *img = warp_rectilinear(img, planes, *center); + } + } + Opcode::WarpRectilinear2 { planes, center, reciprocal, .. } => { + if passes < MAX_LIST3_PASSES { + passes += 1; + *img = warp_rectilinear2(img, planes, *center, *reciprocal); + } + } + Opcode::WarpFisheye { .. } | Opcode::TrimBounds { .. } | Opcode::Unknown { .. } => {} + other => { + if passes >= MAX_LIST3_PASSES { + continue; + } + passes += 1; + let mut flat: Vec = img.data.iter().flat_map(|p| *p).collect(); + apply_list(std::slice::from_ref(other), &mut flat, w, h, 3, None, 1.0); + for (d, c) in img.data.iter_mut().zip(flat.as_chunks::<3>().0) { + *d = [c[0], c[1], c[2]]; + } + } + } + } +} + +/// DNG `WarpRectilinear`: for each output pixel, the source position is the radial + tangential model around the +/// optical centre, with coordinates normalised by the distance to the farthest corner. +pub fn warp_rectilinear(img: &Rgb32f, planes: &[[f64; 6]], center: [f64; 2]) -> Rgb32f { + let (w, h) = (img.width, img.height); + let (cx, cy) = (center[0] * (w as f64 - 1.0), center[1] * (h as f64 - 1.0)); + let m = max_radius(cx, cy, w as f64 - 1.0, h as f64 - 1.0); + let mut out = Rgb32f::new(w, h); + let coef = |p: usize| planes[p.min(planes.len() - 1)]; + crate::raster::par_rows(&mut out.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + for (c, v) in px.iter_mut().enumerate() { + let [kr0, kr1, kr2, kr3, kt0, kt1] = coef(c); + let dx = (x as f64 - cx) / m; + let dy = (y as f64 - cy) / m; + let r2 = dx * dx + dy * dy; + let f = kr0 + r2 * (kr1 + r2 * (kr2 + r2 * kr3)); + let sx = dx * f + kt0 * 2.0 * dx * dy + kt1 * (r2 + 2.0 * dx * dx); + let sy = dy * f + kt1 * 2.0 * dx * dy + kt0 * (r2 + 2.0 * dy * dy); + let (fx, fy) = (cx + m * sx, cy + m * sy); + *v = img.sample_bilinear(fx as f32 + 0.5, fy as f32 + 0.5)[c]; + } + } + }); + out +} + +/// DNG 1.6 `WarpRectilinear2`: the `WarpRectilinear` geometry (centre and normalisation as there), with the radial +/// factor of [`wr2_factor`] in place of the even polynomial in `r²`. A pixel whose factor is not finite stays put. +pub fn warp_rectilinear2(img: &Rgb32f, planes: &[[f64; WR2_LEN]], center: [f64; 2], reciprocal: bool) -> Rgb32f { + let (w, h) = (img.width, img.height); + let Some(last) = planes.len().checked_sub(1) else { return img.clone() }; + let mut out = Rgb32f::new(w, h); + let (cx, cy) = (center[0] * (w as f64 - 1.0), center[1] * (h as f64 - 1.0)); + let m = max_radius(cx, cy, w as f64 - 1.0, h as f64 - 1.0); + crate::raster::par_rows(&mut out.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + for (c, v) in px.iter_mut().enumerate() { + let Some(k) = planes.get(c.min(last)) else { continue }; + let dx = (x as f64 - cx) / m; + let dy = (y as f64 - cy) / m; + let r2 = dx * dx + dy * dy; + let (sx, sy) = match wr2_factor(k, reciprocal, r2.sqrt()) { + Some(f) => { + (dx * f + k[15] * 2.0 * dx * dy + k[16] * (r2 + 2.0 * dx * dx), dy * f + k[16] * 2.0 * dx * dy + k[15] * (r2 + 2.0 * dy * dy)) + } + None => (dx, dy), + }; + let (fx, fy) = (cx + m * sx, cy + m * sy); + *v = img.sample_bilinear(fx as f32 + 0.5, fy as f32 + 0.5)[c]; + } + } + }); + out +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/develop/src/sensor/opcodes/tests.rs b/crates/develop/src/sensor/opcodes/tests.rs new file mode 100644 index 000000000..c97b81eea --- /dev/null +++ b/crates/develop/src/sensor/opcodes/tests.rs @@ -0,0 +1,471 @@ +use super::*; + +pub(crate) struct ListWriter(pub Vec, pub u32); + +impl ListWriter { + pub fn new() -> Self { + ListWriter(Vec::new(), 0) + } + pub fn op(&mut self, id: u32, params: &[u8]) -> &mut Self { + for v in [id, 0x01030000, 0, params.len() as u32] { + self.0.extend_from_slice(&v.to_be_bytes()); + } + self.0.extend_from_slice(params); + self.1 += 1; + self + } + pub fn finish(&self) -> Vec { + let mut v = self.1.to_be_bytes().to_vec(); + v.extend_from_slice(&self.0); + v + } +} + +pub(crate) fn be(vals: &[f64]) -> Vec { + vals.iter().flat_map(|v| v.to_be_bytes()).collect() +} +pub(crate) fn area(a: [u32; 8]) -> Vec { + a.iter().flat_map(|v| v.to_be_bytes()).collect() +} + +/// Warp and bad-pixel records each cost a full-image pass, and a hostile `OpcodeList3` repeats them +/// thousands of times ([`MAX_LIST3_PASSES`] bounds the multiplier); identity warps below the cap must +/// still apply, exactly, so the same image comes out. +#[test] +fn list3_pass_cap_skips_repeated_records() { + let mut img = Rgb32f::new(8, 6); + for (i, px) in img.data.iter_mut().enumerate() { + *px = [i as f32 / 2.0, (i % 8) as f32, (i / 8) as f32]; + } + let orig: Vec<[f32; 3]> = img.data.clone(); + let list: Vec = + (0..MAX_LIST3_PASSES * 5).map(|_| Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }).collect(); + apply_list3(&list, &mut img); + assert_eq!(img.data, orig, "identity warps change nothing, and the cap skips the repeated rest"); + + // a real warp below the cap is still applied + let one = [Opcode::WarpRectilinear { planes: vec![[2.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }]; + apply_list3(&one, &mut img); + assert_ne!(img.data, orig, "a genuine warp record is not skipped"); +} + +#[test] +fn parse_and_apply_area_ops() { + let (w, h) = (4usize, 3usize); + let mut gm = area([0, 0, 3, 4, 0, 1, 1, 1]); + for v in [2u32, 2] { + gm.extend_from_slice(&v.to_be_bytes()); + } + gm.extend(be(&[1.0, 1.0, 0.0, 0.0])); + gm.extend_from_slice(&1u32.to_be_bytes()); + for g in [1.0f32, 2.0, 1.0, 2.0] { + gm.extend_from_slice(&g.to_be_bytes()); + } + let mut dpr = area([0, 0, 3, 4, 0, 1, 1, 1]); + dpr.extend_from_slice(&3u32.to_be_bytes()); + for d in [0.0f32, 0.1, 0.2] { + dpr.extend_from_slice(&d.to_be_bytes()); + } + let mut poly = area([0, 0, 3, 4, 0, 1, 1, 2]); + poly.extend_from_slice(&1u32.to_be_bytes()); + poly.extend(be(&[0.0, 2.0])); + let blob = ListWriter::new().op(9, &gm).op(10, &dpr).op(8, &poly).op(99, &[1, 2, 3]).finish(); + let list = parse_list(&blob); + assert_eq!(list.len(), 4); + assert!(matches!(list[3], Opcode::Unknown { id: 99, .. })); + assert!(list[..3].iter().all(is_applied)); + let mut buf = vec![0.25f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + // gain map: horizontal ramp 1 → 2 across relative x 0..1 (x / w) + let expect = |x: usize, y: usize| { + let g = 1.0 + x as f32 / w as f32; + let v = 0.25 * g + [0.0, 0.1, 0.2][y]; + if x.is_multiple_of(2) { v * 2.0 } else { v } + }; + for y in 0..h { + for x in 0..w { + assert!((buf[y * w + x] - expect(x, y)).abs() < 1e-6, "{x},{y}: {} vs {}", buf[y * w + x], expect(x, y)); + } + } +} + +#[test] +fn map_table_raw_scale_and_bad_pixels() { + let mut t = area([0, 0, 2, 2, 0, 1, 1, 1]); + t.extend_from_slice(&3u32.to_be_bytes()); + for v in [0u16, 30000, 65535] { + t.extend_from_slice(&v.to_be_bytes()); + } + let list = parse_list(&ListWriter::new().op(7, &t).finish()); + let mut buf = vec![0.0, 1.0 / 65535.0, 2.0 / 65535.0, 0.5]; + apply_list(&list, &mut buf, 2, 2, 1, None, 1.0); + assert_eq!(buf[0], 0.0); + assert!((buf[1] - 30000.0 / 65535.0).abs() < 1e-7); + assert_eq!(buf[3], 1.0); + + let mut p = vec![]; + for v in [7u32, 0] { + p.extend_from_slice(&v.to_be_bytes()); + } + let list = parse_list(&ListWriter::new().op(4, &p).finish()); + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut img: Vec = (0..36).map(|i| 100.0 + (i % 6) as f32).collect(); + img[2 * 6 + 2] = 7.0; + apply_list(&list, &mut img, 6, 6, 1, Some(&cfa), 65535.0); + assert_eq!(img[2 * 6 + 2], 102.0); +} + +/// A mosaic equal to the bad-pixel constant, or one rectangle over the whole image, used to list every pixel as +/// bad: w × h entries (plus a set of them), tens of GB at the decoder's size limit. Here the rows between a good +/// first row (500) and a good last row (900) are bad: 2052 rows of 2048 pixels, four rows more than the 1 << 22 +/// cap. Row 1, within the cap, is repaired from the first row; the second-last row, past the cap, must be left +/// as it is (uncapped, it was rewritten from the last row). +fn assert_bad_pixels_capped(op: Opcode) { + let (w, h) = (2048, 2054); + let mut buf = vec![0.0f32; w * h]; + buf[..w].fill(500.0); + buf[(h - 1) * w..].fill(900.0); + apply_list(&[op], &mut buf, w, h, 1, None, 65535.0); + assert!(buf[w..2 * w].iter().all(|&v| v == 500.0), "row 1 (within the cap) not repaired: {:?}", &buf[w..w + 4]); + let past = &buf[(h - 2) * w..(h - 1) * w]; + assert!(past.iter().all(|&v| v == 0.0), "a row past the cap was rewritten: {:?}", &past[..4]); +} + +#[test] +fn bad_pixels_constant_is_capped() { + assert_bad_pixels_capped(Opcode::FixBadPixelsConstant { constant: 0, bayer_phase: 0 }); +} + +#[test] +fn bad_pixels_list_is_capped_inside_a_rectangle() { + // top, left, bottom, right: every row but the first and the last + assert_bad_pixels_capped(Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![], rects: vec![[1, 0, 2053, 2048]] }); +} + +#[test] +fn vignette_and_warp_identity() { + let mut img = Rgb32f::from_fn(9, 7, |x, y| [x as f32 / 9.0, y as f32 / 7.0, 0.5]); + let orig = img.clone(); + let mut p = be(&[0.0; 5]); + p.extend(be(&[0.5, 0.5])); + let mut warp = 1u32.to_be_bytes().to_vec(); + warp.extend(be(&[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5])); + let list = parse_list(&ListWriter::new().op(3, &p).op(1, &warp).finish()); + assert_eq!(list.len(), 2); + apply_list3(&list, &mut img); + for (a, b) in img.data.iter().zip(&orig.data) { + for c in 0..3 { + assert!((a[c] - b[c]).abs() < 1e-5); + } + } + // positive k0 brightens the corners more than the centre + let mut p = be(&[1.0, 0.0, 0.0, 0.0, 0.0]); + p.extend(be(&[0.5, 0.5])); + let list = parse_list(&ListWriter::new().op(3, &p).finish()); + let mut flat = Rgb32f::filled(9, 9, [0.5; 3]); + apply_list3(&list, &mut flat); + assert!(flat.get(0, 0)[0] > 0.85 && (flat.get(4, 4)[0] - 0.5).abs() < 0.01, "{:?}", flat.get(0, 0)); +} + +#[test] +fn warp_barrel_moves_pixels_outward() { + let img = Rgb32f::from_fn(31, 31, |x, y| if x == 24 && y == 15 { [1.0; 3] } else { [0.0; 3] }); + // source radius = r (1 + k r²) with k < 0 → content moves outward + let out = warp_rectilinear(&img, &[[1.0, -0.6, 0.0, 0.0, 0.0, 0.0]], [0.5, 0.5]); + let (bx, _) = (0..31).map(|x| (x, out.get(x, 15)[0])).fold((0, 0.0), |a, b| if b.1 > a.1 { b } else { a }); + assert!(bx >= 25, "{bx}"); +} + +#[test] +fn write_parse_roundtrip() { + let a = Area { top: 1, left: 2, bottom: 30, right: 40, plane: 0, planes: 3, row_pitch: 1, col_pitch: 2 }; + let list = vec![ + Opcode::WarpRectilinear { planes: vec![[1.0, 0.01, -0.002, 0.0, 1e-4, -2e-4]; 3], center: [0.5, 0.49] }, + Opcode::WarpFisheye { planes: vec![[1.0, 0.1, 0.0, 0.0]], center: [0.5, 0.5] }, + Opcode::FixVignetteRadial { k: [0.1, 0.2, 0.0, 0.0, 0.0], center: [0.5, 0.5] }, + Opcode::FixBadPixelsConstant { constant: 0, bayer_phase: 1 }, + Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![(3, 4)], rects: vec![[1, 1, 2, 2]] }, + Opcode::TrimBounds { top: 1, left: 1, bottom: 9, right: 9 }, + Opcode::MapTable { area: a, table: vec![0, 100, 65535] }, + Opcode::MapPolynomial { area: a, coefficients: vec![0.0, 1.0, -0.1] }, + Opcode::GainMap { area: a, points_v: 2, points_h: 1, spacing: [1.0, 1.0], origin: [0.0, 0.0], map_planes: 1, gains: vec![1.0, 1.5] }, + Opcode::DeltaPerRow { area: a, deltas: vec![0.1, 0.2] }, + Opcode::DeltaPerColumn { area: a, deltas: vec![0.3] }, + Opcode::ScalePerRow { area: a, scales: vec![1.1] }, + Opcode::ScalePerColumn { area: a, scales: vec![0.9, 1.0] }, + Opcode::WarpRectilinear2 { + planes: vec![wr2_set(&[(0, 0.5), (3, 0.1)]), wr2_set(&[(0, 0.25)])], + center: [0.5, 0.49], + reciprocal: true, + optional: true, + }, + Opcode::Unknown { id: 77, flags: 1, params: vec![1, 2, 3] }, + ]; + assert_eq!(parse_list(&write_list(&list)), list); +} + +#[test] +fn truncated_lists_do_not_panic() { + let mut gm = area([0, 0, 3, 4, 0, 1, 1, 1]); + gm.extend_from_slice(&[0xff; 64]); + let blob = ListWriter::new().op(9, &gm).op(5, &[0xff; 12]).op(1, &[0, 0, 0, 9]).finish(); + for n in 0..blob.len() { + let l = parse_list(&blob[..n]); + let mut buf = vec![0.5f32; 12]; + apply_list(&l, &mut buf, 4, 3, 1, None, 1.0); + } +} + +/// `WarpRectilinear2` parameter bytes (spec 1.6.0.0: N, then per set kr0..kr14, kt0, kt1, min/max valid radius, +/// then the centre and `reciprocalRadial`). +fn wr2_params(sets: &[[f64; WR2_LEN]], center: [f64; 2], reciprocal: u32) -> Vec { + let mut p = (sets.len() as u32).to_be_bytes().to_vec(); + for s in sets { + p.extend(be(s)); + } + p.extend(be(¢er)); + p.extend_from_slice(&reciprocal.to_be_bytes()); + p +} + +fn wr2_set(kr: &[(usize, f64)]) -> [f64; WR2_LEN] { + let mut k = [0.0; WR2_LEN]; + for &(i, v) in kr { + k[i] = v; + } + k[18] = 1.0; + k +} + +#[test] +fn warp_rectilinear2_parses_the_spec_layout() { + let mut k = wr2_set(&[(0, 1.0), (1, 0.25), (14, -2.0)]); + k[15] = 0.001; + k[16] = -0.002; + k[17] = 0.1; + k[18] = 0.9; + let blob = ListWriter::new().op(14, &wr2_params(&[k, wr2_set(&[(0, 1.0)])], [0.5, 0.25], 1)).finish(); + let list = parse_list(&blob); + assert_eq!( + list, + vec![Opcode::WarpRectilinear2 { planes: vec![k, wr2_set(&[(0, 1.0)])], center: [0.5, 0.25], reciprocal: true, optional: false }] + ); + assert!(is_applied(&list[0]) && list[0].is_lens_correction()); + // written back as opcode 14, version 1.6.0.0, optional flag kept + let again = vec![Opcode::WarpRectilinear2 { planes: vec![k], center: [0.5, 0.5], reciprocal: false, optional: true }]; + let bytes = write_list(&again); + assert_eq!(bytes.get(4..8), Some(&14u32.to_be_bytes()[..])); + assert_eq!(bytes.get(8..12), Some(&0x0106_0000u32.to_be_bytes()[..])); + assert_eq!(parse_list(&bytes), again); +} + +#[test] +fn warp_rectilinear2_identity_leaves_the_image() { + let img = Rgb32f::from_fn(21, 15, |x, y| [x as f32 / 21.0, y as f32 / 15.0, 0.25]); + for reciprocal in [false, true] { + let mut i = img.clone(); + let p = wr2_params(&[wr2_set(&[(0, 1.0)])], [0.5, 0.5], reciprocal as u32); + apply_list3(&parse_list(&ListWriter::new().op(14, &p).finish()), &mut i); + for (a, b) in i.data.iter().zip(&img.data) { + for c in 0..3 { + assert!((a[c] - b[c]).abs() < 1e-5, "{a:?} {b:?}"); + } + } + } +} + +#[test] +fn warp_rectilinear2_matches_warp_rectilinear_on_even_terms() { + // kr0 + kr2 r^2 + kr4 r^4 is WarpRectilinear's kr0 + kr1 r^2 + kr2 r^4 + let img = Rgb32f::from_fn(31, 31, |x, y| [(x * 7 % 13) as f32 / 13.0, (y * 5 % 11) as f32 / 11.0, ((x + y) % 4) as f32 / 4.0]); + let a = warp_rectilinear(&img, &[[1.0, -0.3, 0.1, 0.0, 0.01, -0.02]], [0.5, 0.5]); + let mut k = wr2_set(&[(0, 1.0), (2, -0.3), (4, 0.1)]); + k[15] = 0.01; + k[16] = -0.02; + let b = warp_rectilinear2(&img, &[k], [0.5, 0.5], false); + for (p, q) in a.data.iter().zip(&b.data) { + for c in 0..3 { + assert!((p[c] - q[c]).abs() < 1e-5); + } + } + // odd terms, the reciprocal and the valid-radius clamp give the factor the spec defines + let k = wr2_set(&[(0, 1.0), (1, 0.5)]); + assert_eq!(wr2_factor(&k, false, 0.5), Some(1.25)); + assert_eq!(wr2_factor(&k, true, 0.5), Some(0.8)); + let mut k = k; + k[18] = 0.5; // max_valid_radius + assert_eq!(wr2_factor(&k, false, 0.9), Some(1.25)); + k[17] = 0.25; // min_valid_radius + assert_eq!(wr2_factor(&k, false, 0.0), Some(1.125)); + assert_eq!(wr2_factor(&wr2_set(&[]), true, 0.3), None, "1 / 0"); +} + +#[test] +fn malformed_warp_rectilinear2_is_unknown_not_a_panic() { + let good = wr2_params(&[wr2_set(&[(0, 1.0)])], [0.5, 0.5], 0); + let is_wr2 = |p: &[u8]| matches!(parse_list(&ListWriter::new().op(14, p).finish()).as_slice(), [Opcode::WarpRectilinear2 { .. }]); + assert!(is_wr2(&good)); + // every truncation and any trailing byte + for n in 0..good.len() { + assert!(!is_wr2(&good[..n]), "{n}"); + } + assert!(!is_wr2(&[&good[..], &[0u8][..]].concat())); + // N = 0, N too big for the data, N beyond the plane limit + for n in [0u32, 2, 5, u32::MAX] { + let mut p = good.clone(); + p[..4].copy_from_slice(&n.to_be_bytes()); + assert!(!is_wr2(&p), "N = {n}"); + } + // non-finite or absurd values, in a coefficient, the valid range and the centre + let patch = |at: usize, v: f64| { + let mut p = good.clone(); + p[at..at + 8].copy_from_slice(&v.to_be_bytes()); + p + }; + for (at, v) in [ + (4, f64::NAN), + (4 + 8, f64::INFINITY), + (4 + 8 * 3, 1e300), + (4 + 8 * 17, -0.5), + (4 + 8 * 18, 1.5), + (4 + 8 * 17, 1.0), + (4 + 19 * 8, f64::NAN), + (4 + 19 * 8 + 8, 1e30), + ] { + assert!(!is_wr2(&patch(at, v)), "{at} {v}"); + } + // refused ones stay Unknown and are not applied + let list = parse_list(&ListWriter::new().op(14, &good[..10]).finish()); + assert!(matches!(list.as_slice(), [Opcode::Unknown { id: 14, .. }])); + let mut img = Rgb32f::filled(5, 5, [0.5; 3]); + apply_list3(&list, &mut img); + assert_eq!(img.get(2, 2), [0.5; 3]); + // a hostile but accepted set (huge radial terms) still gives a finite image + let k = wr2_set(&[(0, 1.0), (14, 1e9), (13, -1e9)]); + let img = Rgb32f::from_fn(9, 9, |x, y| [x as f32 / 9.0, y as f32 / 9.0, 0.5]); + for reciprocal in [false, true] { + let out = warp_rectilinear2(&img, &[k], [0.5, 0.5], reciprocal); + assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()))); + } +} + +#[test] +fn warp_list_order_and_the_optional_skip_rule() { + let wr2 = |optional| Opcode::WarpRectilinear2 { planes: vec![wr2_set(&[(0, 1.0)])], center: [0.5, 0.5], reciprocal: false, optional }; + let wr = Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; + let fish = Opcode::WarpFisheye { planes: vec![[1.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; + let vig = Opcode::FixVignetteRadial { k: [0.0; 5], center: [0.5, 0.5] }; + let d = std::mem::discriminant::; + let ids = |l: &[Opcode]| applied_ops(l).map(d).collect::>(); + // WarpRectilinear2 (optional) then WarpRectilinear / WarpFisheye: the second is skipped + assert_eq!(ids(&[wr2(true), wr.clone()]), vec![d(&wr2(true))]); + assert_eq!(ids(&[wr2(true), fish.clone()]), vec![d(&wr2(true))]); + // not optional: both run, in list order + assert_eq!(ids(&[wr2(false), wr.clone()]), vec![d(&wr2(false)), d(&wr)]); + // only the opcode immediately after is skipped + assert_eq!(ids(&[wr2(true), vig.clone(), wr.clone()]), vec![d(&wr2(true)), d(&vig), d(&wr)]); + // two in a row: both run, and the WarpRectilinear after the optional second one is skipped + assert_eq!(ids(&[wr2(true), wr2(true), wr.clone()]), vec![d(&wr2(true)); 2]); + // a WarpRectilinear before the WarpRectilinear2 runs, in list order + assert_eq!(ids(&[wr.clone(), wr2(true)]), vec![d(&wr), d(&wr2(true))]); + // the same from bytes: an optional (flag 1) opcode 14 followed by opcode 1 + let w2 = wr2_params(&[wr2_set(&[(0, 1.0)])], [0.5, 0.5], 0); + let mut one = 1u32.to_be_bytes().to_vec(); + one.extend(be(&[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5])); + let mut blob = 2u32.to_be_bytes().to_vec(); + for (id, flags, p) in [(14u32, 1u32, &w2), (1, 1, &one)] { + for v in [id, 0x0106_0000, flags, p.len() as u32] { + blob.extend_from_slice(&v.to_be_bytes()); + } + blob.extend_from_slice(p); + } + let list = parse_list(&blob); + assert_eq!(list.len(), 2); + assert_eq!(applied_ops(&list).count(), 1); + // a refused (Unknown) opcode 14 triggers no skip + let bad = Opcode::Unknown { id: 14, flags: 1, params: vec![] }; + assert!(applied_ops(&[bad, wr]).any(|o| matches!(o, Opcode::WarpRectilinear { .. }))); +} + +/// `cropped` re-expresses a lens correction for a crop: the corrected crop is the crop of the corrected whole. A +/// linear ramp makes bilinear sampling exact, so only the borders (where the warp reaches past the crop) differ. +#[test] +fn cropped_lens_corrections_correct_the_crop_like_the_whole() { + let (w, h) = (90usize, 64usize); + let crop = super::super::Rect::new(7, 5, 70, 50); + let ramp = Rgb32f::from_fn(w, h, |x, y| [0.002 * x as f32 + 0.001 * y as f32 + 0.1, 0.3 + 0.0015 * y as f32, 0.2]); + let mut wr2 = [0.0; WR2_LEN]; + wr2[..5].copy_from_slice(&[1.0, 0.01, -0.03, 0.0, 0.01]); + wr2[15] = 0.002; + wr2[16] = -0.001; + wr2[17] = 0.05; + wr2[18] = 0.9; + let warps = [ + Opcode::WarpRectilinear { planes: vec![[0.97, 0.04, -0.01, 0.002, 0.003, -0.002]], center: [0.47, 0.53] }, + Opcode::WarpRectilinear2 { planes: vec![wr2], center: [0.52, 0.46], reciprocal: false, optional: true }, + Opcode::WarpRectilinear2 { planes: vec![wr2], center: [0.52, 0.46], reciprocal: true, optional: false }, + ]; + for op in &warps { + let mut whole = ramp.clone(); + apply_list3(std::slice::from_ref(op), &mut whole); + let re = op.cropped(w, h, crop).unwrap(); + let mut part = ramp.clone().into_crop(crop.x, crop.y, crop.width, crop.height); + apply_list3(std::slice::from_ref(&re), &mut part); + let mut worst = 0f32; + for y in 6..crop.height - 6 { + for x in 6..crop.width - 6 { + let (a, b) = (whole.data[(y + crop.y) * w + x + crop.x], part.data[y * crop.width + x]); + worst = (0..3).map(|c| (a[c] - b[c]).abs()).fold(worst, f32::max); + } + } + assert!(worst < 1e-4, "{op:?} → {re:?}: {worst}"); + } + // the vignette, in the warps' centre convention the develop pipeline reads it with + let gain = |k: &[f64; 5], c: [f64; 2], w: usize, h: usize, x: f64, y: f64| { + let (aw, ah) = (w as f64 - 1.0, h as f64 - 1.0); + let (px, py) = (c[0] * aw, c[1] * ah); + let r2 = ((x - px).powi(2) + (y - py).powi(2)) / max_radius(px, py, aw, ah).powi(2); + 1.0 + (0..5).map(|i| k[i] * r2.powi(i as i32 + 1)).sum::() + }; + let (k, center) = ([-0.3, 0.1, -0.05, 0.02, -0.01], [0.45, 0.55]); + let Some(Opcode::FixVignetteRadial { k: k2, center: c2 }) = (Opcode::FixVignetteRadial { k, center }).cropped(w, h, crop) else { + panic!("vignette") + }; + for (x, y) in [(0.0, 0.0), (69.0, 49.0), (33.5, 20.0), (69.0, 0.0), (12.0, 40.0)] { + let (a, b) = (gain(&k, center, w, h, x + crop.x as f64, y + crop.y as f64), gain(&k2, c2, crop.width, crop.height, x, y)); + assert!((a - b).abs() < 1e-12, "({x}, {y}): {a} vs {b}"); + } + // no change for a full-frame "crop"; nothing for other opcodes, tiny images or a crop past the edge + assert_eq!(warps[0].cropped(w, h, super::super::Rect::new(0, 0, w, h)).unwrap(), warps[0]); + assert!(Opcode::TrimBounds { top: 0, left: 0, bottom: 2, right: 2 }.cropped(w, h, crop).is_none()); + assert!(warps[0].cropped(1, h, super::super::Rect::new(0, 0, 1, h)).is_none()); + assert!(warps[0].cropped(w, h, super::super::Rect::new(30, 0, 70, 50)).is_none()); + assert!(warps[0].cropped(w, h, super::super::Rect::new(usize::MAX, 0, 70, 50)).is_none()); +} + +/// Ten thousand full-image polynomials (a few hundred KB of opcode data): the list is held to +/// `MAX_LIST_PASSES` passes of work, the first ones applied and the rest left out. +#[test] +fn a_list_repeating_full_image_work_stops_at_its_budget() { + let (w, h) = (64usize, 48usize); + let a = Area { top: 0, left: 0, bottom: h as u32, right: w as u32, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + // v + 0.001 each, two coefficients: each costs two passes + let list = vec![Opcode::MapPolynomial { area: a, coefficients: vec![0.001, 1.0] }; 10_000]; + let mut buf = vec![0.0f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + let applied = (buf[0] / 0.001).round() as usize; + assert_eq!(applied, MAX_LIST_PASSES / 2, "{}", buf[0]); + assert!(buf.iter().all(|v| *v == buf[0])); +} + +/// Opcodes `apply_list` does nothing for spend none of the budget: a later real one still runs. +#[test] +fn ops_that_apply_nothing_cost_no_budget() { + let (w, h) = (8usize, 8usize); + let a = Area { top: 0, left: 0, bottom: h as u32, right: w as u32, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + let mut list = vec![Opcode::Unknown { id: 9999, flags: 0, params: Vec::new() }; 4 * MAX_LIST_PASSES]; + list.push(Opcode::MapPolynomial { area: a, coefficients: vec![0.5, 1.0] }); + let mut buf = vec![0.0f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + assert_eq!(buf[0], 0.5); +}