PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Raw: cRAW black level without a tag; measured image areas (D800E, ILCE-7) (#1902)
Gotya-OFFCIAL4716d3337278
diff --git a/crates/raw/README.md b/crates/raw/README.mdindex f7775c4cb..c93999005 100644--- a/crates/raw/README.md+++ b/crates/raw/README.md@@ -56,7 +56,7 @@ camera colour tables were copied.| CR2 sRAW / mRAW | Unsupported || NEF / NRW, ARW, PEF and other TIFF/EP raws | Uncompressed and lossless-JPEG (incl. Sony lossless ARW) CFA data || Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files are unsupported (preview fallback) |-| Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits |+| Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits, the curve's 512 black level when no BlackLevel tag is written (the first-generation bodies, e.g. the ILCE-7) || Panasonic / Leica RW2, RawFormat 5 (12- and 14-bit packed) | Decoded, with PanasonicRaw black / white / WB / sensor borders || Olympus ORF, uncompressed 16-bit (E-1, E-400…) | Decoded, with ImageProcessing black / WB / ValidBits / crop || Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 4 and older, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead |diff --git a/crates/raw/src/cameras.rs b/crates/raw/src/cameras.rsindex 0b57a98f5..1c605734f 100644--- a/crates/raw/src/cameras.rs+++ b/crates/raw/src/cameras.rs@@ -15,6 +15,9 @@//! camera's embedded JPEGs (Picture Control Standard, Active D-Lighting off; 52 frames, smooth//! areas, 4 × 4 means): on 15 held-out frames the development is 7.2/255 per channel off the//! camera's JPEG on average, against 34 without a profile.+//!+//! Bodies whose full profile is not measured yet can still get their measured image area — the+//! same alignment method, see [`IMAGE_AREAS`] — so their frames crop like the camera's JPEG.use crate::color::{Calibration, ColorInfo, IDENTITY, Mat3};use crate::sensor::{Rect, Sensor};@@ -82,10 +85,40 @@ const PROFILES: &[Profile] = &[Profile {tone: &D4_TONE,}];-/// Applies the measured profile of the camera that made `s`, when there is one.+/// A measured image area of a body whose remaining profile has not been+/// measured yet. Measured the same way as the profiles: by aligning the decoded+/// plane with the camera's own JPEG.+///+/// Both origins are even, so the Bayer phase of the crop is unchanged.+/// * **D800E** (2 files): the camera's JPEG sits 8 x 6 pixels in from the left+/// and top of the 7424 x 4924 sensor data (56 and 4 pixels of margin on the+/// right and bottom), the same corner as the D4.+/// * **ILCE-7** (2 files): 12 x 12 pixels in from the left and top of the+/// 6048 x 4024 cRAW data (36 and 12 pixels of margin on the right and bottom).+struct ImageArea {+ make: &'static str,+ model: &'static str,+ /// Sensor data size the measurement was taken on.+ size: (usize, usize),+ /// The image area: x, y, width, height.+ crop: (usize, usize, usize, usize),+}++const IMAGE_AREAS: &[ImageArea] = &[+ ImageArea { make: "NIKON CORPORATION", model: "NIKON D800E", size: (7424, 4924), crop: (8, 6, 7360, 4912) },+ ImageArea { make: "SONY", model: "ILCE-7", size: (6048, 4024), crop: (12, 12, 6000, 4000) },+];++/// Applies the measured profile of the camera that made `s`, when there is one,+/// and its measured image area when the profile is not measured yet.pub(crate) fn apply(s: &mut Sensor) {let (Some(make), Some(model)) = (s.make.as_deref(), s.model.as_deref()) else { return };- let Some(p) = PROFILES.iter().find(|p| make.trim() == p.make && model.trim() == p.model && (s.width, s.height) == p.size) else { return };+ let (make, model) = (make.trim(), model.trim());+ if let Some(a) = IMAGE_AREAS.iter().find(|a| a.make == make && a.model == model && a.size == (s.width, s.height)) {+ let (x, y, w, h) = a.crop;+ s.crop = Rect::new(x, y, w, h);+ }+ let Some(p) = PROFILES.iter().find(|p| make == p.make && model == p.model && (s.width, s.height) == p.size) else { return };let (x, y, w, h) = p.crop;s.crop = Rect::new(x, y, w, h);s.white = [p.white; 3];@@ -107,10 +140,10 @@ mod tests {use crate::color::apply as mat_apply;use crate::sensor::BlackLevels;- fn nef(model: &str, width: usize, height: usize) -> Sensor {+ fn sensor(make: &str, model: &str, width: usize, height: usize) -> Sensor {Sensor {format: RawFormat::Nef,- make: Some("NIKON CORPORATION".into()),+ make: Some(make.into()),model: Some(model.into()),width,height,@@ -132,6 +165,10 @@ mod tests {}}+ fn nef(model: &str, width: usize, height: usize) -> Sensor {+ sensor("NIKON CORPORATION", model, width, height)+ }+#[test]fn a_d4_nef_gets_its_crop_levels_matrix_and_curve() {let mut s = nef("NIKON D4", 4992, 3292);@@ -146,6 +183,28 @@ mod tests {assert!(s.color.balanced_to_xyz_d50([0.5, 1.0, 0.7]).is_some());}+ #[test]+ fn measured_image_areas_crop_the_borders_without_touching_the_rest() {+ let mut s = nef("NIKON D800E", 7424, 4924);+ apply(&mut s);+ assert_eq!(s.crop, Rect::new(8, 6, 7360, 4912));+ // Only the image area is measured: levels, colour and tone stay untouched.+ assert!(s.color.calibrations.is_empty() && s.tone_curve.is_empty());+ assert_eq!(s.white, [16383.0; 3]);++ let mut s = sensor("SONY", "ILCE-7", 6048, 4024);+ apply(&mut s);+ assert_eq!(s.crop, Rect::new(12, 12, 6000, 4000));++ // Another size or model of the same maker is left alone.+ let mut s = nef("NIKON D800E", 2496, 1646);+ apply(&mut s);+ assert_eq!(s.crop, Rect::new(0, 0, 2496, 1646));+ let mut s = nef("NIKON D800", 7424, 4924);+ apply(&mut s);+ assert_eq!(s.crop, Rect::new(0, 0, 7424, 4924));+ }+#[test]fn other_cameras_and_sizes_are_left_alone() {for (model, w, h) in [("NIKON D4S", 4992, 3292), ("NIKON D4", 2496, 1646), ("NIKON D800", 7424, 4924)] {diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rsindex cbe8da500..a857e0630 100644--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@ -20,6 +20,8 @@//! * Raws that carry no colour description (NEF) take a camera profile we//! measured from the camera's own output when there is one (`cameras.rs`://! image area, levels, ForwardMatrix, tone curve; the Nikon D4 so far).+//! Bodies whose full profile is not measured yet can still carry a measured+//! image area (the D800E, the ILCE-7).//!//! Decoded today: DNG (uncompressed and lossless-JPEG, strips and tiles, CFA//! and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed ordiff --git a/crates/raw/src/tiffep.rs b/crates/raw/src/tiffep.rsindex 8fd47836b..b940d6bc3 100644--- a/crates/raw/src/tiffep.rs+++ b/crates/raw/src/tiffep.rs@@ -7,10 +7,12 @@//!//! Black and white levels use DNG-style tags when the camera writes them,//! then the vendor's publicly documented tags (Nikon maker note BlackLevel,-//! Sony raw-IFD BlackLevel), else 0 with a warning. The white level falls-//! back to the clipping point found in the data. The as-shot white balance-//! comes from the documented vendor tags (Nikon WB_RBLevels, Sony-//! WB_RGGBLevels); otherwise it is estimated.+//! Sony raw-IFD BlackLevel), else 0 with a warning — cRAW files without a+//! BlackLevel tag (the first generation of cRAW bodies) get the 512 that their+//! tone curve gives the black code. The white level falls back to the clipping+//! point found in the data. The as-shot white balance comes from the documented+//! vendor tags (Nikon WB_RBLevels, Sony WB_RGGBLevels); otherwise it is+//! estimated.use crate::cr2::clip_level;use crate::error::{RawError, Result};@@ -124,7 +126,8 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result<Senreturn Err(RawError::unsupported(format!("{}: no CFA image found", format.name())));};let nikon = if format == RawFormat::Nef { nikon_maker_note(t, &ifds) } else { None };- let plane = if format == RawFormat::Arw && sony::is_craw(t, &raw) {+ let craw = format == RawFormat::Arw && sony::is_craw(t, &raw);+ let plane = if craw {sony::read_craw(t, &raw, limits)?} else if format == RawFormat::Nef && t.tag_uint(&raw, tag::COMPRESSION) == Some(nefc::NIKON_COMPRESSION) {nefc::read_compressed(t, &raw, nikon.as_ref(), limits)?@@ -159,6 +162,13 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result<SenBlackLevels::uniform(*b as f32)} else if let Some(v) = rggb_by_position(&cfa, &vendor_black) {BlackLevels { rows: 2, cols: 2, values: v.to_vec(), delta_h: Vec::new(), delta_v: Vec::new() }+ } else if craw {+ // cRAW files of the first generation (an ILCE-7 writes none) carry no+ // BlackLevel tag; the tone curve maps the black code to 512, so their+ // decoded data has a 512 black level (see `sony.rs`). Other tag-less+ // bodies sit higher (a DSC-RX0's darkest samples are near 800), so 512+ // is a floor, still far closer than 0.+ BlackLevels::uniform(512.0)} else if nikon.is_some() {// Nikon bodies that write no BlackLevel tag subtract the black level in camera: a D3200// NEF's darkest samples are 0–4 (noise around zero), median 81 of 4095.diff --git a/crates/raw/tests/raw_corpus.rs b/crates/raw/tests/raw_corpus.rsindex 354dec984..d90e06a6c 100644--- a/crates/raw/tests/raw_corpus.rs+++ b/crates/raw/tests/raw_corpus.rs@@ -68,7 +68,9 @@ const WANTS: &[Want] = &[model: "DSC-RX0",size: (4832, 3224),cfa: [0, 1, 1, 2],- black: &[0.0],+ // No readable BlackLevel tag: the cRAW fallback of 512 (#1902). The file's darkest+ // samples sit near 800, so this body's real level is still to be read.+ black: &[512.0],white: [16301.0; 3],},// The G9's high-resolution mode: a 10480 × 7794 sensor cropped to 10368 × 7776.diff --git a/crates/raw/tests/vendor_codecs.rs b/crates/raw/tests/vendor_codecs.rsindex a2b193efe..e210c6f31 100644--- a/crates/raw/tests/vendor_codecs.rs+++ b/crates/raw/tests/vendor_codecs.rs@@ -101,6 +101,45 @@ fn craw_unusual_variants_are_unsupported() {assert!(decode(cut, &Limits::default()).is_err());}+/// Renames a tag of the raw SubIFD (tag 330 of IFD0), hiding it from the+/// decoder: the first cRAW bodies write no BlackLevel tag at all.+fn hide_raw_sub_ifd_tag(b: &mut [u8], tag: u16) {+ let ifd = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize;+ let n = u16::from_le_bytes([b[ifd], b[ifd + 1]]) as usize;+ for i in 0..n {+ let e = ifd + 2 + 12 * i;+ if u16::from_le_bytes([b[e], b[e + 1]]) == 330 {+ let sub = u32::from_le_bytes(b[e + 8..e + 12].try_into().unwrap()) as usize;+ let sn = u16::from_le_bytes([b[sub], b[sub + 1]]) as usize;+ for j in 0..sn {+ let se = sub + 2 + 12 * j;+ if u16::from_le_bytes([b[se], b[se + 1]]) == tag {+ b[se..se + 2].copy_from_slice(&0xFFFEu16.to_le_bytes());+ return;+ }+ }+ }+ }+ panic!("tag {tag:#x} not found in the raw SubIFD");+}++#[test]+fn craw_without_a_black_level_tag_reads_black_from_the_tone_curve() {+ // An ILCE-7 cRAW carries no BlackLevel tag (0x7310): the tone curve maps+ // the black code (256) to 512, so the decoded data has a 512 black level.+ let (w, h) = (64, 4);+ let codes = vec![1024u16; w * h];+ let mut b = sony_craw(w, h, &codes, CURVE);+ hide_raw_sub_ifd_tag(&mut b, 0x7310);+ let s = decode(&b, &Limits::default()).unwrap();+ assert_eq!(s.black.values, vec![512.0]);+ assert!(!s.warnings.iter().any(|w| w.contains("black level")), "{:?}", s.warnings);+ // With the tag present the level is the same: 512 either way.+ let b = sony_craw(w, h, &codes, CURVE);+ let s = decode(&b, &Limits::default()).unwrap();+ assert_eq!(s.black.values, vec![512.0; 4]);+}+#[test]fn rw2_round_trip_12_and_14_bit() {for (bits, w, h) in [(12u32, 120usize, 300usize), (14, 117, 260)] {