From b5440f167ffc9d87e8c39860cf63979a2d6a46d5 Mon Sep 17 00:00:00 2001 From: Exalted5373 <247056922+Exalted5373@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:58:32 -0700 Subject: [PATCH] LR-IMP-CAMERA-COVERAGE: CR2 black level from the masked columns only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Canon's SensorInfo left border is not where light starts: on every corpus body 10-36 columns left of it already hold image (EOS 6D: masked columns 0-70, border 84), and the black level was averaged over all of them. The 6D read 2591 instead of 2047 (4 % of the range), so CR2s rendered dark with crushed shadows; 40D +141, 5DS R +131, 5D Mark II +73. The masked run is now measured from the data: columns whose mean stays within 1/256 of the range of the leftmost columns', minus a two-column margin. Against Lightroom Classic (EOS 6D still life, 2000 px, ΔE00): base 7.63 -> 5.23 (p95 24.7 -> 11.3); mean over 86 edit variants abs 9.13 -> 6.19, effect 3.09 -> 2.75. RENDER_CACHE_VERSION 23. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/media.rs | 2 +- crates/raw/src/vendor/cr2.rs | 65 ++++++++++++++++++++++++++++++++---- docs/parity.md | 2 +- docs/whats-new.md | 4 +++ 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 1231221b9..fcfbbe208 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -62,7 +62,7 @@ impl SettingsHashes { } /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 22; +pub const RENDER_CACHE_VERSION: u64 = 23; /// 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]; diff --git a/crates/raw/src/vendor/cr2.rs b/crates/raw/src/vendor/cr2.rs index 4c7522dab..7f52888f4 100644 --- a/crates/raw/src/vendor/cr2.rs +++ b/crates/raw/src/vendor/cr2.rs @@ -13,7 +13,9 @@ //! read per file (no model table); files without the tag fall back to RGGB (issue #85). The parity of the //! `SensorInfo` borders does *not* predict it (RGGB files come with both even and odd top borders). //! - `SensorInfo` (maker note `0x00e0`): sensor width/height and the left/top/right/bottom borders of the image -//! area; the masked columns left of it give the black level. +//! area. Light already reaches some columns left of that border (EOS 6D: masked columns 0–70, border 84; 10–36 +//! such columns on every corpus body), so the masked columns that give the black level are measured from the +//! data ([`masked_columns`]) rather than taken as the whole border. //! - `ColorBalance` (maker note `0x4001`): as-shot `RGGB` levels at a model-dependent offset; we probe the known //! offsets and accept the first plausible quadruple. The array is 16-bit words; some models store it as UNDEFINED //! bytes (ColorData versions -3 and -4), which are paired up in the maker note's byte order first. @@ -26,6 +28,7 @@ use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, Ra use lightcraft_geom::Orientation; use lightcraft_tiff::image::chunk_bytes; use lightcraft_tiff::{ByteOrder, Ifd, Tiff, Value, makernote, tags as t}; +use std::ops::Range; const CR2_SLICE: u16 = 0xc640; const SRAW_TYPE: u16 = 0xc6c5; @@ -79,6 +82,38 @@ fn wb_from_color_balance(v: &[u64]) -> Option<[f32; 3]> { None } +/// The optically black columns left of the image area: from column 2 up to two columns before the first column +/// whose mean (over the image rows) rises above the leftmost columns' level by more than 1/256 of the remaining +/// range (at least 16), else up to two columns before the image area. Empty when the border is too narrow. +fn masked_columns(data: &[u16], width: usize, active: Rect, white: f32) -> Range { + let limit = active.x.saturating_sub(2).min(width); + if limit < 4 || active.height == 0 { + return 0..0; + } + let step = (active.height / 256).max(1); + let column_mean = |x: usize| { + let (mut sum, mut n) = (0.0, 0usize); + for y in (active.y..active.y.saturating_add(active.height)).step_by(step) { + if let Some(&v) = y.checked_mul(width).and_then(|i| data.get(i.checked_add(x)?)) { + sum += f64::from(v); + n += 1; + } + } + (n > 0).then(|| sum / n as f64) + }; + let means: Vec = (2..limit).map_while(column_mean).collect(); + let mut first: Vec = means.iter().take(8).copied().collect(); + first.sort_by(f64::total_cmp); + let Some(&level) = first.get(first.len() / 2) else { return 0..0 }; + let tolerance = ((f64::from(white) - level) / 256.0).max(16.0); + let end = match means.iter().position(|&m| m > level + tolerance) { + // `means[k]` is column `2 + k`: stop two columns before it + Some(k) => k, + None => 2 + means.len(), + }; + 2..end.max(2) +} + pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let tiff = Tiff::parse(bytes)?; let ifd0 = &tiff.ifds[0]; @@ -154,12 +189,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { } let wb = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order))).and_then(|v| wb_from_color_balance(&v)); let cfa = cfa_from_tag(raw.u64(CR2_CFA_PATTERN)).unwrap_or_else(|| Cfa::bayer_static("RGGB")); - let black = if active.x >= 8 { - black_from_columns(&data, width, 2..active.x - 2, active.y..active.y + active.height, active) - } else { - BlackLevel::uniform(0.0) - }; let white = white_from_data(&data, prec as u32); + let black = match masked_columns(&data, width, active, white) { + cols if cols.len() >= 2 => black_from_columns(&data, width, cols, active.y..active.y + active.height, active), + _ => BlackLevel::uniform(0.0), + }; let mut metadata = lightcraft_meta::from_tiff(&tiff); metadata.width = Some(active.width as u32); metadata.height = Some(active.height as u32); @@ -299,6 +333,25 @@ pub(crate) mod tests { assert_eq!(words(&Value::Undefined(vec![1, 0, 2]), ByteOrder::Little), vec![1]); } + /// Light reaches columns left of the `SensorInfo` border (as on the EOS 6D): the black level comes from the + /// masked columns only, not from the image columns between them and the border. + #[test] + fn black_from_masked_columns_only() { + let (w, h, border, light) = (40, 12, 20, 14); + let data: Vec = (0..w * h).map(|i| if i % w < light { 2048 + (i % 2) as u16 } else { 6000 }).collect(); + let active = Rect::new(border, 2, w - border, h - 2); + let cols = masked_columns(&data, w, active, 15000.0); + assert_eq!(cols, 2..light - 2); + let black = black_from_columns(&data, w, cols, 2..h, active); + assert!(black.values.iter().all(|v| (2048.0..=2049.0).contains(v)), "{:?}", black.values); + // the whole border masked: every column but the two next to the image + let dark: Vec = (0..w * h).map(|i| if i % w < border { 2048 } else { 6000 }).collect(); + assert_eq!(masked_columns(&dark, w, active, 15000.0), 2..border - 2); + // too narrow a border, or no samples (headers-only decode): none + assert!(masked_columns(&dark, w, Rect::new(5, 0, 30, h), 15000.0).is_empty()); + assert!(masked_columns(&[], w, active, 15000.0).is_empty()); + } + /// A maker note holding only `ColorData` (`0x4001`) as `ty` (3 = SHORT, 7 = UNDEFINED) with `n` values, a plain /// IFD whose value offset is relative to the TIFF header (patched once the note's position is known). fn note_with_color_data(ty: u16, data: &[u8]) -> Vec { diff --git a/docs/parity.md b/docs/parity.md index 4c27755b5..52b1d6db8 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -144,7 +144,7 @@ under the UI command that wraps it (a no-op error); the UI command now wins. | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | | LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG, PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP; DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared linear primaries without clipping or gamut mapping, checked on one real file with 108 lossy tiles, and any tile that fails to decode makes the file preview-only; a single-chunk JPEG XL preview IFD is offered as the embedded preview), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), ARW (pre-2017 bodies: white balance and black level from enciphered maker-note / `SR2SubIFD` data, issue #148; downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`), Hasselblad 3FR with uncompressed raw data (X1D, X1D II, X2D, CFV 100C: a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`; the lossless-JPEG 3FR and FFF files use scan selection value 8 and stay preview-only), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8 (`crates/raw/tests/cr3_corpus.rs`, `docs/cr3.md`). Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed ORF, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), NEFs labelled compressed (34713) but stored uncompressed without a `0x0096` table (Z 6 packed 14-bit, D850 12-bit uncompressed), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and Kodak DCS TIFFs: IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Canon CRW, Minolta MRW and Sigma X3F (containers recognised by magic, preview found by a structural JPEG scan), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan), and any decode failure of a recognised raw, not only an unsupported variant; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature: `crates/heif`, heic-rs, same policy as PhotoCraft; 8/10-bit, alpha, irot/imir/clap, ICC/EXIF/XMP), palette (indexed-colour) TIFF (refused by the `tiff` crate) | -| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | +| LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/corpus.rs`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; private Z 8 crop verified. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests_import_move.rs`, `crates/ui-egui/src/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | | LR-IMP-DNG-CONVERT | Convert to DNG on import [Classic] | P2 | ✅ | `cmd:library.import` (`dng`), `crates/ui-egui/src/import.rs` | copy imports: Raw files ▸ Copy as DNG (lossless; the card is untouched); the raw copy is removed only once its DNG is verified and on disk (issue #106) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 33557867d..232617206 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -40,6 +40,10 @@ - Samsung SRW files without compression now open as raws: NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1 and WB2000. The compressed ones (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini) still open from their camera JPEG. Photos already imported pick the change up on Reload. +- Canon CR2 raws no longer open too dark with blocked-up shadows: the black level was measured over border columns + that light already reaches (left of the image area Canon records), 4 % of the range too high on the EOS 6D. It is + now measured on the masked columns alone (8 corpus bodies, EOS 40D to 5DS R). On a 6D photo the starting render + moved from ΔE00 7.6 to 5.2 against Lightroom's. - Canon CR2 and Pentax PEF raws get the same starting look fitted to the camera's own JPEG as ARW, NEF, RW2, RAF and CR3, instead of opening flat and desaturated (issue #310). Photos already imported pick it up when re-rendered. - JPEG XL compressed DNGs (DNG 1.7) now open: lossless tiles decode sample for sample (checked on synthetic files);