Merge pull request #2278 from robmdunn/raw-negative-channels

LR-PROF-CAMERACOLOR: raw decoding keeps negative channels
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 14:25:47 +01:00
commit 5a193b63b7
10 files changed
+294 -3

No files matched your search

+108
View File
@@ -1526,6 +1526,114 @@ fn export_weights_follow_the_source_and_output_sizes() {
assert!(render_weight(usize::MAX, 1, SourceLevel::Full, usize::MAX) > 0, "no overflow");
}
/// A raw's linear Rec.2020 near black as decoding leaves it since it stopped clamping channels at zero: a flat dark
/// patch with sensor noise through a saturating camera matrix (a NIKON D780 profile's), so many channels are
/// negative, and a few strongly out-of-gamut pixels. `clamped` is the same frame as decoding left it before.
fn dark_frame_with_negative_channels(clamped: bool) -> lightcraft_raster::Rgb32f {
let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]];
// ±0.004 of noise per channel, a hash of the position
let noise = |x: usize, y: usize, c: usize| {
let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761);
(h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004
};
lightcraft_raster::Rgb32f::from_fn(192, 128, |x, y| {
let rgb = if (x * 3 + y) % 97 == 0 {
[-0.05, 0.01, -0.02]
} else {
let cam: [f32; 3] = std::array::from_fn(|c| 0.002 + noise(x, y, c));
std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2])
};
if clamped { rgb.map(|v: f32| v.max(0.0)) } else { rgb }
})
}
/// Exports `src` pushed +4 EV at half its size, rendered as an export renders it (the options' depth and colour
/// space, a separate HDR render for a gain map JPEG) and written by the export's own encoders.
fn export_dark_frame(src: &lightcraft_raster::Rgb32f, o: &ExportOptions) -> Vec<u8> {
let info = lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() };
let mut s = lightcraft_develop::DevelopSettings::default();
s.light.exposure = 4.0;
s.hdr.enabled = o.hdr;
let render = |depth| {
let req = lightcraft_pipeline::RenderRequest { depth, space: o.effective_space(), ..lightcraft_pipeline::RenderRequest::fit(96, 96) };
lightcraft_pipeline::render(src, &info, &s, &req)
};
let r = render(o.effective_depth());
if o.hdr_output() && o.format == ExportFormat::Jpeg {
let hdr = render(OutputDepth::F32Hdr).deep.expect("an HDR render has float samples");
encode_gain_map_jpeg(&r.image, &hdr, o, None).unwrap()
} else {
encode_rendered(&r, o, None).unwrap()
}
}
/// Mean 8-bit sRGB of a decoded export.
fn mean_srgb8(d: &lightcraft_codecs::Decoded) -> [f64; 3] {
let img = d.to_srgb8();
let n = img.data.len().max(1) as f64;
std::array::from_fn(|c| img.data.iter().map(|p| f64::from(p[c])).sum::<f64>() / n)
}
/// Negative channels from decoding reach the export encoders: a dark frame pushed +4 EV exports in every rendered
/// format, depth and HDR mode as a file that decodes to the right size with finite samples (AVIF, which LightCraft
/// can't decode, and the linear DNG are checked for their structure), and comes out less tinted than the same frame
/// with its channels clamped at decoding. (At full size the white-balance clamp before noise reduction still zeroes
/// them, #2598; the half-size export averages them first.)
#[test]
fn dark_frame_with_negative_channels_exports_in_every_format() {
let src = dark_frame_with_negative_channels(false);
assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives");
let cases = [
(ExportFormat::Jpeg, None, false),
(ExportFormat::Jpeg, None, true),
(ExportFormat::Png, Some(8), false),
(ExportFormat::Png, Some(16), false),
(ExportFormat::Png, None, true),
(ExportFormat::Tiff, Some(8), false),
(ExportFormat::Tiff, Some(16), false),
(ExportFormat::Tiff, Some(32), false),
(ExportFormat::Tiff, Some(32), true),
(ExportFormat::Psd, Some(8), false),
(ExportFormat::Psd, Some(16), false),
(ExportFormat::Webp, None, false),
(ExportFormat::Avif, Some(8), false),
(ExportFormat::Avif, Some(10), false),
(ExportFormat::Avif, None, true),
(ExportFormat::Jxl, Some(8), false),
(ExportFormat::Jxl, Some(16), false),
(ExportFormat::Jxl, None, true),
(ExportFormat::RenderedDng, None, false),
(ExportFormat::RenderedDng, None, true),
];
for (format, bit_depth, hdr) in cases {
let what = format!("{format:?}, {bit_depth:?} bits, HDR {hdr}");
let bytes = export_dark_frame(&src, &ExportOptions { format, bit_depth, hdr, ..Default::default() });
match format {
ExportFormat::Avif => assert_eq!(bytes.get(4..8), Some(&b"ftyp"[..]), "{what}"),
ExportFormat::RenderedDng => {
let dng = lightcraft_raw::decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!((dng.width, dng.height), (96, 64), "{what}");
}
_ => {
let d = lightcraft_codecs::decode(&bytes, Default::default()).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!((d.width, d.height), (96, 64), "{what}");
assert!(d.image.data.iter().flatten().all(|v| v.is_finite()), "{what}: non-finite samples");
if format == ExportFormat::Jpeg && hdr {
let gm = lightcraft_codecs::gainmap::read_jpeg(&bytes).unwrap_or_else(|| panic!("{what}: no gain map"));
assert!(gm.meta.alternate_headroom.is_finite(), "{what}: gain map headroom");
}
}
}
}
let jpeg = ExportOptions::default();
let tint = |src| {
let m = mean_srgb8(&lightcraft_codecs::decode(&export_dark_frame(src, &jpeg), Default::default()).unwrap());
m.iter().copied().fold(f64::MIN, f64::max) - m.iter().copied().fold(f64::MAX, f64::min)
};
let (kept, clamped) = (tint(&src), tint(&dark_frame_with_negative_channels(true)));
assert!(kept < clamped / 2.0, "kept negatives tint the export by {kept:.1} codes, clamped ones by {clamped:.1}");
}
/// A catalog's file name never adds a folder level through the empty-naming fallback or the original's extension.
#[test]
fn file_name_fallback_and_extension_are_one_path_component() {
+14 -2
View File
@@ -84,7 +84,7 @@ impl CameraColourModel<'_> {
}
let out = hue_sat.apply_lanes(rgb);
for (l, p) in chunk.iter_mut().enumerate() {
*p = [out[0][l], out[1][l], out[2][l]].map(|v| v.max(0.0));
*p = finite([out[0][l], out[1][l], out[2][l]]);
}
}
});
@@ -106,10 +106,22 @@ impl CameraColourModel<'_> {
Some(tables) => tables.apply(rgb, gain),
None => rgb.map(|v| v * gain),
};
self.hue_sat.map_or(rgb, |h| h.apply(rgb)).map(|v| v.max(0.0))
finite(self.hue_sat.map_or(rgb, |h| h.apply(rgb)))
}
}
/// `rgb` (linear Rec.2020) as decoding leaves it for the stages after: negative channels kept, non-finite ones zero.
/// Near black, negative channels are sensor noise through the colour matrix, and keeping them keeps the noise zero-mean
/// until noise reduction and the output's gamut mapping (which moves a colour toward its luminance until it is in
/// range) deal with it. Clamping each channel at zero here kept only the positive half of every channel's noise:
/// through a saturating camera matrix (red row 3.5, −2.4, −0.1 on a NIKON D780 profile) red and blue have the widest
/// noise, so pushed shadows and dark frames came out magenta (a black frame pushed 4 EV rendered at sRGB (64, 28, 65)
/// in its darkest 40%, (2, 4, 4) without the clamp). Moving each such colour toward its luminance instead still left
/// it pink, at (34, 14, 22): any per-pixel rule that treats pixels by the sign of their noise biases the mean.
fn finite(rgb: [f32; 3]) -> [f32; 3] {
rgb.map(|v| if v.is_finite() { v } else { 0.0 })
}
/// Remove Hot Pixels leaves a raw alone when more than this share of its photosites would be replaced (Settings ▸
/// Performance ▸ Hot pixel limit, `app.hotPixelLimit`), as `f64` bits. Process-wide, like the GPU switch.
static HOT_PIXEL_LIMIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(lightcraft_raw::HOT_PIXEL_MAX_SHARE.to_bits());
+34
View File
@@ -1235,6 +1235,40 @@ fn yellowing_look() -> lightcraft_color::Mat3 {
lightcraft_color::Mat3([[0.42, 0.548, 0.04], [0.246, 0.728, 0.033], [-0.247, 0.679, 0.447]])
}
/// Decoding passes finite values through, negative ones included, and zeroes NaN and infinities.
#[test]
fn decoding_keeps_negative_channels_and_zeroes_non_finite_ones() {
assert_eq!(finite([0.6, 0.05, -0.04]), [0.6, 0.05, -0.04]);
assert_eq!(finite([f32::NAN, -0.1, f32::INFINITY]), [0.0, -0.1, 0.0]);
}
/// Dark sensor noise through a saturating camera matrix (a NIKON D780 profile's) averages to a neutral colour: the
/// per-channel clamp at zero decoding had kept red's and blue's wider positive halves and turned it magenta.
#[test]
fn dark_noise_through_a_saturating_matrix_stays_neutral() {
let matrix = lightcraft_color::Mat3([[3.48, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]]);
let colour = CameraColourModel { wb: [1.0; 3], matrix, gain: 1.0, tables: None, hue_sat: None };
// a grey 0.002 above black with ±0.004 of noise per channel (a deterministic sequence)
let mut state = 12345u32;
let mut noise = || {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(state >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004
};
let mut img = Rgb32f::new(200, 200);
for p in img.data.iter_mut() {
*p = [0.002 + noise(), 0.002 + noise(), 0.002 + noise()];
}
colour.apply(&mut img);
let mut mean = [0.0f64; 3];
for p in &img.data {
for (m, v) in mean.iter_mut().zip(p) {
*m += f64::from(*v);
}
}
let (hi, lo) = (mean[0].max(mean[1]).max(mean[2]), mean[0].min(mean[1]).min(mean[2]));
assert!(lo > 0.0 && hi / lo < 1.2, "mean {mean:?} is tinted");
}
/// A fitted camera look applied in lanes, on rows that aren't a whole number of them, gives the bits of the
/// pixel-by-pixel path, awkward pixels (black, negative, huge, NaN, infinite) included.
#[test]
+2 -1
View File
@@ -1,9 +1,10 @@
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};
/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
/// 85: raw decoding keeps negative channels (#2278).
/// 84: full-size raw demosaic runs on the white-balanced mosaic with a clip mask (#1328).
/// 83 is reserved by open #3943.
pub const RENDER_CACHE_VERSION: u64 = 84;
pub const RENDER_CACHE_VERSION: u64 = 85;
/// 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];
+28
View File
@@ -1216,6 +1216,34 @@ fn windows_of_a_big_photo_share_one_uploaded_source() {
assert_eq!(lightcraft_gpu::source_uploads() - start, 2);
}
/// Raw decoding keeps negative channels (near-black sensor noise through a saturating camera matrix, a NIKON D780
/// profile's): pushed and edited, the GPU renders them as the CPU does.
#[test]
fn negative_channels_match_cpu() {
if !gpu() {
return;
}
let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]];
let noise = |x: usize, y: usize, c: usize| {
let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761);
(h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004
};
let src = Arc::new(Rgb32f::from_fn(320, 240, |x, y| {
let g = 0.0005 * 1.02f32.powi(x as i32);
let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c));
std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2])
}));
assert!(src.data.iter().flatten().any(|v| *v < 0.0));
let info = SourceInfo { raw: true, ..Default::default() };
let req = RenderRequest::fit(320, 240);
for (name, edit) in cases() {
let mut s = DevelopSettings::default();
edit(&mut s);
s.light.exposure += 4.0;
check(&format!("negatives +4 EV, {name}"), &src, &info, &s, &req);
}
}
/// A non-trivial 3D LUT (cross-process look: lifted blacks, warm highlights, swapped-ish blues).
fn look_lut(n: usize, domain_max: f32) -> lightcraft_pipeline::lut::Lut3d {
let mut data = Vec::with_capacity(n * n * n);
+66
View File
@@ -974,6 +974,72 @@ fn sliver_crops_render_quickly_with_wide_stages_on() {
}
}
/// A raw's linear Rec.2020 as decoding leaves it since it stopped clamping channels at zero: a dark ramp with
/// sensor noise through a saturating camera matrix (a NIKON D780 profile's), so near black many channels are
/// negative, and a few strongly out-of-gamut pixels.
fn negative_noise() -> Rgb32f {
let m = [[3.48f32, -2.41, -0.06], [-0.41, 1.57, -0.16], [0.32, -1.86, 2.58]];
// ±0.004 of noise per channel, a hash of the position
let noise = |x: usize, y: usize, c: usize| {
let h = ((x * 7919 + y * 104_729 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761);
(h >> 8) as f32 / (1u32 << 24) as f32 * 0.008 - 0.004
};
Rgb32f::from_fn(48, 32, |x, y| {
if (x + y) % 37 == 0 {
return [-0.05, 0.01, -0.02];
}
let g = 0.0005 * 1.15f32.powi(x as i32);
let cam: [f32; 3] = std::array::from_fn(|c| g + noise(x, y, c));
std::array::from_fn(|i| m[i][0] * cam[0] + m[i][1] * cam[1] + m[i][2] * cam[2])
})
}
/// Negative channels from decoding reach every stage after it: every slider at its ends, at every output depth
/// (HDR on and off), and the auto settings give finite values only.
#[test]
fn negative_channels_render_finite_everywhere() {
use crate::{DeepSamples, OutputDepth, auto};
let src = negative_noise();
assert!(src.data.iter().flatten().filter(|v| **v < 0.0).count() > src.data.len() / 4, "the source has few negatives");
let info = SourceInfo { raw: true, ..Default::default() };
let finite = |s: &DevelopSettings, depth: OutputDepth, what: &str| {
let r = render(&src, &info, s, &RenderRequest { depth, ..RenderRequest::fit(48, 48) });
assert!(r.histogram.total > 0, "{what}");
match (depth, r.deep.map(|d| d.samples)) {
(OutputDepth::U8, None) | (OutputDepth::U16, Some(DeepSamples::U16(_))) => {}
(OutputDepth::F32Linear | OutputDepth::F32Hdr, Some(DeepSamples::F32(v))) => {
assert!(v.iter().all(|v| v.is_finite()), "{what} {depth:?}: non-finite output");
}
_ => panic!("{what} {depth:?}: missing or wrong deep samples"),
}
};
let mut pushed = DevelopSettings::default();
pushed.light.exposure = 4.0;
pushed.light.shadows = 100.0;
pushed.light.blacks = 100.0;
for hdr in [false, true] {
let mut s = pushed.clone();
s.hdr.enabled = hdr;
for depth in [OutputDepth::U8, OutputDepth::U16, OutputDepth::F32Linear, OutputDepth::F32Hdr] {
finite(&s, depth, &format!("pushed, hdr {hdr}"));
}
}
for c in controls::CONTROLS {
for v in [c.min, c.max] {
let mut s = pushed.clone();
controls::set(&mut s, c.id, v);
finite(&s, OutputDepth::F32Linear, &format!("{} = {v}", c.id));
}
}
let tone = auto::auto_tone(&src, &info, &pushed);
let t = [tone.exposure, tone.contrast, tone.highlights, tone.shadows, tone.whites, tone.blacks, tone.vibrance, tone.saturation];
assert!(t.iter().all(|v| v.is_finite()), "auto tone {t:?}");
assert!(auto::auto_bw_mix(&src, &info, &pushed).iter().all(|v| v.is_finite()));
let (t, k) = auto::auto_wb(&src, &info);
assert!(t.is_finite() && k.is_finite(), "auto WB {t} {k}");
assert!(auto::scene_log_mean(&src, &info, &pushed).is_none_or(f64::is_finite));
}
// Given a cached render with one process, a change to a process with another colour filter (Update
// to Current Process, undo) renders like a fresh render, not the cached denoised image
#[test]
+22
View File
@@ -481,6 +481,28 @@ fn upright_analysis_is_resolution_independent() {
assert_eq!(lazy.data, stored.data);
}
/// Raw decoding keeps negative channels; Upright analyses a dark noisy frame as it did when decoding clipped them at
/// zero (resampled as they are, they lowered the luminance and changed the correction found).
#[test]
fn upright_analysis_clips_negative_channels_first() {
let shot = lightcraft_develop::Geometry { vertical: 30.0, rotate: 1.5, ..Default::default() };
let grid = keystoned_grid(1200, 800, crate::transform::manual(&shot), 80.0);
// ±0.04 of noise per channel, a hash of the position
let noise = |i: usize, c: usize| {
let h = ((i * 7919 + c * 1_299_709) as u32).wrapping_mul(2_654_435_761);
(h >> 8) as f32 / (1u32 << 24) as f32 * 0.08 - 0.04
};
let mut signed = grid.clone();
for (i, p) in signed.data.iter_mut().enumerate() {
*p = std::array::from_fn(|c| p[c] * 0.02 + noise(i, c));
}
let clipped = signed.map(|p| p.map(|v| v.max(0.0)));
assert!(signed.data.iter().flatten().filter(|v| **v < 0.0).count() > signed.data.len() / 4, "the frame has few negatives");
let (info, s) = (SourceInfo::default(), DevelopSettings::default());
let (a, b) = (crate::upright::analysis_plane(&signed, &info, &s), crate::upright::analysis_plane(&clipped, &info, &s));
assert!(a.data == b.data, "negative channels change Upright's analysis image");
}
/// Regression: Upright Auto must not invent perspective in natural scenes (conical trees, ridgelines, a level
/// water line) — the demo library has no buildings, so Auto should stay close to identity everywhere.
#[test]
+10
View File
@@ -579,6 +579,16 @@ pub(crate) fn analysis_key(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings)
/// The image an analysis reads: the lens-corrected source (optics applied, no perspective or crop)
/// at [`ANALYSIS_LONG`] px, as perceptual lightness normalized to its bright end.
pub(crate) fn analysis_plane(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Plane {
// Raw decoding keeps negative channels (noise near black through the camera matrix). Resampled as they are,
// they lower the luminance the segments are found in, so Upright would find a different correction than for
// the same photo decoded with its channels clipped at zero; it analyses that clipped source, as it always has.
let clipped;
let src = if src.data.iter().flatten().any(|v| *v < 0.0) {
clipped = src.map(|p| p.map(|v| v.max(0.0)));
&clipped
} else {
src
};
let mut base = s.clone();
base.geometry = Geometry::default();
base.crop = Crop::default();
+1
View File
@@ -900,6 +900,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) |
| 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) |
| 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) |
| 2026-10-16 | patch | LR-PROF-CAMERACOLOR: raw decoding keeps negative channels (noise near black) instead of clipping each at zero, which turned pushed shadows magenta; status unchanged (🟡) |
| 2026-10-22 | patch | LR-PROF-IMPORT: a real CC0 D750 profile (matrix-only, dual illuminant) and its chart NEFs are a pinned test corpus; against Lightroom Classic 15.6 mean ΔE2000 3.8 / 3.4; status unchanged (✅) |
| 2026-10-12 | minor | LR-PROF-IMPORT: the user's own DNG camera profiles (`.dcp`) import as camera profiles; none ship |
| 2026-10-13 | minor | LRC-LIB-KEYWORDS: the Keyword List marks a keyword that has an applied keyword inside it (a dot in its box); status unchanged |
+9
View File
@@ -427,6 +427,15 @@
declared totals agree, and every APP2 segment is complete. Reordered valid chunks still work. An invalid
sequence uses the existing unsupported-profile sRGB fallback, including when the JPEG is a raw preview.
## 2026-10-26
### Pushed shadows of raws no longer turn magenta
- Raw decoding no longer clips each colour channel at zero. Near black, sensor noise through the camera's colour
matrix has negative values, and clipping kept only the positive half of each channel's noise, so dark areas
pushed up came out purple or magenta, most visibly with saturating camera profiles. In the fitted view, thumbnails
and other views smaller than the photo, where neighbouring pixels are averaged first, pushed shadows now keep their
real colour (a lens-cap frame pushed 4 EV rendered magenta; it is now black), and cached thumbnails are rendered
again. At 100% and in full-size exports white balance still clips each channel before noise reduction (#840).
## 2026-10-25