Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 53 additions & 9 deletions crates/engine/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,19 @@ pub(crate) struct CameraColourModel<'a> {
impl CameraColourModel<'_> {
/// Rebuild sensor-clipped channels; fully clipped highlights become [`clipped_white`] of the matrix, so they
/// come out of [`Self::apply`] neutral.
#[cfg(test)]
pub fn rebuild_highlights(&self, img: &mut Rgb32f) {
lightcraft_raw::highlight::reconstruct_with(img, self.wb, HIGHLIGHT_CLIP, clipped_white(&self.matrix));
self.rebuild_highlights_masked(img, None);
}

/// [`Self::rebuild_highlights`]; with `mask`, a binned image's clip mask
/// ([`lightcraft_raw::RawImage::develop_binned_masked`]) tells the clipped channels.
pub fn rebuild_highlights_masked(&self, img: &mut Rgb32f, mask: Option<&[u8]>) {
let white = clipped_white(&self.matrix);
match mask {
Some(mask) => lightcraft_raw::highlight::reconstruct_masked(img, self.wb, HIGHLIGHT_CLIP, white, mask),
None => lightcraft_raw::highlight::reconstruct_with(img, self.wb, HIGHLIGHT_CLIP, white),
};
}

/// White balance, matrix, tables and baseline exposure, in place.
Expand Down Expand Up @@ -319,8 +330,9 @@ pub fn load_vec_pair(bytes: Vec<u8>, max_edge: usize, spec: &DenoiseSpec) -> Res
}

/// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default
/// crop, and `factor` × `factor` blocks averaged into one pixel when the plain one was binned. `None` when the product
/// is missing, damaged, made from something else or not the size of this raw's active area.
/// crop, and `factor` × `factor` blocks averaged into one pixel when the plain one was binned (plain means: the plain
/// development's clip mask tells highlight reconstruction which of them held clipped samples). `None` when the
/// product is missing, damaged, made from something else or not the size of this raw's active area.
fn denoised_camera_rgb(raw: &lightcraft_raw::RawImage, spec: &DenoiseSpec, factor: usize) -> Option<Rgb32f> {
use lightcraft_denoise::product::{self, Window};
let a = raw.active_area;
Expand All @@ -331,7 +343,7 @@ fn denoised_camera_rgb(raw: &lightcraft_raw::RawImage, spec: &DenoiseSpec, facto
if raw.opcodes.list3.is_empty() {
let c = raw.develop_crop(a.width, a.height);
let window = Window { x: c.x, y: c.y, width: c.width, height: c.height };
product::read_window(&spec.product, &spec.key, Some(window), factor, Some(HIGHLIGHT_CLIP)).ok()
product::read_window(&spec.product, &spec.key, Some(window), factor, None).ok()
} else {
// (the plain development is not binned either when the file has opcodes of this kind: `factor` is 1)
let whole = product::read(&spec.product, &spec.key, 1).ok()?;
Expand Down Expand Up @@ -368,16 +380,17 @@ fn load_bytes_now(
// larger levels (exports, 1:1) demosaic the whole sensor.
let t0 = web_time::Instant::now();
let bin = bin_factor(&raw, max_edge);
// (binned: block means, and which colours had a clipped sample in each block)
let binned = match bin {
Some(k) => raw.develop_binned(k, HIGHLIGHT_CLIP).map_err(|e| e.to_string())?,
Some(k) => raw.develop_binned_masked(k, HIGHLIGHT_CLIP).map_err(|e| e.to_string())?,
None => None,
};
let factor = if binned.is_some() { bin.unwrap_or(1) } else { 1 };
let img = match binned {
Some(img) => img,
let (img, clip_mask) = match binned {
Some((img, mask)) => (img, Some(mask)),
None => {
let method = if max_edge <= 600 { lightcraft_raw::Method::Bilinear } else { lightcraft_raw::Method::Ahd };
raw.develop(method).map_err(|e| e.to_string())?
(raw.develop(method).map_err(|e| e.to_string())?, None)
}
};
// the same development from the denoised mosaic, when the photo has been denoised
Expand All @@ -399,7 +412,7 @@ fn load_bytes_now(
let finish = |mut img: Rgb32f| {
let mut stages = vec![("develop", t0.elapsed())];
stages.push(("transform", t0.elapsed()));
colour.rebuild_highlights(&mut img);
colour.rebuild_highlights_masked(&mut img, clip_mask.as_deref());
stages.push(("highlights", t0.elapsed()));
colour.apply(&mut img);
stages.push(("colour", t0.elapsed()));
Expand Down Expand Up @@ -708,6 +721,37 @@ mod tests {
assert!(probe_bytes("x.jpg", b"not an image").is_err());
}

/// Issue #548: a small preview bins the mosaic by 8; specular points that clip a single green sample
/// of a block on a grey surface must not become green speckles (the block's green used to take the
/// clip level, which highlight reconstruction then kept).
#[test]
fn coarse_binning_keeps_specular_points_neutral() {
let (w, h) = (256usize, 192usize);
// grey after the file's white balance (as-shot neutral 0.5 : 1 : 0.7), brighter to the right
let neutral = [0.5f32, 1.0, 0.7];
let cfa = lightcraft_raw::Cfa::bayer("RGGB").unwrap();
let mut data: Vec<u16> = (0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
let v = (0.3 + 0.2 * x as f32 / w as f32) * neutral[cfa.color_at(x, y).min(2) as usize];
(256.0 + v * (16000.0 - 256.0)).round() as u16
})
.collect();
// one clipped green sample (RGGB: even row, odd column) in every other 8 × 8 block
for by in 0..h / 8 {
for bx in (by % 2..w / 8).step_by(2) {
data[(by * 8 + 4) * w + bx * 8 + 5] = 16000;
}
}
let bytes = crate::tests_xmp::synthetic_dng_of(w, h, "RGGB", data, None, Default::default());
let raw = lightcraft_raw::decode(&bytes).unwrap();
assert_eq!(bin_factor(&raw, 32), Some(8));
let (img, _) = load_bytes(&bytes, 32).unwrap();
assert_eq!((img.width, img.height), (32, 24));
let worst = img.data.iter().map(|p| p[1] / ((p[0] + p[2]) / 2.0).max(1e-6)).fold(0.0f32, f32::max);
assert!(worst < 1.12, "green speckles: green {worst:.2}× the other channels");
}

#[test]
fn cached_denoise_uses_the_same_white_balance_profile_and_orientation_as_plain_raw() {
use lightcraft_denoise::product;
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl SettingsHashes {
}

/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 37;
pub const RENDER_CACHE_VERSION: u64 = 42;

/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
Expand Down
72 changes: 65 additions & 7 deletions crates/raw/src/binned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@
//! interpolation, so there are no demosaicing artefacts; the colour planes are offset by less than
//! one output pixel, which is invisible at these scales.
//!
//! Clipping is preserved for [`crate::highlight::reconstruct`]: a channel whose block contains a
//! sample at or above `clip` takes that block's maximum sample of the colour (instead of a mean that
//! would fall just below the clip level and escape reconstruction).
//! Clipping is decided per sample, before averaging. [`RawImage::develop_binned_masked`] keeps every
//! channel the mean of its samples and says, per output pixel, which colours had a sample at or above
//! `clip` (for [`crate::highlight::reconstruct_masked`], which rebuilds them with the mean as a lower
//! bound). A specular point that clips one green sample of the 32 in an 8 × 8 block thus counts as
//! partly clipped without the block's green jumping to the clip level, which would read as a green
//! speckle once reconstructed. [`RawImage::develop_binned`] instead gives such a channel the block's
//! maximum sample of the colour, so that plain value thresholds see it as clipped.

use crate::{Normalized, RawData, RawImage, Result, Rgb32f};
use rayon::prelude::*;
Expand All @@ -31,6 +35,19 @@ impl RawImage {
/// not oriented). `None` when the data cannot be binned ([`RawImage::can_bin`]) or carries an
/// `OpcodeList3` (whose operations are defined at full resolution); callers then demosaic.
pub fn develop_binned(&self, k: usize, clip: f32) -> Result<Option<Rgb32f>> {
Ok(self.bin(k, clip, true)?.map(|(img, _)| img))
}

/// Like [`RawImage::develop_binned`], with every channel the mean of its block's samples, and the
/// clip mask: per output pixel, bits [`crate::highlight::CLIPPED_R`] / `_G` / `_B` for the colours
/// with a sample at or above `clip` in the block. Hand both to [`crate::highlight::reconstruct_masked`].
pub fn develop_binned_masked(&self, k: usize, clip: f32) -> Result<Option<(Rgb32f, Vec<u8>)>> {
self.bin(k, clip, false)
}

/// The binned image and its clip mask; `keep_max`: a channel with a clipped sample takes the
/// block's maximum sample of the colour instead of the mean.
fn bin(&self, k: usize, clip: f32, keep_max: bool) -> Result<Option<(Rgb32f, Vec<u8>)>> {
self.validate()?;
if !self.can_bin(k) || !self.opcodes.list3.is_empty() {
return Ok(None);
Expand Down Expand Up @@ -63,7 +80,8 @@ impl RawImage {
.collect();
let wlen = bw * k;
let mut out = Rgb32f::new(bw, bh);
out.data.par_chunks_mut(bw).enumerate().for_each(|(by, row)| {
let mut mask = vec![0u8; bw * bh];
out.data.par_chunks_mut(bw).zip(mask.par_chunks_mut(bw)).enumerate().for_each(|(by, (row, mrow))| {
// the block row's k sample rows, normalised
let mut rows = vec![0f32; k * wlen];
for dy in 0..k {
Expand All @@ -86,7 +104,7 @@ impl RawImage {
}
}
let py = (c.y + by * k) % ph;
for (bx, px) in row.iter_mut().enumerate() {
for (bx, (px, m)) in row.iter_mut().zip(mrow.iter_mut()).enumerate() {
let (layout, inv) = &layouts[py * pw + (c.x + bx * k) % pw];
let (mut sum, mut max) = ([0f32; 3], [f32::MIN; 3]);
for dy in 0..k {
Expand All @@ -98,11 +116,13 @@ impl RawImage {
}
}
for ch in 0..3 {
px[ch] = if max[ch] >= clip { max[ch] } else { sum[ch] * inv[ch] };
let clipped = max[ch] >= clip;
px[ch] = if clipped && keep_max { max[ch] } else { sum[ch] * inv[ch] };
*m |= u8::from(clipped) << ch;
}
}
});
Ok(Some(out))
Ok(Some((out, mask)))
}
}

Expand Down Expand Up @@ -177,6 +197,44 @@ mod tests {
assert!((xb.get(4, 3)[2] - 0.3).abs() < 2e-3);
}

/// Issue #548: specular points that clip one green sample in some 8 × 8 blocks of a grey surface.
/// Taking the block's maximum makes those blocks' green the clip level, which reconstruction then
/// keeps (a green speckle); the masked binning keeps the mean and marks the green as clipped.
#[test]
fn clipping_is_decided_before_averaging() {
let img = Rgb32f::filled(64, 64, [0.3, 0.3, 0.3]);
let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0);
if let RawData::U16(d) = &mut raw.data {
// one green sample (RGGB: odd column of an even row) in every other block
for by in 0..8 {
for bx in (by % 2..8).step_by(2) {
d[(by * 8 + 2) * 64 + bx * 8 + 3] = 4095;
}
}
}
let wb = [1.0f32; 3];
let (mut masked, mask) = raw.develop_binned_masked(8, 0.99).unwrap().unwrap();
assert_eq!(mask.len(), 64);
assert_eq!(mask.iter().filter(|&&m| m == highlight::CLIPPED_G).count(), 32);
assert!(mask.iter().all(|&m| m & (highlight::CLIPPED_R | highlight::CLIPPED_B) == 0));
// the clipped block's green is its mean: (31 · 0.3 + 1) / 32
assert!((masked.get(0, 0)[1] - (31.0 * 0.3 + 1.0) / 32.0).abs() < 1e-3, "{:?}", masked.get(0, 0));
assert_eq!(highlight::reconstruct_masked(&mut masked, wb, 0.99, [1.0; 3], &mask), 32);
let green = |img: &Rgb32f| img.data.iter().map(|p| p[1] / p[0]).fold(0.0f32, f32::max);
// (no more than the mean itself: the clipped sample counts at the clip level)
assert!(green(&masked) < 1.08, "green excess {}", green(&masked));
// the maximum rule: a green speckle at the clip level
let mut max = raw.develop_binned(8, 0.99).unwrap().unwrap();
assert!(max.get(0, 0)[1] >= 0.99);
highlight::reconstruct(&mut max, wb, 0.99);
assert!(green(&max) > 3.0, "{}", green(&max));
// without clipped samples both are the same plain means, and the mask is empty
let clean = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0);
let (a, m) = clean.develop_binned_masked(8, 0.99).unwrap().unwrap();
assert!(m.iter().all(|&v| v == 0));
assert!(a.data == clean.develop_binned(8, 0.99).unwrap().unwrap().data);
}

#[test]
fn binning_matches_demosaic_downscaled_on_smooth_images() {
let img = Rgb32f::from_fn(64, 48, |x, y| [0.2 + 0.3 * (x as f32 / 64.0), 0.4 - 0.2 * (y as f32 / 48.0), 0.25]);
Expand Down
Loading