Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

CR2: read ColorData's as-shot white balance as words (#1640)

Elvis33LE6cd2d61398a8
diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml
index 90d4c83d3..5871c9693 100644
--- a/crates/raw/Cargo.toml
+++ b/crates/raw/Cargo.toml
@@ -11,6 +11,8 @@ default = []
# Synthetic raw-file generators (DNG / CR2 / TIFF-EP writers and a lossless-JPEG
# encoder) for tests and fuzz seeds.
testgen = []
+# Real-file corpus tests (opt-in; `cargo xtask test-corpus`), defined with the corpus PR.
+corpus = []
[dependencies]
diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rs
index ee9374719..a0fe896c8 100644
--- a/crates/raw/src/cr2.rs
+++ b/crates/raw/src/cr2.rs
@@ -116,11 +116,18 @@ pub(crate) fn maker_note(t: &Tiff, ifds: &[Ifd]) -> Option<Ifd> {
/// As-shot white-balance multipliers (R, G, B) from ColorData.
fn as_shot_wb(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> {
let e = mn.get(CANON_COLOR_DATA)?;
- let v = t.uints(e);
+ // The entry is UNDEFINED: its bytes are a table of 16-bit words (file byte order), and the
+ // offsets below count words, not bytes. Reads stay inside the entry's own byte count.
+ let bytes = e.unit().checked_mul(e.count as usize)?;
+ let word = |off: usize| {
+ let at = off.checked_mul(2)?.checked_add(e.at)?;
+ (at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten().map(f64::from)
+ };
// Word offsets of WB_RGGBLevelsAsShot used by the ColorData versions.
for off in [0x3F, 0x47, 0x19, 0x22] {
- let Some(l) = v.get(off..off + 4) else { continue };
- let [r, g1, g2, b] = [l[0], l[1], l[2], l[3]].map(f64::from);
+ let (Some(r), Some(g1), Some(g2), Some(b)) = (word(off), word(off + 1), word(off + 2), word(off + 3)) else {
+ continue;
+ };
let g = (g1 + g2) / 2.0;
let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g));
if plausible {
@@ -345,3 +352,75 @@ mod tests {
}
}
}
+#[cfg(all(test, feature = "corpus"))]
+mod wb_debug {
+
+ /// The corpus PowerShot CR2: ColorData's WB_RGGBLevelsAsShot sits at word offset 0x47 (the
+ /// PowerShot SX50 HS's ColorData version), the same words its DNG conversion neutralises
+ /// (AsShotNeutral -> WB ≈ [1.66, 1.0, 1.74]; the ColorData words give [1.70, 1.0, 1.69] —
+ /// the converter re-derives them through the color matrix). The synthetic twin of this
+ /// oracle is `color_data_wb_as_words` above; it runs in every CI.
+ #[test]
+ fn power_shot_color_data_holds_the_as_shot_wb() {
+ let Ok(bytes) = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../corpus/pixls/IMG_4059.CR2")) else {
+ panic!("corpus/pixls is fetched for corpus runs: cargo xtask corpus --pixls");
+ };
+ let s = crate::decode(&bytes, &crate::Limits::default()).expect("decode");
+ let wb = s.camera_wb.expect("the PowerShot's as-shot WB is read now");
+ assert!((wb[0] - 1.696).abs() < 0.01 && wb[1] == 1.0 && (wb[2] - 1.688).abs() < 0.01, "{wb:?}");
+ // The file's white balance is used, not an estimate: no grey-world note in the develop.
+ let d = crate::develop_sensor(&s, &crate::DevelopOptions::default()).expect("develop");
+ assert!(!d.warnings.iter().any(|w| w.contains("estimated automatically")), "{:?}", d.warnings);
+ }
+}
+#[cfg(test)]
+mod wb_words {
+ use crate::testgen::Cr2Spec;
+
+ /// ColorData arrives as UNDEFINED bytes that are 16-bit words; the offsets count words.
+ /// Regression for the byte-scaled lookup that never found the balance (synthetic twin of
+ /// the corpus oracle, runs in every CI).
+ #[test]
+ fn color_data_wb_as_words() {
+ let spec = Cr2Spec {
+ width: 8,
+ height: 8,
+ data: vec![2048u16; 64],
+ precision: 12,
+ components: 1,
+ slices: Vec::new(),
+ borders: None,
+ wb_rggb: Some([1613, 951, 951, 1605]),
+ orientation: 1,
+ model_id: None,
+ };
+ let bytes = spec.build();
+ let s = crate::decode(&bytes, &crate::Limits::default()).expect("decode");
+ let wb = s.camera_wb.expect("the synthetic as-shot WB is read");
+ assert!((wb[0] - 1613.0 / 951.0).abs() < 1e-9 && wb[1] == 1.0 && (wb[2] - 1605.0 / 951.0).abs() < 1e-9, "{wb:?}");
+ }
+
+ /// A ColorData entry too short for the offsets reads no balance instead of running past it.
+ #[test]
+ fn short_color_data_reads_no_wb() {
+ let spec = Cr2Spec { wb_rggb: None, ..minimal_spec() };
+ let bytes = spec.build();
+ let s = crate::decode(&bytes, &crate::Limits::default()).expect("decode");
+ assert!(s.camera_wb.is_none());
+ }
+
+ fn minimal_spec() -> Cr2Spec {
+ Cr2Spec {
+ width: 8,
+ height: 8,
+ data: vec![2048u16; 64],
+ precision: 12,
+ components: 1,
+ slices: Vec::new(),
+ borders: None,
+ wb_rggb: None,
+ orientation: 1,
+ model_id: None,
+ }
+ }
+}
diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs
index 7a784b6e0..c83a04817 100644
--- a/crates/raw/src/testgen.rs
+++ b/crates/raw/src/testgen.rs
@@ -663,7 +663,7 @@ pub struct Cr2Spec {
pub slices: Vec<usize>,
/// Image borders: left, top, right, bottom (inclusive), as in SensorInfo.
pub borders: Option<[u16; 4]>,
- /// As-shot RGGB levels written to ColorData at word offset 0x3F.
+ /// As-shot RGGB levels written to ColorData at word offset 0x47 (the PowerShot version).
pub wb_rggb: Option<[u16; 4]>,
pub orientation: u16,
/// Canon model ID written to MakerNote tag 0x0010.
@@ -703,9 +703,14 @@ impl Cr2Spec {
mn.push((0x00E0, Val::Short(vec![34, w as u16, h as u16, 0, 0, l, tp, r, b, 0, 0, 0, 0, 0, 0, 0, 0])));
}
if let Some(wb) = self.wb_rggb {
- let mut cd = vec![0u16; 1273];
- cd[0x3F..0x43].copy_from_slice(&wb);
- mn.push((0x4001, Val::Short(cd)));
+ // Canon writes ColorData (0x4001) as UNDEFINED bytes that are 16-bit words; the
+ // WB_RGGBLevelsAsShot of the PowerShot version sits at word offset 0x47 (the EOS
+ // versions use 0x3F — see as_shot_wb).
+ let mut cd = vec![0u8; 2 * 1273];
+ for (i, v) in wb.iter().enumerate() {
+ cd[2 * (0x47 + i)..2 * (0x47 + i) + 2].copy_from_slice(&v.to_le_bytes());
+ }
+ mn.push((0x4001, Val::Undefined(cd)));
}
let mut exif: Vec<(u16, Val)> = vec![(33434, Val::Rational(vec![(1, 100)]))];
if !mn.is_empty() {
diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rs
index 764cc8706..5a623044b 100644
--- a/crates/raw/src/tiff.rs
+++ b/crates/raw/src/tiff.rs
@@ -89,7 +89,7 @@ pub(crate) struct Entry {
impl Entry {
/// Size in bytes of one value of this entry's type (0 = unknown type).
- fn unit(&self) -> usize {
+ pub(crate) fn unit(&self) -> usize {
type_size(self.typ)
}
}