Repository navigation
craft-raw: Kelvin presets for more CR2, CR3, PEF and RW2 raws #2234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -120,6 +120,23 @@ struct CameraLevels { | |
| white: Option<f32>, | ||
| } | ||
|
|
||
| /// The Kelvin scale of a body without colour matrices, from the presets in `ColorData` (see [`crate::cr2`] for the | ||
| /// record layout): Daylight, Shade, Cloudy, Tungsten and Flash at their stated temperatures. Word positions from | ||
| /// `exiftool -v3` run as a black-box tool on files of each version: versions 16-19 Daylight at word 136, 32 and 33 at | ||
| /// 150, 34 and 48 at 205 (each with Flash thirty words after Daylight), 64 to 66 at 110 with Flash twenty-five | ||
| /// after (no Auto / Measured / Kelvin records in these). Other versions give none. | ||
| fn kelvin_presets(maker: Option<&Ifd>) -> Option<crate::kelvin::KelvinPresets> { | ||
| let v = maker?.u64s(COLOR_DATA)?; | ||
| let rows = match v.first().copied()? { | ||
| 16..=19 => crate::cr2::preset_records(136, 166), | ||
| 32 | 33 => crate::cr2::preset_records(150, 180), | ||
| 34 | 48 => crate::cr2::preset_records(205, 235), | ||
| 64..=66 => crate::cr2::preset_records(110, 135), | ||
| _ => return None, | ||
| }; | ||
| crate::cr2::presets_at(&v, &rows) | ||
|
Comment on lines
+131
to
+137
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the standalone CR3 feature buildable.
|
||
| } | ||
|
|
||
| /// Canon's versioned word arrays. Offsets are word indices from the published tag tables, not | ||
| /// byte offsets. The four as-shot WB values are R, G, G, B, independent of the CFA layout. | ||
| /// A version without a white-level offset takes its white level from the data (see `docs/cr3.md`). | ||
|
|
@@ -253,7 +270,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma | |
| active_area: active, | ||
| crop, | ||
| orientation: Orientation::from_exif(ifd0.and_then(|i| i.u16(craft_tiff::tags::ORIENTATION)).unwrap_or(1)), | ||
| color: ColorData::default(), | ||
| color: ColorData { kelvin_presets: kelvin_presets(color_maker), ..Default::default() }, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fall back to CMT3 when timed metadata has no usable presets. A timed
|
||
| wb_multipliers: levels.wb, | ||
| linearized: false, | ||
| linearization_table: None, | ||
|
|
@@ -375,6 +392,39 @@ mod tests { | |
| use crate::shared::ASPECT_INFO; | ||
| use craft_tiff::{IfdBuilder, Value}; | ||
|
|
||
| /// The presets of each verified `ColorData` version read back at their stated temperatures; other versions, short | ||
| /// arrays and records that don't make a curve give none. | ||
| #[test] | ||
| fn color_data_presets_by_version() { | ||
| let records = [(2013u16, 1479u16, 5200u16), (2300, 1280, 7000), (2153, 1374, 6000), (1442, 2089, 3200), (2203, 1371, 6156)]; | ||
| for (version, daylight, flash) in | ||
| [(16, 136, 166), (19, 136, 166), (32, 150, 180), (33, 150, 180), (34, 205, 235), (48, 205, 235), (64, 110, 135), (66, 110, 135)] | ||
| { | ||
| let mut words = vec![0u16; 300]; | ||
| words[0] = version; | ||
| for (i, (r, b, k)) in records.into_iter().enumerate() { | ||
| let at = if i == 4 { flash } else { daylight + 5 * i }; | ||
| words[at..at + 5].copy_from_slice(&[r, 1024, 1024, b, k]); | ||
| } | ||
| let ifd = |w: Vec<u16>| { | ||
| let b = IfdBuilder::new().with(COLOR_DATA, Value::Short(w)); | ||
| let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[b]).unwrap(); | ||
| Tiff::parse(&bytes).unwrap().ifds.remove(0) | ||
| }; | ||
| let p = kelvin_presets(Some(&ifd(words.clone()))).unwrap_or_else(|| panic!("{version}")); | ||
| let pts = p.points(); | ||
| assert!( | ||
| pts.iter().any(|&(k, m)| k == 7000.0 && (m[0] - 2300.0 / 1024.0).abs() < 1e-6 && (m[2] - 1280.0 / 1024.0).abs() < 1e-6), | ||
| "{version}: {pts:?}" | ||
| ); | ||
| assert_eq!(pts.len(), 5, "{version}"); | ||
| assert!(kelvin_presets(Some(&ifd(words[..flash].to_vec()))).is_none(), "{version}: short"); | ||
| words[0] = 255; | ||
| assert!(kelvin_presets(Some(&ifd(words))).is_none(), "{version}: unknown"); | ||
| } | ||
| assert!(kelvin_presets(None).is_none()); | ||
| } | ||
|
|
||
| fn maker(version: u16, wb_at: usize, black_at: usize, white_at: usize) -> Ifd { | ||
| let mut words = vec![0u16; white_at + 1]; | ||
| words[0] = version; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,6 +19,9 @@ pub struct KelvinPresets { | |
| /// Multipliers (green = 1) for Illuminant A and D65, when that pair is all the file records. | ||
| #[serde(default)] | ||
| pair: Option<[[f32; 3]; 2]>, | ||
| /// The pair's two lights as CIE 1931 (x, y), warmer first, when they are not Illuminant A and D65. | ||
| #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| lights: Option<[[f64; 2]; 2]>, | ||
| } | ||
|
|
||
| fn usable(m: [f32; 3]) -> bool { | ||
|
|
@@ -40,7 +43,11 @@ impl KelvinPresets { | |
| let (a, b) = (log_point(w[0].1), log_point(w[1].1)); | ||
| w[0].0 < w[1].0 && b[0] > a[0] && b[1] < a[1] | ||
| }); | ||
| ok.then(|| KelvinPresets { points: points.into_iter().map(|(k, m)| (k, [m[0] / m[1], 1.0, m[2] / m[1]])).collect(), pair: None }) | ||
| ok.then(|| KelvinPresets { | ||
| points: points.into_iter().map(|(k, m)| (k, [m[0] / m[1], 1.0, m[2] / m[1]])).collect(), | ||
| pair: None, | ||
| lights: None, | ||
| }) | ||
| } | ||
|
|
||
| /// A curve from presets in any order, as a camera lists them by name (Canon's Daylight, Shade, Cloudy, …): | ||
|
|
@@ -72,7 +79,20 @@ impl KelvinPresets { | |
| } | ||
| let (pa, pd) = (log_point(a), log_point(d65)); | ||
| let unit = |m: [f32; 3]| [m[0] / m[1], 1.0, m[2] / m[1]]; | ||
| (pd[0] > pa[0] && pd[1] < pa[1]).then(|| KelvinPresets { points: Vec::new(), pair: Some([unit(a), unit(d65)]) }) | ||
| (pd[0] > pa[0] && pd[1] < pa[1]).then(|| KelvinPresets { points: Vec::new(), pair: Some([unit(a), unit(d65)]), lights: None }) | ||
| } | ||
|
|
||
| /// [`Self::from_neutral_pair`] for two other lights, given by their CIE 1931 chromaticities, the warmer first | ||
| /// (Panasonic stores its multipliers for D55 and the ISO studio tungsten lamp). `None` unless the multipliers make | ||
| /// a curve as for a pair and the chromaticities are distinct points inside (0, 1). | ||
| pub fn from_neutral_lights(lights: [[f64; 2]; 2], warm: [f32; 3], cool: [f32; 3]) -> Option<KelvinPresets> { | ||
| let inside = |p: [f64; 2]| p.iter().all(|v| *v > 0.0 && *v < 1.0); | ||
| if !inside(lights[0]) || !inside(lights[1]) || lights[0] == lights[1] { | ||
|
Comment on lines
+89
to
+90
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject chromaticities outside the CIE xy triangle.
|
||
| return None; | ||
| } | ||
| let mut out = Self::from_neutral_pair(warm, cool)?; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check the normalized gains before returning a neutral pair. With warm gains
|
||
| out.lights = Some(lights); | ||
| Some(out) | ||
| } | ||
|
|
||
| /// The presets as (Kelvin, multipliers with green = 1), ascending in Kelvin. Empty for a neutral pair. | ||
|
|
@@ -84,6 +104,11 @@ impl KelvinPresets { | |
| pub fn neutral_pair(&self) -> Option<[[f32; 3]; 2]> { | ||
| self.pair | ||
| } | ||
|
|
||
| /// The chromaticities of the pair's lights from [`Self::from_neutral_lights`]; `None` for Illuminant A and D65. | ||
| pub fn neutral_lights(&self) -> Option<[[f64; 2]; 2]> { | ||
| self.lights | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
|
|
@@ -148,4 +173,17 @@ mod tests { | |
| None | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn neutral_lights_keep_their_chromaticities() { | ||
| let (warm, cool) = ([1.0, 1.0, 2.8], [1.5, 1.0, 1.9]); | ||
| let lights = [[0.4232, 0.3991], [0.3324, 0.3474]]; | ||
| let k = KelvinPresets::from_neutral_lights(lights, warm, cool).unwrap(); | ||
| assert_eq!((k.neutral_pair(), k.neutral_lights()), (Some([warm, cool]), Some(lights))); | ||
| assert_eq!(KelvinPresets::from_neutral_pair(warm, cool).unwrap().neutral_lights(), None); | ||
| assert!(KelvinPresets::from_neutral_lights(lights, cool, warm).is_none()); | ||
| assert!(KelvinPresets::from_neutral_lights([lights[0], lights[0]], warm, cool).is_none()); | ||
| assert!(KelvinPresets::from_neutral_lights([[0.0, 0.4], lights[1]], warm, cool).is_none()); | ||
| assert!(KelvinPresets::from_neutral_lights([[f64::NAN, 0.4], lights[1]], warm, cool).is_none()); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,7 @@ const CROP_ORIGIN: u16 = 0x0038; | |
| const CROP_SIZE: u16 = 0x0039; | ||
| const BLACK_POINT: u16 = 0x0200; | ||
| const WB_LEVELS: u16 = 0x0201; | ||
| const KELVIN_WB: u16 = 0x0221; | ||
| const HUFFMAN: u16 = 0x0220; | ||
|
|
||
| /// Parse the maker-note Huffman table. | ||
|
|
@@ -122,6 +123,24 @@ fn dark_trimmed(d: &[u16], w: usize, h: usize, black: Option<f64>, white: f32) - | |
| Rect::new(left, top, width, height) | ||
| } | ||
|
|
||
| /// The Kelvin presets of maker note `0x0221` (tag number and layout from `exiftool -v3` run as a black-box tool on | ||
| /// the files, then checked against the files' own bytes): a `u16`, then 8-byte entries of four `u16`, the first | ||
| /// the temperature as `53190 - K`, then 0, then the red and blue multipliers in units of 8192 (green 1). The first | ||
| /// entry is the daylight white (5205 K) and the rest run from 2500 K up. `None` unless they make a curve. | ||
| fn kelvin_presets(mn: Option<&makernote::MakerNote>) -> Option<crate::kelvin::KelvinPresets> { | ||
| let mn = mn?; | ||
| let craft_tiff::Value::Undefined(b) = mn.ifd.value(KELVIN_WB)? else { return None }; | ||
| let words: Vec<u16> = b.as_chunks::<2>().0.iter().map(|c| mn.order.u16(*c)).collect(); | ||
| let points = words | ||
| .get(1..)? | ||
| .as_chunks::<4>() | ||
| .0 | ||
| .iter() | ||
| .filter(|e| e[0] != 0 && e[0] < 53190 && e[2] != 0 && e[3] != 0) | ||
| .map(|e| ((53190 - u32::from(e[0])) as f32, [f32::from(e[2]), 8192.0, f32::from(e[3])])); | ||
|
Comment on lines
+139
to
+140
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Filter implausible temperatures before building the PEF curve. If the 2500 K record in the test changes its encoded temperature to
|
||
| crate::kelvin::KelvinPresets::from_unordered(points) | ||
| } | ||
|
|
||
| /// Whether every strip or tile of a one-sample-per-pixel image holds exactly the bytes that its rows need when | ||
| /// the samples are packed MSB-first at the declared bit depth, rows starting on byte boundaries (TIFF 6.0 | ||
| /// section 7). A real PackBits stream of such an image has a different length (almost always shorter), so the | ||
|
|
@@ -235,7 +254,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma | |
| active_area: active, | ||
| crop: Rect::new(0, 0, active.width, active.height), | ||
| orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), | ||
| color: ColorData::default(), | ||
| color: ColorData { kelvin_presets: kelvin_presets(mn.as_ref()), ..Default::default() }, | ||
| wb_multipliers: wb, | ||
| linearized: false, | ||
| linearization_table: None, | ||
|
|
@@ -255,6 +274,32 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma | |
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn kelvin_presets_from_maker_note_0221() { | ||
| use craft_tiff::{IfdBuilder, TiffWriter, Value}; | ||
| // a u16, then entries of (53190 - K, 0, red * 8192, blue * 8192): daylight first, then 2500 K upward | ||
| let entry = |k: u32, r: f64, b: f64| [(53190 - k) as u16, 0, (r * 8192.0) as u16, (b * 8192.0) as u16]; | ||
| let mut words = vec![0u16]; | ||
| for e in [entry(5205, 1.83, 1.16), entry(2500, 1.06, 2.32), entry(3330, 1.4, 1.9), entry(4550, 1.7, 1.45), entry(6500, 2.0, 1.05)] { | ||
| words.extend(e); | ||
| } | ||
| let note = |words: &[u16]| { | ||
| let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_be_bytes()).collect(); | ||
| let ifd = IfdBuilder::new().with(KELVIN_WB, Value::Undefined(bytes)); | ||
| let file = TiffWriter::new(ByteOrder::Big, false).write(&[ifd]).unwrap(); | ||
| let ifd = Tiff::parse(&file).unwrap().ifds.remove(0); | ||
| makernote::MakerNote { kind: makernote::MakerNoteKind::Plain, order: ByteOrder::Big, base: 0, ifd } | ||
| }; | ||
| let p = kelvin_presets(Some(¬e(&words))).unwrap(); | ||
| let kelvins: Vec<f32> = p.points().iter().map(|p| p.0).collect(); | ||
| assert_eq!(kelvins, [2500.0, 3330.0, 4550.0, 5205.0, 6500.0]); | ||
| let daylight = p.points()[3].1; | ||
| assert!((daylight[0] - 1.83).abs() < 1e-3 && (daylight[2] - 1.16).abs() < 1e-3, "{daylight:?}"); | ||
| // no tag, or too few usable entries: none | ||
| assert!(kelvin_presets(None).is_none()); | ||
| assert!(kelvin_presets(Some(¬e(&words[..9]))).is_none()); | ||
| } | ||
|
|
||
| /// Our own prefix code for categories 0..=14: lengths 2,2,3,3,4,5,..., codes assigned canonically. | ||
| fn test_table() -> (Vec<u8>, Vec<(u16, u8)>) { | ||
| let lens: [u8; 15] = [3, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12]; | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Select the version-10 layout by ColorData word count, not by one temperature word.
For version 10,
kelvin_presets_from_color_datapicks the first candidate whose word 107 equals 5200. Word 107 is the Daylight temperature only in the 103 layout. In the 128 layout it isColorTempUnknown6, an unlabelled temperature field that can also hold 5200. A 128-layout file with 5200 at word 107 is therefore read with the 103 offsets. The decoder can then return gains from unrelated records. If those records do not form a curve, the decoder returnsNoneand does not try the 128 layout.Select the layout from the ColorData word count, as ExifTool does. ExifTool uses
ColorData6for counts 1273 and 1275 (the 1200D family) andColorData7for counts 1312, 1313, 1316, and 1506. Confirm thatkelvin_presets_from_color_datareceives the full ColorData array, so that its length gives the count.Add a regression fixture for a version-10 file that uses the 128 layout and has 5200 at word 107. Write its offsets as literal values, not from
preset_rows. The existing second-layout test usespreset_rows(10)[1], so it does not detect an incorrect offset.