From a8d463fabc7a775dd82c3e96e05fa3b3214605f0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:13:08 +0100 Subject: [PATCH 1/4] raw: rebuild sensor-clipped highlights instead of clipping after white balance Develops a clipped Bayer frame unclamped and rebuilds the clipped highlights with craft-develop's reconstruct_masked, so RAW Open matches LightCraft before tone. Frames too large to rebuild within the memory limit keep the clip and report a warning. Rebless the RAW Open baseline corner pixels and Linux hashes. Fixes #16494 Part of storytold/craft-libs#778 --- crates/io/tests/it/raw.rs | 16 +- crates/raw/src/develop.rs | 302 +++++++++++++++++++++++++++++++------- 2 files changed, 253 insertions(+), 65 deletions(-) diff --git a/crates/io/tests/it/raw.rs b/crates/io/tests/it/raw.rs index c7439bee46..8c6225ebcc 100644 --- a/crates/io/tests/it/raw.rs +++ b/crates/io/tests/it/raw.rs @@ -739,15 +739,15 @@ fn raw_open_legacy_baseline_pixels() { // center pixel `[47838, 39368, 49721]` matches legacy bit-for-bit); `tuned_px`/`tuned_hash` reflects // the `craft_develop` cutover for `RawTuning` (`camera_raw::develop`). Whole-image hashes differ by // 1 LSB between MSVC and glibc `libm` float math on Windows. - let expected_def_hash = if cfg!(target_os = "windows") { 9_388_097_638_634_194_548 } else { 4_616_854_110_774_268_375 }; - let expected_tuned_hash = if cfg!(target_os = "windows") { 5_472_991_315_859_343_413 } else { 17_835_173_337_254_648_648 }; + let expected_def_hash = if cfg!(target_os = "windows") { 9_388_097_638_634_194_548 } else { 10_802_259_885_448_765_778 }; + let expected_tuned_hash = if cfg!(target_os = "windows") { 5_472_991_315_859_343_413 } else { 12_255_299_099_314_572_538 }; assert_eq!( (def_px, def_hash, wb, tuned_px, tuned_hash), ( - [[29689, 25226, 50514], [47838, 39368, 49721], [54535, 41252, 44908]], + [[29689, 25226, 50514], [47838, 39368, 49721], [58598, 42281, 45071]], expected_def_hash, false, - [[39311, 33399, 65535], [63418, 52119, 65535], [65535, 54440, 59060]], + [[39333, 33449, 65535], [63354, 52144, 65535], [65535, 55781, 59230]], expected_tuned_hash, ) ); @@ -809,13 +809,13 @@ fn raw_open_camera_wb_legacy_baseline_pixels() { // Default RAW Open (`def_px`/`def_hash`) runs `craft_develop::sensor::demosaic` (`reflect` borders; // center pixel `[51905, 40291, 54669]` matches legacy bit-for-bit); `tuned_px`/`tuned_hash` reflects // the `craft_develop` cutover for `RawTuning` (`camera_raw::develop`). - let expected_tuned_hash = if cfg!(target_os = "windows") { 16_896_394_607_103_456_502 } else { 1_068_984_693_251_983_675 }; + let expected_tuned_hash = if cfg!(target_os = "windows") { 16_896_394_607_103_456_502 } else { 8_451_299_581_473_829_420 }; assert_eq!( (def_px, def_hash, tuned_px, tuned_hash), ( - [[32235, 25796, 56002], [51905, 40291, 54669], [55142, 41405, 49143]], - 11_523_078_668_107_121_059, - [[42084, 33938, 65535], [65535, 53409, 65535], [65535, 54586, 62244]], + [[32235, 25796, 56002], [51905, 40291, 54669], [63986, 43623, 49478]], + 6_651_437_429_964_055_359, + [[42154, 34080, 65535], [65535, 53404, 65535], [65535, 57910, 62593]], expected_tuned_hash, ) ); diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index 9d598b684b..7c93de195a 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -403,13 +403,15 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result Result 0.0 && black.is_finite()) { return (0.0, 0.0); } - let gain = mult[usize::from(cfa.color(x, y)).min(2)] / range; + let gain = gains[usize::from(cfa.color(x, y)).min(2)] / range; // Scalar normalization rejects a non-finite quotient before // white balance. A finite gain alone does not prove that // every U16 numerator divided by this range stays finite. @@ -442,13 +444,13 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result { for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { - *v = ((f32::from(raw) - black) * gain).clamp(0.0, 1.0); + *v = ((f32::from(raw) - black) * gain).clamp(0.0, top); } } Some(l) => { for ((v, &raw), &(black, gain)) in row.iter_mut().zip(src).zip(ks) { let lin = f32::from(l.get(usize::from(raw)).or_else(|| l.last()).copied().unwrap_or(raw)); - *v = ((lin - black) * gain).clamp(0.0, 1.0); + *v = ((lin - black) * gain).clamp(0.0, top); } } } @@ -462,42 +464,78 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result craft_develop::sensor::Method::Bilinear, + Demosaic::Ahd | Demosaic::Mhc => craft_develop::sensor::Method::Ahd, + }; + let shared = matches!(opts.demosaic, Demosaic::Bilinear | Demosaic::Ahd); + let clipped = shared && sensor_clipped(w, h, band, &|iy, row| fill_with(iy, row, [1.0; 3], f32::INFINITY)); + let rebuild = if clipped { + let method = if bayer { shared_method } else { craft_develop::sensor::Method::Bilinear }; + if rebuild_fits(w, h, method, orient_copy, &opts.limits) { + Some(method) + } else { + warnings.push("clipped highlights are clipped, not rebuilt: the frame is too large to rebuild within the memory limit".into()); + None + } + } else { + None + }; + // Rows for the shared demosaics when nothing is rebuilt. + let shared_row = |iy: usize, row: &mut [f32]| if clipped { fill_row(iy, row) } else { open_row(iy, row) }; + let cfa_at = |p: Vec, cw: usize, ch: usize| craft_develop::sensor::Cfa { width: cw, height: ch, pattern: p, origin_x: 0, origin_y: 0 }; + let rebuilt = |method, cw, ch, p: Vec| { + develop_rebuilt(w, h, band, cfa_at(p, cw, ch), method, mult, &|iy, row| fill_with(iy, row, [1.0; 3], f32::INFINITY)) + }; let names = |p: &[u8]| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect::(); - if bayer && fused && matches!(opts.demosaic, Demosaic::Bilinear | Demosaic::Ahd) { + if bayer && fused && shared { let p = cfa.phase(c.x, c.y); pattern = Some(names(&p)); - let method = match opts.demosaic { - Demosaic::Bilinear => craft_develop::sensor::Method::Bilinear, - Demosaic::Ahd | Demosaic::Mhc => craft_develop::sensor::Method::Ahd, - }; + let method = shared_method; let mut o = vec![0u16; w * h * 3]; - par::chunks_mut_grouped(&mut o, band * w * 3, jobs, |b, chunk| { - let y0 = b * band; - let rows = chunk.len() / (w * 3); - let y_start = y0.saturating_sub(PAD); - let y_end = (y0 + rows + PAD).min(h); - let sh = y_end - y_start; - let mut strip = vec![0.0f32; w * sh]; - for (r, row) in strip.chunks_exact_mut(w).enumerate() { - fill_row(y_start + r, row); - } - let norm = craft_develop::sensor::Normalized { - width: w, - height: sh, - cpp: 1, - data: strip, - cfa: Some(craft_develop::sensor::Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: y_start % 2 }), - }; - let dem = craft_develop::sensor::demosaic(&norm, method); - let top_pad = y0 - y_start; - let dem_f32: Vec = dem.data[top_pad * w..(top_pad + rows) * w].iter().flat_map(|px| *px).collect(); - encode_plain(&dem_f32, chunk); - }); - fused_out = Some(o); + if let Some(method) = rebuild { + let rgb = rebuilt(method, 2, 2, p.to_vec()); + par::chunks_mut(&mut o, band * w * 3, |b, chunk| { + let start = b * band * w * 3; + encode_plain(&rgb[start..start + chunk.len()], chunk); + }); + fused_out = Some(o); + } else { + par::chunks_mut_grouped(&mut o, band * w * 3, jobs, |b, chunk| { + let y0 = b * band; + let rows = chunk.len() / (w * 3); + let y_start = y0.saturating_sub(PAD); + let y_end = (y0 + rows + PAD).min(h); + let sh = y_end - y_start; + let mut strip = vec![0.0f32; w * sh]; + for (r, row) in strip.chunks_exact_mut(w).enumerate() { + shared_row(y_start + r, row); + } + let norm = craft_develop::sensor::Normalized { + width: w, + height: sh, + cpp: 1, + data: strip, + cfa: Some(craft_develop::sensor::Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: y_start % 2 }), + }; + let dem = craft_develop::sensor::demosaic(&norm, method); + let top_pad = y0 - y_start; + let dem_f32: Vec = dem.data[top_pad * w..(top_pad + rows) * w].iter().flat_map(|px| *px).collect(); + encode_plain(&dem_f32, chunk); + }); + fused_out = Some(o); + } } else if bayer && fused { // No padded plane either: every band normalizes its own rows. let p = cfa.phase(c.x, c.y); @@ -505,7 +543,7 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result Result>().join("/")); (pat.w, pat.h, pat.colors) }; - let mut norm_data = vec![0.0f32; w * h]; - par::chunks_mut(&mut norm_data, band * w, |b, chunk| { - for (r, row) in chunk.chunks_exact_mut(w).enumerate() { - fill_row(b * band + r, row); - } - }); - let norm = craft_develop::sensor::Normalized { - width: w, - height: h, - cpp: 1, - data: norm_data, - cfa: Some(craft_develop::sensor::Cfa { width: cfa_w, height: cfa_h, pattern: cfa_pat, origin_x: 0, origin_y: 0 }), - }; - let method = if !bayer { - craft_develop::sensor::Method::Bilinear + if let Some(method) = rebuild { + rgb = rebuilt(method, cfa_w, cfa_h, cfa_pat); } else { - match opts.demosaic { - Demosaic::Bilinear => craft_develop::sensor::Method::Bilinear, - Demosaic::Ahd | Demosaic::Mhc => craft_develop::sensor::Method::Ahd, - } - }; - let dem = craft_develop::sensor::demosaic(&norm, method); - rgb = dem.data.into_iter().flatten().collect(); + let mut norm_data = vec![0.0f32; w * h]; + par::chunks_mut(&mut norm_data, band * w, |b, chunk| { + for (r, row) in chunk.chunks_exact_mut(w).enumerate() { + shared_row(b * band + r, row); + } + }); + let norm = craft_develop::sensor::Normalized { width: w, height: h, cpp: 1, data: norm_data, cfa: Some(cfa_at(cfa_pat, cfa_w, cfa_h)) }; + let method = if bayer { shared_method } else { craft_develop::sensor::Method::Bilinear }; + let dem = craft_develop::sensor::demosaic(&norm, method); + rgb = dem.data.into_iter().flatten().collect(); + } } else { let mut plane = Padded::new(w, h); let stride = plane.stride; @@ -652,6 +681,89 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result bool { + let mut bands = vec![false; h.div_ceil(band.max(1))]; + par::chunks_mut(&mut bands, 1, |b, hit| { + let mut row = vec![0.0f32; w]; + let rows = b * band..((b + 1) * band).min(h); + hit[0] = rows.into_iter().any(|y| { + sensor_row(y, &mut row); + row.iter().any(|v| *v >= SENSOR_CLIP) + }); + }); + bands.contains(&true) +} + +/// Bytes [`develop_rebuilt`] holds at its peak, plus the encode that follows it. +fn rebuild_bytes(w: usize, h: usize, method: craft_develop::sensor::Method, orient_copy: bool) -> u64 { + let pixels = (w as u64).saturating_mul(h as u64); + // The mosaic, its clip mask, the RGB frame, and the highlight rebuild's half-resolution + // pyramids (well under 16 bytes a pixel), next to the whole-frame demosaic's own buffers. + let ahd = method == craft_develop::sensor::Method::Ahd; + let rebuild = pixels.saturating_mul(4 + 1 + 12 + 16).saturating_add(shared_bayer_peak(w, h, h, ahd, 1, 1)); + // Then the RGB frame and the encoded output (and its oriented copy). + let encode = pixels.saturating_mul(if orient_copy { 24 } else { 18 }); + rebuild.max(encode).saturating_add((GAMMA_STEPS as u64 + 2) * 4) +} + +fn rebuild_fits(w: usize, h: usize, method: craft_develop::sensor::Method, orient_copy: bool, limits: &Limits) -> bool { + let need = rebuild_bytes(w, h, method, orient_copy); + need <= limits.max_alloc && usize::try_from(need).is_ok() +} + +/// The balanced RGB frame (interleaved) of a CFA mosaic with clipped samples, developed as +/// LightCraft does: demosaiced white-balanced and unclipped, then the channels that depend on +/// clipped samples rebuilt from nearby reliable colour with the shared clip mask. Fully clipped +/// areas come out neutral, partly clipped ones keep the colour around them. +fn develop_rebuilt( + w: usize, + h: usize, + band: usize, + cfa: craft_develop::sensor::Cfa, + method: craft_develop::sensor::Method, + mult: [f32; 3], + sensor_row: &(impl Fn(usize, &mut [f32]) + Sync), +) -> Vec { + use craft_develop::sensor::{self, highlight}; + let mut data = vec![0.0f32; w * h]; + par::chunks_mut(&mut data, band * w, |b, chunk| { + for (r, row) in chunk.chunks_exact_mut(w).enumerate() { + sensor_row(b * band + r, row); + } + }); + let mut n = sensor::Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + let mask = sensor::clip_mask(&n, sensor::Rect::new(0, 0, w, h), method, SENSOR_CLIP); + if let Some(cfa) = &n.cfa { + let cfa = cfa.clone(); + par::chunks_mut(&mut n.data, band * w, |b, chunk| { + for (r, row) in chunk.chunks_exact_mut(w).enumerate() { + for (x, v) in row.iter_mut().enumerate() { + *v *= mult[usize::from(cfa.color_at(x, b * band + r)).min(2)]; + } + } + }); + } + let mut rgb = sensor::demosaic(&n, method); + drop(n); + if let Some(mask) = mask { + let unbalance = |px: &mut [f32; 3], k: fn(f32, f32) -> f32| { + for c in 0..3 { + px[c] = k(px[c], mult[c]); + } + }; + rgb.data.iter_mut().for_each(|px| unbalance(px, |v, m| v / m)); + // Balanced camera RGB [1, 1, 1] is the colour model's white. + highlight::reconstruct_masked(&mut rgb, mult, SENSOR_CLIP, [1.0; 3], &mask); + rgb.data.iter_mut().for_each(|px| unbalance(px, |v, m| v * m)); + } + rgb.data.into_flattened() +} + /// How the frame is developed, for [`working_memory`]. #[derive(Clone, Copy)] struct Shape { @@ -1040,6 +1152,82 @@ mod tests { } } + /// A 48 x 48 RGGB sensor whose normalized samples are `scene(x, y)` for the CFA colour at + /// (x, y), developed with white-balance multipliers (2, 1, 2) and 2 EV under. + fn develop_scene(scene: impl Fn(usize, usize, usize) -> f32, method: Demosaic, fused: bool, limits: Option) -> Developed { + let (w, h) = (48, 48); + let mut s = test_sensor(w, h, crate::Cfa::bayer("RGGB"), 1); + let cfa = s.cfa.clone().unwrap(); + s.data = (0..w * h).map(|i| (64.0 + scene(i % w, i / w, usize::from(cfa.color(i % w, i / w))) * 3936.0).round() as u16).collect(); + let mut opts = DevelopOptions { demosaic: method, white_balance: WhiteBalance::Multipliers([2.0, 1.0, 2.0]), exposure: -2.0, ..Default::default() }; + if let Some(l) = limits { + opts.limits = l; + } + develop(&s, &opts, fused).unwrap() + } + + fn centre(d: &Developed) -> [u16; 3] { + let i = (24 * d.width as usize + 24) * 3; + [d.rgb[i], d.rgb[i + 1], d.rgb[i + 2]] + } + + #[test] + fn red_lifted_past_white_by_white_balance_keeps_its_measured_level() { + // Red measured at 0.8 of white is 1.6 after balance; 0.5 is exactly white. The sensor + // clipped neither, so the brighter red must stay brighter. + for method in [Demosaic::Ahd, Demosaic::Bilinear] { + for fused in [true, false] { + let red = |r: f32| develop_scene(move |_, _, c| if c == 0 { r } else { 0.2 }, method, fused, None); + let (bright, white) = (centre(&red(0.8)), centre(&red(0.5))); + assert!(bright[0] > white[0], "{method:?} fused {fused}: red {} not above {}", bright[0], white[0]); + } + } + } + + /// Green clipped by the sensor in a disc, red and blue measured below white there; a grey + /// surround. Returns the centre pixel and the development's warnings. + fn clipped_green_disc(method: Demosaic, fused: bool, limits: Option) -> ([u16; 3], Vec) { + let disc = |x: usize, y: usize| (x as f32 - 24.0).powi(2) + (y as f32 - 24.0).powi(2) < 100.0; + let d = develop_scene( + |x, y, c| match (disc(x, y), c) { + (true, 1) => 1.0, + (true, _) => 0.6, + (false, 1) => 0.4, + (false, _) => 0.2, + }, + method, + fused, + limits, + ); + (centre(&d), d.warnings) + } + + fn spread(p: [u16; 3]) -> f32 { + let (lo, hi) = (p.iter().min().copied().unwrap_or(0), p.iter().max().copied().unwrap_or(0)); + f32::from(hi - lo) / f32::from(hi.max(1)) + } + + #[test] + fn highlights_the_sensor_clipped_are_rebuilt_neutral() { + for method in [Demosaic::Ahd, Demosaic::Bilinear] { + for fused in [true, false] { + let (p, warnings) = clipped_green_disc(method, fused, None); + // Unclipped, the balanced disc is (1.2, 1, 1.2): magenta. + assert!(spread(p) < 0.03, "{method:?} fused {fused}: clipped green disc {p:?} is not neutral"); + assert!(!warnings.iter().any(|w| w.contains("not rebuilt")), "{method:?} fused {fused}: {warnings:?}"); + } + } + } + + #[test] + fn a_frame_too_large_to_rebuild_clips_after_white_balance_and_says_so() { + let need = rebuild_bytes(48, 48, craft_develop::sensor::Method::Bilinear, false); + let limits = Limits { max_alloc: need - 1, ..Limits::default() }; + let (p, warnings) = clipped_green_disc(Demosaic::Bilinear, false, Some(limits)); + assert!(warnings.iter().any(|w| w.contains("not rebuilt")), "{warnings:?}"); + assert!(spread(p) < 0.03, "clipped after balance, the disc stays neutral: {p:?}"); + } + #[test] fn fused_bayer_ahd_matches_full_frame_across_odd_strip_boundaries() { // Our in-code synthetic sensor is textured; this width yields 109-row bands, so From b8726d6e225a3b181b30e04db1e22f4767f64df2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:55:52 +0700 Subject: [PATCH 2/4] raw: rebless the Windows RAW Open baseline hashes from hosted CI Values from windows / test 4/6 of CI run 45325257093 (MSVC libm). Part of storytold/craft-libs#778 --- crates/io/tests/it/raw.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/io/tests/it/raw.rs b/crates/io/tests/it/raw.rs index 8c6225ebcc..17f3660016 100644 --- a/crates/io/tests/it/raw.rs +++ b/crates/io/tests/it/raw.rs @@ -739,8 +739,8 @@ fn raw_open_legacy_baseline_pixels() { // center pixel `[47838, 39368, 49721]` matches legacy bit-for-bit); `tuned_px`/`tuned_hash` reflects // the `craft_develop` cutover for `RawTuning` (`camera_raw::develop`). Whole-image hashes differ by // 1 LSB between MSVC and glibc `libm` float math on Windows. - let expected_def_hash = if cfg!(target_os = "windows") { 9_388_097_638_634_194_548 } else { 10_802_259_885_448_765_778 }; - let expected_tuned_hash = if cfg!(target_os = "windows") { 5_472_991_315_859_343_413 } else { 12_255_299_099_314_572_538 }; + let expected_def_hash = if cfg!(target_os = "windows") { 15_396_184_765_895_906_317 } else { 10_802_259_885_448_765_778 }; + let expected_tuned_hash = if cfg!(target_os = "windows") { 2_792_208_992_597_872_838 } else { 12_255_299_099_314_572_538 }; assert_eq!( (def_px, def_hash, wb, tuned_px, tuned_hash), ( @@ -809,7 +809,7 @@ fn raw_open_camera_wb_legacy_baseline_pixels() { // Default RAW Open (`def_px`/`def_hash`) runs `craft_develop::sensor::demosaic` (`reflect` borders; // center pixel `[51905, 40291, 54669]` matches legacy bit-for-bit); `tuned_px`/`tuned_hash` reflects // the `craft_develop` cutover for `RawTuning` (`camera_raw::develop`). - let expected_tuned_hash = if cfg!(target_os = "windows") { 16_896_394_607_103_456_502 } else { 8_451_299_581_473_829_420 }; + let expected_tuned_hash = if cfg!(target_os = "windows") { 6_427_926_143_910_930_207 } else { 8_451_299_581_473_829_420 }; assert_eq!( (def_px, def_hash, tuned_px, tuned_hash), ( From e75657ae557d825072852bf65ad8637a695dfb54 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:47:00 +0100 Subject: [PATCH 3/4] raw: answer the highlight-rebuild review (budget, CFA period, white) - The rebuild's memory admission counts the AHD tile scratch of every worker the whole-frame demosaic runs, not one; a frame that no longer fits keeps the clip-after-balance fallback and its warning. - `Cfa::is_bayer` requires an even period on both axes: a 3x2 RGR/GBG looked Bayer over two columns, and the rebuild then applied the green gain to a red sample at x = 3. - The rebuild's white is the balanced camera RGB the active colour model renders neutral (a camera look may tint [1, 1, 1]); models that already render [1, 1, 1] neutral keep it exactly, so existing output is unchanged. - Tests: the odd-strip AHD fixture stays below the sensor clip and says so; both clipped-disc tests require the disc brighter than its surround; new tests for the worker budget, the tinting look and the 3x2 CFA each fail without their fix. Part of storytold/craft-libs#778 --- crates/raw/src/develop.rs | 139 +++++++++++++++++++++++++++++++++----- crates/raw/src/sensor.rs | 5 +- 2 files changed, 125 insertions(+), 19 deletions(-) diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index 7c93de195a..204133acb0 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -483,7 +483,7 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result Result, cw: usize, ch: usize| craft_develop::sensor::Cfa { width: cw, height: ch, pattern: p, origin_x: 0, origin_y: 0 }; + let white = rebuild_white(&color::mul(&color::xyz_d50_to_prophoto(), &to_xyz)); let rebuilt = |method, cw, ch, p: Vec| { - develop_rebuilt(w, h, band, cfa_at(p, cw, ch), method, mult, &|iy, row| fill_with(iy, row, [1.0; 3], f32::INFINITY)) + develop_rebuilt((w, h), band, cfa_at(p, cw, ch), method, mult, white, &|iy, row| fill_with(iy, row, [1.0; 3], f32::INFINITY)) }; let names = |p: &[u8]| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect::(); if bayer && fused && shared { @@ -699,20 +700,21 @@ fn sensor_clipped(w: usize, h: usize, band: usize, sensor_row: &(impl Fn(usize, bands.contains(&true) } -/// Bytes [`develop_rebuilt`] holds at its peak, plus the encode that follows it. -fn rebuild_bytes(w: usize, h: usize, method: craft_develop::sensor::Method, orient_copy: bool) -> u64 { +/// Bytes [`develop_rebuilt`] holds at its peak, plus the encode that follows it, with +/// `workers` threads running the whole-frame demosaic's AHD tiles at once. +fn rebuild_bytes(w: usize, h: usize, method: craft_develop::sensor::Method, orient_copy: bool, workers: usize) -> u64 { let pixels = (w as u64).saturating_mul(h as u64); // The mosaic, its clip mask, the RGB frame, and the highlight rebuild's half-resolution // pyramids (well under 16 bytes a pixel), next to the whole-frame demosaic's own buffers. let ahd = method == craft_develop::sensor::Method::Ahd; - let rebuild = pixels.saturating_mul(4 + 1 + 12 + 16).saturating_add(shared_bayer_peak(w, h, h, ahd, 1, 1)); + let rebuild = pixels.saturating_mul(4 + 1 + 12 + 16).saturating_add(shared_bayer_peak(w, h, h, ahd, 1, workers.max(1))); // Then the RGB frame and the encoded output (and its oriented copy). let encode = pixels.saturating_mul(if orient_copy { 24 } else { 18 }); rebuild.max(encode).saturating_add((GAMMA_STEPS as u64 + 2) * 4) } -fn rebuild_fits(w: usize, h: usize, method: craft_develop::sensor::Method, orient_copy: bool, limits: &Limits) -> bool { - let need = rebuild_bytes(w, h, method, orient_copy); +fn rebuild_fits(w: usize, h: usize, method: craft_develop::sensor::Method, orient_copy: bool, limits: &Limits, workers: usize) -> bool { + let need = rebuild_bytes(w, h, method, orient_copy, workers); need <= limits.max_alloc && usize::try_from(need).is_ok() } @@ -721,12 +723,12 @@ fn rebuild_fits(w: usize, h: usize, method: craft_develop::sensor::Method, orien /// clipped samples rebuilt from nearby reliable colour with the shared clip mask. Fully clipped /// areas come out neutral, partly clipped ones keep the colour around them. fn develop_rebuilt( - w: usize, - h: usize, + (w, h): (usize, usize), band: usize, cfa: craft_develop::sensor::Cfa, method: craft_develop::sensor::Method, mult: [f32; 3], + white: [f32; 3], sensor_row: &(impl Fn(usize, &mut [f32]) + Sync), ) -> Vec { use craft_develop::sensor::{self, highlight}; @@ -757,13 +759,28 @@ fn develop_rebuilt( } }; rgb.data.iter_mut().for_each(|px| unbalance(px, |v, m| v / m)); - // Balanced camera RGB [1, 1, 1] is the colour model's white. - highlight::reconstruct_masked(&mut rgb, mult, SENSOR_CLIP, [1.0; 3], &mask); + highlight::reconstruct_masked(&mut rgb, mult, SENSOR_CLIP, white, &mask); rgb.data.iter_mut().for_each(|px| unbalance(px, |v, m| v * m)); } rgb.data.into_flattened() } +/// The white-balanced camera RGB that `to_prophoto` (balanced camera → linear ProPhoto) renders +/// neutral, at the brightness balanced `[1, 1, 1]` renders at: the `white` of the shared highlight +/// rebuild, so fully clipped highlights come out neutral under the active colour model. A model +/// that already renders `[1, 1, 1]` neutral (a calibration, the sRGB fallback, up to rounding) +/// keeps `[1, 1, 1]` exactly, as does a matrix with no inverse. +fn rebuild_white(to_prophoto: &Mat3) -> [f32; 3] { + let y_row = color::rgb_to_xyz(color::ROMM, color::D50_XY)[1]; + let rendered = color::apply(to_prophoto, [1.0; 3]); + let y = y_row[0] * rendered[0] + y_row[1] * rendered[1] + y_row[2] * rendered[2]; + let neutral = rendered.iter().all(|v| (v - y).abs() <= 1e-6 * y.abs()); + match color::invert(to_prophoto) { + Some(inv) if !neutral && y.is_finite() && y > 0.0 => color::apply(&inv, [y; 3]).map(|v| v as f32), + _ => [1.0; 3], + } +} + /// How the frame is developed, for [`working_memory`]. #[derive(Clone, Copy)] struct Shape { @@ -1185,8 +1202,8 @@ mod tests { } /// Green clipped by the sensor in a disc, red and blue measured below white there; a grey - /// surround. Returns the centre pixel and the development's warnings. - fn clipped_green_disc(method: Demosaic, fused: bool, limits: Option) -> ([u16; 3], Vec) { + /// surround. Returns the centre pixel, a surround pixel and the development's warnings. + fn clipped_green_disc(method: Demosaic, fused: bool, limits: Option) -> ([u16; 3], [u16; 3], Vec) { let disc = |x: usize, y: usize| (x as f32 - 24.0).powi(2) + (y as f32 - 24.0).powi(2) < 100.0; let d = develop_scene( |x, y, c| match (disc(x, y), c) { @@ -1199,7 +1216,14 @@ mod tests { fused, limits, ); - (centre(&d), d.warnings) + let i = (4 * d.width as usize + 4) * 3; + (centre(&d), [d.rgb[i], d.rgb[i + 1], d.rgb[i + 2]], d.warnings) + } + + /// The clipped disc is a highlight: every channel of it above every channel of the grey + /// surround, so a path that turns it black (or dark) fails even though black has no spread. + fn brighter_than(p: [u16; 3], surround: [u16; 3]) -> bool { + p.iter().min() > surround.iter().max() } fn spread(p: [u16; 3]) -> f32 { @@ -1211,9 +1235,10 @@ mod tests { fn highlights_the_sensor_clipped_are_rebuilt_neutral() { for method in [Demosaic::Ahd, Demosaic::Bilinear] { for fused in [true, false] { - let (p, warnings) = clipped_green_disc(method, fused, None); + let (p, surround, warnings) = clipped_green_disc(method, fused, None); // Unclipped, the balanced disc is (1.2, 1, 1.2): magenta. assert!(spread(p) < 0.03, "{method:?} fused {fused}: clipped green disc {p:?} is not neutral"); + assert!(brighter_than(p, surround), "{method:?} fused {fused}: clipped green disc {p:?} not above the surround {surround:?}"); assert!(!warnings.iter().any(|w| w.contains("not rebuilt")), "{method:?} fused {fused}: {warnings:?}"); } } @@ -1221,11 +1246,85 @@ mod tests { #[test] fn a_frame_too_large_to_rebuild_clips_after_white_balance_and_says_so() { - let need = rebuild_bytes(48, 48, craft_develop::sensor::Method::Bilinear, false); + let need = rebuild_bytes(48, 48, craft_develop::sensor::Method::Bilinear, false, 1); let limits = Limits { max_alloc: need - 1, ..Limits::default() }; - let (p, warnings) = clipped_green_disc(Demosaic::Bilinear, false, Some(limits)); + let (p, surround, warnings) = clipped_green_disc(Demosaic::Bilinear, false, Some(limits)); assert!(warnings.iter().any(|w| w.contains("not rebuilt")), "{warnings:?}"); assert!(spread(p) < 0.03, "clipped after balance, the disc stays neutral: {p:?}"); + assert!(brighter_than(p, surround), "clipped after balance, the disc {p:?} stays above the surround {surround:?}"); + } + + /// A 2048 x 128 RGGB frame with a sensor-clipped stripe, developed AHD on `threads` workers + /// under `limits`; returns the warnings. + fn clipped_wide_ahd_warnings(threads: usize, limits: Limits) -> Vec { + let (w, h) = (2048, 128); + let mut s = test_sensor(w, h, crate::Cfa::bayer("RGGB"), 1); + s.data = (0..w * h).map(|i| if (60..68).contains(&(i / w)) { 4000 } else { 1000 }).collect(); + let opts = DevelopOptions { demosaic: Demosaic::Ahd, white_balance: WhiteBalance::Multipliers([2.0, 1.0, 2.0]), limits, ..Default::default() }; + with_threads(threads, || develop(&s, &opts, false).unwrap()).warnings + } + + #[test] + fn the_rebuild_budget_counts_the_ahd_tiles_of_every_worker() { + // Enough for the rebuild when one worker runs the AHD tiles; 16 workers each hold a tile's + // scratch at once, so the same limit must refuse the rebuild and clip after balance. + let one = rebuild_bytes(2048, 128, craft_develop::sensor::Method::Ahd, false, 1); + let limits = Limits { max_alloc: one, ..Limits::default() }; + let refused = |w: &[String]| w.iter().any(|w| w.contains("not rebuilt")); + let single = clipped_wide_ahd_warnings(1, limits); + assert!(!refused(&single), "one worker fits: {single:?}"); + let many = clipped_wide_ahd_warnings(16, limits); + assert!(refused(&many), "16 workers' tile scratch exceeds the limit: {many:?}"); + } + + #[test] + fn fully_clipped_highlights_stay_neutral_under_a_look_that_tints_camera_white() { + // A look that renders balanced camera [1, 1, 1] as ProPhoto [1, 0.5, 1]: a magenta cast if + // the rebuild takes [1, 1, 1] as white. Exposure is 2 EV under, so the disc is not clamped. + let (w, h) = (48, 48); + let mut s = test_sensor(w, h, crate::Cfa::bayer("RGGB"), 1); + let disc = |x: usize, y: usize| (x as f32 - 24.0).powi(2) + (y as f32 - 24.0).powi(2) < 100.0; + s.data = (0..w * h).map(|i| if disc(i % w, i / w) { 4000 } else { 1000 }).collect(); + let tint = [[1.0, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 1.0]]; + let to_xyz = color::mul(&color::invert(&color::xyz_d50_to_prophoto()).unwrap(), &tint); + let look = CameraLook { to_xyz, tone: None, delta_e: 1.0, delta_e_fallback: 2.0 }; + let opts = DevelopOptions { white_balance: WhiteBalance::Multipliers([2.0, 1.0, 2.0]), exposure: -2.0, camera_look: Some(look), ..Default::default() }; + for method in [Demosaic::Ahd, Demosaic::Bilinear] { + for fused in [true, false] { + let d = develop(&s, &DevelopOptions { demosaic: method, ..opts.clone() }, fused).unwrap(); + let p = centre(&d); + assert!(spread(p) < 0.03, "{method:?} fused {fused}: fully clipped disc {p:?} is not neutral"); + } + } + } + + #[test] + fn an_odd_period_cfa_is_not_developed_as_bayer() { + // `RGR/GBG`: Bayer over its first two columns, red again at column 3 where a 2×2 period has + // green. Each colour is measured at the level its white-balance gain brings to the same + // grey, so a right development is grey, with and without a sensor-clipped spot. + let cfa = crate::Cfa { width: 3, height: 2, colors: vec![0, 1, 0, 1, 2, 1], origin_x: 0, origin_y: 0 }; + assert!(!cfa.is_bayer()); + let (w, h) = (48, 48); + let mult = [2.0f32, 1.0, 1.5]; + for spot in [false, true] { + let mut s = test_sensor(w, h, Some(cfa.clone()), 1); + s.data = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let level = if spot && x >= 40 && y >= 40 { 1.0 } else { 0.4 / mult[usize::from(cfa.color(x, y))] }; + (64.0 + level * 3936.0).round() as u16 + }) + .collect(); + for method in [Demosaic::Ahd, Demosaic::Bilinear] { + let opts = + DevelopOptions { demosaic: method, white_balance: WhiteBalance::Multipliers(mult.map(f64::from)), exposure: -1.0, ..Default::default() }; + let d = develop(&s, &opts, false).unwrap(); + let i = (12 * d.width as usize + 12) * 3; + let p = [d.rgb[i], d.rgb[i + 1], d.rgb[i + 2]]; + assert!(spread(p) < 0.03, "{method:?} spot {spot}: balanced grey {p:?} is not grey"); + } + } } #[test] @@ -1235,6 +1334,12 @@ mod tests { // edges as well as the internal seams rather than trimming the compared output. let (w, h) = (600, 350); let mut s = test_sensor(w, h, crate::Cfa::bayer("RGGB"), 1); + // Keep the texture below the sensor clip, so the fused path stays on its strips instead of + // rebuilding the whole frame (which would compare two whole-frame renders). + for v in &mut s.data { + *v = 64 + (*v - 64) * 3 / 4; + } + assert!(s.data.iter().all(|&v| (f32::from(v) - 64.0) / 3936.0 < SENSOR_CLIP), "the fixture must not be sensor-clipped"); s.color.calibrations.push(color::Calibration { temperature: 6500.0, color_matrix: [[0.61, 0.23, 0.16], [0.18, 0.73, 0.09], [0.07, 0.16, 0.77]], diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rs index e0d106ff75..b1c55b4449 100644 --- a/crates/raw/src/sensor.rs +++ b/crates/raw/src/sensor.rs @@ -80,9 +80,10 @@ impl Cfa { } /// `true` for a Bayer pattern: a 2×2 period holding one red, one blue and two - /// diagonal greens. + /// diagonal greens. The declared period must be even on both axes: a `3×2` `RGR/GBG` + /// looks Bayer over its first two columns but wraps to red where a 2×2 period has green. pub fn is_bayer(&self) -> bool { - if self.width == 0 || self.height == 0 || self.width > 16 || self.height > 16 { + if self.width == 0 || self.height == 0 || self.width > 16 || self.height > 16 || !self.width.is_multiple_of(2) || !self.height.is_multiple_of(2) { return false; } let (ox, oy) = (self.origin_x % self.width, self.origin_y % self.height); From f7fe0b1c89a5c25fa3d0167944cb3afc880fc9d5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:13:12 +0100 Subject: [PATCH 4/4] raw: tell sensor clipping before lens shading; native-only worker test - `sensor_clipped` and the rebuild's clip mask read the measured sample before the DNG gain map: a gain above one no longer makes an unclipped sample count as clipped, and a gain below one no longer hides a sample the sensor clipped. The rebuild applies the gain map after the mask, before white balance; the clamped path is unchanged. - The worker-budget test runs only where `with_threads` can size a pool (not wasm32). - New test: a sensor-clipped green disc under a 0.8 gain map is rebuilt neutral (fails without the fix: [28740, 27176, 29334]). Part of storytold/craft-libs#778 --- crates/raw/src/develop.rs | 62 ++++++++++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs index 204133acb0..a51287ee38 100644 --- a/crates/raw/src/develop.rs +++ b/crates/raw/src/develop.rs @@ -405,7 +405,8 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result Result Result craft_develop::sensor::Method::Ahd, }; let shared = matches!(opts.demosaic, Demosaic::Bilinear | Demosaic::Ahd); - let clipped = shared && sensor_clipped(w, h, band, &|iy, row| fill_with(iy, row, [1.0; 3], f32::INFINITY)); + // Whether the sensor clipped is told from the measured sample, before lens shading lifts or lowers it. + let clipped = shared && sensor_clipped(w, h, band, &|iy, row| fill_raw(iy, row, [1.0; 3], f32::INFINITY)); let rebuild = if clipped { let method = if bayer { shared_method } else { craft_develop::sensor::Method::Bilinear }; if rebuild_fits(w, h, method, orient_copy, &opts.limits, par::workers()) { @@ -497,7 +505,9 @@ fn develop(s: &Sensor, opts: &DevelopOptions, allow_fused: bool) -> Result, cw: usize, ch: usize| craft_develop::sensor::Cfa { width: cw, height: ch, pattern: p, origin_x: 0, origin_y: 0 }; let white = rebuild_white(&color::mul(&color::xyz_d50_to_prophoto(), &to_xyz)); let rebuilt = |method, cw, ch, p: Vec| { - develop_rebuilt((w, h), band, cfa_at(p, cw, ch), method, mult, white, &|iy, row| fill_with(iy, row, [1.0; 3], f32::INFINITY)) + develop_rebuilt((w, h), band, cfa_at(p, cw, ch), method, (mult, white), &|iy, row| fill_raw(iy, row, [1.0; 3], f32::INFINITY), &|iy, row| { + shade(iy, row, f32::INFINITY) + }) }; let names = |p: &[u8]| p.iter().map(|c| ['R', 'G', 'B'][usize::from(*c).min(2)]).collect::(); if bayer && fused && shared { @@ -727,9 +737,9 @@ fn develop_rebuilt( band: usize, cfa: craft_develop::sensor::Cfa, method: craft_develop::sensor::Method, - mult: [f32; 3], - white: [f32; 3], + (mult, white): ([f32; 3], [f32; 3]), sensor_row: &(impl Fn(usize, &mut [f32]) + Sync), + shade_row: &(impl Fn(usize, &mut [f32]) + Sync), ) -> Vec { use craft_develop::sensor::{self, highlight}; let mut data = vec![0.0f32; w * h]; @@ -739,11 +749,13 @@ fn develop_rebuilt( } }); let mut n = sensor::Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + // Clipping is told from the measured samples; lens shading then scales them. let mask = sensor::clip_mask(&n, sensor::Rect::new(0, 0, w, h), method, SENSOR_CLIP); if let Some(cfa) = &n.cfa { let cfa = cfa.clone(); par::chunks_mut(&mut n.data, band * w, |b, chunk| { for (r, row) in chunk.chunks_exact_mut(w).enumerate() { + shade_row(b * band + r, row); for (x, v) in row.iter_mut().enumerate() { *v *= mult[usize::from(cfa.color_at(x, b * band + r)).min(2)]; } @@ -1264,6 +1276,40 @@ mod tests { with_threads(threads, || develop(&s, &opts, false).unwrap()).warnings } + #[test] + fn a_sensor_clipped_highlight_is_rebuilt_even_where_lens_shading_lowers_it() { + // Green clipped by the sensor in a disc, under a 0.8 gain map: after shading the disc's + // green is 0.8, below the clip level. Clipping is told from the measured sample, so the + // disc is still rebuilt neutral instead of keeping its balanced magenta (1.2, 1, 1.2). + use crate::testgen::{DngSpec, gain_map_opcode_list}; + let (w, h) = (48usize, 48usize); + let disc = |x: usize, y: usize| (x as f32 - 24.0).powi(2) + (y as f32 - 24.0).powi(2) < 100.0; + let data = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let green = x.is_multiple_of(2) != y.is_multiple_of(2); + let level = match (disc(x, y), green) { + (true, true) => 1.0, + (true, false) => 0.6, + (false, true) => 0.4, + (false, false) => 0.2, + }; + (level * 65535.0f64).round() as u16 + }) + .collect(); + let mut spec = DngSpec::cfa(w, h, data); + spec.opcode_list2 = Some(gain_map_opcode_list([0, 0, h as u32, w as u32], 1, [[0.8, 0.8], [0.8, 0.8]])); + let opts = DevelopOptions { white_balance: WhiteBalance::Multipliers([2.0, 1.0, 2.0]), exposure: -2.0, ..Default::default() }; + let sensor = crate::decode(&spec.build(), &opts.limits).unwrap(); + assert_eq!(sensor.gain_maps.len(), 1); + for method in [Demosaic::Ahd, Demosaic::Bilinear] { + let p = centre(&develop(&sensor, &DevelopOptions { demosaic: method, ..opts.clone() }, false).unwrap()); + assert!(spread(p) < 0.03, "{method:?}: sensor-clipped disc under lens shading {p:?} is not neutral"); + } + } + + // `with_threads` cannot size a pool on wasm32. + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_rebuild_budget_counts_the_ahd_tiles_of_every_worker() { // Enough for the rebuild when one worker runs the AHD tiles; 16 workers each hold a tile's